branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>let nums = [1, -1, 5, 3, -7, 4, 5, 6, -100, 4]
function largestSubarraySum(nums){
let maxSum = 0;
for (let i = 0; i < nums.length; i++) {
let sumFixedStart = 0;
for (let j = i; j < nums.length; j++) {
sumFixedStart += nums[j];
maxSum = Math.max(maxSum, sumFixedStart);
}
}
return maxSum;
}
largestSubarraySum(nums)
|
5096125b8bd8aa2df1e934f2067d31f8fb582cf3
|
[
"JavaScript"
] | 1 |
JavaScript
|
speedy012/postgrad-challenge-largest-subarray-sum
|
30cad5a2e33d2aaf23dc2f1882fd40dd01bd1fa3
|
781faaa8c890c4344477386e07d0fecd558a0c83
|
refs/heads/master
|
<repo_name>alanarangotema/ClientesHANA_Administracion<file_sep>/webapp/controller/ViewAdministracion.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"clientesadministracion/Clientes_Administracion/model/models",
"clientesadministracion/Clientes_Administracion/constants/constants"
], function (Controller, Model) {
"use strict";
return Controller.extend("clientesadministracion.Clientes_Administracion.controller.ViewAdministracion", {
onInit: function () {
window.gOriginalData = null;
//Carga los datos de los usuarios en el modelo de la tabla
this.cargarDatos();
},
cargarDatos: function(){
var oModelTablaUsuarios = Model.createDataUsuariosModel();
oModelTablaUsuarios.attachRequestCompleted(function onCompleted(oEvent) {
//Esto guarda una copia de los datos sin referencia a los mismos para que no se actualicen al actualizar la tabla
window.gOriginalData = JSON.parse(JSON.stringify(oModelTablaUsuarios.getProperty("/d/results")));
});
//Obtiene los datos de los accesos de los usuarios y lo asigna al modelo de la tabla
this.getView().setModel(oModelTablaUsuarios, "dataAccesoUsuarios");
},
guardarCambios: function () {
var oModelTablaUsuarios = this.getView().getModel("dataAccesoUsuarios");
var arrayModelTablaUsuarios = oModelTablaUsuarios.getProperty("/d/results");
window.gBusy = new sap.m.BusyDialog(); //Handler de estado de cursor
gBusy.open(); //Cursor busy ON
this.guardarCambiosRecur(arrayModelTablaUsuarios, window.gOriginalData);
},
guardarCambiosRecur: function (datosActuales, datosOriginales) {
if (datosActuales && datosActuales.length){
var itemActual = datosActuales.shift();
var itemOriginal = datosOriginales.shift();
var errorMsg = "Usuario " + itemActual.UserSCP + ": ";
if(itemActual.AppCertificaciones != itemOriginal.AppCertificaciones){
//Modifica entrada incorrecta
var request = "/AccesosSet(Land1='" + itemActual.Land1 + "',Usuario='" + itemActual.Usuario + "')";
var body = {"AppCertificaciones" : itemActual.AppCertificaciones};
this.modificarUsuario(request, body, errorMsg, datosActuales, datosOriginales);
} else {
this.guardarCambiosRecur(datosActuales, datosOriginales);
}
}
else
{
//Termino con todas las consultas y recarga la tabla
gBusy.close(); //Cursor busy OFF
//Carga de nuevo los datos de los usuarios
this.cargarDatos();
}
},
modificarUsuario: function(request, body, errorMsg, datosActuales, datosOriginales){
var oData = new sap.ui.model.odata.v2.ODataModel({
serviceUrl: CONSTCLIENTEADMIN.URI.ODATA_PORTAL_CLIENTES_URI,
defaultUpdateMethod: sap.ui.model.odata.UpdateMethod.Put
});
var oThis = this;
//Escribe la factura en la base de datos
oData.update(request, body, {
success: function(oData, response){
console.log(oData);
console.log(response);
oThis.guardarCambiosRecur(datosActuales, datosOriginales);
},
error: function(oError){
console.log(oError);
alert(errorMsg + oError.message);
oThis.guardarCambiosRecur(datosActuales, datosOriginales);
}
});
}
});
});<file_sep>/webapp/model/models.js
sap.ui.define([
"sap/ui/model/json/JSONModel",
"sap/ui/Device"
], function (JSONModel, Device) {
"use strict";
return {
createDataUsuariosModel: function () {
var oBusy = new sap.m.BusyDialog();
/*var jsonTestData = {"d":{
"results": [
{
"UserSCP":"P000001",
"Kunnr":"0000231446",
"Name1":"Cliente 1",
"CertA":true
},
{
"UserSCP":"P000002",
"Kunnr":"0000987763",
"Name1":"Cliente 2",
"CertA":false
}
]}
};
*/
var oModel = new sap.ui.model.json.JSONModel();
oBusy.open();
var oModel = new sap.ui.model.json.JSONModel();
oModel.loadData(CONSTCLIENTEADMIN.URI.LISTA_ACCESOS_USUARIOS);
oModel.attachRequestCompleted(function onCompleted(oEvent) {
oBusy.close();
console.log(oModel);
});
return oModel;
},
createActualizaUsuariosModel: function () {
var oBusy = new sap.m.BusyDialog();
var oModel = new sap.ui.model.json.JSONModel(jsonTestData);
/*DESCOMENTAR CUANDO FUNCIONE EL SERVICIO
oBusy.open();
var oModel = new sap.ui.model.json.JSONModel();
oModel.loadData(CONSTCLIENTEADMIN.URI.LISTA_ACCESOS_USUARIOS);
oModel.attachRequestCompleted(function onCompleted(oEvent) {
oBusy.close();
console.log(oModel);
});*/
return oModel;
},
};
});<file_sep>/webapp/i18n/i18n.properties
title=Panel de Administración de Clientes
appTitle=Panel de Administración de Clientes
appDescription=App Description
tituloTabla=Accesos de Usuarios a Aplicaciones
colUsuarioSCP=Usuario SCP
colCodCliente=Cod. Cliente
colNomCliente=Nombre de Cliente
colCertificaciones=Certificaciones
colPais=País
btnGuardar=Guardar<file_sep>/webapp/constants/constants.js
(function (window) {
"use strict";
window.CONSTCLIENTEADMIN = {
ID : {
APP : "idApp",
PAGE: "idPage",
TABLE: "idTablaAccesosUsuarios",
BTN_GUARDAR: "idBtnGuardar"
},
URI: {
//ALIAS: "TDH",
//ALIAS: "TDHCLNT700",
ALIAS: "HANA",
CURRENT_USER : "/services/userapi/currentUser",
ODATA_PORTAL_CLIENTES_URI : "/sap/opu/odata/sap/ZSCP_PORTAL_CLIENTES_HANA_SRV",
LISTA_ACCESOS_USUARIOS : "/sap/opu/odata/sap/ZSCP_PORTAL_CLIENTES_HANA_SRV/AccesosSet"
}
};
}(window));
|
0d6fe768f04027cbb1421b73a3c3fffe1d5dfcaa
|
[
"JavaScript",
"INI"
] | 4 |
JavaScript
|
alanarangotema/ClientesHANA_Administracion
|
a9e175b636a7735d085a783f200d8763e9aa3d40
|
3aa72c705127714a845133a699ddae93016fc95d
|
refs/heads/master
|
<repo_name>devjpsmith/kotlin-dagger-template<file_sep>/app/src/main/java/com/development/james/myapplication/network/NetworkApi.kt
package com.development.james.myapplication.network
import android.content.Context
import dagger.Module
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NetworkApi: INetworkApi {
var mContext: Context
@Inject
constructor(context: Context) {
mContext = context
}
override fun validateInput(input: String): Boolean = mContext.packageName.isNotEmpty() && input.isNotEmpty()
}<file_sep>/app/src/main/java/com/development/james/myapplication/dagger/AppComponent.kt
package com.development.james.myapplication.dagger
import com.development.james.myapplication.ui.main.MainActivity
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = [ AppModule::class ])
interface AppComponent {
fun inject(target: MainActivity)
}
<file_sep>/app/src/main/java/com/development/james/myapplication/network/INetworkApi.kt
package com.development.james.myapplication.network
interface INetworkApi {
fun validateInput(input: String) : Boolean
}<file_sep>/app/src/main/java/com/development/james/myapplication/dagger/ActivityModule.kt
package com.development.james.myapplication.dagger
import com.development.james.myapplication.ui.main.MainActivity
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class ActivityModule {
@Provides
@Singleton
fun provideMainActivity(): MainActivity = MainActivity()
}<file_sep>/app/src/main/java/com/development/james/myapplication/application/MainApplication.kt
package com.development.james.myapplication.application
import android.app.Application
import com.development.james.myapplication.dagger.AppComponent
import com.development.james.myapplication.dagger.AppModule
import com.development.james.myapplication.dagger.DaggerAppComponent
class MainApplication : Application(){
lateinit var appComponent: AppComponent
private fun initDagger(app: MainApplication): AppComponent =
DaggerAppComponent.builder()
.appModule(AppModule(app))
.build()
override fun onCreate() {
super.onCreate()
appComponent = initDagger(this)
}
}<file_sep>/app/src/main/java/com/development/james/myapplication/ui/main/MainActivity.kt
package com.development.james.myapplication.ui.main
import android.app.Activity
import android.os.Bundle
import android.util.Log
import com.development.james.myapplication.R
import com.development.james.myapplication.application.MainApplication
import com.development.james.myapplication.network.INetworkApi
import com.development.james.myapplication.network.NetworkApi
import javax.inject.Inject
class MainActivity : Activity() {
private val TAG: String = "MainActivity"
@Inject
lateinit var mNetworkApi: NetworkApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as MainApplication).appComponent.inject(this)
Log.d(TAG, "Dependency Injection worked: "
+ mNetworkApi.validateInput("hello world"))
}
}
|
1ef8a2b9644ddeb527dfcea8a99442f963856d1d
|
[
"Kotlin"
] | 6 |
Kotlin
|
devjpsmith/kotlin-dagger-template
|
e46585e7fceea456d931251848d1ce6e9aa05e76
|
24590767b671e98bdd8f5e39ae454de0f7a2781d
|
refs/heads/main
|
<repo_name>engelsjk/gmartini<file_sep>/terrain_test.go
package gmartini
import (
"bufio"
"encoding/binary"
"image"
_ "image/png"
"io"
"os"
"testing"
gmu "github.com/engelsjk/gomathutils"
)
// references
// [1] https://github.com/kylebarron/pymartini/blob/master/test/create_test_data.js
func TestTerrain(t *testing.T) {
terrainFile := "data/fuji.png"
expectedTerrainFile := "data/fuji_terrain" // generated by ref[1]
encoding := "mapbox"
var epsilon float32 = 100
// generate terrain
file1, err := os.Open(terrainFile)
if err != nil {
t.Error(err)
}
defer file1.Close()
img, _, err := image.Decode(file1)
if err != nil {
t.Error(err)
}
terrain, err := DecodeElevation(img, encoding, true)
if err != nil {
t.Error(err)
}
// load expected terrain
file2, err := os.Open(expectedTerrainFile)
if err != nil {
t.Error(err)
}
defer file2.Close()
var expectedTerrain []float32
reader := bufio.NewReader(file2)
var i float32
for {
err := binary.Read(reader, binary.LittleEndian, &i)
if err == io.EOF {
break
}
expectedTerrain = append(expectedTerrain, i)
}
var max, min float32
max, min = gmu.MaxminFloat32(terrain)
t.Logf("terrain: %f max, %f min", max, min)
max, min = gmu.MaxminFloat32(expectedTerrain)
t.Logf("expected terrain: %f max, %f min", max, min)
for i, v := range terrain {
delta := v - expectedTerrain[i]
if gmu.AbsFloat32(delta) > epsilon {
t.Logf("terrain mismatch exceeding %f epsilon: calculated %f, expected %f (delta %f)", epsilon, v, expectedTerrain[i], delta)
}
}
if !gmu.EqualFloat32(terrain, expectedTerrain, epsilon) {
t.Logf("terrain doesn't match expected at epsilon %f", epsilon)
t.Fail()
} else {
t.Logf("terrain matches expected at epsilon %f", epsilon)
}
}
<file_sep>/martini.go
package gmartini
import (
"fmt"
)
type Martini struct {
GridSize int32
NumTriangles int
NumParentTriangles int
Indices []int32
Coords []int32
}
// New instantiates a Martini instance which includes a CreateTile method and also inititializes arrays for both Coords and Indices.
// By default, Martini assumes a 257 grid size (2^n+1) but can be initialized with a different OptionGridSize(gridSize int32).
func New(opts ...func(*Martini) error) (*Martini, error) {
martini := &Martini{}
martini.GridSize = 257
for _, opt := range opts {
err := opt(martini)
if err != nil {
return nil, err
}
}
tileSize := martini.GridSize - 1
if tileSize&(tileSize-1) == 1 {
return nil, fmt.Errorf(`expected grid size to be 2^n+1, got %d`, martini.GridSize)
}
martini.NumTriangles = int(tileSize*tileSize*2 - 2)
martini.NumParentTriangles = martini.NumTriangles - int(tileSize*tileSize)
martini.Indices = make([]int32, martini.GridSize*martini.GridSize)
// coordinates for all possible triangles in an RTIN tile
martini.Coords = make([]int32, martini.NumTriangles*4)
// get triangle coordinates from its index in an implicit binary tree
var id, k int
var ax, ay, bx, by, cx, cy int32
size := tileSize
for i := 0; i < martini.NumTriangles; i++ {
id = i + 2
ax, ay, bx, by, cx, cy = 0, 0, 0, 0, 0, 0
if id&1 == 1 {
bx, by, cx = size, size, size // bottom-left triangle
} else {
ax, ay, cy = size, size, size // top-right triangle
}
for (id >> 1) > 1 {
id = id >> 1
mx := (ax + bx) >> 1
my := (ay + by) >> 1
if id&1 == 1 { // left half
bx, by = ax, ay
ax, ay = cx, cy
} else { // right half
ax, ay = bx, by
bx, by = cx, cy
}
cx, cy = mx, my
}
k = i * 4
martini.Coords[k+0] = ax
martini.Coords[k+1] = ay
martini.Coords[k+2] = bx
martini.Coords[k+3] = by
}
return martini, nil
}
// OptionGridSize can be used to specify the gridsize (int32) in initializing a Martini instance.
func OptionGridSize(gridSize int32) func(*Martini) error {
return func(m *Martini) error {
m.GridSize = gridSize
return nil
}
}
// CreateTile creates a Tile instance of the generated RTIN hierarchy based on the specified terrain map.
// This hierarchy is an array of error values determined by interpolated height values relative to the terrain map.
func (m *Martini) CreateTile(terrain []float32) (*Tile, error) {
return NewTile(terrain, m)
}
<file_sep>/benchmark/time_test.go
package benchmark
import (
"fmt"
"image"
"log"
"os"
"testing"
"time"
"github.com/engelsjk/gmartini"
)
func stopwatch(start time.Time, name string) {
elapsed := time.Since(start)
log.Printf("%s: %.03fms", name, float64(elapsed.Nanoseconds())/1000000)
}
func TestExecutionTime(t *testing.T) {
var terrainFile string = "../data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
file, err := os.Open(terrainFile)
if err != nil {
panic(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
terrain, err := gmartini.DecodeElevation(img, encoding, true)
if err != nil {
panic(err)
}
martini, err := initTileset(gridSize)
if err != nil {
panic(err)
}
tile, err := createTile(martini, terrain)
if err != nil {
panic(err)
}
maxErrors := []float32{0, 2, 5, 10, 20, 30, 50, 75, 100, 250, 500}
for i := 0; i < len(maxErrors); i++ {
generateMesh(tile, maxErrors[i])
}
}
func initTileset(gridSize int32) (*gmartini.Martini, error) {
defer stopwatch(time.Now(), "init tileset")
return gmartini.New(gmartini.OptionGridSize(gridSize))
}
func createTile(martini *gmartini.Martini, terrain []float32) (*gmartini.Tile, error) {
defer stopwatch(time.Now(), "create tile")
return martini.CreateTile(terrain)
}
func generateMesh(tile *gmartini.Tile, maxError float32) {
start := time.Now()
mesh := tile.GetMesh(gmartini.OptionMaxError(maxError))
elapsed := time.Since(start)
name := fmt.Sprintf("mesh (max error = %.0f)", maxError)
vt := fmt.Sprintf("(vertices: %d, triangles: %d)", mesh.NumVertices, mesh.NumTriangles)
log.Printf("%s: %.03fms %s\n", name, float64(elapsed.Nanoseconds())/1000000, vt)
}
<file_sep>/benchmark/martini_test.go
package benchmark
import (
"testing"
"github.com/engelsjk/gmartini"
)
func BenchmarkMartini(b *testing.B) {
var gridSize int32 = 513
for n := 0; n < b.N; n++ {
gmartini.New(gmartini.OptionGridSize(gridSize))
}
}
<file_sep>/tile.go
package gmartini
import (
"fmt"
gmu "github.com/engelsjk/gomathutils"
)
type Tile struct {
GridSize int32
NumTriangles int
NumParentTriangles int
Indices []int32
Coords []int32
Terrain []float32
Errors []float32
}
// NewTile instantiates a new Tile instance of the generated RTIN hierarchy using a specified terrain map and an initialized Martini instance.
// This hierarchy is an array of error values determined by interpolated height values relative to the specified terrain map.
func NewTile(terrain []float32, martini *Martini) (*Tile, error) {
tile := &Tile{}
size := martini.GridSize
if len(terrain) != int(size*size) {
return nil, fmt.Errorf(`expected terrain data of length %d (%d x %d), got %d`, size*size, size, size, len(terrain))
}
tile.Terrain = terrain
tile.Errors = make([]float32, len(terrain))
tile.GridSize = martini.GridSize
tile.NumTriangles = martini.NumTriangles
tile.NumParentTriangles = martini.NumParentTriangles
tile.Indices = martini.Indices
tile.Coords = martini.Coords
tile.update()
return tile, nil
}
func (t *Tile) update() {
var k int
var ax, ay, bx, by, cx, cy, mx, my int32
var interpolatedHeight, middleError float32
var middleIndex, leftChildIndex, rightChildIndex int32
var aIndex, bIndex int32
for i := t.NumTriangles - 1; i >= 0; i-- {
k = i * 4
ax = t.Coords[k+0]
ay = t.Coords[k+1]
bx = t.Coords[k+2]
by = t.Coords[k+3]
mx = (ax + bx) >> 1
my = (ay + by) >> 1
cx = mx + my - ay
cy = my + ax - mx
// calculate error in the middle of the long edge of the triangle
aIndex = ay*t.GridSize + ax
bIndex = by*t.GridSize + bx
interpolatedHeight = (t.Terrain[aIndex] + t.Terrain[bIndex]) / 2
middleIndex = my*t.GridSize + mx
middleError = gmu.AbsFloat32(interpolatedHeight - t.Terrain[middleIndex])
t.Errors[middleIndex] = gmu.MaxFloat32x2(t.Errors[middleIndex], middleError)
if i < t.NumParentTriangles { // bigger triangles; accumulate error with children
leftChildIndex = ((ay+cy)>>1)*t.GridSize + ((ax + cx) >> 1)
rightChildIndex = ((by+cy)>>1)*t.GridSize + ((bx + cx) >> 1)
t.Errors[middleIndex] = gmu.MaxFloat32x3(t.Errors[middleIndex], t.Errors[leftChildIndex], t.Errors[rightChildIndex])
}
}
}
// GetMesh generates a new mesh of vertices and triangles for the Tile with a max error (default 0).
func (t *Tile) GetMesh(opts ...func(*Mesh) error) *Mesh {
return NewMesh(t, opts...)
}
<file_sep>/terrain.go
package gmartini
import (
"fmt"
"image"
_ "image/png"
"strings"
)
// DecodeElevation decodes the pixel values of an image.Image (e.g. a Mapbox Terrain RGB raster tile) into a 1D array of heightmap values.
// A backfill option is included to satisfy the martini requirement of a 2^n+1 grid size.
func DecodeElevation(img image.Image, encoding string, addBackfill bool) ([]float32, error) {
allowedEncodings := make(map[string]bool)
allowedEncodings["mapbox"] = true
allowedEncodings["terrarium"] = true
encodings := []string{}
for k, v := range allowedEncodings {
if v {
encodings = append(encodings, k)
}
}
allowed, ok := allowedEncodings[encoding]
if !ok {
return nil, fmt.Errorf("encoding not recognized, must be one of %s", strings.Join(encodings, ", "))
}
if !allowed {
return nil, fmt.Errorf("encoding not allowed, must be one of %s", strings.Join(encodings, ", "))
}
minX := img.Bounds().Min.X
maxX := img.Bounds().Max.X
minY := img.Bounds().Min.Y
maxY := img.Bounds().Max.Y
width := maxX - minX
height := maxY - minY
if width != height {
return nil, fmt.Errorf("width (%d) must equal height (%d)", width, height)
}
tileSize := width
gridSize := width + 1
terrain := make([]float32, gridSize*gridSize)
for y := 0; y < tileSize; y++ {
for x := 0; x < tileSize; x++ {
r, g, b, a := img.At(x, y).RGBA()
terrain[y*gridSize+x] = rgbaToTerrain(r, g, b, a, encoding)
}
}
if addBackfill {
terrain = ComputeBackfill(terrain, gridSize)
}
return terrain, nil
}
func ComputeBackfill(arr []float32, gridSize int) []float32 {
if len(arr) != gridSize*gridSize {
return arr
}
for x := 0; x < gridSize-1; x++ {
arr[gridSize*(gridSize-1)+x] = arr[gridSize*(gridSize-2)+x] //backfill bottom border
}
for y := 0; y < gridSize; y++ {
arr[gridSize*y+gridSize-1] = arr[gridSize*y+gridSize-2] //backfill right border
}
// for i := 0; i < gridSize*gridSize-1; i++ {
// row := i / gridSize
// if i == (row*gridSize + size) { // right border
// arrBackfilled[i] = arr[i-row-1]
// } else if row > (size - 1) { // bottom border
// arrBackfilled[i] = arr[i-row-gridSize]
// } else {
// arrBackfilled[i] = arr[i-row]
// }
// arrBackfilled[gridSize*gridSize-1] = arrBackfilled[gridSize*gridSize-2]
// }
return arr
}
// func RescalePosition() {
// func getPixel(img image.Image, x, y int, flipPNG bool) color.Color {
// if flipPNG {
// return img.At(y, x)
// }
// return img.At(x, y)
// }
func rgbaToTerrain(r uint32, g uint32, b uint32, a uint32, encoding string) float32 {
switch encoding {
case "mapbox":
return (float32(r>>8)*(256.0*256.0)+float32(g>>8)*256.0+float32(b>>8))/10 - 10000.0
case "terrarium":
return (float32(r>>8)*256.0 + float32(g>>8) + float32(b>>8)/256) - 32768.0
default:
return 0
}
}
<file_sep>/mesh.go
package gmartini
import gmu "github.com/engelsjk/gomathutils"
type Mesh struct {
MaxError float32
NumVertices int32
NumTriangles int
TriIndex int
Vertices []int32
Triangles []int32
}
// NewMesh instanties a new mesh for the specified Tile with a max error (default 0).
func NewMesh(tile *Tile, opts ...func(*Mesh) error) *Mesh {
mesh := &Mesh{}
mesh.NumVertices = 0
mesh.NumTriangles = 0
mesh.MaxError = 0
for _, opt := range opts {
err := opt(mesh)
if err != nil {
return nil
}
}
max := tile.GridSize - 1
// use an index grid to keep track of vertices that were already used to avoid duplication
for i := range tile.Indices {
tile.Indices[i] = 0
}
// retrieve mesh in two stages that both traverse the error map:
// - countElements: find used vertices (and assign each an index), and count triangles (for minimum allocation)
// - processTriangle: fill the allocated vertices & triangles typed arrays
mesh.countElements(tile, 0, 0, max, max, max, 0)
mesh.countElements(tile, max, max, 0, 0, 0, max)
mesh.Vertices = make([]int32, mesh.NumVertices*2)
mesh.Triangles = make([]int32, mesh.NumTriangles*3)
mesh.TriIndex = 0
mesh.processTriangle(tile, 0, 0, max, max, max, 0)
mesh.processTriangle(tile, max, max, 0, 0, 0, max)
return mesh
}
// OptionMaxError can be used to set the max error of the generated Mesh.
func OptionMaxError(maxError float32) func(*Mesh) error {
return func(m *Mesh) error {
m.MaxError = maxError
return nil
}
}
func (m *Mesh) countElements(tile *Tile, ax, ay, bx, by, cx, cy int32) {
mx := (ax + bx) >> 1
my := (ay + by) >> 1
middleIndex := my*tile.GridSize + mx
if gmu.AbsInt32(ax-cx)+gmu.AbsInt32(ay-cy) > 1 && tile.Errors[middleIndex] > m.MaxError {
m.countElements(tile, cx, cy, ax, ay, mx, my)
m.countElements(tile, bx, by, cx, cy, mx, my)
} else {
aIndex := ay*tile.GridSize + ax
bIndex := by*tile.GridSize + bx
cIndex := cy*tile.GridSize + cx
if tile.Indices[aIndex] == 0 {
m.NumVertices++
tile.Indices[aIndex] = m.NumVertices
}
if tile.Indices[bIndex] == 0 {
m.NumVertices++
tile.Indices[bIndex] = m.NumVertices
}
if tile.Indices[cIndex] == 0 {
m.NumVertices++
tile.Indices[cIndex] = m.NumVertices
}
m.NumTriangles++
}
}
func (m *Mesh) processTriangle(tile *Tile, ax, ay, bx, by, cx, cy int32) {
mx := (ax + bx) >> 1
my := (ay + by) >> 1
indices := tile.Indices
middleIndex := my*tile.GridSize + mx
if gmu.AbsInt32(ax-cx)+gmu.AbsInt32(ay-cy) > 1 && tile.Errors[middleIndex] > m.MaxError {
// triangle doesn't approximate the surface well enough; drill down further
m.processTriangle(tile, cx, cy, ax, ay, mx, my)
m.processTriangle(tile, bx, by, cx, cy, mx, my)
} else {
aIndex := ay*tile.GridSize + ax
bIndex := by*tile.GridSize + bx
cIndex := cy*tile.GridSize + cx
// add a triangle
a := indices[aIndex] - 1
b := indices[bIndex] - 1
c := indices[cIndex] - 1
m.Vertices[2*a] = ax
m.Vertices[2*a+1] = ay
m.Vertices[2*b] = bx
m.Vertices[2*b+1] = by
m.Vertices[2*c] = cx
m.Vertices[2*c+1] = cy
m.Triangles[m.TriIndex] = a
m.TriIndex++
m.Triangles[m.TriIndex] = b
m.TriIndex++
m.Triangles[m.TriIndex] = c
m.TriIndex++
}
}
<file_sep>/draw_test.go
package gmartini
import (
"fmt"
"image"
_ "image/png"
"math"
"os"
"testing"
"github.com/engelsjk/colormap"
"github.com/engelsjk/colormap/palette"
gmu "github.com/engelsjk/gomathutils"
"github.com/fogleman/gg"
)
func drawTerrain(dc *gg.Context, terrain []float32) {
var cutoff, max float32 = 1.0, 1.0
size := int(math.Sqrt(float64(len(terrain))))
upLeft := image.Point{0, 0}
lowRight := image.Point{size, size}
img := image.NewRGBA(image.Rectangle{upLeft, lowRight})
maxZ, minZ := gmu.MaxminFloat32(terrain)
cm := colormap.Colormap{Palette: palette.Turbo{}}
for y := 0; y < size; y++ {
for x := 0; x < size; x++ {
k := y*size + x
v := gmu.MinFloat32v(max, max*gmu.MinFloat32v((terrain[k]-minZ)/(maxZ-minZ), cutoff)/cutoff)
px := cm.ToRGBA(float64(v), 255)
img.Set(x, y, px)
}
}
dc.DrawImage(img, 0, 0)
}
func drawVertices(dc *gg.Context, mesh *Mesh) {
dc.SetRGB(0, 0, 0)
for i := 0; i < (len(mesh.Vertices) - 2); i += 2 {
dc.DrawCircle(float64(mesh.Vertices[i]), float64(mesh.Vertices[i+1]), 0.5)
dc.Fill()
}
}
func drawTriangles(dc *gg.Context, mesh *Mesh) {
dc.ClearPath()
dc.SetRGB(0, 0, 0)
dc.SetLineWidth(0.5)
for i := 0; i < (len(mesh.Triangles) - 3); i += 3 {
a, b, c := mesh.Triangles[i], mesh.Triangles[i+1], mesh.Triangles[i+2]
ax, ay := float64(mesh.Vertices[2*a]), float64(mesh.Vertices[2*a+1])
bx, by := float64(mesh.Vertices[2*b]), float64(mesh.Vertices[2*b+1])
cx, cy := float64(mesh.Vertices[2*c]), float64(mesh.Vertices[2*c+1])
dc.MoveTo(ax, ay)
dc.LineTo(bx, by)
dc.LineTo(cx, cy)
dc.LineTo(ax, ay)
}
dc.Stroke()
}
func TestDrawTerrain(t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var imageFile string = "test/terrain.png"
file, err := os.Open(terrainFile)
if err != nil {
t.Error(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
t.Error(err)
}
terrain, err := DecodeElevation(img, encoding, true)
if err != nil {
t.Error(err)
}
dc := gg.NewContext(512, 512)
dc.SetRGB(1, 1, 1)
dc.Clear()
drawTerrain(dc, terrain)
dc.SavePNG(imageFile)
t.Logf("test image saved at %s", imageFile)
}
func load(terrainFile, encoding string, gridSize int32, maxError float32) ([]float32, *Mesh) {
file, err := os.Open(terrainFile)
if err != nil {
panic(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
terrain, err := DecodeElevation(img, encoding, true)
if err != nil {
panic(err)
}
martini, err := New(OptionGridSize(gridSize))
if err != nil {
panic(err)
}
tile, err := martini.CreateTile(terrain)
if err != nil {
panic(err)
}
mesh := tile.GetMesh(OptionMaxError(maxError))
return terrain, mesh
}
func TestDrawVerticesErr5(t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
var maxError float32 = 5.0
var imageFile string = "test/vertices-%d.png"
_, mesh := load(terrainFile, encoding, gridSize, maxError)
dc := gg.NewContext(512, 512)
dc.SetRGB(1, 1, 1)
dc.Clear()
drawVertices(dc, mesh)
dc.SavePNG(fmt.Sprintf(imageFile, int(maxError)))
t.Logf("test image saved at %s", fmt.Sprintf(imageFile, int(maxError)))
}
func TestDrawVerticesErr50(t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
var maxError float32 = 50.0
var imageFile string = "test/vertices-%d.png"
_, mesh := load(terrainFile, encoding, gridSize, maxError)
dc := gg.NewContext(512, 512)
dc.SetRGB(1, 1, 1)
dc.Clear()
drawVertices(dc, mesh)
dc.SavePNG(fmt.Sprintf(imageFile, int(maxError)))
t.Logf("test image saved at %s", fmt.Sprintf(imageFile, int(maxError)))
}
func TestDrawVerticesErr500(t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
var maxError float32 = 500.0
var imageFile string = "test/vertices-%d.png"
_, mesh := load(terrainFile, encoding, gridSize, maxError)
dc := gg.NewContext(512, 512)
dc.SetRGB(1, 1, 1)
dc.Clear()
drawVertices(dc, mesh)
dc.SavePNG(fmt.Sprintf(imageFile, int(maxError)))
t.Logf("test image saved at %s", fmt.Sprintf(imageFile, int(maxError)))
}
func TestDrawTrianglesErr5(t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
var maxError float32 = 5.0
var imageFile string = "test/triangles-%d.png"
_, mesh := load(terrainFile, encoding, gridSize, maxError)
dc := gg.NewContext(512, 512)
dc.SetRGB(1, 1, 1)
dc.Clear()
drawTriangles(dc, mesh)
dc.SavePNG(fmt.Sprintf(imageFile, int(maxError)))
t.Logf("test image saved at %s", fmt.Sprintf(imageFile, int(maxError)))
}
func TestDrawTrianglesErr50(t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
var maxError float32 = 50.0
var imageFile string = "test/triangles-%d.png"
_, mesh := load(terrainFile, encoding, gridSize, maxError)
dc := gg.NewContext(512, 512)
dc.SetRGB(1, 1, 1)
dc.Clear()
drawTriangles(dc, mesh)
dc.SavePNG(fmt.Sprintf(imageFile, int(maxError)))
t.Logf("test image saved at %s", fmt.Sprintf(imageFile, int(maxError)))
}
func TestDrawTrianglesErr500(t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
var maxError float32 = 500.0
var imageFile string = "test/triangles-%d.png"
_, mesh := load(terrainFile, encoding, gridSize, maxError)
dc := gg.NewContext(512, 512)
dc.SetRGB(1, 1, 1)
dc.Clear()
drawTriangles(dc, mesh)
dc.SavePNG(fmt.Sprintf(imageFile, int(maxError)))
t.Logf("test image saved at %s", fmt.Sprintf(imageFile, int(maxError)))
}
func TestDrawAll(t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
var maxError float32 = 50.0
var imageFile string = "test/martini-%d.png"
terrain, mesh := load(terrainFile, encoding, gridSize, maxError)
dc := gg.NewContext(512, 512)
dc.SetRGB(1, 1, 1)
dc.Clear()
drawTerrain(dc, terrain)
drawVertices(dc, mesh)
drawTriangles(dc, mesh)
dc.SavePNG(fmt.Sprintf(imageFile, int(maxError)))
t.Logf("test image saved at %s", fmt.Sprintf(imageFile, int(maxError)))
}
<file_sep>/benchmark/mesh_test.go
package benchmark
import (
"image"
"os"
"testing"
"github.com/engelsjk/gmartini"
)
func benchmarkMesh(maxError float32, b *testing.B) {
var terrainFile string = "../data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
file, err := os.Open(terrainFile)
if err != nil {
panic(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
terrain, err := gmartini.DecodeElevation(img, encoding, true)
if err != nil {
panic(err)
}
martini, err := gmartini.New(gmartini.OptionGridSize(gridSize))
if err != nil {
panic(err)
}
tile, err := martini.CreateTile(terrain)
if err != nil {
panic(err)
}
for n := 0; n < b.N; n++ {
tile.GetMesh(gmartini.OptionMaxError(maxError))
}
}
func BenchmarkMeshErr5(b *testing.B) { benchmarkMesh(5, b) }
func BenchmarkMeshErr10(b *testing.B) { benchmarkMesh(10, b) }
func BenchmarkMeshErr50(b *testing.B) { benchmarkMesh(50, b) }
func BenchmarkMeshErr100(b *testing.B) { benchmarkMesh(100, b) }
func BenchmarkMeshErr500(b *testing.B) { benchmarkMesh(500, b) }
<file_sep>/README.md
# gmartini

A Go port of the RTIN terrain mesh generator [mapbox/martini](https://github.com/mapbox/martini) by [mourner](https://github.com/mourner).
Additional info on martini can be found at the Observable notebook, "[MARTINI: Real-Time RTIN Terrain Mesh](https://observablehq.com/@mourner/martin-real-time-rtin-terrain-mesh)", written by [mourner](https://github.com/mourner). Original algorithm based on the paper ["Right-Triangulated Irregular Networks" by Will Evans et. al. (1997)](https://www.cs.ubc.ca/~will/papers/rtin.pdf).
Sanity checks of porting correctness and static typing nuance by referencing [kylebarron](https://github.com/kylebarron)'s Cython port [pymartini](https://github.com/kylebarron/pymartini).
## Mesh
A mesh consisting of vertices and triangles can be generated from a terrain PNG image.
```
file, _ := os.Open("data/fuji.png")
img, _, _ := image.Decode(file)
terrain, _ := gmartini.DecodeElevation(img, "mapbox", true)
martini, _ := gmartini.New(gmartini.OptionGridSize(513))
tile, _ := martini.CreateTile(terrain)
mesh := tile.GetMesh(gmartini.OptionMaxError(30))
```
## Install
```
go get github.com/engelsjk/gmartini
```
## Benchmark
Benchmarking shows comparable results to [mapbox/martini](https://github.com/mapbox/martini) for preparation steps and to [pymartini](https://github.com/kylebarron/pymartini) for mesh generation.
```bash
go test ./benchmark -run TestExecutionTime -v
```
```
init tileset: 39.450ms
create tile: 10.201ms
mesh (max error = 0): 14.202ms (vertices: 261880, triangles: 521768)
mesh (max error = 2): 11.739ms (vertices: 176260, triangles: 351014)
mesh (max error = 5): 6.633ms (vertices: 94496, triangles: 187912)
mesh (max error = 10): 3.313ms (vertices: 45107, triangles: 89490)
mesh (max error = 20): 1.329ms (vertices: 17764, triangles: 35095)
mesh (max error = 30): 0.779ms (vertices: 9708, triangles: 19094)
mesh (max error = 50): 0.361ms (vertices: 4234, triangles: 8261)
mesh (max error = 75): 0.191ms (vertices: 2117, triangles: 4094)
mesh (max error = 100): 0.120ms (vertices: 1239, triangles: 2373)
mesh (max error = 250): 0.032ms (vertices: 200, triangles: 359)
mesh (max error = 500): 0.018ms (vertices: 46, triangles: 75)
```
<file_sep>/go.mod
module github.com/engelsjk/gmartini
go 1.15
require (
github.com/engelsjk/colormap v0.0.0-20210424004146-1a9b1ef81ca3
github.com/engelsjk/gomathutils v0.0.0-20200809214211-f547ed365720
github.com/fogleman/gg v1.3.0
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb // indirect
)
<file_sep>/mesh_test.go
package gmartini
import (
"image"
_ "image/png"
"os"
"testing"
gmu "github.com/engelsjk/gomathutils"
)
func testMesh(expectedVertices, expectedTriangles []int32, maxError float32, t *testing.T) {
var terrainFile string = "data/fuji.png"
var encoding string = "mapbox"
var gridSize int32 = 513
file, err := os.Open(terrainFile)
if err != nil {
t.Error(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
t.Error(err)
}
terrain, err := DecodeElevation(img, encoding, true)
if err != nil {
t.Error(err)
}
martini, err := New(OptionGridSize(gridSize))
if err != nil {
t.Error(err)
}
tile, err := martini.CreateTile(terrain)
if err != nil {
t.Error(err)
}
mesh := tile.GetMesh(OptionMaxError(maxError))
if !gmu.EqualInt32(mesh.Vertices, expectedVertices) {
t.Logf("mesh vertices doesn't match expected at max error %f", maxError)
t.Fail()
} else {
t.Logf("mesh vertices matches expected at max error %f", maxError)
}
if !gmu.EqualInt32(mesh.Triangles, expectedTriangles) {
t.Logf("mesh triangles doesn't match expected at max error %f", maxError)
t.Fail()
} else {
t.Logf("mesh triangles matches expected at max error %f", maxError)
}
}
func TestMeshMaxError500(t *testing.T) {
// reference mesh : https://github.com/mapbox/martini/blob/master/test/test.js
expectedVertices := []int32{
320, 64, 256, 128, 320, 128, 384, 128, 256, 0, 288, 160, 256, 192, 288, 192, 320, 192, 304, 176, 256, 256, 288,
224, 352, 160, 320, 160, 512, 0, 384, 0, 128, 128, 128, 0, 64, 64, 64, 0, 0, 0, 32, 32, 192, 192, 384, 384, 512,
256, 384, 256, 320, 320, 320, 256, 512, 512, 512, 128, 448, 192, 384, 192, 128, 384, 256, 512, 256, 384, 0,
512, 128, 256, 64, 192, 0, 256, 64, 128, 32, 96, 0, 128, 32, 64, 16, 48, 0, 64, 0, 32,
}
expectedTriangles := []int32{
0, 1, 2, 3, 0, 2, 4, 1, 0, 5, 6, 7, 7, 8, 9, 5, 7, 9, 1, 6, 5, 6, 10, 11, 11, 8, 7, 6, 11, 7, 12, 2, 13, 8, 12,
13, 3, 2, 12, 2, 1, 5, 13, 5, 9, 8, 13, 9, 2, 5, 13, 3, 14, 15, 15, 4, 0, 3, 15, 0, 16, 4, 17, 18, 17, 19, 19,
20, 21, 18, 19, 21, 16, 17, 18, 1, 16, 22, 22, 10, 6, 1, 22, 6, 4, 16, 1, 23, 24, 25, 26, 25, 27, 10, 26, 27,
23, 25, 26, 28, 24, 23, 29, 3, 30, 24, 29, 30, 14, 3, 29, 8, 25, 31, 31, 3, 12, 8, 31, 12, 27, 8, 11, 10, 27,
11, 25, 8, 27, 25, 24, 30, 30, 3, 31, 25, 30, 31, 32, 33, 34, 10, 32, 34, 35, 33, 32, 33, 28, 23, 34, 23, 26,
10, 34, 26, 33, 23, 34, 36, 16, 37, 38, 36, 37, 36, 10, 22, 16, 36, 22, 39, 18, 40, 41, 39, 40, 16, 18, 39, 42,
21, 43, 44, 42, 43, 18, 21, 42, 21, 20, 45, 45, 44, 43, 21, 45, 43, 44, 41, 40, 40, 18, 42, 44, 40, 42, 41, 38,
37, 37, 16, 39, 41, 37, 39, 38, 35, 32, 32, 10, 36, 38, 32, 36,
}
testMesh(expectedVertices, expectedTriangles, 500, t)
}
// func TestMeshMaxError5(t *testing.T) { testMesh(5, t) }
// func TestMeshMaxError10(t *testing.T) { testMesh(10, t) }
// func TestMeshMaxError50(t *testing.T) { testMesh(50, t) }
// func TestMeshMaxError100(t *testing.T) { testMesh(100, t) }
<file_sep>/example/main.go
package main
import (
"fmt"
"image"
"math"
"os"
"github.com/engelsjk/gmartini"
)
func main() {
file, err := os.Open("data/fuji.png")
if err != nil {
panic(err)
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
terrain, err := gmartini.DecodeElevation(img, "mapbox", true)
if err != nil {
panic(err)
}
martini, err := gmartini.New(gmartini.OptionGridSize(513))
if err != nil {
panic(err)
}
tile, err := martini.CreateTile(terrain)
if err != nil {
panic(err)
}
mesh := tile.GetMesh(gmartini.OptionMaxError(30))
fmt.Printf("gmartini\n")
fmt.Printf("terrain: %.0f+1 x %.0f+1\n", math.Sqrt(float64(len(terrain)))-1, math.Sqrt(float64(len(terrain)))-1)
fmt.Printf("max error: %d\n", 30)
fmt.Printf("mesh vertices: %d\n", mesh.NumVertices)
fmt.Printf("mesh triangles: %d\n", mesh.NumTriangles)
}
|
4abc6291db24a42ffa7e5fc3a7214d73dc1ede71
|
[
"Markdown",
"Go Module",
"Go"
] | 13 |
Go
|
engelsjk/gmartini
|
3cb76a722a470864234703689e3f72be9c403d67
|
9a2ebdafc398ae40330f4420cdec1781bc6f93ee
|
refs/heads/master
|
<file_sep>const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const PetSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Name of pet is required"],
minlength: [3, "Name of pet must be at least 3 characters long"],
unique: true
},
type: {
type: String,
required: [true, "Type of pet is required"],
minlength: [3, "Type of pet must be at least 3 characters long"]
},
description: {
type: String,
required: [true, "Description is required"],
minlength: [5, "Description must be at least 3 characters long"]
},
skills: {
type: [String],
required: [false],
validate: [arrayLimit, 'Pet can have at most 3 skills']
}
}, { timestamps: true });
function arrayLimit(val) {
return val.length <=3;
}
PetSchema.plugin(uniqueValidator, { message: 'Pet with name "{VALUE}" already exists'});
module.exports.Pet = mongoose.model('Pet', PetSchema);<file_sep>import React, { useEffect, useState } from 'react';
import axios from 'axios';
import PetForm from '../components/PetForm/PetForm';
import Header from "../components/Header/Header";
export default () => {
const initialFormSettings = {
name: "",
type: "",
description: "",
skills: ["", "", ""]
}
const [pets, setPets] = useState([]);
const [errors, setErrors] = useState([]);
useEffect(() =>{
axios.get('http://localhost:8000/api/pets')
.then(res => {
setPets(res.data.pets);
});
}, [])
const createPet = pet => {
axios.post('http://localhost:8000/api/pets/new', pet)
.then(res=>{
console.log(res)
setPets([...pets, res.data])
})
.catch(err=>{
const errorResponse = err.response.data.errors;
const errorArr = [];
for(const key of Object.keys(errorResponse)){
errorArr.push(errorResponse[key].message)
}
setErrors(errorArr);
console.log(err)
})
}
return (
<div>
<Header source={"create"} />
<h1>Add a Pet</h1>
{errors.map((err, idx) => <p key={idx}>{err}</p>)}
<PetForm onSubmitProp={createPet} initialSettingsProp={initialFormSettings}/>
</div>
)
}<file_sep>import React, { useEffect, useState } from "react";
import axios from 'axios';
import { Link, navigate } from "@reach/router";
import DeleteButton from "../components/DeleteButton/DeleteButton";
import Header from "../components/Header/Header";
import './styles/Detail.css'
export default (props) => {
const [pet, setPet] = useState({})
const [loaded, setLoaded] = useState(false)
useEffect(() => {
axios.get(`http://localhost:8000/api/pets/${props.id}`)
.then(res => {
setPet(res.data)
setLoaded(true);
});
}, []);
return(
<div>
<Header source={"detail"} />
<h2>Details about: {pet.name}</h2>
<div id={"large-container"}>
<div id={"medium-container"}>
<div className={"container"} id={"type-container"}>
<p className={"columns"}>Pet type: </p>
<p className={"columns"}>{pet.type}</p>
</div>
<div className={"container"} id={"description-container"}>
<p className={"columns"}>Description: </p>
<p className={"columns"}>{pet.description}</p>
</div>
<div className={"container"} id={"skills-container"}>
<p className={"columns"}>Skills: </p>
<div className={"columns"}>
{loaded && pet.skills.map((skill, idx) => {
return(
<p key={idx}>{skill}</p>
)
})}
</div>
</div>
</div>
</div>
<Link to={`/pets/edit/${pet._id}`}>
Edit
</Link>
<br/>
<DeleteButton petName={pet.name} petId={pet._id} successCallback={() => navigate('/')} />
</div>
)
}
<file_sep>import React, { useEffect, useState } from 'react'
import axios from 'axios';
import PetForm from "../components/PetForm/PetForm";
import Header from "../components/Header/Header";
import {navigate} from "@reach/router";
export default props => {
const { id } = props;
const [pet, setPet] = useState();
const [loaded, setLoaded] = useState(false)
const [errors, setErrors] = useState([]);
useEffect(() => {
axios.get(`http://localhost:8000/api/pets/${id}`)
.then(res => {
setPet(res.data);
setLoaded(true);
})
}, [])
const updatePet = pet => {
axios.put(`http://localhost:8000/api/pets/${id}`, pet)
.then(res => navigate('/'))
.catch(err=>{
const errorResponse = err.response.data.errors;
const errorArr = [];
for(const key of Object.keys(errorResponse)){
errorArr.push(errorResponse[key].message)
}
setErrors(errorArr);
console.log(err)
})
}
return (
<>
<Header source={"update"} />
<div>
{loaded && <h1>Edit {pet.name}</h1>}
{errors.map((err, idx) => <p key={idx}>{err}</p>)}
{loaded && (<PetForm onSubmitProp={updatePet} initialSettingsProp={pet}/>)}
</div>
</>
)
}<file_sep>const { Pet } = require('../models/pet.model')
module.exports = {
index: (req, res) => {
Pet.find()
.then(allPets => res.json({ pets: allPets }))
.catch(err => res.json({ message: "Something went wrong", error: err}))
},
getPet: (req, res) => {
Pet.findOne({_id: req.params.id})
.then(pet => res.json(pet))
.catch(err => res.json(err))
},
createPet: (req, res) => {
const { name, type, description, skills } = req.body;
Pet.create({
name,
type,
description,
skills
})
.then(pet => res.json(pet))
.catch(err => res.status(400).json(err));
},
editPet: (req, res) => {
Pet.findOneAndUpdate({_id: req.params.id}, req.body, {new: true, runValidators: true, context: 'query'})
.then(updatedPet => res.json(updatedPet))
.catch(err => res.status(400).json(err))
},
deletePet: (req, res) => {
Pet.findOneAndRemove({_id: req.params.id})
.then(deleteConfirmation => res.json(deleteConfirmation))
.catch(err => res.json(err))
}
}
|
36ad2bde702b5ed20a2a9b13942cd3bce6e9f647
|
[
"JavaScript"
] | 5 |
JavaScript
|
airnopkun/MERN-Exam
|
59dafeca84f1c70dba42dfd451f0022153bc6fb5
|
d7d40b12128a91ff9b8d138b3a372cae561d641d
|
refs/heads/master
|
<repo_name>botbotpod/profile_generator<file_sep>/README.md
# profile_generator
This project has been created to generate a *readable* dummy profile.
By *readable*; meaning that it looks like an actual profile of a person without using an actual persons name and address.
## Motivation
When someone is tasked in creating a dummy profile from scratch, they would encounter the following scenario's:
1. Create an fake profile like below:
```
Name: Batman
Address: 123 Batcave , Gotham City
```
2. Create a profile with a standard name and search actual addresses on the internet to use with the profile,
realising later on that it takes more time and effort than expected to do it manually.
This project aims to save time in generating dummy data for testing by automating this process.
This profile generator will generate the following information **into a CSV file**:
```
First Name:
Last Name:
Address:
Phone:
Email:
```
It uses over a thousand common names and hundreds of cities of the respectful country, which are randomly selected and generated
to look like an actual profile.
## How to use it
Download the folders and go to the respective python file inside the folder, follow the instructions inside the file
and then run the file to have it generate the data.
It is recommended to download the whole folder to generate the data offline.
<file_sep>/profile_generator_USA/usa_profile_generator_offline.py
import os
import random
import csv
'''
This function will create a csv file that will generate a dummy profile that contains
a first name, last name, street address, phone number and email
The default profiles being generated is set to 200
'''
def dummy_export(folder_dir,fname,lname,street,city,profile_size):
try:
os.chdir(folder_dir)
with open(fname,'r') as first_name, open(lname,'r') as last_name, open(street,'r') as street, \
open(city,'r') as city:
#read files containing first names and last names
read_first = first_name.read()
list_first = read_first.split("\n")
read_last = last_name.read()
list_last = read_last.split("\n")
#Most common email domain address list
email_list = ['gmail.com','outlook.com','icloud.com','aol.com','yahoo.com','mail.com','hotmail.com','msn.com']
#List of US Streets
read_street = street.read()
list_street = read_street.split('\n')
#List of US Cities and States
city_state = city.read()
list_city_state = city_state.split("\n")
#Creating CSV File
with open('usa_profile.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(("First Name", "Last Name", "Address", "City", "State", "Zip Code", "Phone", "Email"))
#Generating the Profile Data
for num in range(profile_size):
first = random.choice(list_first)
last = random.choice(list_last)
phone = f'{random.randint(100, 999)}-{random.randint(100, 999)}-{random.randint(1000,9999)}'
email = first.lower() + last.lower() + '@' + random.choice(email_list)
#Generate Random Street Address
street_num = random.randint(1,9999)
street = random.choice(list_street)
city_state = random.choice(list_city_state)
zip_code = random.randint(10000,99950)
address = f'{street_num} {street},{city_state},{zip_code}'
format_str = f'{first},{last},{address},{phone},{email}'
split_str = format_str.split(",")
#Print out the profile for testing, please uncomment if you don't want to see the output
print(split_str)
#Export/write all the profile data into a csv file
writer.writerow(split_str)
except Exception as e:
print(e)
#This will run the function and generate a csv file with dummy data
dummy_export('''Please enter your folder directory here''','us_first_names.txt','us_last_names.txt','us_streets.txt','us_cities&states.txt',200)
|
321d5e57264d3f88bc60cc9dbe47c0acb2302f39
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
botbotpod/profile_generator
|
f9c1d868df0de569de205bc71d288d4f244dcd07
|
280db0869f6fdc2f2e2842fbf49af9cb6566c6a6
|
refs/heads/main
|
<file_sep>;ATK2 AUTOSAR R4.0 用ジェネレータ設定ファイル
;AUTOSARの対応バージョン(3または4のみ対応)
AUTOSARVersion=4
;AUTOSARスキーマのファイル名(cfg.exeの相対パスで記載)
Schema=./AUTOSAR_4-0-3_STRICT.xsd
;AUTOSARスキーマのロケーション情報
SchemaLocation=http://autosar.org/schema/r4.0
;多重度チェックのコンテナのパス情報
ContainerPath=/AUTOSAR/EcucDefs
;対象モジュール名
ModuleName=Os
;未定義パラメータチェックオプション(TRUE:未定義パラメータに対して警告を表示,
;FALSE:未定義パラメータに対して警告を表示しない,省略時はFALSEと見なす)
CheckUnknownParameter=FALSE
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: task.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* タスク制御モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "task.h"
#include "interrupt.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_TSKSTAT
#define LOG_TSKSTAT(p_tcb)
#endif /* LOG_TSKSTAT */
/* 内部関数のプロトタイプ宣言 */
LOCAL_INLINE uint16 bitmap_search(uint16 bitmap);
LOCAL_INLINE boolean primap_empty(void);
LOCAL_INLINE PriorityType primap_search(void);
LOCAL_INLINE void primap_set(PriorityType pri);
LOCAL_INLINE void primap_clear(PriorityType pri);
#ifdef TOPPERS_task_initialize
/*
* 実行状態のタスク
*/
TCB *p_runtsk;
/*
* 最高優先順位タスク
*/
TCB *p_schedtsk;
/*
* レディキュー中の最高優先度
*/
PriorityType nextpri;
/*
* レディキュー
*/
QUEUE ready_queue[TNUM_TPRI];
/*
* レディキューサーチのためのビットマップ
*/
uint16 ready_primap;
/*
* タスク管理モジュールの初期化
*/
void
task_initialize(void)
{
TaskType i;
TCB *p_tcb;
p_runtsk = NULL;
p_schedtsk = NULL;
for (i = 0U; i < TNUM_TPRI; i++) {
queue_initialize(&(ready_queue[i]));
}
nextpri = TPRI_MINTASK;
ready_primap = 0U;
for (i = 0U; i < tnum_task; i++) {
p_tcb = &(tcb_table[i]);
p_tcb->p_tinib = &(tinib_table[i]);
p_tcb->actcnt = 0U;
p_tcb->tstat = SUSPENDED;
if ((p_tcb->p_tinib->autoact & ((AppModeType) 1 << appmodeid)) != APPMODE_NONE) {
(void) make_active(p_tcb);
}
}
}
#endif /* TOPPERS_task_initialize */
/*
* ビットマップサーチ関数
*
* bitmap内の1のビットの内,最も下位(右)のものをサーチし,そのビッ
* ト番号を返す
* ビット番号は,最下位ビットを0とする.bitmapに0を指定
* してはならない.この関数では,bitmapが16ビットであることを仮定し,
* uint16型としている
*
* ビットサーチ命令を持つプロセッサでは,ビットサーチ命令を使うように
* 書き直した方が効率が良い場合がある
* このような場合には,ターゲット依存部でビットサーチ命令を使った
* bitmap_searchを定義し,OMIT_BITMAP_SEARCHをマクロ定義すればよい
* また,ビットサーチ命令のサーチ方向が逆などの理由で優先度とビット
* との対応を変更したい場合には,PRIMAP_BITをマクロ定義すればよい
*
* また,標準ライブラリにffsがあるなら,次のように定義して標準ライブ
* ラリを使った方が効率が良い可能性もある
* #define bitmap_search(bitmap) (ffs(bitmap) - 1)
*/
#ifndef PRIMAP_BIT
#define PRIMAP_BIT(pri) ((uint16) ((uint16) 1U << (pri)))
#endif /* PRIMAP_BIT */
#ifndef OMIT_BITMAP_SEARCH
LOCAL_INLINE uint16
bitmap_search(uint16 bitmap)
{
/*
* ビットマップサーチ関数用テーブル
*/
const uint8 bitmap_search_table[BITMAP_NUM] = {
0U, 1U, 0U, 2U, 0U, 1U, 0U,
3U, 0U, 1U, 0U, 2U, 0U, 1U, 0U
};
uint16 n = 0U;
ASSERT(bitmap != 0U);
if ((bitmap & 0x00ffU) == 0U) {
bitmap >>= 8U;
n += 8U;
}
if ((bitmap & 0x0fU) == 0U) {
bitmap >>= 4U;
n += 4U;
}
return(n + bitmap_search_table[(bitmap & 0x000fU) - 1U]);
}
#endif /* OMIT_BITMAP_SEARCH */
/*
* 優先度ビットマップが空かのチェック
*/
LOCAL_INLINE boolean
primap_empty(void)
{
return(ready_primap == 0U);
}
/*
* 優先度ビットマップのサーチ
*/
LOCAL_INLINE PriorityType
primap_search(void)
{
return((PriorityType) bitmap_search(ready_primap));
}
/*
* 優先度ビットマップのセット
*/
LOCAL_INLINE void
primap_set(PriorityType pri)
{
ready_primap |= PRIMAP_BIT(pri);
}
/*
* 優先度ビットマップのクリア
*/
LOCAL_INLINE void
primap_clear(PriorityType pri)
{
ready_primap &= (uint16) ~PRIMAP_BIT(pri);
}
/*
* 最高優先順位タスクのサーチ
*/
#ifdef TOPPERS_search_schedtsk
void
search_schedtsk(void)
{
if (primap_empty() != FALSE) {
p_schedtsk = NULL;
}
else {
p_schedtsk = (TCB *) (queue_delete_next(&(ready_queue[nextpri])));
if (queue_empty(&(ready_queue[nextpri])) != FALSE) {
primap_clear(nextpri);
nextpri = (primap_empty() != FALSE) ?
TPRI_MINTASK : primap_search();
}
}
}
#endif /* TOPPERS_search_schedtsk */
/*
* 実行できる状態への移行
*/
#ifdef TOPPERS_make_runnable
boolean
make_runnable(TCB *p_tcb)
{
PriorityType pri, schedpri;
boolean is_next_schedtsk = TRUE;
p_tcb->tstat = READY;
LOG_TSKSTAT(p_tcb);
if (p_schedtsk != NULL) {
pri = p_tcb->curpri;
schedpri = p_schedtsk->curpri;
if (pri >= schedpri) {
/*
* schedtsk の方が優先度が高い場合,p_tcb をレ
* ディキューの最後に入れる
*/
queue_insert_prev(&(ready_queue[pri]), &(p_tcb->task_queue));
primap_set(pri);
if (pri < nextpri) {
nextpri = pri;
}
is_next_schedtsk = FALSE;
}
else {
/*
* p_tcb の方が優先度が高い場合,schedtsk をレディキュー
* の先頭に入れ,p_tcb を新しい schedtsk とする
*/
queue_insert_next(&(ready_queue[schedpri]), &(p_schedtsk->task_queue));
primap_set(schedpri);
nextpri = schedpri;
}
}
if (is_next_schedtsk != FALSE) {
p_schedtsk = p_tcb;
}
return(is_next_schedtsk);
}
#endif /* TOPPERS_make_runnable */
/*
* 実行できる状態から他の状態への遷移
*
* SC1-MCでmake_non_runnableが実装されるため
* SC1にもmake_non_runableを実装し,SC1もSC1-MCの関数構成に合せる
* (SC1-MCでは,p_runtskとp_schedtskが一致していることを確認する処理を入れる必要があるが,
* SC1では,search_schedtskのみ呼び出す処理とする)
*/
#ifdef TOPPERS_make_non_runnable
void
make_non_runnable(void)
{
search_schedtsk();
}
#endif /* TOPPERS_make_non_runnable */
/*
* タスクの起動
*
* TerminateTask や ChainTask の中で,自タスクに対して make_active を
* 呼ぶ場合があるので注意する
*/
#ifdef TOPPERS_make_active
boolean
make_active(TCB *p_tcb)
{
p_tcb->curpri = p_tcb->p_tinib->inipri;
if (TSKID(p_tcb) < tnum_exttask) {
p_tcb->curevt = EVTMASK_NONE;
p_tcb->waievt = EVTMASK_NONE;
}
p_tcb->p_lastrescb = NULL;
activate_context(p_tcb);
return(make_runnable(p_tcb));
}
#endif /* TOPPERS_make_active */
/*
* タスクのプリエンプト
*/
#ifdef TOPPERS_preempt
void
preempt(void)
{
PriorityType pri;
ASSERT(p_runtsk == p_schedtsk);
pri = p_runtsk->curpri;
queue_insert_next(&(ready_queue[pri]), &(p_runtsk->task_queue));
primap_set(pri);
search_schedtsk();
}
#endif /* TOPPERS_preempt */
/*
* 実行中のタスクをSUSPENDED状態にする
*/
#ifdef TOPPERS_suspend
void
suspend(void)
{
p_runtsk->tstat = SUSPENDED;
LOG_TSKSTAT(p_runtsk);
make_non_runnable();
if (p_runtsk->actcnt > 0U) {
p_runtsk->actcnt -= 1U;
(void) make_active(p_runtsk);
}
}
#endif /* TOPPERS_suspend */
/*
* タスクの不正終了時の保護
* TerminateTask(),ChainTask()なしでの自タスクの終了
* (タスクの関数からリターン)した場合の処理
*/
#ifdef TOPPERS_exit_task
/*
* タスクの全リソース返却
*/
LOCAL_INLINE void
release_taskresources(TCB *p_tcb)
{
if (p_tcb->p_lastrescb != NULL) {
if (p_tcb->curpri <= TPRI_MINISR) {
/* リソースを全部解放すれば割込み許可になる */
x_set_ipm((PriorityType) TIPM_ENAALL);
}
/* リソースを全部解放すれば実行中優先度に戻る */
p_tcb->curpri = p_tcb->p_tinib->exepri;
/* OS割込み禁止状態以上で来る */
do {
p_tcb->p_lastrescb->lockflg = FALSE;
p_tcb->p_lastrescb = p_tcb->p_lastrescb->p_prevrescb;
} while (p_tcb->p_lastrescb != NULL);
}
}
void
exit_task(void)
{
x_nested_lock_os_int();
/* 割込み禁止状態の場合は割込み禁止を解除する */
release_interrupts(OSServiceId_Invalid);
/* リソース確保したままの場合はリソースを解放する */
release_taskresources(p_runtsk);
#ifdef CFG_USE_ERRORHOOK
/* エラーフックを呼ぶ */
call_errorhook(E_OS_MISSINGEND, OSServiceId_TaskMissingEnd);
#endif /* CFG_USE_ERRORHOOK */
suspend();
/* ポストタスクフックが有効な場合はポストタスクフックが呼ばれる */
exit_and_dispatch();
}
#endif /* TOPPERS_exit_task */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: uart.c 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* シリアルI/Oデバイス(SIO)ドライバ(UART用)
*/
#include "Os.h"
#include "target_serial.h"
#include "uart.h"
#include "Os_Lcfg.h"
/*
* 受信用バッファ
*/
static uint8 rx_buf;
/* 内部関数のプロトタイプ宣言 */
LOCAL_INLINE boolean uart_getready(void);
LOCAL_INLINE uint8 uart_getchar(void);
/*
* 文字を受信したかチェック
*/
LOCAL_INLINE boolean
uart_getready(void)
{
boolean ans;
uint8 stat;
uint8 rx_tmp;
stat = sil_reb_mem((void *) URTEnSTR1); /* ステータスの読み込み */
rx_tmp = sil_reb_mem((void *) URTEnRX); /* 受信データを読み込み */
ans = FALSE;
if ((stat & 0x07) == 0) {
rx_buf = rx_tmp;
ans = TRUE;
}
sil_wrb_mem((void *) URTEnSTC, 0x1f); /* ステータスクリア */
return(ans);
}
/*
* 受信した文字の取り出し
*/
LOCAL_INLINE uint8
uart_getchar(void)
{
return(rx_buf);
}
/*
* 初期化処理
*/
void
InitHwSerial(void)
{
sil_wrh_mem((void *) URTEnCTL2, URTEnCTL2_VAL);
sil_wrh_mem((void *) URTEnCTL1, 0x0103); /* 8bit, LSB First */
sil_wrb_mem((void *) URTEnCTL0, 0x80);
sil_wrb_mem((void *) URTEnCTL0, 0xe0);
}
/*
* シリアルI/Oポートのクローズ
*/
void
TermHwSerial(void)
{
/* 受信割込みの禁止 */
sil_wrb_mem((void *) URTEnCTL0, 0x00);
}
/*
* SIOの割込みハンドラ
*/
ISR(RxHwSerialInt)
{
if (uart_getready() != FALSE) {
/*
* 受信通知コールバックルーチンを呼び出す
*/
RxSerialInt(uart_getchar());
}
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: uart_rlin.h 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* シリアルI/Oデバイス(SIO)ドライバ(RLIN用)
*/
#ifndef TOPPERS_UART_RLIN_H
#define TOPPERS_UART_RLIN_H
#include "prc_sil.h"
#include "target_serial.h"
#ifdef RLIN3x_USE_PORT0
#define RLIN3x_BASE RLIN30_BASE
#elif defined(RLIN3x_USE_PORT1)
#define RLIN3x_BASE RLIN31_BASE
#elif defined(RLIN3x_USE_PORT2)
#define RLIN3x_BASE RLIN32_BASE
#elif defined(RLIN3x_USE_PORT3)
#define RLIN3x_BASE RLIN33_BASE
#elif defined(RLIN3x_USE_PORT4)
#define RLIN3x_BASE RLIN34_BASE
#elif defined(RLIN3x_USE_PORT5)
#define RLIN3x_BASE RLIN35_BASE
#else
#error please define RLIN3x port number.
#endif /* RLIN3x_USE_PORT0 */
#define RLIN3xLWBR_B 0x00000001
#define RLIN3xLBRP01_H 0x00000002
#define RLIN3xLBRP0_B 0x00000002
#define RLIN3xLBRP1_B 0x00000003
#define RLIN3xLSTC_B 0x00000004
#define RLIN3xLMD_B 0x00000008
#define RLIN3xLBFC_B 0x00000009
#define RLIN3xLSC_B 0x0000000a
#define RLIN3xLWUP_B 0x0000000b
#define RLIN3xLIE_B 0x0000000c
#define RLIN3xLEDE_B 0x0000000d
#define RLIN3xLCUC_B 0x0000000e
#define RLIN3xLTRC_B 0x00000010
#define RLIN3xLMST_B 0x00000011
#define RLIN3xLST_B 0x00000012
#define RLIN3xLEST_B 0x00000013
#define RLIN3xLDFC_B 0x00000014
#define RLIN3xLIDB_B 0x00000015
#define RLIN3xLCBR_B 0x00000016
#define RLIN3xLUDB0_B 0x00000017
#define RLIN3xLDBR1_B 0x00000018
#define RLIN3xLDBR2_B 0x00000019
#define RLIN3xLDBR3_B 0x0000001a
#define RLIN3xLDBR4_B 0x0000001b
#define RLIN3xLDBR5_B 0x0000001c
#define RLIN3xLDBR6_B 0x0000001d
#define RLIN3xLDBR7_B 0x0000001e
#define RLIN3xLDBR8_B 0x0000001f
#define RLIN3xLUOER_B 0x00000020
#define RLIN3xLUOR1_B 0x00000021
#define RLIN3xLUTDR_H 0x00000024
#define RLIN3xLUTDRL_B 0x00000024
#define RLIN3xLUTDRH_B 0x00000025
#define RLIN3xLURDR_H 0x00000026
#define RLIN3xLURDRL_B 0x00000026
#define RLIN3xLURDRH_B 0x00000027
#define RLIN3xLUWTDR_H 0x00000028
#define RLIN3xLUWTDRL_B 0x00000028
#define RLIN3xLUWTDRH_B 0x00000029
#ifndef TOPPERS_MACRO_ONLY
/*
* カーネルの低レベル出力用関数
*/
LOCAL_INLINE void uart_putc(char8 c);
LOCAL_INLINE void
uart_putc(char8 c)
{
while ((sil_reb_mem((void *) (RLIN3x_BASE + RLIN3xLST_B)) & 0x10) == 0x10) ;
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLUTDRL_B), c);
}
/*
* serial.c から呼び出される関数群
*/
/*
* 初期化処理
*/
extern void InitHwSerial(void);
/*
* 終了処理
*/
extern void TermHwSerial(void);
/*
* 受信コールバックハンドラ
*/
extern void RxSerialInt(uint8 character);
extern ISR(RxHwSerialInt);
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_UART_RLIN_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: task.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* タスク管理機能
*/
#ifndef TOPPERS_TASK_H
#define TOPPERS_TASK_H
#include "queue.h"
#include "resource.h"
/*
* イベントマスク値の定義
*/
#define EVTMASK_NONE ((EventMaskType) 0) /* イベントなし */
/*
* 優先度の範囲(外部表現)
*/
#define TMIN_TPRI UINT_C(0) /* タスク優先度の最小値(最低値)*/
#define TMAX_TPRI UINT_C(15) /* タスク優先度の最大値(最高値)*/
/*
* 優先度の段階数の定義
*/
#define TNUM_TPRI ((TMAX_TPRI - TMIN_TPRI) + 1U)
/*
* 優先度値の定義(内部表現)
*/
#define TPRI_MINTASK ((PriorityType) (TNUM_TPRI - 1U)) /* 最低タスク優先度 */
#define TPRI_MAXTASK ((PriorityType) (0)) /* 最高タスク優先度 */
/*
* タスクIDからTCBを取り出すためのマクロ
*/
#define get_tcb(tskid) (&(tcb_table[(tskid)]))
/*
* TCBからタスクIDを取り出すためのマクロ
* p_tcb がNULLの場合は使えない
*/
#define TSKID(p_tcb) ((TaskType) ((p_tcb) - tcb_table))
#ifndef OMIT_BITMAP_SEARCH
#define BITMAP_NUM 15 /* bitmap_search_tableのサイズ */
#endif /* OMIT_BITMAP_SEARCH */
/*
* タスク数を保持する変数の宣言(Os_Lcfg.c)
*/
extern const TaskType tnum_task; /* タスクの数 */
extern const TaskType tnum_exttask; /* 拡張タスクの数 */
/*
* タスク初期化ブロック
*
* タスクに関する情報を,値が変わらないためにROMに置ける部分(タスク
* 初期化ブロック)と,値が変化するためにRAMに置かなければならない部
* 分(タスク管理ブロック,TCB)に分離し,TCB内に対応するタスク初期化
* ブロックを指すポインタを入れる
* タスク初期化ブロック内に対応するTCBを指すポインタを入れる方法の方が,
* RAMの節約の観点からは望ましいが,実行効率が悪くなるために採用
* していない
* 他のオブジェクトについても同様に扱う
*/
typedef struct task_initialization_block {
FunctionRefType task; /* タスクの起動番地 */
#ifdef USE_TSKINICTXB
TSKINICTXB tskinictxb; /* タスク初期化コンテキストブロック */
#else /* USE_TSKINICTXB */
MemorySizeType stksz; /* スタック領域のサイズ(丸めた値) */
void *stk; /* スタック領域の先頭番地 */
#endif /* USE_TSKINICTXB */
PriorityType inipri; /* 初期優先度 (内部表現)*/
PriorityType exepri; /* 実行開始時の優先度 (内部表現)*/
uint8 maxact; /* 多重起動要求の最大数 */
AppModeType autoact; /* 起動するモード */
} TINIB;
/*
* タスク管理ブロック(Os_Lcfg.c)
*/
struct task_control_block {
QUEUE task_queue; /* タスクキュー(構造体の先頭に入る必要) */
const TINIB *p_tinib; /* 初期化ブロックへのポインタ */
PriorityType curpri; /* 現在の優先度(内部表現)*/
TaskStateType tstat; /* タスク状態(内部表現)*/
uint8 actcnt; /* 多重起動要求数 */
EventMaskType curevt; /* イベントの現在値 */
EventMaskType waievt; /* 待っているイベント */
RESCB *p_lastrescb; /* 最後に獲得したリソース管理ブロックへのポインタ */
TSKCTXB tskctxb; /* タスクコンテキストブロック */
};
/*
* 実行状態のタスク
*
* 実行状態のタスクがない場合には,NULL にする
*/
extern TCB *p_runtsk;
/*
* 最高優先順位タスク
*
* タスク実行中は,runtsk と一致する
* 実行できる状態(実行状態または実行可能状態)のタスクがない場合には,
* NULL にする
*/
extern TCB *p_schedtsk;
/*
* レディキュー中の最高優先度
*
* レディキューには実行可能状態のタスクのみを含むので,実行可能状態の
* タスクの中での最高優先度を保持する
* レディキューが空の時(実行可能状態のタスクが無い時)は TPRI_MINTASKにする
*/
extern PriorityType nextpri;
/*
* レディキュー
*
* レディキューは,実行できる状態のタスクを管理するためのキューである
* レディキューは,優先度ごとのタスクキューで構成されている
* タスクのTCBは,該当する優先度のキューに登録される
*/
extern QUEUE ready_queue[TNUM_TPRI];
/*
* レディキューサーチのためのビットマップ
*
* レディキューのサーチを効率よく行うために,優先度ごとのタスクキュー
* にタスクが入っているかどうかを示すビットマップを用意している
* ビットマップを使うことで,メモリアクセスの回数を減らすことができるが,
* ビット操作命令が充実していないプロセッサで,優先度の段階数が少ない
* 場合には,ビットマップ操作のオーバーヘッドのために,逆に効率が落ち
* る可能性もある
*
* 優先度が16段階であることを仮定しているため,uint16型としている
*/
extern uint16 ready_primap;
/*
* タスク初期化ブロックのエリア(Os_Lcfg.c)
*/
extern const TINIB tinib_table[];
/*
* TCBのエリア(Os_Lcfg.c)
*/
extern TCB tcb_table[];
/*
* タスク管理モジュールの初期化
*/
extern void task_initialize(void);
/*
* タスクの起動
*
* 対象タスク(p_tcbで指定したタスク)を起動する
* (休止状態から実行できる状態に遷移させる)
* タスクの起動時に必要な初期化を行う
*/
extern boolean make_active(TCB *p_tcb);
/*
* 実行できる状態への移行
*
* 対象タスク(p_tcbで指定したタスク)を実行できる状態に遷移させる
* 対象タスクの優先度が,最高優先度タスク(schedtsk)の優先度よりも高
* い場合には,対象タスクを新しい最高優先度タスクとし,それまでの最高
* 優先度タスクをレディキューの先頭に入れる
* そうでない場合には,対象タスクをレディキューの末尾に入れる
* 対象タスクを最高優先度タスクとした場合に,TRUE を返す
*/
extern boolean make_runnable(TCB *p_tcb);
/*
* 実行できる状態から他の状態への遷移
*/
extern void make_non_runnable(void);
/*
* 最高優先順位タスクのサーチ
*
* レディキュー中の最高優先順位のタスクをサーチする
* レディキューが空の場合には,この関数を呼び出してはならない
*/
extern void search_schedtsk(void);
/*
* タスクのプリエンプト
*
* 自タスクを実行可能状態に移行させ,最高優先度タスクを実行状態にする
* この関数から戻った後に,dispatch を呼び出して他のタスクへ切り替える
* ことを想定している
*/
extern void preempt(void);
/*
* 実行中のタスクをSUSPENDED状態にする
*/
extern void suspend(void);
/*
* 満了処理専用タスクの起動
*
* 条件:OS割込み禁止状態で呼ばれる
*/
extern StatusType activate_task_action(TaskType TaskID);
/*
* 満了処理専用イベントのセット
*
* 条件:OS割込み禁止状態で呼ばれる
*/
extern StatusType set_event_action(TaskType TaskID, EventMaskType Mask);
/*
* タスク不正終了時に呼ぶ関数
*/
extern void exit_task(void);
#endif /* TOPPERS_TASK_H_ */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2011-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: Compiler.h 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* コンパイラ依存定義
*/
#ifndef TOPPERS_COMPILER_H
#define TOPPERS_COMPILER_H
#include "Compiler_Cfg.h"
#define AUTOMATIC
#define TYPEDEF
#define NULL_PTR ((void *) 0)
#define FUNC(rettype, memclass) rettype
#define FUNC_P2CONST(rettype, ptrclass, memclass) const rettype *
#define FUNC_P2VAR(rettype, ptrclass, memclass) rettype *
#define P2VAR(ptrtype, memclass, ptrclass) ptrtype *
#define P2CONST(ptrtype, memclass, ptrclass) const ptrtype *
#define CONSTP2VAR(ptrtype, memclass, ptrclass) ptrtype * const
#define CONSTP2CONST(ptrtype, memclass, ptrclass) const ptrtype * const
#define P2FUNC(rettype, ptrclass, fctname) rettype (*fctname)
#define CONST(consttype, memclass) const consttype
#define VAR(vartype, memclass) vartype
/*
* CXでは,インライン関数は「#pragma」を利用して、関数定義の前に
* インライン化するシンボルを予め指定しなければならない.
* インライン化するシンボルは,"xxx_inline_symbol.h"にて定義し,
* そのため,「Inline」シンボルは空マクロとして実装する.
*/
#define INLINE
#define LOCAL_INLINE static
/* インライン指定シンボルの登録 */
#include "target_inline_symbols.h"
//#define asm __asm
//#define Asm __asm /* インラインアセンブラ(最適化抑止)*/
#define NoReturn
/* コンパイラ依存のデータ型の定義 */
#ifndef TOPPERS_MACRO_ONLY
#include <limits.h>
/*
* 空ラベルの定義
* cxでは大きさゼロの配列はコンパイルエラーになるため、
* ここで別途定義する。
*/
#define TOPPERS_EMPTY_LABEL(x, y) x y[1]
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_COMPILER_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2005-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: trace_config.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* トレースログ機能
*/
#include "kernel_impl.h"
#include "task.h"
#include "target_timer.h"
/*
* 内部関数プロトタイプ宣言
*/
static StatusType trace_wri_log(TRACE *p_trace);
/*
* トレースログバッファとそれにアクセスするためのポインタ
*/
static TRACE trace_buffer[TCNT_TRACE_BUFFER]; /* トレースログバッファ */
static uint32 trace_count; /* トレースログバッファ中のログの数 */
static uint32 trace_head; /* 先頭のトレースログの格納位置 */
static uint32 trace_tail; /* 次のトレースログの格納位置 */
static TraceModeType trace_mode = TRACE_AUTOSTOP; /* トレースモード */
/*
* トレースログ機能の初期化
*/
void
trace_initialize(uintptr exinf)
{
TraceModeType mode = ((TraceModeType) exinf);
trace_count = 0U;
trace_head = 0U;
trace_tail = 0U;
trace_mode = mode;
}
/*
* トレースログの開始
*/
StatusType
trace_sta_log(TraceModeType mode)
{
if ((mode & TRACE_CLEAR) != 0U) {
trace_count = 0U;
trace_head = 0U;
trace_tail = 0U;
}
trace_mode = mode;
return(E_OK);
}
/*
* トレースログの書込み
*/
static StatusType
trace_wri_log(TRACE *p_trace)
{
SIL_PRE_LOC;
if (trace_mode != TRACE_STOP) {
SIL_LOC_INT();
/*
* トレース時刻の設定
*
* LOG_WRI_LOG_ENTERから呼ばれた場合にp_trace->logtimを書き換
* えてしまうのは気持ちが悪いが,wri_logの方で上書きするため問
* 題はない
*/
p_trace->logtim = GET_UTIM();
/*
* トレースバッファに記録
*/
trace_buffer[trace_tail] = *p_trace;
trace_tail++;
if (trace_tail >= TCNT_TRACE_BUFFER) {
trace_tail = 0U;
}
if (trace_count < TCNT_TRACE_BUFFER) {
trace_count++;
if ((trace_count >= TCNT_TRACE_BUFFER)
&& ((trace_mode & TRACE_AUTOSTOP) != 0U)) {
trace_mode = TRACE_STOP;
}
}
else {
trace_head = trace_tail;
}
SIL_UNL_INT();
}
return(E_OK);
}
/*
* トレースログの読出し
*/
StatusType
trace_rea_log(TRACE *p_trace)
{
StatusType ercd;
SIL_PRE_LOC;
SIL_LOC_INT();
/*
* トレースログバッファからの取出し
*/
if (trace_count > 0U) {
*p_trace = trace_buffer[trace_head];
trace_count--;
trace_head++;
if (trace_head >= TCNT_TRACE_BUFFER) {
trace_head = 0U;
}
ercd = E_OK;
}
else {
ercd = E_NOT_OK;
}
SIL_UNL_INT();
return(ercd);
}
/*
* トレースログを出力するためのライブラリ関数
*/
void
trace_write_0(uint32 type)
{
TRACE trace;
trace.logtype = type;
(void) trace_wri_log(&trace);
}
void
trace_write_1(uint32 type, const uintptr arg1)
{
TRACE trace;
trace.logtype = type;
trace.loginfo[0] = arg1;
(void) trace_wri_log(&trace);
}
void
trace_write_2(uint32 type, uintptr arg1, uintptr arg2)
{
TRACE trace;
trace.logtype = type;
trace.loginfo[0] = arg1;
trace.loginfo[1] = arg2;
(void) trace_wri_log(&trace);
}
void
trace_write_3(uint32 type, uintptr arg1, uintptr arg2, uintptr arg3)
{
TRACE trace;
trace.logtype = type;
trace.loginfo[0] = arg1;
trace.loginfo[1] = arg2;
trace.loginfo[2] = arg3;
(void) trace_wri_log(&trace);
}
void
trace_write_4(uint32 type, uintptr arg1, uintptr arg2, uintptr arg3,
uintptr arg4)
{
TRACE trace;
trace.logtype = type;
trace.loginfo[0] = arg1;
trace.loginfo[1] = arg2;
trace.loginfo[2] = arg3;
trace.loginfo[3] = arg4;
(void) trace_wri_log(&trace);
}
void
trace_write_5(uint32 type, uintptr arg1, uintptr arg2, uintptr arg3,
uintptr arg4, uintptr arg5)
{
TRACE trace;
trace.logtype = type;
trace.loginfo[0] = arg1;
trace.loginfo[1] = arg2;
trace.loginfo[2] = arg3;
trace.loginfo[3] = arg4;
trace.loginfo[4] = arg5;
(void) trace_wri_log(&trace);
}
/*
* アセンブリ言語で記述されるコードからトレースログを出力するための関
* 数
*/
void
log_dsp_enter(const TCB *p_tcb)
{
trace_1(LOG_TYPE_DSP | LOG_ENTER, (const uintptr) p_tcb);
}
void
log_dsp_leave(const TCB *p_tcb)
{
trace_1(LOG_TYPE_DSP | LOG_LEAVE, (const uintptr) p_tcb);
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: prc_insn.h 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* プロセッサの特殊命令のインライン関数定義(V850用)
*/
#ifndef TOPPERS_PRC_INSN_H
#define TOPPERS_PRC_INSN_H
#include <prc_tool.h>
/*
* V850E3V5のみサポート
*/
#ifndef __v850e3v5__
#error Only support v850e3v5 architecture!!
#endif /* __v850e3v5__ */
#ifndef TOPPERS_MACRO_ONLY
#define SYNCM __syncm();
LOCAL_INLINE void
disable_int(void)
{
__DI();
}
LOCAL_INLINE void
enable_int(void)
{
__EI();
}
LOCAL_INLINE uint32
current_psw(void)
{
return(__stsr_rh(5, 0));
}
LOCAL_INLINE void
set_psw(uint32 psw)
{
__ldsr_rh(5, 0, psw);
}
/*
* V850E3V5用の割込みコントローラ操作ルーチン
*/
LOCAL_INLINE void
set_pmr(uint16 pmr)
{
uint32 psw;
/* PMR must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
__ldsr_rh(11, 2, pmr);
set_psw(psw);
}
LOCAL_INLINE uint16
get_ispr(void)
{
return(__stsr_rh(10, 2));
}
LOCAL_INLINE void
clear_ispr(void)
{
uint32 psw;
/* ISPR must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
__ldsr_rh(13, 2, 1); /* INTCFG = 1; ISPR を書き換え可能に */
__ldsr_rh(10, 2, 0); /* ISPR = 0 */
__ldsr_rh(13, 2, 0); /* INTCFG = 0; ISPR を書き換え禁止に(自動更新に) */
__syncp();
set_psw(psw);
}
LOCAL_INLINE void
set_intbp(uint32 intbp)
{
uint32 psw;
/* INTBP must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
__ldsr_rh(4, 1, intbp);
set_psw(psw);
}
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_PRC_INSN_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2006-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: queue.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* キュー操作ライブラリ
*
* このキュー操作ライブラリでは,キューヘッダを含むリング構造のダブル
* リンクキューを扱う.具体的には,キューヘッダの次エントリはキューの
* 先頭のエントリ,前エントリはキューの末尾のエントリとする.また,キ
* ューの先頭のエントリの前エントリと,キューの末尾のエントリの次エン
* トリは,キューヘッダとする.空のキューは,次エントリ,前エントリと
* も自分自身を指すキューヘッダであらわす
*/
#ifndef TOPPERS_QUEUE_H
#define TOPPERS_QUEUE_H
/*
* キューのデータ構造の定義
*/
typedef struct queue {
struct queue *p_next; /* 次エントリへのポインタ */
struct queue *p_prev; /* 前エントリへのポインタ */
} QUEUE;
/*
* キューの初期化
*/
LOCAL_INLINE void
queue_initialize(QUEUE *p_queue)
{
p_queue->p_prev = p_queue;
p_queue->p_next = p_queue;
}
/*
* キューの前エントリへの挿入
*/
LOCAL_INLINE void
queue_insert_prev(QUEUE *p_queue, QUEUE *p_entry)
{
p_entry->p_prev = p_queue->p_prev;
p_entry->p_next = p_queue;
p_queue->p_prev->p_next = p_entry;
p_queue->p_prev = p_entry;
}
/*
* キューの後エントリへの挿入
*/
LOCAL_INLINE void
queue_insert_next(QUEUE *p_queue, QUEUE *p_entry)
{
p_entry->p_next = p_queue->p_next;
p_entry->p_prev = p_queue;
p_queue->p_next->p_prev = p_entry;
p_queue->p_next = p_entry;
}
/*
* エントリの削除
*/
LOCAL_INLINE void
queue_delete(QUEUE *p_entry)
{
p_entry->p_prev->p_next = p_entry->p_next;
p_entry->p_next->p_prev = p_entry->p_prev;
}
/*
* キューの次エントリの取出し
*/
LOCAL_INLINE QUEUE *
queue_delete_next(QUEUE *p_queue)
{
QUEUE *p_entry;
ASSERT(p_queue->p_next != p_queue);
p_entry = p_queue->p_next;
p_queue->p_next = p_entry->p_next;
p_entry->p_next->p_prev = p_queue;
return(p_entry);
}
/*
* キューが空かどうかのチェック
*/
LOCAL_INLINE boolean
queue_empty(const QUEUE *p_queue)
{
return(p_queue->p_next == p_queue);
}
#endif /* TOPPERS_QUEUE_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2015-2019 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2018-2019 by CRESCO LTD., JAPAN
* Copyright (C) 2018-2019 by ICOMSYSTECH Co.,Ltd., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: hsbrh850f1k.h 886 2019-04-04 08:53:11Z nces-mtakada $
*/
/*
* HSBRH850F1Kボードの定義
*/
#ifndef TOPPERS_HSBRH850F1K_H
#define TOPPERS_HSBRH850F1K_H
#include "v850_gcc/rh850_f1k.h"
/*
* クロック速度
*/
/*
* PLL関連の定義
*/
#define MAINOSC_CLOCK_MHZ 16 /* Main OSC is 16MHz */
#define SUBOSC_CLOCK_KHZ 32768 /* Sub OSC is 32.768kHz */
#define INTOSCH_CLK_MHZ 8 /* High Speed Internal OSC Clock is 8MHz */
#define INTOSCL_CLK_KHZ 240 /* Low Speed Internal OSC Clock is 240kHz */
#define PLL_CLK_MHZ 120 /* PLL is 120MHz */
#define PLLC_DEFAULT_VALUE 0x00010300U
#define PLLC_M 0x01U
#define PLLC_N 0x3BU
/*
* Port 8 Configuration for LED
* P8_4: LED4(OUT)
* P8_5: LED3(OUT)
* P8_6: LED2(OUT)
* P8_7: LED1(OUT)
*/
#define LED_P8_MASK ((uint16) 0x00F0)
#define LED_PM8_INIT ((uint16) 0xFF0F)
#define LED_P8_INIT ((uint16) 0x00F0)
/*
* Port 10 Configration for RLIN31
* P10_12 : RLIN31TX (第2兼用)
* P10_11 : RLIN31RX (第2兼用)
*/
#define RLIN31_P10_MASK ((uint16) 0x1800)
#define RLIN31_PMC10_INIT ((uint16) 0x1800)
#define RLIN31_PFC10_INIT ((uint16) 0x1800)
#define RLIN31_PM10_INIT ((uint16) 0x0800)
#define RLIN31_PIBC10_INIT ((uint16) 0x0800)
/*
* Macro for hsbrh850f1k_led_output
*/
#define POS_LED1 ((uint16) 0x01)
#define POS_LED2 ((uint16) 0x02)
#define POS_LED3 ((uint16) 0x04)
#define POS_LED4 ((uint16) 0x08)
#define POS_LED_ALL ((uint16) 0x0F)
#endif /* TOPPERS_HSBRH850F1K_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: alarm.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* アラーム管理モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "alarm.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_GETALB_ENTER
#define LOG_GETALB_ENTER(almid)
#endif /* LOG_GETALB_ENTER */
#ifndef LOG_GETALB_LEAVE
#define LOG_GETALB_LEAVE(ercd, info)
#endif /* LOG_GETALB_LEAVE */
#ifndef LOG_GETALM_ENTER
#define LOG_GETALM_ENTER(almid)
#endif /* LOG_GETALM_ENTER */
#ifndef LOG_GETALM_LEAVE
#define LOG_GETALM_LEAVE(ercd, p_tick)
#endif /* LOG_GETALM_LEAVE */
#ifndef LOG_SETREL_ENTER
#define LOG_SETREL_ENTER(almid, incr, cycle)
#endif /* LOG_SETREL_ENTER */
#ifndef LOG_SETREL_LEAVE
#define LOG_SETREL_LEAVE(ercd)
#endif /* LOG_SETREL_LEAVE */
#ifndef LOG_SETABS_ENTER
#define LOG_SETABS_ENTER(almid, start, cycle)
#endif /* LOG_SETABS_ENTER */
#ifndef LOG_SETABS_LEAVE
#define LOG_SETABS_LEAVE(ercd)
#endif /* LOG_SETABS_LEAVE */
#ifndef LOG_CANALM_ENTER
#define LOG_CANALM_ENTER(almid)
#endif /* LOG_CANALM_ENTER */
#ifndef LOG_CANALM_LEAVE
#define LOG_CANALM_LEAVE(ercd)
#endif /* LOG_CANALM_LEAVE */
#ifndef LOG_ALM_ENTER
#define LOG_ALM_ENTER(p_cntexpinfo)
#endif /* LOG_ALM_ENTER */
#ifndef LOG_ALM_LEAVE
#define LOG_ALM_LEAVE(p_cntexpinfo)
#endif /* LOG_ALM_LEAVE */
/*
* アラーム機能の初期化
*/
#ifdef TOPPERS_alarm_initialize
void
alarm_initialize(void)
{
AlarmType i;
ALMCB *p_almcb;
for (i = 0U; i < tnum_alarm; i++) {
p_almcb = &(almcb_table[i]);
p_almcb->p_alminib = &(alminib_table[i]);
(p_almcb->cntexpinfo).expirefunc = &alarm_expire;
if ((p_almcb->p_alminib->autosta & ((AppModeType) 1 << appmodeid)) != APPMODE_NONE) {
if ((p_almcb->p_alminib->actatr & ABSOLUTE) == ABSOLUTE) {
/*
* 絶対時間の起動
* 満了時間が0の場合,次の周期の0のタイミングとなる
* (get_abstickに考慮済み)
*/
(p_almcb->cntexpinfo).expiretick =
get_abstick(p_almcb->p_alminib->p_cntcb, p_almcb->p_alminib->almval);
}
else {
/* 相対時間の起動 */
(p_almcb->cntexpinfo).expiretick =
get_reltick(p_almcb->p_alminib->p_cntcb, p_almcb->p_alminib->almval);
}
p_almcb->cycle = p_almcb->p_alminib->cycle;
insert_cnt_expr_que(&(p_almcb->cntexpinfo), p_almcb->p_alminib->p_cntcb);
}
else {
queue_initialize(&(p_almcb->cntexpinfo.cntexpque));
}
}
}
#endif /* TOPPERS_alarm_initialize */
/*
* アラーム情報の取得
*/
#ifdef TOPPERS_GetAlarmBase
StatusType
GetAlarmBase(AlarmType AlarmID, AlarmBaseRefType Info)
{
StatusType ercd = E_OK;
ALMCB *p_almcb;
CNTCB *p_cntcb;
LOG_GETALB_ENTER(AlarmID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_GETALARMBASE);
CHECK_ID(AlarmID < tnum_alarm);
CHECK_PARAM_POINTER(Info);
p_almcb = get_almcb(AlarmID);
p_cntcb = p_almcb->p_alminib->p_cntcb;
Info->maxallowedvalue = p_cntcb->p_cntinib->maxval;
Info->ticksperbase = p_cntcb->p_cntinib->tickbase;
Info->mincycle = p_cntcb->p_cntinib->mincyc;
exit_no_errorhook:
LOG_GETALB_LEAVE(ercd, Info);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.almid = AlarmID;
temp_errorhook_par2.p_info = Info;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetAlarmBase);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetAlarmBase */
/*
* アラームの状態参照
*/
#ifdef TOPPERS_GetAlarm
StatusType
GetAlarm(AlarmType AlarmID, TickRefType Tick)
{
StatusType ercd = E_OK;
TickType curval;
ALMCB *p_almcb;
CNTCB *p_cntcb;
LOG_GETALM_ENTER(AlarmID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_GETALARM);
CHECK_ID(AlarmID < tnum_alarm);
CHECK_PARAM_POINTER(Tick);
p_almcb = get_almcb(AlarmID);
p_cntcb = p_almcb->p_alminib->p_cntcb;
x_nested_lock_os_int();
S_D_CHECK_NOFUNC(queue_empty(&(p_almcb->cntexpinfo.cntexpque)) == FALSE);
/*
* カウンタの現在値を取得
* ハードウェアカウンタの場合,既に満了している可能性がある
*/
curval = get_curval(p_cntcb, CNTID(p_cntcb));
*Tick = diff_tick(p_almcb->cntexpinfo.expiretick, curval, p_cntcb->p_cntinib->maxval2);
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_GETALM_LEAVE(ercd, Tick);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.almid = AlarmID;
temp_errorhook_par2.p_tick = Tick;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetAlarm);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetAlarm */
/*
* アラームの設定(相対値)
*/
#ifdef TOPPERS_SetRelAlarm
StatusType
SetRelAlarm(AlarmType AlarmID, TickType increment, TickType cycle)
{
StatusType ercd = E_OK;
#if defined(CFG_USE_EXTENDEDSTATUS)
TickType maxval;
#endif /* CFG_USE_EXTENDEDSTATUS */
ALMCB *p_almcb;
CNTCB *p_cntcb;
LOG_SETREL_ENTER(AlarmID, increment, cycle);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_SETRELALARM);
CHECK_ID(AlarmID < tnum_alarm);
p_almcb = get_almcb(AlarmID);
p_cntcb = p_almcb->p_alminib->p_cntcb;
#if defined(CFG_USE_EXTENDEDSTATUS)
maxval = p_cntcb->p_cntinib->maxval;
CHECK_VALUE((0U < increment) && (increment <= maxval));
CHECK_VALUE((cycle == 0U)
|| ((p_cntcb->p_cntinib->mincyc <= cycle) && (cycle <= maxval)));
#endif /* CFG_USE_EXTENDEDSTATUS */
x_nested_lock_os_int();
S_D_CHECK_STATE(queue_empty(&(p_almcb->cntexpinfo.cntexpque)) != FALSE);
p_almcb->cntexpinfo.expiretick = get_reltick(p_cntcb, increment);
p_almcb->cycle = cycle;
insert_cnt_expr_que(&(p_almcb->cntexpinfo), p_cntcb);
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_SETREL_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.almid = AlarmID;
temp_errorhook_par2.incr = increment;
temp_errorhook_par3.cycle = cycle;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_SetRelAlarm);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_SetRelAlarm */
/*
* アラームの設定(絶対値)
*/
#ifdef TOPPERS_SetAbsAlarm
StatusType
SetAbsAlarm(AlarmType AlarmID, TickType start, TickType cycle)
{
StatusType ercd = E_OK;
#if defined(CFG_USE_EXTENDEDSTATUS)
TickType maxval;
#endif /* CFG_USE_EXTENDEDSTATUS */
ALMCB *p_almcb;
CNTCB *p_cntcb;
LOG_SETABS_ENTER(AlarmID, start, cycle);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_SETABSALARM);
CHECK_ID(AlarmID < tnum_alarm);
p_almcb = get_almcb(AlarmID);
p_cntcb = p_almcb->p_alminib->p_cntcb;
#if defined(CFG_USE_EXTENDEDSTATUS)
maxval = p_cntcb->p_cntinib->maxval;
CHECK_VALUE(start <= maxval);
CHECK_VALUE((cycle == 0U)
|| ((p_cntcb->p_cntinib->mincyc <= cycle) && (cycle <= maxval)));
#endif /* CFG_USE_EXTENDEDSTATUS */
x_nested_lock_os_int();
S_D_CHECK_STATE(queue_empty(&(p_almcb->cntexpinfo.cntexpque)) != FALSE);
p_almcb->cntexpinfo.expiretick = get_abstick(p_cntcb, start);
p_almcb->cycle = cycle;
insert_cnt_expr_que(&(p_almcb->cntexpinfo), p_cntcb);
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_SETABS_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.almid = AlarmID;
temp_errorhook_par2.start = start;
temp_errorhook_par3.cycle = cycle;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_SetAbsAlarm);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_SetAbsAlarm */
/*
* アラームのキャンセル
*/
#ifdef TOPPERS_CancelAlarm
StatusType
CancelAlarm(AlarmType AlarmID)
{
StatusType ercd = E_OK;
ALMCB *p_almcb;
LOG_CANALM_ENTER(AlarmID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_CANCELALARM);
CHECK_ID(AlarmID < tnum_alarm);
p_almcb = get_almcb(AlarmID);
x_nested_lock_os_int();
S_D_CHECK_NOFUNC(queue_empty(&(p_almcb->cntexpinfo.cntexpque)) == FALSE);
delete_cnt_expr_que(&(p_almcb->cntexpinfo), p_almcb->p_alminib->p_cntcb);
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_CANALM_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.almid = AlarmID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_CancelAlarm);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_CancelAlarm */
/*
* アラーム満了アクション処理用関数
*/
#ifdef TOPPERS_alarm_expire
void
alarm_expire(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb)
{
ALMCB *p_almcb;
p_almcb = (ALMCB *) p_cntexpinfo;
/* カウンタ満了キューへの再挿入(周期アラームの場合) */
if (p_almcb->cycle > 0U) {
p_cntexpinfo->expiretick = add_tick(p_cntexpinfo->expiretick, p_almcb->cycle,
p_cntcb->p_cntinib->maxval2);
insert_cnt_expr_que(p_cntexpinfo, (CNTCB *) p_cntcb);
}
/*
* アラームコールバックのみOS処理レベルで実行し,
* それ以外は呼び出し元の処理レベルで実行する
*
* アラームコールバックの場合,割込みを許可せず,
* 実行中のコンテキストをTCL_ALRMCBAKにする
*/
LOG_ALM_ENTER(p_almcb);
if ((p_almcb->p_alminib->actatr & CALLBACK) == CALLBACK) {
ENTER_CALLEVEL(TCL_ALRMCBAK);
}
/* アラーム満了アクションの呼出し */
(p_almcb->p_alminib->action)();
if ((p_almcb->p_alminib->actatr & CALLBACK) == CALLBACK) {
LEAVE_CALLEVEL(TCL_ALRMCBAK);
}
LOG_ALM_LEAVE(p_almcb);
}
#endif /* TOPPERS_alarm_expire */
<file_sep>#!python
# -*- coding: utf-8 -*-
#
# TOPPERS ATK2
# Toyohashi Open Platform for Embedded Real-Time Systems
# Automotive Kernel Version 2
#
# Copyright (C) 2013-2021 by Center for Embedded Computing Systems
# Graduate School of Information Science, Nagoya Univ., JAPAN
# Copyright (C) 2013-2021 by FUJI SOFT INCORPORATED, JAPAN
# Copyright (C) 2013-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
# Copyright (C) 2013-2014 by Renesas Electronics Corporation, JAPAN
# Copyright (C) 2013-2014 by <NAME> Inc., JAPAN
# Copyright (C) 2013-2014 by TOSHIBA CORPORATION, JAPAN
# Copyright (C) 2013-2014 by Witz Corporation, JAPAN
#
# 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
# ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
# 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
# (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
# 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
# スコード中に含まれていること.
# (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
# 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
# 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
# の無保証規定を掲載すること.
# (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
# 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
# と.
# (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
# 作権表示,この利用条件および下記の無保証規定を掲載すること.
# (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
# 報告すること.
# (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
# 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
# また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
# 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
# 免責すること.
#
# 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
# 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
# はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
# 用する者に対して,AUTOSARパートナーになることを求めている.
#
# 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
# よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
# に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
# アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
# の責任を負わない.
#
# $Id: configure_body.py 929 2021-01-06 08:51:23Z nces-mtakada $
#
import os.path
import os
import shutil
# call common file
common.Source(src_abs_path + "/arch/ccrh/common.py")
src_abs_path = os.path.abspath(SRCDIR)
wd_abs_path = os.path.abspath('.')
cfg_mtsp = wd_abs_path + r"\cfg\cfg.mtsp"
kernel_mtsp = wd_abs_path + r"\kernel\kernel.mtsp"
atk2_sc1_mtpj = wd_abs_path + r"\atk2-sc1.mtpj"
if COPY_SAMPLE1:
shutil.copy(src_abs_path + r'/sample/sample1.c', '.')
shutil.copy(src_abs_path + r'/sample/sample1.h', '.')
shutil.copy(src_abs_path + r'/sample/sample1.arxml', '.')
shutil.copy(src_abs_path + r'/sample/Rte_Type.h', '.')
#
# close project
#
#project.Close()
print wd_abs_path + "\\atk2-sc1"
project.Create(wd_abs_path + "\\atk2-sc1",
MicomType.RH850,
TARGET_MCU,
ProjectKind.Empty,
Compiler.CC_RH,
False)
project.Create(wd_abs_path + "\\cfg\\cfg",
MicomType.RH850,
TARGET_MCU,
ProjectKind.Empty,
Compiler.CC_RH,
True)
project.Create(wd_abs_path + "\\kernel\\kernel",
MicomType.RH850,
TARGET_MCU,
ProjectKind.Library,
Compiler.CC_RH,
True)
#
# Change debug tool
#
debugger.DebugTool.Change(DebugTool.E1Lpd)
#
# Add files for atk2-sc1 project
#
for file in app_app_files:
project.File.Add(wd_abs_path + "\\" + file, u"app")
for file in app_sysmod_files:
project.File.Add(src_abs_path + "\\" + file, u"sysmod")
for file in app_library_files:
project.File.Add(src_abs_path + "\\" + file, u"library")
for file in app_configuration_files:
project.File.Add(wd_abs_path + "\\cfg\\" + file, u"configuration")
str = src_abs_path + '\\' + statup_file
project.File.Add(str, u"startup")
#
# Add files fot cfg project
#
project.Change(cfg_mtsp)
file_list = project.File.Information()
for file in file_list:
project.File.Remove(file)
str = src_abs_path + '\\' + statup_file
project.File.Add(str, u"startup")
for file in cfg_configuration_files:
project.File.Add(wd_abs_path + "\\cfg\\" + file, u"configuration")
#
# Add files fot kernel project
#
project.Change(kernel_mtsp)
file_list = project.File.Information()
for file in file_list:
project.File.Remove(file)
for file in kernel_kernel_files:
project.File.Add(src_abs_path + "\\" + file, u"kernel")
for file in kernel_arch_files:
project.File.Add(src_abs_path + "\\" + file, u"arch")
for file in kernel_target_files:
project.File.Add(src_abs_path + "\\" + file, u"target")
project.Close(True)
#
# Modify atk2-sc1.mtpfj
#
inputstr = ReadFile('atk2-sc1.mtpj')
# Set cx include path
inputstr = NewSetCCRHIncludes(inputstr, atk2_sc1_rel_includes, INCLUDES, SRCDIR)
# Set libary path and file
#inputstr = NewSetLibIncludes(inputstr, atk2_sc1_lib_includes, [], SRCDIR)
inputstr = NewSetLibFiles(inputstr, atk2_sc1_lib_files)
# change Option
inputstr = ChangeItemXml(inputstr, 'OutputMessageFormat-0', '%Program% %Options%')
#inputstr = ChangeItemXml(inputstr, 'UseProEpiRuntimeLibrary-0', 'False')
#inputstr = ChangeItemXml(inputstr, 'HexadecimalFileFormat-0','MotrolaSType32Bit')
inputstr = ChangeItemXml(inputstr, 'HexOptionOutputFileName-0', r'%ProjectName%.srec')
#inputstr = ChangeItemXml(inputstr, 'OutputLinkMapFile-0', 'True')
inputstr = ChangeItemXml(inputstr, 'LinkOptionShowSymbol-0', 'True')
#inputstr = ChangeItemXml(inputstr, 'OutputSymbolInformationToLinkMapFile-0', 'True')
inputstr = ChangeItemXml(inputstr, 'DebuggerProperty-EssentialProperty-Clock-MainClockGeneration', MAIN_CLK)
inputstr = ChangeItemXml(inputstr, 'GeneralOptionXreserveR2-0', 'True')
inputstr = ChangeItemXml(inputstr, 'COptionOsize-0', 'AdvancedSpeed')
# Change linkoption if link_option is exist.
try:
link_option = link_option
inputstr = ChangeItemXml(inputstr, 'LinkOptionStart-0', link_option)
except NameError:
link_option = ''
# Set user macro definitions
inputstr = NewSetDefine(inputstr, USER_MACRO)
# Set Prebuild/Postbuile
inputstr = NewSetPostbuild(inputstr, atk2_sc1_post_python_files, SRCDIR)
WriteFile('atk2-sc1.mtpj', inputstr)
#
# Modify ./cfg/cfg.mtsp
#
inputstr = ReadFile('./cfg/cfg.mtsp')
# Set cx include path
inputstr = NewSetCCRHIncludes(inputstr, cfg_rel_includes, INCLUDES, "../" + SRCDIR)
# change Option
inputstr = ChangeItemXml(inputstr, 'OutputMessageFormat-0', '%Program% %Options%')
#inputstr = ChangeItemXml(inputstr, 'UseProEpiRuntimeLibrary-0', 'False')
#inputstr = ChangeItemXml(inputstr, 'HexadecimalFileFormat-0','MotrolaSType32Bit')
inputstr = ChangeItemXml(inputstr, 'HexOptionOutputFileName-0', 'cfg1_out.srec')
#inputstr = ChangeItemXml(inputstr, 'OutputLinkMapFile-0', 'True')
inputstr = ChangeItemXml(inputstr, 'LinkOptionShowSymbol-0', 'True')
inputstr = ChangeItemXml(inputstr, 'HexOptionOutputFolder-0', '.')
# Set Prebuild/Postbuile
inputstr = NewSetPrebuild(inputstr, cfg_pre_python_files, "../" + SRCDIR)
inputstr = NewSetPostbuild(inputstr, cfg_post_python_files, "../" + SRCDIR)
# Set user macro definitions
inputstr = NewSetDefine(inputstr, USER_MACRO)
WriteFile('./cfg/cfg.mtsp', inputstr)
#
# Mofity ./kernel/kernel.mtsp
#
inputstr = ReadFile('./kernel/kernel.mtsp')
# Add user macro definitions
kernel_define = kernel_define + USER_MACRO
# Set cx include path
inputstr = NewSetCCRHIncludes(inputstr, kernel_rel_includes, INCLUDES, "../" + SRCDIR)
# Set cx define
inputstr = NewSetDefine(inputstr, kernel_define)
# Set cx addition option
inputstr = NewSetCAddOpt(inputstr, kernel_c_addopt)
inputstr = NewSetAsmAddOpt(inputstr, kernel_asm_addopt)
# change Option
inputstr = ChangeItemXml(inputstr, 'OutputMessageFormat-0', '%Program% %Options%')
#inputstr = ChangeItemXml(inputstr, 'UseProEpiRuntimeLibrary-0', 'False')
inputstr = ChangeItemXml(inputstr, 'GeneralOptionXreserveR2-0', 'True')
inputstr = ChangeItemXml(inputstr, 'COptionOsize-0', 'AdvancedSpeed')
WriteFile('./kernel/kernel.mtsp', inputstr)
project.Open(wd_abs_path + r'\atk2-sc1.mtpj')
project.Change(atk2_sc1_mtpj)
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: uart_rlin.c 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* シリアルI/Oデバイス(SIO)ドライバ(RLIN用)
*/
#include "Os.h"
#include "target_serial.h"
#include "uart_rlin.h"
#include "Os_Lcfg.h"
/* 内部関数のプロトタイプ宣言 */
LOCAL_INLINE uint8 uart_getchar(void);
/*
* 受信した文字の取り出し
*/
LOCAL_INLINE uint8
uart_getchar(void)
{
return(sil_reb_mem((void *) (RLIN3x_BASE + RLIN3xLURDRL_B)));
}
/*
* 初期化処理
*/
void
InitHwSerial(void)
{
/* Uart Mode を有効(ノイズフィルタも有効) */
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLMD_B), 0x31);
/* ボーレート設定 */
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLWBR_B), RLIN3xLWBR_VAL);
sil_wrh_mem((void *) (RLIN3x_BASE + RLIN3xLBRP01_H), RLIN3xLBRP01_VAL);
/* エラー検出許可 */
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLEDE_B), 0x0d);
/* データ フォーマット */
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLBFC_B), 0x00);
/* リセット解除 */
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLCUC_B), 0x01);
/* リセット解除待ち */
while (sil_reb_mem((void *) (RLIN3x_BASE + RLIN3xLMST_B)) == 0x00) {
}
/* 送受信動作許可 */
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLUOER_B), 0x03);
/* 受信割込み許可 */
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLIE_B), 0x02);
}
/*
* シリアルI/Oポートのクローズ
*/
void
TermHwSerial(void)
{
/* 受信割込みの禁止 */
sil_wrb_mem((void *) (RLIN3x_BASE + RLIN3xLIE_B), 0x00);
}
/*
* SIOの割込みハンドラ
*/
ISR(RxHwSerialInt)
{
/*
* 受信通知コールバックルーチンを呼び出す
*/
RxSerialInt(uart_getchar());
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2014 by Spansion LLC, USA
* Copyright (C) 2014 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2014 by <NAME> Inc., JAPAN
* Copyright (C) 2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: tauj_hw_counter.c 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* 以下ハードウェアカウンタプログラムのターゲット依存定義(fl850fx4用)
*
* 使用するタイマ:
* 差分タイマ:目的の時間を設定する時の現在時間(現在値タイマ)
* と次の満了時間との相対時間をカウントすることで
* 目的の絶対時間に満了したこととする
* count mode:count down once
*
* 現在値タイマ:カウンタ周期分のベースタイマを実現
* (絶対時間をカウント)
* count mode:continuous count down
*
* また上記のタイマは32bitのダウンカウンタタイマである
*
* 制御方針:
*
* 現在値タイマはユーザ定義カウンタ最大値2倍+1までカウントし,
* 周期タイマとして連続カウントダウンして,常に現在時刻を
* 取得する.割込み発生する必要がないため,割込みなしモード
*
* 差分タイマは,満了処理を行うため,割込みありモードで動く
* アラームなどの満了点とタイマー1で示した現在時刻の差を
* 現在値タイマに設定する
*
* ポイント:
* 満了処理は,現在時刻を影響しないため,現在値タイマを設けている
*
*/
#include "Os.h"
#include "prc_sil.h"
#include "target_hw_counter.h"
/*
* =begin ハードウェアカウンタのTAUJn依存部
*/
/*
* ハードウェアカウンタの初期化
* n_d : 差分タイマのユニット番号
* ch_d : 差分タイマのチャネル
* n_c : 現在値タイマのユニット番号
* ch_c : 現在値タイマのチャネル
*/
static void
init_hwcounter_tauj(uint8 n_d, uint8 ch_d, uint8 n_c, uint8 ch_c, TickType maxval, TimeType nspertick, TickRefType cycle)
{
uint16 wk;
*cycle = maxval;
/* assert((tauj_id + 1) < TAUJ_MAX); */
/* 差分タイマ停止処理 */
SetTimerStopTAUJ(n_d, ch_d);
/* 割込み禁止 */
HwcounterDisableInterrupt(TAUJ_INTNO(n_d, ch_d));
/* 割込み要求クリア */
HwcounterClearInterrupt(TAUJ_INTNO(n_d, ch_d));
/* 差分タイマのプリスケーラを設定 PCLK/2^0 */
wk = sil_reh_mem((void *) TAUJTPS(n_d));
wk &= MCU_TAUJ_MASK_CK0;
wk |= MCU_TAUJ_CK0_0;
sil_wrh_mem((void *) TAUJTPS(n_d), wk);
/* 現在値タイマのプリスケーラを設定 PCLK/2^0 */
wk = sil_reh_mem((void *) TAUJTPS(n_c));
wk &= MCU_TAUJ_MASK_CK0;
wk |= MCU_TAUJ_CK0_0;
sil_wrh_mem((void *) TAUJTPS(n_c), wk);
/* 差分タイマをインターバルタイマとして設定 */
sil_wrh_mem((void *) TAUJCMOR(n_d, ch_d), MCU_TAUJ00_CMOR);
sil_wrb_mem((void *) TAUJCMUR(n_d, ch_d), MCU_TAUJ00_CMUR);
/* 現在値タイマ停止処理 */
SetTimerStopTAUJ(n_c, ch_c);
/* 割込み禁止 */
HwcounterDisableInterrupt(TAUJ_INTNO(n_c, ch_c));
/* 割込み要求クリア */
HwcounterClearInterrupt(TAUJ_INTNO(n_c, ch_c));
/* 現在値タイマをインターバルタイマとして設定 */
sil_wrh_mem((void *) TAUJCMOR(n_c, ch_c), MCU_TAUJ00_CMOR);
sil_wrb_mem((void *) TAUJCMUR(n_c, ch_c), MCU_TAUJ00_CMUR);
/* タイマカウント周期設定 */
sil_wrw_mem((void *) TAUJCDR(n_c, ch_c), maxval);
}
/*
* ハードウェアカウンタの開始
*/
static void
start_hwcounter_tauj(uint8 n_c, uint8 ch_c)
{
/* 現在値タイマ開始 */
SetTimerStartTAUJ(n_c, ch_c);
}
/*
* ハードウェアカウンタの停止
* n_d : 差分タイマのユニット番号
* ch_d : 差分タイマのチャネル
* n_c : 現在値タイマのユニット番号
* ch_c : 現在値タイマのチャネル
*/
static void
stop_hwcounter_tauj(uint8 n_d, uint8 ch_d, uint8 n_c, uint8 ch_c)
{
/* 差分タイマの停止 */
SetTimerStopTAUJ(n_d, ch_d);
/* 差分タイマの割込み禁止 */
HwcounterDisableInterrupt(TAUJ_INTNO(n_d, ch_d));
/* 差分タイマの割込み要求のクリア */
HwcounterClearInterrupt(TAUJ_INTNO(n_d, ch_d));
/* 現在値タイマの停止 */
SetTimerStopTAUJ(n_c, ch_c);
/* 現在値タイマの割込み禁止 */
/* HwcounterDisableInterrupt(TAUJ_INTNO(tauj_id + 1)); */
/* 現在値タイマの割込み要求のクリア */
HwcounterClearInterrupt(TAUJ_INTNO(n_c, ch_c));
}
/*
* ハードウェアカウンタへの満了時間の設定
* n_d : 差分タイマのユニット番号
* ch_d : 差分タイマのチャネル
* n_c : 現在値タイマのユニット番号
* ch_c : 現在値タイマのチャネル
*/
static void
set_hwcounter_tauj(uint8 n_d, uint8 ch_d, uint8 n_c, uint8 ch_c, TickType exprtick, TickType maxval)
{
TickType curr_time;
TickType value;
/* 差分タイマの割込み要求のクリア */
HwcounterClearInterrupt(TAUJ_INTNO(n_d, ch_d));
/* 差分タイマの割込み許可 */
HwcounterEnableInterrupt(TAUJ_INTNO(n_d, ch_d));
/* 現在時刻の取得 */
curr_time = GetCurrentTimeTAUJ(n_c, ch_c, maxval);
/* タイマに設定する値を算出 */
if (exprtick >= curr_time) {
value = exprtick - curr_time;
}
else {
value = (exprtick - curr_time) + (maxval + 1U);
}
/*
* タイマに0x00を設定し,割込み発生後,再度0を設定した場合,2回目の
* 0x00設定後の割込みは発生しないので,0x00設定値を0x01に直して設定
*/
if (value == 0x00U) {
value = 0x01U;
}
/* 差分タイマのタイマ値設定 */
sil_wrw_mem((void *) TAUJCDR(n_d, ch_d), (value));
/*
* カウント開始
*/
SetTimerStartTAUJ(n_d, ch_d);
}
/*
* ハードウェアカウンタの現在時間の取得
*/
static TickType
get_hwcounter_tauj(uint8 n_c, uint8 ch_c, TickType maxval)
{
return(GetCurrentTimeTAUJ(n_c, ch_c, maxval));
}
/*
* ハードウェアカウンタの設定された満了時間の取消
*/
static void
cancel_hwcounter_tauj(uint8 n_d, uint8 ch_d)
{
/* 差分タイマの停止 */
SetTimerStopTAUJ(n_d, ch_d);
}
/*
* ハードウェアカウンタの強制割込み要求
*/
static void
trigger_hwcounter_tauj(uint8 n_d, uint8 ch_d)
{
/* 差分タイマ停止 */
SetTimerStopTAUJ(n_d, ch_d);
/* 差分タイマの割込み要求のクリア */
HwcounterClearInterrupt(TAUJ_INTNO(n_d, ch_d));
/* 差分タイマの割込み許可 */
HwcounterEnableInterrupt(TAUJ_INTNO(n_d, ch_d));
/* 差分タイマカウンターに0x01をセットすることで,すぐ満了 */
sil_wrw_mem((void *) TAUJCDR(n_d, ch_d), (1));
/* 差分タイマ開始 */
SetTimerStartTAUJ(n_d, ch_d);
}
/*
* 割込み要求のクリア
*/
static void
int_clear_hwcounter_tauj(uint8 n_d, uint8 ch_d)
{
/* 割込み要求クリア */
HwcounterClearInterrupt(TAUJ_INTNO(n_d, ch_d));
}
/*
* 割込み要求のキャンセル
* ペンディングされている割込み要求をキャンセル
*/
static void
int_cancel_hwcounter_tauj(uint8 n_d, uint8 ch_d)
{
/* 割込み要求クリア */
HwcounterClearInterrupt(TAUJ_INTNO(n_d, ch_d));
}
/*
* ハードウェアカウンタのインクリメント
*/
static void
increment_hwcounter_tauj(uint8 n_d, uint8 ch_d)
{
/* 未サポート */
return;
}
/*
* =end ハードウェアカウンタのTAUJn依存部
*/
/*
* =begin MAIN_HW_COUNTERの定義
*/
/* カウンタの最大値の2倍+1 */
static TickType MAIN_HW_COUNTER_maxval;
/*
* ハードウェアカウンタの初期化
*/
void
init_hwcounter_MAIN_HW_COUNTER(TickType maxval, TimeType nspertick)
{
init_hwcounter_tauj(HWC_DTIM_UNIT, HWC_DTIM_ID,
HWC_CTIM_UNIT, HWC_CTIM_ID,
maxval, nspertick, &MAIN_HW_COUNTER_maxval);
}
/*
* ハードウェアカウンタの開始
*/
void
start_hwcounter_MAIN_HW_COUNTER(void)
{
start_hwcounter_tauj(HWC_CTIM_UNIT, HWC_CTIM_ID);
}
/*
* ハードウェアカウンタの停止
*/
void
stop_hwcounter_MAIN_HW_COUNTER(void)
{
stop_hwcounter_tauj(HWC_DTIM_UNIT, HWC_DTIM_ID,
HWC_CTIM_UNIT, HWC_CTIM_ID);
}
/*
* ハードウェアカウンタへの満了時間の設定
*/
void
set_hwcounter_MAIN_HW_COUNTER(TickType exprtick)
{
set_hwcounter_tauj(HWC_DTIM_UNIT, HWC_DTIM_ID,
HWC_CTIM_UNIT, HWC_CTIM_ID,
exprtick, MAIN_HW_COUNTER_maxval);
}
/*
* ハードウェアカウンタの現在時間の取得
*/
TickType
get_hwcounter_MAIN_HW_COUNTER(void)
{
return(get_hwcounter_tauj(HWC_CTIM_UNIT, HWC_CTIM_ID,
MAIN_HW_COUNTER_maxval));
}
/*
* ハードウェアカウンタの設定された満了時間の取消
*/
void
cancel_hwcounter_MAIN_HW_COUNTER(void)
{
cancel_hwcounter_tauj(HWC_DTIM_UNIT, HWC_DTIM_ID);
}
/*
* ハードウェアカウンタの強制割込み要求
*/
void
trigger_hwcounter_MAIN_HW_COUNTER(void)
{
trigger_hwcounter_tauj(HWC_DTIM_UNIT, HWC_DTIM_ID);
}
/*
* ハードウェアカウンタの設定された満了時間の取消
*/
void
int_clear_hwcounter_MAIN_HW_COUNTER(void)
{
int_clear_hwcounter_tauj(HWC_DTIM_UNIT, HWC_DTIM_ID);
}
/*
* ハードウェアカウンタの設定された満了時間の取消
*/
void
int_cancel_hwcounter_MAIN_HW_COUNTER(void)
{
int_cancel_hwcounter_tauj(HWC_DTIM_UNIT, HWC_DTIM_ID);
}
/*
* ハードウェアカウンタのインクリメント
*/
void
increment_hwcounter_MAIN_HW_COUNTER(void)
{
increment_hwcounter_tauj(HWC_DTIM_UNIT, HWC_DTIM_ID);
}
/*
* =end MAIN_HW_COUNTERの定義
*/
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: osctl.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* OS制御モジュール
*/
#include "kernel_impl.h"
#include "interrupt.h"
#include "task.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_ERRHOOK_ENTER
#define LOG_ERRHOOK_ENTER(ercd)
#endif /* LOG_ERRHOOK_ENTER */
#ifndef LOG_ERRHOOK_LEAVE
#define LOG_ERRHOOK_LEAVE()
#endif /* LOG_ERRHOOK_LEAVE */
#ifndef LOG_PROHOOK_ENTER
#define LOG_PROHOOK_ENTER(ercd)
#endif /* LOG_PROHOOK_ENTER */
#ifndef LOG_PROHOOK_LEAVE
#define LOG_PROHOOK_LEAVE(pret)
#endif /* LOG_PROHOOK_LEAVE */
#ifndef LOG_SHUTHOOK_ENTER
#define LOG_SHUTHOOK_ENTER(ercd)
#endif /* LOG_SHUTHOOK_ENTER */
#ifndef LOG_SHUTHOOK_LEAVE
#define LOG_SHUTHOOK_LEAVE()
#endif /* LOG_SHUTHOOK_LEAVE */
#ifndef LOG_STUTOS_ENTER
#define LOG_STUTOS_ENTER(ercd)
#endif /* LOG_STUTOS_ENTER */
#ifndef LOG_STUTOS_LEAVE
#define LOG_STUTOS_LEAVE()
#endif /* LOG_STUTOS_LEAVE */
#ifdef CFG_USE_ERRORHOOK
/*
* エラーフックに渡す情報を格納する変数
*/
#ifdef TOPPERS_internal_call_errorhook
#ifdef CFG_USE_GETSERVICEID
OSServiceIdType errorhook_svcid;
#endif /* CFG_USE_GETSERVICEID */
#ifdef CFG_USE_PARAMETERACCESS
ErrorHook_Par temp_errorhook_par1;
ErrorHook_Par temp_errorhook_par2;
ErrorHook_Par temp_errorhook_par3;
ErrorHook_Par errorhook_par1;
ErrorHook_Par errorhook_par2;
ErrorHook_Par errorhook_par3;
#endif /* CFG_USE_PARAMETERACCESS */
/*
* エラーフックの呼び出し
*/
void
internal_call_errorhook(StatusType ercd, OSServiceIdType svcid)
{
if ((callevel_stat & (TCL_ERROR | TSYS_ISR1)) == TCL_NULL) {
#ifdef CFG_USE_GETSERVICEID
errorhook_svcid = svcid;
#endif /* CFG_USE_GETSERVICEID */
#ifdef CFG_USE_PARAMETERACCESS
errorhook_par1 = temp_errorhook_par1;
errorhook_par2 = temp_errorhook_par2;
errorhook_par3 = temp_errorhook_par3;
#endif /* CFG_USE_PARAMETERACCESS */
ENTER_CALLEVEL(TCL_ERROR);
LOG_ERRHOOK_ENTER(ercd);
ErrorHook(ercd);
LOG_ERRHOOK_LEAVE();
LEAVE_CALLEVEL(TCL_ERROR);
}
}
#endif /* TOPPERS_internal_call_errorhook */
#endif /* CFG_USE_ERRORHOOK */
#ifdef CFG_USE_POSTTASKHOOK
/*
* ポストタスクフックの呼び出し
*/
#ifdef TOPPERS_call_posttaskhook
void
call_posttaskhook(void)
{
ENTER_CALLEVEL(TCL_PREPOST);
PostTaskHook();
LEAVE_CALLEVEL(TCL_PREPOST);
}
#endif /* TOPPERS_call_posttaskhook */
#endif /* CFG_USE_POSTTASKHOOK */
#ifdef CFG_USE_PRETASKHOOK
/*
* プレタスクフックの呼び出し
*/
#ifdef TOPPERS_call_pretaskhook
void
call_pretaskhook(void)
{
ENTER_CALLEVEL(TCL_PREPOST);
PreTaskHook();
LEAVE_CALLEVEL(TCL_PREPOST);
}
#endif /* TOPPERS_call_pretaskhook */
#endif /* CFG_USE_PRETASKHOOK */
#ifdef CFG_USE_STACKMONITORING
#ifdef TOPPERS_init_stack_magic_region
/*
* スタックモニタリング機能の初期化
* スタックモニタリング機能のためのマジックナンバー領域の初期化
*/
void
init_stack_magic_region(void)
{
TaskType i;
StackType *p_stack_magic_region;
/*
* スタックモニタリング機能のため,スタック成長方向考慮した
* 非タスクスタックのマジックナンバー領域の初期化
*/
p_stack_magic_region = TOPPERS_ISTK_MAGIC_REGION(ostk, ostksz);
*p_stack_magic_region = STACK_MAGIC_NUMBER;
/*
* スタックモニタリング機能のため,スタック成長方向考慮した
* 各タスクスタックのマジックナンバー領域の初期化
* スタック共有したタスクのマジックナンバー領域が合わせっている
*/
for (i = 0U; i < tnum_task; i++) {
p_stack_magic_region =
TOPPERS_TSTK_MAGIC_REGION(&tinib_table[i]);
*p_stack_magic_region = STACK_MAGIC_NUMBER;
}
}
#endif /* TOPPERS_init_stack_magic_region */
#endif /* CFG_USE_STACKMONITORING */
/*
* プロテクションフックの呼び出し
*/
#ifdef TOPPERS_call_protectionhk_main
void
call_protectionhk_main(StatusType ercd)
{
#ifdef CFG_USE_PROTECTIONHOOK
ProtectionReturnType pret;
/* プロテクションフック実行中に保護違反が発生した場合 */
if ((callevel_stat & TCL_PROTECT) == TCL_PROTECT) {
internal_shutdownos(E_OS_PROTECTION_FATAL);
}
ENTER_CALLEVEL(TCL_PROTECT);
LOG_PROHOOK_ENTER(ercd);
pret = ProtectionHook(ercd);
LOG_PROHOOK_LEAVE(pret);
LEAVE_CALLEVEL(TCL_PROTECT);
/* 以下 ProtectionHook 実行後の処理 */
switch (pret) {
case PRO_SHUTDOWN:
internal_shutdownos(ercd);
break;
case PRO_IGNORE:
if (ercd != E_OS_PROTECTION_EXCEPTION) {
internal_shutdownos(E_OS_PROTECTION_FATAL);
}
break;
default:
/* ProtectionHookから不正な値が返った場合 */
internal_shutdownos(E_OS_PROTECTION_FATAL);
break;
}
#else /* CFG_USE_PROTECTIONHOOK */
/*
* プロテクションフックがコンフィギュレーション時に無効と
* されている場合,OSは保護違反時処理としてOSシャットダウンを
* 行う
* このとき,OSシャットダウンのパラメータとして,
* 違反の区別を示すエラーコードを指定する
*/
internal_shutdownos(ercd);
#endif /* CFG_USE_PROTECTIONHOOK */
}
#endif /* TOPPERS_call_protectionhk_main */
/*
* OS内部からのShutdownOSの呼び出し
*/
#ifdef TOPPERS_internal_shutdownos
void
internal_shutdownos(StatusType ercd)
{
LOG_STUTOS_ENTER(ercd);
x_nested_lock_os_int();
#ifdef CFG_USE_SHUTDOWNHOOK
call_shutdownhook(ercd);
#endif /* CFG_USE_SHUTDOWNHOOK */
/* 各モジュールの終了処理 */
object_terminate();
/* 全割込み禁止状態に移行 */
x_lock_all_int();
LOG_STUTOS_LEAVE();
/* ターゲット依存の終了処理 */
target_exit();
/*
* ターゲット依存部から処理が返ってきた場合,
* 無限ループを行う
*/
while (1) {
}
}
#endif /* TOPPERS_internal_shutdownos */
#ifdef TOPPERS_internal_call_shtdwnhk
#ifdef CFG_USE_SHUTDOWNHOOK
void
internal_call_shtdwnhk(StatusType ercd)
{
/*
* シャットダウンフック中のシャットダウンではシャットダウンフック
* は呼び出さない
*/
if ((callevel_stat & TCL_SHUTDOWN) == TCL_NULL) {
ENTER_CALLEVEL(TCL_SHUTDOWN);
LOG_SHUTHOOK_ENTER(ercd);
ShutdownHook(ercd);
LOG_SHUTHOOK_LEAVE();
LEAVE_CALLEVEL(TCL_SHUTDOWN);
}
}
#endif /* CFG_USE_SHUTDOWNHOOK */
#endif /* TOPPERS_internal_call_shtdwnhk */
<file_sep>
ABREX - AUTOSAR BSW and RTE XML Generator -
本ドキュメントは,ABREXを使用するために必要な事項を説明するものである.
----------------------------------------------------------------------
ABREX
AUTOSAR BSW and RTE XML Generator
Copyright (C) 2013-2016 by Center for Embedded Computing Systems
Graduate School of Information Science, Nagoya Univ., JAPAN
Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
Copyright (C) 2013-2016 by FUJI SOFT INCORPORATED, JAPAN
Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
Copyright (C) 2014-2016 by NEC Communication Systems, Ltd., JAPAN
Copyright (C) 2013-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
Copyright (C) 2013-2014 by Renesas Electronics Corporation, JAPAN
Copyright (C) 2014-2016 by SCSK Corporation, JAPAN
Copyright (C) 2013-2016 by Sunny Giken Inc., JAPAN
Copyright (C) 2015-2016 by SUZUKI MOTOR CORPORATION
Copyright (C) 2013-2016 by TOSHIBA CORPORATION, JAPAN
Copyright (C) 2013-2016 by Witz Corporation
上記著作権者は,以下の (1)〜(3)の条件を満たす場合に限り,本ドキュメ
ント(本ドキュメントを改変したものを含む.以下同じ)を使用・複製・改
変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
(1) 本ドキュメントを利用する場合には,上記の著作権表示,この利用条件
および下記の無保証規定が,そのままの形でドキュメント中に含まれて
いること.
(2) 本ドキュメントを改変する場合には,ドキュメントを改変した旨の記述
を,改変後のドキュメント中に含めること.ただし,改変後のドキュメ
ントが,TOPPERSプロジェクト指定の開発成果物である場合には,この限
りではない.
(3) 本ドキュメントの利用により直接的または間接的に生じるいかなる損害
からも,上記著作権者およびTOPPERSプロジェクトを免責すること.また,
本ドキュメントのユーザまたはエンドユーザからのいかなる理由に基づ
く請求からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
本ドキュメントは,AUTOSAR(AUTomotive Open System ARchitecture)仕様
に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するものではな
い.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利用する
者に対して,AUTOSARパートナーになることを求めている.
本ドキュメントは,無保証で提供されているものである.上記著作権者およ
びTOPPERSプロジェクトは,本ドキュメントに関して,特定の使用目的に対す
る適合性も含めて,いかなる保証も行わない.また,本ドキュメントの利用
により直接的または間接的に生じたいかなる損害に関しても,その責任を負
わない.
$Id: readme.txt 785 2017-03-07 08:45:46Z nces-mtakada $
----------------------------------------------------------------------
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
(1) ABREX概要
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ABREXは,OS,COMを始めとするBSWと,RTEのコンフィギュレーションファイル
(XML)を生成するツールである.YAMLフォーマットで記述したコンフィギュレー
ション情報を入力として,対応するXMLを生成する.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
(2) 使い方
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
———————————————————————————————————
(2.1) 動作環境
———————————————————————————————————
ABREXはRubyによって記述されているため,Rubyの実行環境が必要である.
Cygwinに含まれる以下のバージョンのRubyで動作確認済みである.
ruby 1.9.3p327 (2012-11-10 revision 37606) [i386-cygwin]
———————————————————————————————————
(2.2) コンテナ情報の生成
———————————————————————————————————
※本手順は既にparam_info.yamlが存在する場合,不要である
-pオプションに,AUTOSARから公開されているECUコンフィギュレーションパラ
メータコンテナ情報ファイル(*)を引数として与え,実行する.
(*)http://www.autosar.org
Methodology and Templates -> Templates -> Standard Specifications
-> AUTOSAR_MOD_ECUConfigurationParameters.zip
解凍すると"AUTOSAR_MOD_ECUConfigurationParameters.arxml"となる
$ ruby abrex.rb -p AUTOSAR_MOD_ECUConfigurationParameters.arxml
各パラメータコンテナのデータ型,外部参照型の参照先情報などが,
param_info.yamlに出力される.
———————————————————————————————————
(2.3) YAMLファイルの作成
———————————————————————————————————
生成したいXMLファイルの情報をYAMLフォーマットで記述する.
・最上位のレイヤがパッケージ名,その次がECUモジュール名となる.
・ECUモジュール名の下に該当モジュールに含まれるパラメータ名をキーとして,
パラメータコンテナと値をハッシュ形式で記述する.
・サブコンテナは,ハッシュをネストすることで表現する.
・コンテナへの参照は,YAMLファイルに定義したパッケージ名に従ってパスを
記述する.
■OSの例
Os:
Os:
MainApp:
DefinitionRef: OsAppMode
OsOS:
OsStackMonitoring: 1
OsStatus: EXTENDED
OsUseGetServiceId: 1
OsUseParameterAccess: 1
OsScalabilityClass: SC1
OsHooks:
OsErrorHook: 0
OsPostTaskHook: 0
OsPreTaskHook: 0
OsProtectionHook: 0
OsShutdownHook: 0
OsStartupHook: 0
OsHookStack:
OsHookStackSize: 1024
OsOsStack:
OsOsStackSize: 1024
TASK1:
DefinitionRef: OsTask
OsTaskActivation: 1
OsTaskPriority: 10
OsTaskSchedule: FULL
OsTaskStackSize: 1024
OsTaskEventRef: /Os/Os/EVENT1
OsTaskAutostart:
OsTaskAppModeRef: /Os/Os/MainApp
EVENT1:
DefinitionRef: OsEvent
———————————————————————————————————
(2.4) XMLファイルの生成
———————————————————————————————————
作成したYAMLファイルを引数として,abrex.rbを実行する.
$ ruby abrex.rb ./sample.yaml
入力したYAMLファイルの情報に対応するXMLファイルが,入力ファイル名の拡張
子をarxmlに変更したファイルに出力される.
※上記例の場合,sample.arxml
・(2.1)で生成したparam_info.yamlに含まれないキー名が登場した場合,エラ
ー終了する.
・サブコンテナ名はparam_info.yamlに含まれず,YAMLファイルに記述した名称
が正しいものとして,サブコンテナを生成する.
・設定値の妥当性等のチェックは一切行わない.
引数のYAMLファイルは複数指定することができ,すべてのYAMLファイルの情報
をマージしたXMLファイルを生成する.同じパスのコンテナが異なるファイルに
存在する場合,1つのコンテナにマージする.例えば,以下のa.yamlとb.yamlを
入力した場合,MAIN_HW_COUNTERには両方のファイルに指定されたすべてのパラ
メータが設定されたXMLファイルとなる.
<a.yaml>
Os:
Os:
MAIN_HW_COUNTER:
DefinitionRef: OsCounter
OsCounterMaxAllowedValue: 0x7FFFFFFF
OsCounterTicksPerBase: 10
OsCounterMinCycle: 4000
OsCounterType: HARDWARE
OsSecondsPerTick: 1.666666e-08
OsCounterIsrRef: /Os/Os/ISR1
<b.yaml>
Os:
Os:
MAIN_HW_COUNTER:
OsCounterAccessingApplication: OSAP1
※同じパスのパラメータが複数のファイルに含まれる場合は,多重度が*と判断
して,複数のコンテナを生成する.(パラメータ毎の多重度情報は保持しない)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
(3) その他の機能
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
———————————————————————————————————
(3.1) XMLからYAMLを作成する(逆変換)
———————————————————————————————————
ABREXでは,作成済みのXMLファイルから,YAMLファイルを作成することが出来
る.-iオプションに,AUTOSAR準拠のXMLを引数として与え,実行する.
$ ruby abrex.rb -i sample.arxml
入力したXMLファイルの情報に対応するYAMLファイルが,入力ファイル名の拡張
子をyamlに変更したファイルに出力される.
※上記例の場合,sample.yaml
———————————————————————————————————
(3.2) ジェネレータ用csvファイルの生成
———————————————————————————————————
TOPPERS/ATK2で使用するジェネレータ(cfg.exe)はXMLコンテナ情報をCSVファイ
ルで与える必要があるが,ECUコンフィギュレーションパラメータコンテナ情報
ファイルから生成することが可能である.-cオプションに,ECUコンフィギュレ
ーションパラメータコンテナ情報ファイルを引数として与え,-bオプションに,
生成する対象のモジュール名(*)を引数として与え,実行する.
(*)http://www.autosar.org
Software Architecture -> General -> AUTOSAR_TR_BSWModuleList.pdf
上記ファイルに規定されているModule abbreviationで指定する.
$ ruby abrex.rb -b Com -c AUTOSAR_MOD_ECUConfigurationParameters.arxml
指定した対象のモジュール名のCSVファイルに出力される.
※上記例の場合,xCom.csv
<注意事項>
生成するCSVファイルのコンテナの短縮名は,コンテナ名をそのまま使用する.
従って,同じ名称のコンテナが異なるコンテナのサブコンテナとして存在する
場合は,ジェネレータ実行時に区別できなくなる.この場合,手動で区別でき
るように修正する必要がある.
(例)ComのComTxModeFalseとComTxModeTrueに含まれるComTxModeコンテナ
/AUTOSAR/EcucDefs/Com/ComConfig/ComIPdu/ComTxIPdu/ComTxModeFalse/ComTxMode,ComTxMode,,1
/AUTOSAR/EcucDefs/Com/ComConfig/ComIPdu/ComTxIPdu/ComTxModeTrue/ComTxMode,ComTxMode,,1
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
(4) 注意事項
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
———————————————————————————————————
(4.1) ECUコンフィギュレーションパラメータコンテナ情報ファイルの誤記修正
———————————————————————————————————
コンテナ情報の生成(本ドキュメントの2.2章を参照)において使用している,
ECUコンフィギュレーションパラメータコンテナ情報ファイルである
AUTOSAR_MOD_ECUConfigurationParameters.arxmlの誤記を修正する必要がある.
現在判明している誤記を以下に示す.
・(誤)WdgMInternallCheckpointFinalRef
(正)WdgMInternalCheckpointFinalRef
以上
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: counter.c 778 2017-03-06 07:21:41Z nces-hibino $
*/
/*
* カウンタ制御モジュール
*/
#include "kernel_impl.h"
#include "task.h"
#include "counter.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_INCCNT_ENTER
#define LOG_INCCNT_ENTER(cntid)
#endif /* LOG_INCCNT_ENTER */
#ifndef LOG_INCCNT_LEAVE
#define LOG_INCCNT_LEAVE(ercd)
#endif /* LOG_INCCNT_LEAVE */
#ifndef LOG_GETCNT_ENTER
#define LOG_GETCNT_ENTER(cntid, p_val)
#endif /* LOG_GETCNT_ENTER */
#ifndef LOG_GETCNT_LEAVE
#define LOG_GETCNT_LEAVE(ercd, val)
#endif /* LOG_GETCNT_LEAVE */
#ifndef LOG_GETECT_ENTER
#define LOG_GETECT_ENTER(cntid, val, p_eval)
#endif /* LOG_GETECT_ENTER */
#ifndef LOG_GETECT_LEAVE
#define LOG_GETECT_LEAVE(ercd, val, eval)
#endif /* LOG_GETECT_LEAVE */
/*
* カウンタ満了キューへの挿入
*/
#ifdef TOPPERS_insert_cnt_expr_que
void
insert_cnt_expr_que(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb)
{
TickType enqval, curval;
QUEUE *next;
CounterType cntid;
enqval = p_cntexpinfo->expiretick;
cntid = CNTID(p_cntcb);
if (!is_hwcnt(cntid)) {
curval = p_cntcb->curval;
}
else {
curval = get_curval(p_cntcb, cntid);
}
/* 挿入場所のサーチ */
next = p_cntcb->cntexpque.p_next;
if (curval < enqval) {
/* カウンタのオーバーフローが起こらない場合 */
while ((next != &(p_cntcb->cntexpque)) &&
(diff_tick(curval, ((CNTEXPINFO *) next)->expiretick, p_cntcb->p_cntinib->maxval2) <= p_cntcb->p_cntinib->maxval ||
((curval <= ((CNTEXPINFO *) next)->expiretick) &&
(((CNTEXPINFO *) next)->expiretick <= enqval)))) {
next = next->p_next;
}
}
else {
/* カウンタのオーバーフローが起こる場合 */
while ((next != &(p_cntcb->cntexpque)) &&
((diff_tick(curval, ((CNTEXPINFO *) next)->expiretick, p_cntcb->p_cntinib->maxval2) <= p_cntcb->p_cntinib->maxval) ||
(curval <= ((CNTEXPINFO *) next)->expiretick) ||
(((CNTEXPINFO *) next)->expiretick <= enqval))) {
next = next->p_next;
}
}
queue_insert_prev(next, &(p_cntexpinfo->cntexpque));
/*
* ハードウェアカウンタかつ先頭に挿入した場合,再度ハードウェアカウンタに
* 満了時間を設定し直す必要がある
*/
if (is_hwcnt(cntid) && (p_cntcb->cntexpque.p_next == &(p_cntexpinfo->cntexpque))) {
/* 現在設定されている時刻をキャンセル */
(hwcntinib_table[cntid].cancel)();
/* 先頭に挿入した時刻に再設定 */
(hwcntinib_table[cntid].set)(enqval);
p_cntcb->hwset = TRUE;
/*
* 再設定中に次の満了時間を過ぎてしまったかチェック
*
* 過ぎてしまった場合, 強制割込みにより満了処理を実行する
* またsetした時間とgetした時間が同じであった場合,
* ハードウェアで取りこぼしていると想定し, 強制割込みを発生させる
* ハードウェアで取りこぼしていない場合に強制割込みを起こしても問題ない
*/
if (diff_tick((hwcntinib_table[cntid].get)(), enqval,
p_cntcb->p_cntinib->maxval2) <= p_cntcb->p_cntinib->maxval) {
/* 現在設定されている時刻をキャンセル */
(hwcntinib_table[cntid].cancel)();
/* 強制割込みを発生させる */
(hwcntinib_table[cntid].trigger)();
}
}
}
#endif /* TOPPERS_insert_cnt_expr_que */
/*
* カウンタ満了キューから削除
*/
#ifdef TOPPERS_delete_cnt_expr_que
void
delete_cnt_expr_que(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb)
{
CounterType cntid;
QUEUE *p_cntexpque;
/* カウンタキューから満了処理を削除する前の先頭キュー保持 */
p_cntexpque = p_cntcb->cntexpque.p_next;
queue_delete(&(p_cntexpinfo->cntexpque));
queue_initialize(&(p_cntexpinfo->cntexpque));
/*
* ハードウェアカウンタかつ削除する満了処理はカウンタ満了の
* 先頭の場合,タイマをキャンセルする
*/
cntid = CNTID(p_cntcb);
if (is_hwcnt(cntid) && (p_cntcb->cntexpque.p_next != p_cntexpque)) {
/* 現在設定されている時刻をキャンセル */
(hwcntinib_table[cntid].cancel)();
/* ペンディング中の割込み要求をキャンセル */
(hwcntinib_table[cntid].intcancel)();
/*
* p_cntexpinfoで指定された満了処理削除後,カウンタ満了次の
* 満了処理の満了点を設定する
*/
if (queue_empty(&(p_cntcb->cntexpque)) == FALSE) {
/* 先頭に挿入した時刻に再設定 */
(hwcntinib_table[cntid].set)(((CNTEXPINFO *) p_cntcb->cntexpque.p_next)->expiretick);
p_cntcb->hwset = TRUE;
/*
* 再設定中に次の満了時間を過ぎてしまったかチェック
*
* 過ぎてしまった場合, 強制割込みにより満了処理を実行する
* またsetした時間とgetした時間が同じであった場合,
* ハードウェアで取りこぼしていると想定し, 強制割込みを発生させる
* ハードウェアで取りこぼしていない場合に強制割込みを起こしても問題ない
*/
if (diff_tick((hwcntinib_table[cntid].get)(),
((CNTEXPINFO *) p_cntcb->cntexpque.p_next)->expiretick,
p_cntcb->p_cntinib->maxval2) <= p_cntcb->p_cntinib->maxval) {
/* 現在設定されている時刻をキャンセル */
(hwcntinib_table[cntid].cancel)();
/* 強制割込みを発生させる */
(hwcntinib_table[cntid].trigger)();
}
}
}
}
#endif /* TOPPERS_delete_cnt_expr_que */
/*
* カウンタ機能の初期化
*/
#ifdef TOPPERS_counter_initialize
void
counter_initialize(void)
{
CounterType i;
CNTCB *p_cntcb;
for (i = 0U; i < tnum_counter; i++) {
p_cntcb = &(cntcb_table[i]);
p_cntcb->p_cntinib = &(cntinib_table[i]);
p_cntcb->curval = 0U;
queue_initialize(&(p_cntcb->cntexpque));
p_cntcb->cstat = CS_NULL;
}
for (i = 0U; i < tnum_hardcounter; i++) {
(hwcntinib_table[i].init)(cntinib_table[i].maxval2,
hwcntinib_table[i].nspertick);
(hwcntinib_table[i].start)();
}
}
#endif /* TOPPERS_counter_initialize */
/*
* カウンタ機能の終了処理
*/
#ifdef TOPPERS_counter_terminate
void
counter_terminate(void)
{
CounterType i;
for (i = 0U; i < tnum_hardcounter; i++) {
(hwcntinib_table[i].stop)();
}
}
#endif /* TOPPERS_counter_terminate */
/*
* 指定した相対時間からのカウンタ値取得(APIからの取得)
*
* 指定したカウンタの現在値と, 渡された相対値を足しこみ更新値を
* 戻り値として返す
*/
#ifdef TOPPERS_get_reltick
TickType
get_reltick(const CNTCB *p_cntcb, TickType relval)
{
CounterType cntid;
TickType result;
TickType curval;
cntid = CNTID(p_cntcb);
curval = get_curval(p_cntcb, cntid);
/* 現在時間から指定されたオフセット分過ぎた時間を算出する */
result = add_tick(curval, relval, p_cntcb->p_cntinib->maxval2);
return(result);
}
#endif /* TOPPERS_get_reltick */
/*
* 指定した絶対時間からのカウンタ値取得(APIからの取得)
*
* 引数で渡された絶対値を指定したカウンタの現在値に変換し
* 更新値を戻り値として返す
*/
#ifdef TOPPERS_get_abstick
TickType
get_abstick(const CNTCB *p_cntcb, TickType absval)
{
CounterType cntid;
TickType result;
TickType curval;
TickType nextval;
cntid = CNTID(p_cntcb);
curval = get_curval(p_cntcb, cntid);
/* maxval2を考慮した絶対時間に変換 */
nextval = absval + p_cntcb->p_cntinib->maxval + 1U;
if (curval < (p_cntcb->p_cntinib->maxval + 1U)) {
/*
* カウンタの現在値が0〜maxvalの間の場合,
* 絶対時刻に未到達なので,絶対時刻を返す
*/
if (absval > curval) {
result = absval;
}
else {
result = nextval;
}
}
else {
/*
* カウンタの現在値がmaxval〜maxval2の間の場合,
* maxval2考慮した絶対も超えたので,絶対時刻を返す
*/
if (nextval <= curval) {
result = absval;
}
else {
result = nextval;
}
}
return(result);
}
#endif /* TOPPERS_get_abstick */
/*
* カウンタの満了処理
*/
#ifdef TOPPERS_expire_process
void
expire_process(CNTCB *p_cntcb, CounterType cntid)
{
CNTEXPINFO *p_cntexpinfo;
TickType nowval;
p_cntcb->hwset = FALSE;
nowval = get_curval(p_cntcb, cntid);
/*
* カウンタの満了処理
*
* キューが空でなく, リアルタイムな現在時間から見てキューの先頭の満了
* 時間が既に過ぎていれば, 満了処理を実行する
*
* リアルタイムな現在時間をその都度取得するため,キューの先頭満了処理
* の満了時間を再設定する時に目的の満了時間を超えてしまってもカバー
* できる
*/
while ((queue_empty(&(p_cntcb->cntexpque)) == FALSE) &&
(diff_tick(nowval, ((CNTEXPINFO *) p_cntcb->cntexpque.p_next)->expiretick,
p_cntcb->p_cntinib->maxval2) <= p_cntcb->p_cntinib->maxval)) {
/* カウンタ満了キューの先頭の満了処理を,キューから外す */
p_cntexpinfo = (CNTEXPINFO *) p_cntcb->cntexpque.p_next;
queue_delete(&(p_cntexpinfo->cntexpque));
queue_initialize(&(p_cntexpinfo->cntexpque));
if (is_hwcnt(cntid)) {
/*
* 次の満了点の設定
* 次の満了点が実時間を経過していない場合設定する
*/
if ((queue_empty(&(p_cntcb->cntexpque)) == FALSE) && ((diff_tick((hwcntinib_table[cntid].get)(),
((CNTEXPINFO *) p_cntcb->cntexpque.p_next)->expiretick, p_cntcb->p_cntinib->maxval2)) >
p_cntcb->p_cntinib->maxval)) {
(hwcntinib_table[cntid].set)(((CNTEXPINFO *) p_cntcb->cntexpque.p_next)->expiretick);
p_cntcb->hwset = TRUE;
}
}
/* カウンタ満了処理呼出し */
(p_cntexpinfo->expirefunc)(p_cntexpinfo, p_cntcb);
/*
* タスクからの呼び出し時,高優先度タスクレディ状態になった場合あるので,
* チェックしてディスパッチする
*/
if ((p_runtsk != p_schedtsk) && (callevel_stat == TCL_TASK)) {
dispatch();
}
/*
* 割込みレスポンス考慮し,1個の満了点処理後に
* 1回の割込許可/禁止を実施
*/
x_nested_unlock_os_int();
x_nested_lock_os_int();
nowval = get_curval(p_cntcb, cntid);
}
if (is_hwcnt(cntid) && (queue_empty(&(p_cntcb->cntexpque)) == FALSE) && (p_cntcb->hwset == FALSE)) {
(hwcntinib_table[cntid].set)(((CNTEXPINFO *) p_cntcb->cntexpque.p_next)->expiretick);
}
}
#endif /* TOPPERS_expire_process */
<file_sep>#!python
# -*- coding: utf-8 -*-
#
# TOPPERS ATK2
# Toyohashi Open Platform for Embedded Real-Time Systems
# Automotive Kernel Version 2
#
# Copyright (C) 2013-2014 by Center for Embedded Computing Systems
# Graduate School of Information Science, Nagoya Univ., JAPAN
# Copyright (C) 2013-2014 by FUJI SOFT INCORPORATED, JAPAN
# Copyright (C) 2013-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
# Copyright (C) 2013-2014 by Renesas Electronics Corporation, JAPAN
# Copyright (C) 2013-2014 by <NAME> Inc., JAPAN
# Copyright (C) 2013-2014 by TOSHIBA CORPORATION, JAPAN
# Copyright (C) 2013-2014 by Witz Corporation, JAPAN
#
# 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
# ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
# 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
# (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
# 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
# スコード中に含まれていること.
# (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
# 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
# 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
# の無保証規定を掲載すること.
# (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
# 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
# と.
# (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
# 作権表示,この利用条件および下記の無保証規定を掲載すること.
# (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
# 報告すること.
# (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
# 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
# また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
# 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
# 免責すること.
#
# 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
# 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
# はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
# 用する者に対して,AUTOSARパートナーになることを求めている.
#
# 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
# よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
# に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
# アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
# の責任を負わない.
#
# $Id: pre_cfg.py 663 2016-06-30 07:19:44Z ertl-honda $
#
import subprocess
import os
import sys
from System import Threading
# set relative path from top proj
proj_rel_dir = "../"
# call definition file
common.Source(proj_rel_dir + "def.py")
# path
src_abs_path = os.path.abspath(proj_rel_dir + SRCDIR)
# call common file
common.Source(src_abs_path + "/arch/ccrh/common.py")
#
# make command
#
cfg_command = cfg + " --pass 1 " + "--kernel " + CFG_KERNEL
cfg_command += " --api-table " + cfg_api_table
cfg_command += " " + cfg_cfg1_def_tables + cfg_includes
cfg_command += " --ini-file " + cfg_ini_file
cfg_command += " " + cfg_input_str
print cfg_command
#
# stop build
#
def BuildStop():
buid.Stop()
#
# Execute cfg path 1
#
try:
output = subprocess.check_output(cfg_command, stderr=subprocess.STDOUT,)
except subprocess.CalledProcessError, e:
print "ERROR!! : ", e.output
thread = Threading.Thread(Threading.ThreadStart(BuildStop))
thread.IsBackground = True
thread.Start()
print output
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2013-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: prc_inline_symbols.h 829 2017-09-23 02:08:24Z ertl-honda $
*/
/*
* コンパイラ依存定義
*/
#ifndef PRC_INLINE_SYMBOL_H
#define PRC_INLINE_SYMBOL_H
#include "kernel_inline_symbols.h"
/* v850.h */
#pragma inline set_pmr
#pragma inline get_ispr
#pragma inline clear_ispr
/* prc_config.h */
#pragma inline x_lock_all_int
#pragma inline x_unlock_all_int
#pragma inline x_nested_lock_os_int
#pragma inline x_nested_unlock_os_int
#pragma inline x_set_ipm
#pragma inline x_get_ipm
#pragma inline x_disable_int
#pragma inline x_enable_int
#pragma inline x_clear_int
#pragma inline x_probe_int
#pragma inline i_begin_int
#pragma inline i_end_int
/* prc_insn.h */
#pragma inline disable_int
#pragma inline enable_int
#pragma inline current_psw
#pragma inline set_psw
/* prc_sil.h */
#pragma inline sil_reb_mem
#pragma inline sil_wrb_mem
#pragma inline sil_reh_mem
#pragma inline sil_wrh_mem
#pragma inline sil_rew_mem
#pragma inline sil_wrw_mem
#pragma inline TOPPERS_disint
#pragma inline TOPPERS_enaint
/* taua_timer.h */
#pragma inline target_timer_get_current
#pragma inline target_timer_probe_int
/* uart.h */
#pragma inline uart_putc
/* uart.c */
#pragma inline uart_getready
#pragma inline uart_getchar
#endif /* PRC_INLINE_SYMBOL_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2006-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: histogram.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* 実行時間分布集計モジュール
*/
#include "histogram.h"
#include "target_timer.h"
#include "target_test.h"
/*
* 実行時間分布計測の数
*/
#ifndef TNUM_HIST
#define TNUM_HIST 10
#endif /* TNUM_HIST */
/*
* ターゲット依存部で設定変更するためのマクロ
*/
#ifndef HISTTIM /* 実行時間計測用の時刻のデータ型 */
#define HISTTIM SystemTimeUsType
#endif /* HISTTIM */
#ifndef HIST_GET_TIM /* 実行時間計測用の現在時刻の取得 */
#ifndef TOPPERS_SUPPORT_GET_UTM
#error get_utm is not supported
#endif /* TOPPERS_SUPPORT_GET_UTM */
#define HIST_GET_TIM(p_time) ((void) get_utm(p_time))
#endif /* HIST_GET_TIM */
#ifndef HIST_CONV_TIM /* 時刻の差から実行時間への変換 */
#define HIST_CONV_TIM(time) ((uint32) (time))
#endif /* HIST_CONV_TIM */
#ifndef HIST_BM_HOOK /* 実行時間計測直前に行うべき処理 */
#define HIST_BM_HOOK()
#endif /* HIST_BM_HOOK */
LOCAL_INLINE void
get_utm(HISTTIM *p_time)
{
#ifndef GET_UTIM
*p_time = (HISTTIM) get_tim_utime();
#else /* GET_UTIM */
*p_time = (HISTTIM) GET_UTIM();
#endif /* GET_UTIM */
}
/*
* 実行時間分布計測管理ブロック
*/
typedef struct histogram_control_block {
HISTTIM begin_time; /* 計測開始時刻 */
uint32 maxval; /* 分布を記録する最大時間 */
uint32 *histarea; /* 分布を記録するメモリ領域 */
uint32 over; /* 最大時間を超えた度数 */
uint32 under; /* 時間の逆転が疑われる度数 */
boolean initialized; /* 初期化済みかどうかのフラグ */
} HISTCB;
/*
* 実行時間分布計測管理ブロックのエリア
*/
HISTCB histcb_table[TNUM_HIST];
/*
* 実行時間分布計測IDの最小値と最大値
*/
#define TMIN_HISTID 1
#define TMAX_HISTID ((TMIN_HISTID + TNUM_HIST) - 1)
/*
* 実行時間分布計測の初期化
*/
boolean
init_hist(ObjectIDType histid, uint32 maxval, uint32 *histarea)
{
HISTCB *p_histcb;
uint32 i;
boolean ret = TRUE;
/* 不正な分布計測IDの場合FALSEを返す */
if ((histid < TMIN_HISTID) || (histid > TMAX_HISTID)) {
ret = FALSE;
}
else {
p_histcb = &(histcb_table[histid - TMIN_HISTID]);
for (i = 0U; i <= maxval; i++) {
histarea[i] = 0U;
}
p_histcb->maxval = maxval;
p_histcb->histarea = histarea;
p_histcb->over = 0U;
p_histcb->under = 0U;
p_histcb->initialized = TRUE;
}
return(ret);
}
/*
* 実行時間計測の開始
*/
boolean
begin_measure(ObjectIDType histid)
{
HISTCB *p_histcb;
boolean ret = TRUE;
/* 不正な分布計測IDの場合FALSEを返す */
if ((histid < TMIN_HISTID) || (histid > TMAX_HISTID)) {
ret = FALSE;
}
else {
p_histcb = &(histcb_table[histid - TMIN_HISTID]);
/* 初期化していない場合FALSEを返す */
if (p_histcb->initialized == FALSE) {
ret = FALSE;
}
else {
HIST_BM_HOOK();
HIST_GET_TIM(&(p_histcb->begin_time));
}
}
return(ret);
}
/*
* 実行時間計測の終了
*/
boolean
end_measure(ObjectIDType histid)
{
HISTCB *p_histcb;
HISTTIM end_time;
uint32 val;
boolean ret = TRUE;
HIST_GET_TIM(&end_time);
/* 不正な分布計測IDの場合FALSEを返す */
if ((histid < TMIN_HISTID) || (histid > TMAX_HISTID)) {
ret = FALSE;
}
else {
p_histcb = &(histcb_table[histid - TMIN_HISTID]);
/* 初期化していない場合FALSEを返す */
if (p_histcb->initialized == FALSE) {
ret = FALSE;
}
else {
val = HIST_CONV_TIM(end_time - p_histcb->begin_time);
if (val <= p_histcb->maxval) {
p_histcb->histarea[val]++;
}
else if (val <= ((uint32) 0x7fffffff)) {
p_histcb->over++;
}
else {
p_histcb->under++;
}
}
}
return(ret);
}
/*
* 実行時間分布計測の表示
*/
boolean
print_hist(ObjectIDType histid)
{
HISTCB *p_histcb;
uint32 i;
boolean ret = TRUE;
/* 不正な分布計測IDの場合FALSEを返す */
if ((histid < TMIN_HISTID) || (histid > TMAX_HISTID)) {
ret = FALSE;
}
else {
p_histcb = &(histcb_table[histid - TMIN_HISTID]);
/* 初期化していない場合FALSEを返す */
if (p_histcb->initialized == FALSE) {
ret = FALSE;
}
else {
for (i = 0U; i <= p_histcb->maxval; i++) {
if (p_histcb->histarea[i] > 0U) {
#ifndef MEASURE_100_NANO
syslog_2(LOG_NOTICE, "%d : %d", i, p_histcb->histarea[i]);
#else
syslog_3(LOG_NOTICE, "%d.%d : %d", i / 10, i % 10, p_histcb->histarea[i]);
#endif /* MEASURE_100_NANO */
}
}
if (p_histcb->over > 0U) {
syslog_2(LOG_NOTICE, "> %d : %d", p_histcb->maxval, p_histcb->over);
}
if (p_histcb->under > 0U) {
syslog_1(LOG_NOTICE, "> 0x7fffffff : %d", p_histcb->under);
}
}
}
return(ret);
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: serial.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* サンプル向けシリアルIOモジュール
*/
#include "Os.h"
#include "target_serial.h"
#include "target_sysmod.h"
#include "serial.h"
/*
* 受信用データ
*/
static uint8 rx_char;
static boolean rx_flag;
/*
* シリアルIOモジュール初期化処理
*
* 割込み禁止状態で呼出すこと
*/
void
InitSerial(void)
{
/*
* 受信フラグ初期化
*/
rx_flag = FALSE;
/*
* 依存部初期化処理実行
*/
InitHwSerial();
}
/*
* シリアルIOモジュール停止処理
*
* 出力が完了していることは保障しない(デッドロック防止)
* コンテキストロックして出力するので,ほぼ問題なし(最後の2文字のみ)
*
* 割込み禁止状態で呼出すこと
*/
void
TermSerial(void)
{
/*
* 依存部初期化処理実行
*/
TermHwSerial();
/*
* 受信データ無効化
*/
rx_flag = FALSE;
}
/*
* 文字受信処理
*/
void
RecvPolSerialChar(uint8 *character)
{
SuspendAllInterrupts();
if (rx_flag != FALSE) {
/*
* 割込み禁止にして受信データ取得・フラグクリア
*/
*character = rx_char;
rx_flag = FALSE;
}
else {
/*
* 受信データがない場合は'\0'を返す
*/
*character = '\0';
}
ResumeAllInterrupts();
}
/*
* 受信コールバック関数
*/
void
RxSerialInt(uint8 character)
{
/*
* 割込み禁止にして受信データ保持・フラグクリア
*/
SuspendAllInterrupts();
rx_char = character;
rx_flag = TRUE;
ResumeAllInterrupts();
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: scheduletable.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* スケジュールテーブル機能
*/
#ifndef TOPPERS_SCHEDULETABLE_H
#define TOPPERS_SCHEDULETABLE_H
#include "counter.h"
/*
* 満了点テーブル制御用特殊な満了点インデックス
*/
#define EXPPTINDEX_TOP ((uint8) 0x00)
#define EXPPTINDEX_INITIAL ((uint8) 0xff)
/*
* スケジュールテーブルIDからスケジュールテーブル管理ブロックを取り出すためのマクロ
*/
#define get_schtblcb(schtblid) (&(schtblcb_table[(schtblid)]))
/*
* 暗黙同期スケジュールテーブルに関する定義
*/
#define is_implschtbl(schtblid) ((schtblid) < tnum_implscheduletable)
/*
* 個々の満了点テーブル型
*/
typedef struct scheduletable_expire_point_block {
TickType offset; /* オフセット値 */
FunctionRefType expptfnt; /* 満了点処理関数のポインタ */
} SCHTBLEXPPTCB;
/*
* スケジュールテーブル初期化ブロック
*/
typedef struct scheduletable_initialization_block {
CNTCB *p_cntcb; /* 駆動カウンタ管理ブロックのポインタ */
TickType length; /* 周期の長さ */
AppModeType autosta; /* 起動するアプリケーションモード */
AttributeType actatr; /* 自動起動の属性 */
TickType staval; /* 自動起動ティック値 */
const SCHTBLEXPPTCB *p_exppt; /* 満了点テーブルの先頭ポインタ */
boolean repeat; /* 周期制御の有無 */
uint8 tnum_exppt; /* 満了点数 */
} SCHTBLINIB;
/*
* スケジュールテーブル管理ブロック
*/
typedef struct scheduletable_control_block {
CNTEXPINFO cntexpinfo; /* カウンタ満了情報(構造体の先頭に入る必要) */
const SCHTBLINIB *p_schtblinib; /* 初期化ブロックへのポインタ */
struct scheduletable_control_block *p_prevschtblcb; /* 自分をNextにしたスケジュールテーブル管理ブロックへのポインタ */
struct scheduletable_control_block *p_nextschtblcb; /* Nextスケジュールテーブル管理ブロックへのポインタ */
ScheduleTableStatusType status; /* スケジュールテーブル状態 */
uint8 expptindex; /* 満了点インデックス */
} SCHTBLCB;
/*
* 満了処理実行用管理情報
*/
typedef struct scheduletable_expire_info {
SCHTBLCB *p_schtblcb; /* スケジュールテーブル管理ブロックのアドレス */
} SCHTBLEXPINFO;
/*
* スケジュールテーブル数を保持する変数の宣言
*/
extern const ScheduleTableType tnum_scheduletable; /* 全スケジュールテーブルの数 */
extern const ScheduleTableType tnum_implscheduletable; /* 暗黙同期スケジュールテーブル数 */
/*
* スケジュールテーブル初期化ブロックのエリア(Os_Lcfg.c)
*/
extern const SCHTBLINIB schtblinib_table[];
/*
* スケジュールテーブル管理ブロックのエリア(Os_Lcfg.c)
*/
extern SCHTBLCB schtblcb_table[];
/*
* スケジュールテーブルオブジェクトの初期化
*/
extern void schtbl_initialize(void);
/*
* スケジュールテーブル満了処理関数
*/
extern void schtbl_expire(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb);
/*
* 満了処理関数から各タイミング処理の実行
*/
extern void schtbl_expiry_process(SCHTBLEXPINFO *p_schtblexpinfo, const CNTCB *p_cntcb);
/*
* スケジュールテーブルの開始処理
*/
extern boolean schtbl_head(SCHTBLCB *p_schtblcb, const CNTCB *p_cntcb);
/*
* スケジュールテーブルの各満了点処理
*/
extern boolean schtbl_exppoint_process(SCHTBLCB *p_schtblcb, const CNTCB *p_cntcb);
/*
* スケジュールテーブルの終端処理
*/
extern boolean schtbl_tail(SCHTBLCB *p_schtblcb, SCHTBLEXPINFO *p_schtblexpinfo, const CNTCB *p_cntcb);
#endif /* TOPPERS_SCHEDULETABLE_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: v850.h 716 2017-01-19 01:02:05Z ertl-honda $
*/
/*
* V850のハードウェア資源の定義(開発環境共通)
*/
#ifndef TOPPERS_V850_H
#define TOPPERS_V850_H
#ifdef __v850e2v3__
#ifdef _V850E2M_
#define TNUM_INTPRI 16
#elif defined(_V850E2S_)
#define TNUM_INTPRI 8
#else
#error please define ether _V850E2M_ or _V850E2S_
#endif /* _V850E2M_ */
/*
* V850E2用の割込みコントローラ操作ルーチン
*/
#ifndef TOPPERS_MACRO_ONLY
#include "prc_sil.h"
LOCAL_INLINE void
set_pmr(uint16 pmr)
{
sil_wrh_mem((void *) PMR, pmr);
SYNCM;
}
LOCAL_INLINE uint16
get_ispr(void)
{
return(sil_reh_mem((void *) ISPR_H));
}
LOCAL_INLINE void
clear_ispr(void)
{
sil_wrh_mem((void *) ISPC_H, 0xffff);
sil_wrh_mem((void *) ISPR_H, 0x0000);
}
#endif /* TOPPERS_MACRO_ONLY */
#elif defined(__v850e3v5__)
#ifdef _RH850G3M_
#define TNUM_INTPRI 16
#elif defined(_RH850G3K_)
#define TNUM_INTPRI 8
#elif defined(_RH850G3KH_)
#define TNUM_INTPRI 16
#else
#error please define ether _RH850G3M_ or _RH850G3K_ or _RH850G3KH_
#endif /* _RH850G3M_ */
#else /* __v850e3v5__ */
#error please define ether __v850e2v3__ or __v850e3v5__
#endif /* __v850e2v3__ */
#endif /* TOPPERS_V850_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2005-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: check.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* エラーチェック用マクロ
*/
#ifndef TOPPERS_CHECK_H
#define TOPPERS_CHECK_H
#include "Os_Cfg.h"
/*
* 汎用チェックマクロ
*/
#define CHECK_ERROR_ERCD(exp, error) \
do { \
if (!(exp)) { \
ercd = (error); \
goto error_exit; \
} \
} while (0)
#define CHECK_ERROR_NO_ERCD(exp) \
do { \
if (!(exp)) { \
goto error_exit; \
} \
} while (0)
#define D_CHECK_ERROR_ERCD(exp, error) \
do { \
if (!(exp)) { \
ercd = (error); \
goto d_error_exit; \
} \
} while (0)
#define D_CHECK_ERROR_NO_ERCD(exp) \
do { \
if (!(exp)) { \
goto d_error_exit; \
} \
} while (0)
/*
* 標準エラーのチェックマクロ
*/
#define S_CHECK_ERROR(exp, error) CHECK_ERROR_ERCD(exp, error)
#ifdef CFG_USE_ERRORHOOK
/*
* エラーフック使用有無によるラベルの再定義
*/
#define error_exit exit_errorhook
#define d_error_exit d_exit_errorhook
/*
* エラーフックを使用する時はエラーコードを代入する
*/
#define S_N_CHECK_ERROR(exp, error) CHECK_ERROR_ERCD(exp, error)
#else /* CFG_USE_ERRORHOOK */
/*
* エラーフック使用有無によるラベルの再定義
*/
#define error_exit exit_no_errorhook
#define d_error_exit d_exit_no_errorhook
/*
* エラーフックを使用しない時はエラーコードを代入しない
*/
#define S_N_CHECK_ERROR(exp, error) CHECK_ERROR_NO_ERCD(exp)
#endif /* CFG_USE_ERRORHOOK */
/* 以下のチェックマクロをOS内部で用いる */
/*
* エラーコードに対応したマクロ
* 標準エラー
*/
#ifdef OMIT_STANDARD_DISALLINT
#define S_CHECK_DISALLINT()
#define S_N_CHECK_DISALLINT()
#else /* OMIT_STANDARD_DISALLINT */
#define S_CHECK_DISALLINT() \
S_CHECK_ERROR( \
((callevel_stat & TSYS_DISALLINT) == TSYS_NULL), \
E_OS_DISABLEDINT \
)
#define S_N_CHECK_DISALLINT() \
S_N_CHECK_ERROR( \
((callevel_stat & TSYS_DISALLINT) == TSYS_NULL), \
E_OS_DISABLEDINT \
)
#endif /* OMIT_STANDARD_DISALLINT */
#define S_CHECK_STATE(exp) S_CHECK_ERROR(exp, E_OS_STATE)
#define S_N_CHECK_STATE(exp) S_N_CHECK_ERROR(exp, E_OS_STATE)
#define S_CHECK_LIMIT(exp) S_CHECK_ERROR(exp, E_OS_LIMIT)
#define S_N_CHECK_LIMIT(exp) S_N_CHECK_ERROR(exp, E_OS_LIMIT)
#define S_D_CHECK_NOFUNC(exp) D_CHECK_ERROR_ERCD(exp, E_OS_NOFUNC)
#define S_D_CHECK_STATE(exp) D_CHECK_ERROR_ERCD(exp, E_OS_STATE)
#define S_D_CHECK_LIMIT(exp) D_CHECK_ERROR_ERCD(exp, E_OS_LIMIT)
/*
* エラーコードに対応したマクロ
* 拡張エラー
*/
#ifdef CFG_USE_EXTENDEDSTATUS
#define CHECK_ACCESS(exp) CHECK_ERROR_ERCD(exp, E_OS_ACCESS)
#define D_CHECK_ACCESS(exp) D_CHECK_ERROR_ERCD(exp, E_OS_ACCESS)
#define CHECK_CALLEVEL(clmask) \
CHECK_ERROR_ERCD( \
((callevel_stat | (clmask)) == (clmask)), \
E_OS_CALLEVEL \
)
#define CHECK_NOFUNC(exp) CHECK_ERROR_ERCD(exp, E_OS_NOFUNC)
#define CHECK_RESOURCE(exp) CHECK_ERROR_ERCD(exp, E_OS_RESOURCE)
#define CHECK_STATE(exp) CHECK_ERROR_ERCD(exp, E_OS_STATE)
#define D_CHECK_STATE(exp) D_CHECK_ERROR_ERCD(exp, E_OS_STATE)
#define CHECK_VALUE(exp) CHECK_ERROR_ERCD(exp, E_OS_VALUE)
#define CHECK_DISABLEDINT() \
CHECK_ERROR_ERCD( \
((callevel_stat & \
(TSYS_DISALLINT | TSYS_SUSALLINT | TSYS_SUSOSINT)) == \
TSYS_NULL \
), \
E_OS_DISABLEDINT \
)
#define CHECK_PARAM_POINTER(p_exp) CHECK_ERROR_ERCD(((p_exp) != NULL), OS_E_PARAM_POINTER)
#define CHECK_ID(exp) CHECK_ERROR_ERCD(exp, E_OS_ID)
#else /* CFG_USE_EXTENDEDSTATUS */
#define CHECK_ACCESS(exp)
#define D_CHECK_ACCESS(exp)
#define CHECK_CALLEVEL(clmask)
#define CHECK_NOFUNC(exp)
#define CHECK_RESOURCE(exp)
#define D_CHECK_STATE(exp)
#define CHECK_VALUE(exp)
#define CHECK_DISABLEDINT()
#define CHECK_PARAM_POINTER(p_exp)
#define CHECK_ID(exp)
#endif /* CFG_USE_EXTENDEDSTATUS */
#endif /* TOPPERS_CHECK_H */
<file_sep>#!python
# -*- coding: utf-8 -*-
#
# TOPPERS ATK2
# Toyohashi Open Platform for Embedded Real-Time Systems
# Automotive Kernel Version 2
#
# Copyright (C) 2015 by Center for Embedded Computing Systems
# Graduate School of Information Science, Nagoya Univ., JAPAN
#
# 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
# ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
# 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
# (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
# 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
# スコード中に含まれていること.
# (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
# 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
# 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
# の無保証規定を掲載すること.
# (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
# 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
# と.
# (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
# 作権表示,この利用条件および下記の無保証規定を掲載すること.
# (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
# 報告すること.
# (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
# 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
# また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
# 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
# 免責すること.
#
# 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
# 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
# はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
# 用する者に対して,AUTOSARパートナーになることを求めている.
#
# 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
# よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
# に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
# アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
# の責任を負わない.
#
# $Id: target.py 38 2014-07-19 06:32:10Z ertl-honda $
#
MAIN_CLK = '16000'
INCLUDES = INCLUDES + ["target/hsbrh850f1k_ccrh", "target/hsbrh850f1k_gcc"]
statup_file = 'arch/v850_ccrh/start.asm'
kernel_target_files = ['target/hsbrh850f1k_gcc/target_config.c','arch/v850_gcc/tauj_hw_counter.c','arch/v850_gcc/uart_rlin.c','arch/v850_gcc/rh850_f1k.c' ]
link_option = 'RESET,EIINTTBL,.const,.INIT_DSEC.const,.INIT_BSEC.const,.text,.data/00000000,.data.R,.bss,.stack.bss/FEBD0000'
# soucre prc file
execfile(srcdir + "arch/v850_ccrh/prc.py")
<file_sep>#! ruby -Ku
if ARGV.size != 1 then
puts "Argment Error!"
exit
end
#Input from gcc file
begin
gcc_asm_file = open(ARGV[0])
rescue
puts "File Open Error!"
exit
end
cx_asm = ""
#Convert
while line = gcc_asm_file.gets
line = line.gsub('.section .reset.text', "RESET .cseg text")
line = line.sub('/*', ';/*')
line = line.sub(/^(\s*)\*/, '\1;*')
line = line.sub(/.macro\s+(\w+)/, '\1 .macro')
line = line.sub(/#include\s+[<"](.+)[>"]/, '$include (\1)')
line = line.sub('.global', '.extern')
line = line.gsub(/AMARG\((\w+)\)/, '\1')
line = line.gsub(/FLABEL\((\w+)\)/, '\1:')
line = line.gsub('~', '!')
line = line.gsub('#ifdef', '$ifdef')
line = line.gsub('#ifndef', '$ifndef')
line = line.gsub('#endif', '$endif')
line = line.gsub('#else', '$else')
line = line.gsub('.section', '.cseg')
line = line.gsub(/\.endr/i, '.endm')
line = line.gsub(/\.text/i, 'text')
line = line.gsub(/\b_fe_exception_entry\b/,'_kernel_fe_exception_entry')
line = line.gsub(/\b_ei_exception_entry\b/,'_kernel_ei_exception_entry')
line = line.gsub(/\b_interrupt\b/,'_kernel_interrupt')
line = line.gsub(/\b_exit_and_dispatch\b/,'_kernel_exit_and_dispatch')
line = line.gsub(/\b_start_dispatch\b/,'_kernel_start_dispatch')
line = line.gsub(/\b _dispatch\b/,' _kernel_dispatch')
line = line.gsub(/\b_dispatch\b/,'_kernel_dispatch')
line = line.gsub(/\b_start_r\b/,'_kernel_start_r')
line = line.gsub(/\b_stack_change_and_call_func_1\b/,'_kernel_stack_change_and_call_func_1')
line = line.gsub(/\b_stack_change_and_call_func_2\b/,'_kernel_stack_change_and_call_func_2')
line = line.gsub(/\b_return_main\b/,'_kernel_return_main')
line = line.gsub(/\b_ostk\b/,'_kernel_ostk')
line = line.gsub(/\b_ostkpt\b/,'_kernel_ostkpt')
line = line.gsub(/\b_except_nest_cnt\b/,'_kernel_except_nest_cnt')
line = line.gsub(/\b_nested_lock_os_int_cnt\b/,'_kernel_nested_lock_os_int_cnt')
line = line.gsub(/\b_current_iintpri\b/,'_kernel_current_iintpri')
line = line.gsub(/\b_pmr_setting_tbl\b/,'_kernel_pmr_setting_tbl')
line = line.gsub(/\b_pmr_isr1_mask\b/,'_kernel_pmr_isr1_mask')
line = line.gsub(/\b_pmr_isr2_mask\b/,'_kernel_pmr_isr2_mask')
line = line.gsub(/\b_v850_cpu_exp_sp\b/,'_kernel_v850_cpu_exp_sp')
line = line.gsub(/\b_v850_cpu_exp_no\b/,'_kernel_v850_cpu_exp_no')
line = line.gsub(/\b_v850_cpu_exp_pc\b/,'_kernel_v850_cpu_exp_pc')
line = line.gsub(/\b_call_protectionhk_main\b/,'_kernel_call_protectionhk_main')
line = line.gsub(/\b_kerflg\b/,'_kernel_kerflg')
line = line.gsub(/\b_isr_p_isrcb_tbl\b/,'_kernel_isr_p_isrcb_tbl')
line = line.gsub(/\b_exit_task\b/,'_kernel_exit_task')
line = line.gsub(/\b_p_runtsk\b/,'_kernel_p_runtsk')
line = line.gsub(/\b_p_runisr\b/,'_kernel_p_runisr')
line = line.gsub(/\b_default_int_handler\b/,'_kernel_default_int_handler')
line = line.gsub(/\b_call_pretaskhook\b/,'_kernel_call_pretaskhook')
line = line.gsub(/\b_call_posttaskhook\b/,'_kernel_call_posttaskhook')
line = line.gsub(/\b_exit_isr2\b/,'_kernel_exit_isr2')
line = line.gsub(/\b_callevel_stat\b/,'_kernel_callevel_stat')
line = line.gsub(/\b_p_schedtsk\b/,'_kernel_p_schedtsk')
line = line.gsub(/\b_isr_tbl\b/,'_kernel_isr_tbl')
cx_asm = cx_asm + line
end
cx_asm_file_name = File::basename(ARGV[0].sub(".S", ".asm"))
print sprintf("Output %s\n", cx_asm_file_name)
#Output to asm file
File.open(cx_asm_file_name, 'w') {|file|
file.write cx_asm
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: rh850_f1l.h 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* RH850/F1Lのハードウェア資源の定義
*/
#ifndef TOPPERS_RH850_F1L_H
#define TOPPERS_RH850_F1L_H
#define _RH850G3K_
/*
* 保護コマンドレジスタ
*/
#define PROTCMD0 0xFFF80000
#define PROTCMD1 0xFFF88000
#define CLMA0PCMD 0xFFF8C010
#define CLMA1PCMD 0xFFF8D010
#define CLMA2PCMD 0xFFF8E010
#define PROTCMDCLMA 0xFFF8C200
#define JPPCMD0 0xFFC204C0
#define PPCMD0 0xFFC14C00
#define PPCMD1 0xFFC14C04
#define PPCMD2 0xFFC14C08
#define PPCMD8 0xFFC14C20
#define PPCMD9 0xFFC14C24
#define PPCMD10 0xFFC14C28
#define PPCMD11 0xFFC14C2C
#define PPCMD12 0xFFC14C30
#define PPCMD18 0xFFC14C48
#define PPCMD20 0xFFC14C50
#define PROTCMDCVM 0xFFF50100
#define FLMDPCMD 0xFFA00004
/*
* 保護ステータスレジスタ
*/
#define PROTS0 0xFFF80004
#define PROTS1 0xFFF88004
#define CLMA0PS 0xFFF8C014
#define CLMA1PS 0xFFF8D014
#define CLMA2PS 0xFFF8E014
#define PROTSCLMA 0xFFF8C204
#define JPPROTS0 0xFFC204B0
#define PPROTS0 0xFFC14B00
#define PPROTS1 0xFFC14B04
#define PPROTS2 0xFFC14B08
#define PPROTS8 0xFFC14B20
#define PPROTS9 0xFFC14B24
#define PPROTS10 0xFFC14B28
#define PPROTS11 0xFFC14B2C
#define PPROTS12 0xFFC14B30
#define PPROTS18 0xFFC14B48
#define PPROTS20 0xFFC14B50
#define PROTSCVM 0xFFF50104
#define FLMDPS 0xFFA00008
/*
* 保護コマンドレジスタの番号
*/
#define PNO_CtrlProt0 0
#define PNO_CtrlProt1 1
#define PNO_ClkMonitorCtrlProt0 2
#define PNO_ClkMonitorCtrlProt1 3
#define PNO_ClkMonitorCtrlProt2 4
#define PNO_ClkMonitorTestProt 5
#define PNO_PortProt1_0 6
#define PNO_PortProt1_1 7
#define PNO_PortProt1_2 8
#define PNO_PortProt1_8 9
#define PNO_PortProt1_9 10
#define PNO_PortProt1_10 11
#define PNO_PortProt1_11 12
#define PNO_PortProt1_12 13
#define PNO_PortProt1_18 14
#define PNO_PortProt1_20 15
#define PNO_PortProt2 16
#define PNO_CoreVMonitorProt 17
#define PNO_SelfProgProt 18
/*
* PORTレジスタ
*/
#define PORT_BASE UINT_C(0xffc10000)
/* 端子機能設定 (USE)*/
#define PMC(n) ((PORT_BASE) + 0x0400 + (n * 0x04U)) /* ポート・モード・コントロール・レジスタ */
#define PMCSR(n) ((PORT_BASE) + 0x0900 + (n * 0x04U)) /* ポート・モード・コントロール・セット/リセット・レジスタ */
#define PIPC(n) ((PORT_BASE) + 0x4200 + (n * 0x04U)) /* ポートIP コントロール・レジスタ */
#define PM(n) ((PORT_BASE) + 0x0300 + (n * 0x04U)) /* ポート・モード・レジスタ */
#define PMSR(n) ((PORT_BASE) + 0x0800 + (n * 0x04U)) /* ポート・モード・セット/リセット・レジスタ */
#define PIBC(n) ((PORT_BASE) + 0x4000 + (n * 0x04U)) /* ポート入力バッファ・コントロール・レジスタ */
#define PFC(n) ((PORT_BASE) + 0x0500 + (n * 0x04U)) /* ポート機能コントロール・レジスタ */
#define PFCE(n) ((PORT_BASE) + 0x0600 + (n * 0x04U)) /* ポート機能コントロール・レジスタ */
#define PFCAE(n) ((PORT_BASE) + 0x0A00 + (n * 0x04U)) /* ポート機能コントロール・拡張レジスタ */
/* 端子データ入力/出力 (USE)*/
#define PBDC(n) ((PORT_BASE) + 0x4100 + (n * 0x04U)) /* ポート双方向コントロール・レジスタ */
#define PPR(n) ((PORT_BASE) + 0x0200 + (n * 0x04U)) /* ポート端子リード・レジスタ */
#define P(n) ((PORT_BASE) + 0x0000 + (n * 0x04U)) /* ポート・レジスタ */
#define PNOT(n) ((PORT_BASE) + 0x0700 + (n * 0x04U)) /* ポート・ノット・レジスタ */
#define PSR(n) ((PORT_BASE) + 0x0100 + (n * 0x04U)) /* ポート・セット/リセット・レジスタ */
/*
* PLL関連のレジスタと定義
*/
/* Main OSC */
#define MOSCE 0xfff81100
#define MOSCS 0xfff81104
#define MOSCC 0xfff81108
#define MOSCST 0xfff8110c
#define MOSCSTPM 0xfff81118
/* Sub OSC */
#define SOSCE 0xfff81200
#define SOSCS 0xfff81204
/* PLL */
#define PLLE 0xfff89000
#define PLLS 0xfff89004
#define PLLC 0xfff89008
#define CKSC_CPUCLKS_CTL 0xfff8a000
#define CKSC_CPUCLKS_ACT 0xfff8a008
#define CKSC_CPUCLKD_CTL 0xfff8a100
#define CKSC_CPUCLKD_ACT 0xfff8a108
#define CKSC_ATAUJS_CTL 0xfff82100
#define CKSC_ATAUJS_ACT 0xfff82108
#define CKSC_ATAUJD_CTL 0xfff82200
#define CKSC_ATAUJD_ACT 0xfff82208
#define MHz(n) ((n) * 1000 * 1000)
#define CLK_MHz(num) (num * 1000 * 1000)
/* xxxS Register (USE) */
#define CLK_S_STPACK 0x08
#define CLK_S_CLKEN 0x04
#define CLK_S_CLKACT 0x02
#define CLK_S_CLKSTAB 0x01
/* Return Parameter */
#define UC_SUCCESS 0
#define UC_ERROR 1
#define UC_INVALIDPARAM 2
#define UC_PROTREGERROR 3
#define UC_CLKSTATUSERR 4
#define UC_CLKNOTENABLE 5
#define UC_CLKNOTACTIVE 6
#define UC_CLKNOTSTAB 7
/*
* INTC
*/
#define INTC1_BASE 0xFFFF9000
#define INTC2_BASE 0xFFFFA000
#define INTC2_EIC 0x040
#define INTC2_EIBD 0x880
#define INTC2_INTNO_OFFSET 32
/* intno は unsigned を想定 */
#define EIC_ADDRESS(intno) (intno <= 31) ? (INTC1_BASE + (intno * 2)) : (INTC2_BASE + INTC2_EIC + ((intno - INTC2_INTNO_OFFSET) * 2))
#define TMIN_INTNO UINT_C(0)
#define TMAX_INTNO UINT_C(287)
#define TNUM_INT UINT_C(288)
#define RLIN30_BASE 0xffcf0000
#define RLIN31_BASE 0xffcf0040
#define RLIN32_BASE 0xffcf0080
#define RLIN33_BASE 0xffcf00c0
#define RLIN34_BASE 0xffcf0100
#define RLIN35_BASE 0xffcf0140
/*
* INTNO
*/
#define RLIN31_TX_INTNO UINT_C(113)
#define RLIN31_RX_INTNO UINT_C(114)
#define RLIN32_TX_INTNO UINT_C(157)
#define RLIN32_RX_INTNO UINT_C(158)
#define RLIN32_ER_INTNO UINT_C(159)
#define RLIN35_TX_INTNO UINT_C(229)
#define RLIN35_RX_INTNO UINT_C(230)
#define RLIN35_ER_INTNO UINT_C(231)
#define TAUFJ0I0_INTNO UINT_C(72)
#define TAUFJ0I1_INTNO UINT_C(73)
#define TAUFJ0I2_INTNO UINT_C(74)
#define TAUFJ0I3_INTNO UINT_C(75)
#define TAUFJ1I0_INTNO UINT_C(160)
#define TAUFJ1I1_INTNO UINT_C(161)
#define TAUFJ1I2_INTNO UINT_C(162)
#define TAUFJ1I3_INTNO UINT_C(163)
#ifndef TOPPERS_MACRO_ONLY
extern uint32 EnableSubOSC(void);
extern uint32 EnableMainOSC(uint32 clk_in);
extern uint32 EnablePLL(void);
extern uint32 SetClockSelection(uint32 s_control, uint32 s_status, uint8 regno, uint16 sel,
uint32 d_control, uint32 d_status, uint8 divider);
#endif /* TOPPERS_MACRO_ONLY */
#include "v850.h"
#endif /* TOPPERS_RH850_F1L_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: v850e2_fx4.c 540 2015-12-29 01:00:01Z ertl-honda $
*/
#include "kernel_impl.h"
#include "v850e2_fx4.h"
#include "Os.h"
#include "prc_sil.h"
/*******************************************************************************************/
/* Outline : Write protected register */
/* Argument : Register address */
/* Register data */
/* Register No */
/* Return value : 0: write success / 1: write error */
/* Description : Write protected register */
/* */
/*******************************************************************************************/
static uint32
write_protected_reg(uint32 addr, uint32 data, uint8 regno)
{
uint32 reg_top = 0xff420000;
uint32 reg_stat;
uint8 wk;
SIL_PRE_LOC;
if (regno > 2) {
return(UC_INVALIDPARAM);
}
switch (regno) {
case 0:
reg_top += 0x4000; /* PROTCMD0 */
break;
case 1:
reg_top += 0x8000; /* PROTCMD1 */
break;
case 2:
reg_top += 0x0300; /* PROTCMD2 */
break;
}
reg_stat = reg_top + 4; /* PROTS0/PROTS1/PROTS2 */
SIL_LOC_INT();
sil_wrb_mem((void *) reg_top, 0xA5);
sil_wrw_mem((void *) addr, data);
sil_wrw_mem((void *) addr, ~data);
sil_wrw_mem((void *) addr, data);
SIL_UNL_INT();
wk = sil_reb_mem((void *) reg_stat);
wk &= 0x01;
return((wk == 0) ? UC_SUCCESS : UC_PROTREGERROR);
} /* write_protected_reg */
/********************************************************************************************/
/* Function Name : V850Drv_nop */
/* Input : none */
/* Output : none */
/* Description : nop command */
/********************************************************************************************/
static void
V850Drv_nop(void)
{
Asm("nop");
} /* V850Drv_nop */
/*******************************************************************************************/
/* Outline : Sub Oscillator enable */
/* Argument : - */
/* Return value : 0: successfly set / 1: set error */
/* Description : Sub Oscillator register setting */
/* */
/*******************************************************************************************/
uint32
EnableSubOSC(void)
{
uint32 ucret;
sil_wrw_mem((void *) SOSCST, 0x02); /* stabilization time -> 262ms */
ucret = write_protected_reg(SOSCE, 0x01, PROT_SOSCE); /* SubOSC start */
if (ucret != UC_SUCCESS) return(ucret);
while (((sil_rew_mem((void *) SOSCS)) & CLK_S_CLKSTAB) == 0) { /* Wait stabilization */
V850Drv_nop();
}
return(UC_SUCCESS);
} /* EnableSubOSC */
/*******************************************************************************************/
/* Outline : Main Oscillator enable */
/* Argument : Main Cscillator frequency(Hz) */
/* Return value : 0: successfly set / 1: set error */
/* Description : Main Oscillator register setting */
/* */
/*******************************************************************************************/
uint32
EnableMainOSC(uint32 clk_in)
{
uint8 ampsel;
uint32 ucret;
if (clk_in == CLK_MHz(4)) {
ampsel = 0x03;
}
else if (CLK_MHz(4) < clk_in && clk_in <= CLK_MHz(8)) {
ampsel = 0x02;
}
else if (CLK_MHz(8) < clk_in && clk_in <= CLK_MHz(16)) {
ampsel = 0x01;
}
else if (CLK_MHz(16) < clk_in && clk_in <= CLK_MHz(20)) {
ampsel = 0x00;
}
else {
return(UC_INVALIDPARAM);
}
sil_wrw_mem((void *) MOSCC, 0x00 | ampsel); /* Normal stabilization time mode */
sil_wrw_mem((void *) MOSCST, 0x0F); /* stabilization time -> Max */
ucret = write_protected_reg(MOSCE, 0x01, PROT_MOSCE); /* MainOSC start */
if (ucret != UC_SUCCESS) return(ucret);
while (((sil_rew_mem((void *) MOSCS)) & CLK_S_CLKSTAB) == 0) { /* Wait stabilization */
V850Drv_nop();
}
return(UC_SUCCESS);
} /* EnableMainOSC */
/*******************************************************************************************/
/* Outline : PLL enable */
/* Argument : PLL No */
/* Multiplying rate */
/* Register data */
/* Return value : 0: successfly set / 1: set error */
/* Description : PLL register setting */
/* */
/*******************************************************************************************/
static uint32
EnablePLL(uint32 pllno, uint8 clk_mul, uint8 p_val)
{
uint32 ucret;
if (clk_mul > 50)
return(UC_INVALIDPARAM);
sil_wrw_mem((void *) PLLC(pllno), (0x800000 | (p_val << 8) | (clk_mul - 1))); /* PLL Mode, P, Nr */
sil_wrw_mem((void *) PLLST(pllno), 0x07); /* stabilization time -> Max */
ucret = write_protected_reg(PLLE(pllno), 0x01, PROT_PLLE); /* PLL Start */
if (ucret != UC_SUCCESS)
return(ucret);
while (((sil_rew_mem((void *) PLLS(pllno))) & CLK_S_CLKSTAB) == 0) { /* Wait stabilization */
/* V850Drv_nop(); */
}
return(UC_SUCCESS);
} /* EnablePLL */
/*******************************************************************************************/
/* Outline : Set PLL frequency */
/* Argument : PLL select No */
/* PLL frequency */
/* PLL frequency */
/* Return value : 0: successfly set / 1: set error */
/* Description : Set PLL register from frequency */
/* */
/*******************************************************************************************/
uint32
SetPLL(uint32 pllno, uint32 mhz, uint32 *outclk)
{
uint32 mul;
if (mhz < 20) {
return(UC_ERROR);
}
else if (mhz < 50) {
mul = (mhz / MAINOSC_CLOCK) * 4;
if (mul <= 5 && 51 <= mul)
return(UC_ERROR);
*outclk = MAINOSC_CLOCK * mul / 4;
return(EnablePLL(pllno, mul, PDIV4R0_025TO050));
}
else if (mhz < 100) {
mul = (mhz / MAINOSC_CLOCK) * 2;
if (mul <= 5 && 51 <= mul)
return(UC_ERROR);
*outclk = MAINOSC_CLOCK * mul / 2;
return(EnablePLL(pllno, mul, PDIV2R0_050TO100));
}
else if (mhz < 200) {
mul = (mhz / MAINOSC_CLOCK) * 1;
if (mul <= 5 && 51 <= mul)
return(UC_ERROR);
*outclk = MAINOSC_CLOCK * mul / 1;
return(EnablePLL(pllno, mul, PDIV1R0_100TO200));
}
else if (mhz < 400) {
mul = (mhz / MAINOSC_CLOCK) / 2;
if (mul <= 5 && 51 <= mul)
return(UC_ERROR);
*outclk = MAINOSC_CLOCK * mul * 2;
return(EnablePLL(pllno, mul, PDIV0R5_200TO400));
}
return(UC_ERROR);
} /* SetPLL */
/*******************************************************************************************/
/* Outline : Clock switcher setting */
/* Argument : Control reginster address */
/* Status reginster address */
/* Register No */
/* Select No */
/* Return value : 0: successfly set / 1: set error */
/* Description : Select clock source of CKSCLK_mn */
/* */
/*******************************************************************************************/
uint32
set_clock_selection(uint32 control, uint32 status, uint8 regno, uint16 sel)
{
uint32 ucret;
ucret = write_protected_reg(control, sel << 1, regno);
if (ucret != UC_SUCCESS) {
return(ucret);
}
/* Wait for SelectEnable */
while (((sil_rew_mem((void *) status)) & 0x01) == 0) {
V850Drv_nop();
}
return(UC_SUCCESS);
} /* set_clock_selection */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: counter.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* カウンタ機能
*/
#ifndef TOPPERS_COUNTER_H
#define TOPPERS_COUNTER_H
#include "queue.h"
/*
* カウンタ状態の定義
* IncrementCounterのネスト防止策
*/
#define CS_NULL (FALSE) /* 非操作中 */
#define CS_DOING (TRUE) /* 操作中 */
/*
* カウンタIDからカウンタ管理ブロックを取り出すためのマクロ
*/
#define get_cntcb(cntid) (&(cntcb_table[(cntid)]))
/*
* カウンタIDでハードウェアカウンタかチェック用マクロ
*/
#define is_hwcnt(cntid) ((cntid) < tnum_hardcounter)
/*
* CNTCBからカウンタIDを取り出すためのマクロ
*/
#define CNTID(p_cntcb) ((CounterType) ((p_cntcb) - cntcb_table))
/*
* 満了アクションの属性
*/
#define ACTIVATETASK UINT_C(0x01) /* タスク起動 */
#define SETEVENT UINT_C(0x02) /* イベントセット */
#define CALLBACK UINT_C(0x04) /* コールバック */
#define INCREMENTCOUNTER UINT_C(0x08) /* カウンタインクリメント */
/*
* 自動起動の属性
*/
#define ABSOLUTE UINT_C(0x10) /* 絶対値起動 */
#define RELATIVE UINT_C(0x20) /* 相対値起動 */
/*
* 各ハードウェアカウンタ処理関数型
*/
typedef void (*HardwareCounterInitRefType)(TickType maxval, TimeType nspertick); /* 初期化関数型 */
typedef void (*HardwareCounterStartRefType)(void); /* 開始関数型 */
typedef void (*HardwareCounterStopRefType)(void); /* 停止関数型 */
typedef void (*HardwareCounterSetRefType)(TickType exprtick); /* 時間設定関数型 */
typedef TickType (*HardwareCounterGetRefType)(void); /* 時間取得関数型 */
typedef void (*HardwareCounterCancelRefType)(void); /* 設定時間取消関数型 */
typedef void (*HardwareCounterTriggerRefType)(void); /* 強制割込み要求関数型 */
typedef void (*HardwareCounterIntClearRefType)(void); /* 割込み要求クリア関数型 */
typedef void (*HardwareCounterIntCancelRefType)(void); /* 割込み要求取消関数型 */
typedef void (*HardwareCounterIncrementRefType)(void); /* インクリメント関数型 */
/*
* ハードウェアカウンタ処理関数型
*/
typedef struct hardware_counter_initialization_block {
HardwareCounterInitRefType init; /* 初期化関数ポインタ */
HardwareCounterStartRefType start; /* 開始関数ポインタ */
HardwareCounterStopRefType stop; /* 停止関数ポインタ */
HardwareCounterSetRefType set; /* 時間設定関数ポインタ */
HardwareCounterGetRefType get; /* 時間取得関数ポインタ*/
HardwareCounterCancelRefType cancel; /* 時間取消関数ポインタ */
HardwareCounterTriggerRefType trigger; /* 強制割込み要求関数ポインタ */
HardwareCounterIntClearRefType intclear; /* 割込み要求クリア関数型 */
HardwareCounterIntCancelRefType intcancel; /* 割込み要求取消関数型 */
HardwareCounterIncrementRefType increment; /* インクリメント関数ポインタ */
TimeType nspertick; /* ハードウェアカウンタでの1ティックの重み(ns単位) */
} HWCNTINIB;
/*
* カウンタ初期化ブロック
*/
typedef struct counter_initialization_block {
TickType maxval; /* カウンタの最大値 */
TickType maxval2; /* カウンタの最大値の2倍+1 */
TickType tickbase; /* OS内部では使用せず,ユーザが自由に使用する値 */
TickType mincyc; /* 周期の最小値 */
} CNTINIB;
/*
* カウンタ管理ブロック
*/
typedef struct counter_control_block {
QUEUE cntexpque; /* カウンタ満了キュー */
const CNTINIB *p_cntinib; /* カウンタ初期化ブロックポインタ */
TickType curval; /* カウンタの現在ティック */
boolean cstat; /* カウンタ操作中フラグ */
boolean hwset; /* ハードウェアカウンタセットフラグ */
} CNTCB;
/*
* カウンタ満了情報
*/
typedef struct counter_expire_info CNTEXPINFO;
/*
* 満了処理関数型
*/
typedef void (*EXPFP)(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb);
/*
* カウンタ満了情報
*/
struct counter_expire_info {
QUEUE cntexpque; /* カウンタ満了キュー(構造体の先頭に入る必要) */
TickType expiretick; /* 満了するカウンタ上のティック値 */
EXPFP expirefunc; /* 満了処理関数ポインタ */
};
/*
* ハードウェアカウンタ数を保持する変数の宣言(Os_Lcfg.c)
*/
extern const CounterType tnum_hardcounter;
/*
* カウンタ数を保持する変数の宣言(Os_Lcfg.c)
*/
extern const CounterType tnum_counter;
/*
* カウンタ初期化ブロックのエリア(Os_Lcfg.c)
*/
extern const CNTINIB cntinib_table[];
/*
* カウンタ管理ブロックのエリア(Os_Lcfg.c)
*/
extern CNTCB cntcb_table[];
/*
* ハードウェアカウンタ処理関数テーブル(Os_Lcfg.c)
*/
extern const HWCNTINIB hwcntinib_table[];
/*
* ティック値の加算
*/
LOCAL_INLINE TickType
add_tick(TickType val, TickType incr, TickType maxval2)
{
TickType result;
/*
* 素直な条件式は val + incr <= maxval2 であるが,この条件式で
* は,val + incr が TickType で表せる範囲を超える場合に正しく
* 判定できなくなるため,次の条件式としている
*/
if (incr <= (maxval2 - val)) {
result = val + incr;
}
else {
/*
* 下の計算式で,val + incr と maxval2 + 1 が TickType で表
* せる範囲を超える場合があるが,オーバフローしても求まる値は
* 正しいため差し支えない
*/
result = (val + incr) - (maxval2 + 1U);
}
return(result);
}
/*
* ティック値の差
*/
LOCAL_INLINE TickType
diff_tick(TickType val1, TickType val2, TickType maxval2)
{
TickType result;
if (val1 >= val2) {
result = val1 - val2;
}
else {
/*
* 下の計算式で,val1 - val2 と maxval2 + 1 が TickType で表せ
* る範囲を超える場合があるが,オーバフローしても求まる値は正
* しいため差し支えない
*/
result = (val1 - val2) + (maxval2 + 1U);
}
return(result);
}
/*
* カウンタの現在値取得
* ソフトウェアカウンタの場合, CNTCBのcurvalデータを返す
* ハードウェアカウンタの場合, 最新の現在時間を返す
*/
LOCAL_INLINE TickType
get_curval(const CNTCB *p_cntcb, CounterType cntid)
{
TickType curval;
/* カウンタ値の取得 */
if (is_hwcnt(cntid)) {
curval = (hwcntinib_table[cntid].get)();
}
else {
curval = p_cntcb->curval;
}
return(curval);
}
/*
* 指定した相対時間からのカウンタ値取得(APIからの取得)
*/
extern TickType get_reltick(const CNTCB *p_cntcb, TickType relval);
/*
* 指定した絶対時間からのカウンタ値取得(APIからの取得)
*/
extern TickType get_abstick(const CNTCB *p_cntcb, TickType absval);
/*
* カウンタ機能の初期化
*/
extern void counter_initialize(void);
/*
* カウンタ機能の終了処理
*/
extern void counter_terminate(void);
/*
* カウンタ満了キューへの挿入
*/
extern void insert_cnt_expr_que(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb);
/*
* カウンタ満了キューから削除
*/
extern void delete_cnt_expr_que(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb);
/*
* カウンタの満了処理
*/
extern void expire_process(CNTCB *p_cntcb, CounterType cntid);
/*
* ハードウェアカウンタ満了処理
*/
extern void notify_hardware_counter(CounterType cntid);
/*
* カウンタのインクリメント
*
* 条件:割込み禁止状態で呼ばれる
*/
extern StatusType incr_counter_action(CounterType CounterID);
#endif /* TOPPERS_COUNTER_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: task_manage.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* タスク管理モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "task.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_TSKSTAT
#define LOG_TSKSTAT(p_tcb)
#endif /* LOG_TSKSTAT */
#ifndef LOG_ACTTSK_ENTER
#define LOG_ACTTSK_ENTER(tskid)
#endif /* LOG_ACTTSK_ENTER */
#ifndef LOG_ACTTSK_LEAVE
#define LOG_ACTTSK_LEAVE(ercd)
#endif /* LOG_ACTTSK_LEAVE */
#ifndef LOG_TERTSK_ENTER
#define LOG_TERTSK_ENTER()
#endif /* LOG_TERTSK_ENTER */
#ifndef LOG_TERTSK_LEAVE
#define LOG_TERTSK_LEAVE(ercd)
#endif /* LOG_TERTSK_LEAVE */
#ifndef LOG_CHNTSK_ENTER
#define LOG_CHNTSK_ENTER(tskid)
#endif /* LOG_CHNTSK_ENTER */
#ifndef LOG_CHNTSK_LEAVE
#define LOG_CHNTSK_LEAVE(ercd)
#endif /* LOG_CHNTSK_LEAVE */
#ifndef LOG_SCHED_LEAVE
#define LOG_SCHED_ENTER()
#endif /* LOG_SCHED_LEAVE */
#ifndef LOG_SCHED_LEAVE
#define LOG_SCHED_LEAVE(ercd)
#endif /* LOG_SCHED_LEAVE */
#ifndef LOG_GETTID_ENTER
#define LOG_GETTID_ENTER()
#endif /* LOG_GETTID_ENTER */
#ifndef LOG_GETTID_LEAVE
#define LOG_GETTID_LEAVE(ercd, p_tskid)
#endif /* LOG_GETTID_LEAVE */
#ifndef LOG_GETTST_ENTER
#define LOG_GETTST_ENTER(tskid)
#endif /* LOG_GETTST_ENTER */
#ifndef LOG_GETTST_LEAVE
#define LOG_GETTST_LEAVE(ercd, p_state)
#endif /* LOG_GETTST_LEAVE */
/*
* タスクの起動
*/
#ifdef TOPPERS_ActivateTask
StatusType
ActivateTask(TaskType TaskID)
{
StatusType ercd = E_OK;
TCB *p_tcb;
LOG_ACTTSK_ENTER(TaskID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_ACTIVATETASK);
CHECK_ID(TaskID < tnum_task);
p_tcb = get_tcb(TaskID);
x_nested_lock_os_int();
if (p_tcb->tstat == SUSPENDED) {
if ((make_active(p_tcb) != FALSE) && (callevel_stat == TCL_TASK)) {
dispatch();
}
}
else {
S_D_CHECK_LIMIT(p_tcb->actcnt < p_tcb->p_tinib->maxact);
p_tcb->actcnt += 1U;
}
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_ACTTSK_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.tskid = TaskID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_ActivateTask);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_ActivateTask */
/*
* 自タスクの終了
*/
#ifdef TOPPERS_TerminateTask
StatusType
TerminateTask(void)
{
StatusType ercd = E_OK;
LOG_TERTSK_ENTER();
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_TERMINATETASK);
CHECK_RESOURCE(p_runtsk->p_lastrescb == NULL);
x_nested_lock_os_int();
/*
* 内部リソースの解放は優先度を下げるだけなので,ここでは
* 何もしなくてよい
*/
suspend();
LOG_TERTSK_LEAVE(E_OK);
exit_and_dispatch();
ASSERT_NO_REACHED;
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
call_errorhook(ercd, OSServiceId_TerminateTask);
x_nested_unlock_os_int();
#endif /* CFG_USE_ERRORHOOK */
exit_no_errorhook:
LOG_TERTSK_LEAVE(ercd);
return(ercd);
}
#endif /* TOPPERS_TerminateTask */
/*
* 自タスクの終了とタスクの起動
*/
#ifdef TOPPERS_ChainTask
StatusType
ChainTask(TaskType TaskID)
{
/*
* ここでの ercd の初期化は本来は不要であるが,コンパイラの警
* 告メッセージを避けるために初期化している
*/
StatusType ercd = E_OK;
TCB *p_tcb;
LOG_CHNTSK_ENTER(TaskID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_CHAINTASK);
CHECK_RESOURCE(p_runtsk->p_lastrescb == NULL);
CHECK_ID(TaskID < tnum_task);
p_tcb = get_tcb(TaskID);
x_nested_lock_os_int();
if (p_tcb == p_runtsk) {
make_non_runnable();
(void) make_active(p_runtsk);
}
else {
/*
* エラー時に副作用が残らないように,エラーチェックは
* タスク終了処理の前に行う必要がある
*/
S_D_CHECK_LIMIT((p_tcb->tstat == SUSPENDED)
|| (p_tcb->actcnt < p_tcb->p_tinib->maxact));
suspend();
if (p_tcb->tstat == SUSPENDED) {
(void) make_active(p_tcb);
}
else {
p_tcb->actcnt += 1U;
}
}
LOG_CHNTSK_LEAVE(E_OK);
exit_and_dispatch();
ASSERT_NO_REACHED;
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.tskid = TaskID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_ChainTask);
#endif /* CFG_USE_ERRORHOOK */
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_CHNTSK_LEAVE(ercd);
return(ercd);
}
#endif /* TOPPERS_ChainTask */
/*
* スケジューラの呼び出し
*/
#ifdef TOPPERS_Schedule
StatusType
Schedule(void)
{
/*
* ここでの ercd の初期化は本来は不要であるが,コンパイラの警
* 告メッセージを避けるために初期化している
*/
StatusType ercd = E_OK;
LOG_SCHED_ENTER();
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_SCHEDULE);
CHECK_RESOURCE(p_runtsk->p_lastrescb == NULL);
x_nested_lock_os_int();
if (p_runtsk->p_tinib->inipri > nextpri) {
p_runtsk->curpri = p_runtsk->p_tinib->inipri;
preempt();
dispatch();
p_runtsk->curpri = p_runtsk->p_tinib->exepri;
}
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_SCHED_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
call_errorhook(ercd, OSServiceId_Schedule);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_Schedule */
/*
* 実行状態のタスクIDの参照
*/
#ifdef TOPPERS_GetTaskID
StatusType
GetTaskID(TaskRefType TaskID)
{
StatusType ercd = E_OK;
LOG_GETTID_ENTER();
CHECK_CALLEVEL(CALLEVEL_GETTASKID);
CHECK_PARAM_POINTER(TaskID);
*TaskID = (p_runtsk == NULL) ? INVALID_TASK : TSKID(p_runtsk);
exit_no_errorhook:
LOG_GETTID_LEAVE(ercd, TaskID);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.p_tskid = TaskID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetTaskID);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetTaskID */
/*
* タスク状態の参照
*/
#ifdef TOPPERS_GetTaskState
StatusType
GetTaskState(TaskType TaskID, TaskStateRefType State)
{
StatusType ercd = E_OK;
TCB *p_tcb;
LOG_GETTST_ENTER(TaskID);
CHECK_CALLEVEL(CALLEVEL_GETTASKSTATE);
CHECK_ID(TaskID < tnum_task);
CHECK_PARAM_POINTER(State);
p_tcb = get_tcb(TaskID);
*State = (p_tcb == p_runtsk) ? RUNNING : p_tcb->tstat;
exit_no_errorhook:
LOG_GETTST_LEAVE(ercd, State);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.tskid = TaskID;
temp_errorhook_par2.p_stat = State;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetTaskState);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetTaskState */
/*
* 満了処理専用タスクの起動
*
* 条件:OS割込み禁止状態で呼ばれる
*/
#ifdef TOPPERS_activate_task_action
StatusType
activate_task_action(TaskType TaskID)
{
StatusType ercd = E_OK;
TCB *p_tcb;
LOG_ACTTSK_ENTER(TaskID);
p_tcb = get_tcb(TaskID);
if (p_tcb->tstat == SUSPENDED) {
(void) make_active(p_tcb);
}
else if (p_tcb->actcnt < p_tcb->p_tinib->maxact) {
p_tcb->actcnt += 1U;
}
else {
ercd = E_OS_LIMIT;
#ifdef CFG_USE_ERRORHOOK
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.tskid = TaskID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_ActivateTask);
#endif /* CFG_USE_ERRORHOOK */
}
LOG_ACTTSK_LEAVE(ercd);
return(ercd);
}
#endif /* TOPPERS_activate_task_action */
<file_sep>
TOPPERS/ATK2-SC1
<CS+用プロジェクト生成スクリプトマニュアル>
このドキュメントはCS+用プロジェクト生成スクリプトの情報を記述したもの
である.
----------------------------------------------------------------------
TOPPERS ATK2
Toyohashi Open Platform for Embedded Real-Time Systems
Automotive Kernel Version 2
Copyright (C) 2013-2021 by Center for Embedded Computing Systems
Graduate School of Information Science, Nagoya Univ., JAPAN
Copyright (C) 2013-2014 by FUJI SOFT INCORPORATED, JAPAN
Copyright (C) 2013-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
Copyright (C) 2013-2014 by Renesas Electronics Corporation, JAPAN
Copyright (C) 2013-2014 by <NAME> Inc., JAPAN
Copyright (C) 2013-2014 by TOSHIBA CORPORATION, JAPAN
Copyright (C) 2013-2014 by Witz Corporation, JAPAN
上記著作権者は,以下の (1)~(3)の条件を満たす場合に限り,本ドキュメ
ント(本ドキュメントを改変したものを含む.以下同じ)を使用・複製・改
変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
(1) 本ドキュメントを利用する場合には,上記の著作権表示,この利用条件
および下記の無保証規定が,そのままの形でドキュメント中に含まれて
いること.
(2) 本ドキュメントを改変する場合には,ドキュメントを改変した旨の記述
を,改変後のドキュメント中に含めること.ただし,改変後のドキュメ
ントが,TOPPERSプロジェクト指定の開発成果物である場合には,この限
りではない.
(3) 本ドキュメントの利用により直接的または間接的に生じるいかなる損害
からも,上記著作権者およびTOPPERSプロジェクトを免責すること.また,
本ドキュメントのユーザまたはエンドユーザからのいかなる理由に基づ
く請求からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
本ドキュメントは,AUTOSAR(AUTomotive Open System ARchitecture)仕様
に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するものではな
い.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利用する
者に対して,AUTOSARパートナーになることを求めている.
本ドキュメントは,無保証で提供されているものである.上記著作権者およ
びTOPPERSプロジェクトは,本ドキュメントに関して,特定の使用目的に対す
る適合性も含めて,いかなる保証も行わない.また,本ドキュメントの利用
により直接的または間接的に生じたいかなる損害に関しても,その責任を負
わない.
$Id: README.txt 929 2021-01-06 08:51:23Z nces-mtakada $
----------------------------------------------------------------------
○概要
CS+用プロジェクト生成スクリプトは,RH850用のATK2のプロジェクトを作成す
るスクリプトである.
動作確認を行ったCS+のバージョンは次の通りである.
CS+ V6.03.00, V7.00.00, V8.04.00
○使用方法
以下の手順でターゲット用のプロジェクトファイルを生成する.
1.本フォルダ(configure)を適当な場所にコピーする.以下のファイルが含ま
れている.
./configure.mtpj
./configure.py
./def.py
./README.txt
2.def.pyの編集
以下のdef.pyの設定値を参考に設定する.
3.configure.mtpjをダブルクリック
configure.py が実行され,atk2-sc1.mtpjが作成され開かれる.
4.アクティブプロジェクトを変更
アクティブプロジェクトをatk2-sc1に変更する.
プロジェクトファイル生成後は,atk2-sc1.mtpj を使用する.なお,プロジェ
クトファイル生成後はconfigure.mtpjとconfigure.pyは削除可能である.
○def.pyの設定値
・SRCDIR
・ATK2のソースコードのトップとの相対位置
./atk2-sc1/yyy/xxx/ にコピーした場合は,,
SRCDIR = "../../"
となる.
・CFGNAME
・コンフィギュレーションファイル名の指定.
入力として必要なXMLファイル名を全て指定.
・TARGET
・ターゲットの指定../target 以下のいずれかのフォルダ名.
・TARGET_MCU
・ターゲットMCU名の指定.
・app_app_files
・アプリケーションファイルの指定.
・USER_INCLUDE
・インクルードパスの指定
・COPY_SAMPLE1
・sample1のファイルを./sampleからコピーするか指定.
○プロジェクト構成
atk2-sc1 : トッププロジェクト
cfg : サブプロジェクト コンフィギュレータ実行
kernel : サブプロジェクト カーネルビルド用
○変更履歴
2021/01/06
・CS+ V8.04.00 対応
2017/09/23
・CS+ V6.00.00 対応
2014/10/14
・CS+ V3.00.00 対応
2014/05/01
・ターゲットフォルダ名をv850e2_gccからv850_gccに変更.
・sample1をコピーする際に,Rte_Type.h も対象に追加.
・カーネルビルド時の Rte_Type.h のインクルードのため,Rte_Type.h を置
いているフォルダをカーネルビルド時のインクルード対象とする.
以上.
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: v850e2_px4.h 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* V850E2/Px4のハードウェア資源の定義
*/
#ifndef TOPPERS_V850E2_PX4_H
#define TOPPERS_V850E2_PX4_H
#define _V850E2M_
#define VPNECR 0xffff5110
#define VPNADR 0xffff5114
#define VPNTID 0xffff5118
#define VPTTID 0xffff511A
#define VPTECR 0xffff5120
#define VPTADR 0xffff5124
/*
* ポートレジスタ
*/
#define PM0 0xffff8300
#define PMC0 0xffff8400
#define PFC0 0xffff8500
#define PFCE0 0xffff8600
#define P4 0xffff8010
#define PM4 0xffff8310
#define PMC4 0xffff8410
#define PFC4 0xffff8510
#define PFCE4 0xffff8610
#define FCLA0CTL0 0xFF414000
#define FCLA1CTL2 0xFF414028
#define FCLA1CTL3 0xFF41402c
#define FCLA27CTL3 0xff41624c
#define FCLA27CTL6 0xff416258
/*
* Interval Timer(TAUA0)
*/
#define TAUA0_BASE0 UINT_C(0xFF808000) /* TAUA0 */
#define TAUA0_BASE1 UINT_C(0xFFFFC400) /* TAUA0 */
#define TAUA0_IRQ UINT_C(54) /* TAUA0 */
#define TAUA1_IRQ UINT_C(55) /* TAUA1 */
#define TAUA2_IRQ UINT_C(56) /* TAUA2 */
#define TAUA3_IRQ UINT_C(57) /* TAUA3 */
#define TAUA4_IRQ UINT_C(58) /* TAUA4 */
#define TAUA5_IRQ UINT_C(59) /* TAUA5 */
#define TAUA6_IRQ UINT_C(60) /* TAUA6 */
#define TAUA7_IRQ UINT_C(61) /* TAUA7 */
#define TAUA8_IRQ UINT_C(62) /* TAUA8 */
#define TAUA9_IRQ UINT_C(63) /* TAUA9 */
#define TAUA10_IRQ UINT_C(64) /* TAUA10 */
#define TAUA11_IRQ UINT_C(65) /* TAUA11 */
#define TAUA12_IRQ UINT_C(66) /* TAUA12 */
#define TAUA13_IRQ UINT_C(67) /* TAUA13 */
#define TAUA14_IRQ UINT_C(68) /* TAUA14 */
#define TAUA15_IRQ UINT_C(69) /* TAUA15 */
#define TAUA_CH0 0
#define TAUA_CH1 1
#define TAUA_CH2 2
#define TAUA_CH3 3
#define TAUA_CH4 4
#define TAUA_CH5 5
#define TAUA_CH6 6
#define TAUA_CH7 7
#define TAUA_CH8 8
#define TAUA_CH9 9
#define TAUA_CH10 10
#define TAUA_CH11 11
#define TAUA_CH12 12
#define TAUA_CH13 13
#define TAUA_CH14 14
#define TAUA_CH15 15
/*
* TAUA0 Timer ハードウェア定義
*/
/*
* レジスタ
*/
/* TAUA0 プリスケーラ・レジスタ */
#define TAUA0TPS (TAUA0_BASE0 + 0x240U) /* プリスケーラ・クロック選択レジス */
#define TAUA0BRS (TAUA0_BASE0 + 0x244U) /* プリスケーラ・ボー・レート設定レジスタ */
/* TAUA0 制御レジスタ */
#define TAUA0CDR(CH) (TAUA0_BASE1 + (CH * 4U)) /* データ・レジスタ */
#define TAUA0CNT(CH) (TAUA0_BASE1 + (0x80U + (CH * 4U))) /* カウンタ・レジスタ */
#define TAUA0CMOR(CH) (TAUA0_BASE0 + (0x200U + (CH * 4U))) /* モードOS レジスタ */
#define TAUA0CMUR(CH) (TAUA0_BASE1 + (0xC0 + (CH * 4U))) /* モード・ユーザ・レジスタ */
#define TAUA0CSR(CH) (TAUA0_BASE1 + (0x140U + (CH * 4U))) /* ステータス・レジスタ */
#define TATA0CSC(CH) (TAUA0_BASE1 + (0x180U + (CH * 4U))) /* ステータス・クリア・トリガ・レジスタ */
#define TAUA0TS (TAUA0_BASE1 + 0x1C4U) /* スタート・トリガ・レジスタ */
#define TAUA0TE (TAUA0_BASE1 + 0x1C0U) /* 許可ステータス・レジスタ */
#define TAUA0TT (TAUA0_BASE1 + 0x1C8U) /* ストップ・トリガ・レジスタ */
/* TAUA0 出力レジスタ */
#define TAUA0TOE (TAUA0_BASE1 + 0x5CU) /* 出力許可レジスタ */
#define TAUA0TO (TAUA0_BASE1 + 0x58U) /* 出力レジスタ */
#define TAUA0TOM (TAUA0_BASE0 + 0x248U) /* 出力モード・レジスタ */
#define TAUA0TOC (TAUA0_BASE0 + 0x24CU) /* 出力コンフィギュレーション・レジスタ */
#define TAUA0TOL (TAUA0_BASE1 + 0x40U) /* 出力アクティブ・レベル・レジスタ */
#define TAUA0TDE (TAUA0_BASE0 + 0x250U) /* デッド・タイム出力許可レジスタ */
#define TAUA0TDM (TAUA0_BASE0 + 0x254U) /* デッド・タイム出力モード・レジスタ */
#define TAUA0TDL (TAUA0_BASE1 + 0x54U) /* デッド・タイム出力レベル・レジスタ */
#define TAUA0TRO (TAUA0_BASE1 + 0x4CU) /* リアルタイム出力レジスタ */
#define TAUA0TRE (TAUA0_BASE0 + 0x258U) /* リアルタイム出力許可レジスタ */
#define TAUA0TRC (TAUA0_BASE0 + 0x25CU) /* リアルタイム出力制御レジスタ */
#define TAUA0TME (TAUA0_BASE1 + 0x50U) /* 変調出力許可レジスタ */
/* TAUA0 リロード・データ・レジスタ */
#define TAUA0RDE (TAUA0_BASE0 + 0x260U) /* リロード・データ許可レジスタ */
#define TAUA0RDM (TAUA0_BASE0 + 0x264U) /* リロード・データ・モード・レジスタ */
#define TAUA0RDS (TAUA0_BASE0 + 0x268U) /* リロード・データ制御CH 選択・リロード・データ制御CH 選択 */
#define TAUA0RDC (TAUA0_BASE0 + 0x26CU) /* リロード・データ制御レジスタ */
#define TAUA0RDT (TAUA0_BASE1 + 0x44U) /* リロード・データ・トリガ・レジスタ */
#define TAUA0RSF (TAUA0_BASE1 + 0x48U) /* リロード・ステータス・レジスタ */
#define MCU_TAUA0_MASK_CK0 ((uint16) 0x000f)
#define MCU_TAUA0_CK0 ((uint16) 0x0000) /* 2^0 */
#define MCU_TAUA00_CMOR ((uint16) 0x0001)
#define MCU_TAUA00_CMUR ((uint8) 0x01)
#define MCU_TAUA00_DI ((uint16) 0x0080)
#define MCU_TAUA00_EI ((uint16) 0x0000)
#define MCU_TAUA00_MASK_ENB ((uint16) 0x0001)
#define MCU_TIMER_STOP ((uint8) 0x0)
#define MCU_TIMER_START ((uint8) 0x1)
#define ICTAUA0_BASE 0xffff606c /* チャンネル0割り込み */
#define ICTAUA0I(CH) (ICTAUA0_BASE + (CH * 0x02))
/*
* TAUA0 マスク定義
*/
#define TAUA0_MASK_BIT 0x0xfffe /* bit0 = TAUA0 */
/*
* UARTE
*/
#define URTE0_BASE 0xFF5C0000
#define URTE1_BASE 0xFF5D0000
#define URTE2_BASE0 0xFF5E0000
#define URTE2_BASE1 0xFFFFEC00
#define URTEnCTL0 (URTE2_BASE1 + 0x00U)
#define URTEnCTL1 (URTE2_BASE0 + 0x40U)
#define URTEnCTL2 (URTE2_BASE0 + 0x44U)
#define URTEnTRG (URTE2_BASE1 + 0x0cU)
#define URTEnSTR0 (URTE2_BASE1 + 0x10U)
#define URTEnSTR1 (URTE2_BASE1 + 0x14U)
#define URTEnSTC (URTE2_BASE1 + 0x18U)
#define URTEnRX (URTE2_BASE1 + 0x1cU)
#define URTEnTX (URTE2_BASE1 + 0x2cU)
#define URTE2_INTNO UINT_C(197)
#define INTNO_URTE2_IS 114
#define INTNO_URTE2_IR 115
#define INTNO_URTE2_IT 116
/*
* INT
*/
#define EIC_BASE UINT_C(0xffff6000)
#define EIC_ADDRESS(intno) (EIC_BASE + (intno * 2))
#define PMR UINT_C(0xFFFF6448)
#define ISPR_H UINT_C(0xFFFF6440)
#define ISPC_H UINT_C(0xffff6450)
#define TMIN_INTNO UINT_C(0)
#define TMAX_INTNO UINT_C(255)
#define TNUM_INT UINT_C(256)
#include "v850.h"
#endif /* TOPPERS_V850E2_PX4_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2011-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: Std_Types.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* AUTOSAR仕様共通規定のデータ型・定数・マクロ
*
* このヘッダファイルは,AUTOSAR仕様共通規定のデータ型・定数・マクロ
* の定義を含むヘッダファイル
* AUTOSAR仕様との互換性を必要とするアプリケーションがインクルード
* することを想定している
* ATK2のコンパイルに必要な共通の定義も本ヘッダにて定義する
*
* アセンブリ言語のソースファイルからこのファイルをインクルードする時
* は,TOPPERS_MACRO_ONLYを定義しておく
* これにより,マクロ定義以外を除くようになっている
*/
#ifndef TOPPERS_STD_TYPES_H
#define TOPPERS_STD_TYPES_H
#include "Platform_Types.h"
#include "Compiler.h"
/*
* Type definitions
*/
#ifndef TOPPERS_MACRO_ONLY
typedef uint8 Std_ReturnType;
typedef struct {
uint16 vendorID;
uint16 moduleID;
uint8 sw_major_version;
uint8 sw_minor_version;
uint8 sw_patch_version;
} Std_VersionInfoType;
#endif /* TOPPERS_MACRO_ONLY */
/*
* Symbol definitions
*/
#ifndef STATUSTYPEDEFINED
#define STATUSTYPEDEFINED
#ifndef TOPPERS_MACRO_ONLY
typedef unsigned char StatusType; /* OSEK compliance */
#endif /* TOPPERS_MACRO_ONLY */
#define E_OK UINT_C(0x00)
#endif /* STATUSTYPEDEFINED */
#define E_NOT_OK UINT_C(0x01)
#define STD_HIGH UINT_C(1) /* Physical state 5V or 3.3V */
#define STD_LOW UINT_C(0) /* Physical state 0V */
#define STD_ACTIVE UINT_C(1) /* Logical state active */
#define STD_IDLE UINT_C(0) /* Logical state idle */
#define STD_ON UINT_C(1)
#define STD_OFF UINT_C(0)
#endif /* TOPPERS_STD_TYPES_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2014-2016 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2014 by Spansion LLC, USA
* Copyright (C) 2014 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2014 by <NAME> Inc., JAPAN
* Copyright (C) 2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2014 by <NAME>, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: target_hw_counter.h 911 2020-07-24 06:25:32Z nces-mtakada $
*/
/*
* ハードウェアカウンタのターゲット依存定義(HSBRH850F1K用)
*/
#ifndef TOPPERS_TARGET_HW_COUNTER_H
#define TOPPERS_TARGET_HW_COUNTER_H
/*
* 使用するタイマーのユニット番号と差分タイマと現在値タイマのチャネル
*/
#define HWC_DTIM_UNIT 0 /* 0 or 1 */
#define HWC_DTIM_ID 0
#define HWC_CTIM_UNIT 0 /* 0 or 1 */
#define HWC_CTIM_ID 1
/*
* 割込み番号
*/
#if (HWC_DTIM_UNIT == 0)
#define HWC_DTIM_INTNO (TAUFJ0I0_INTNO + HWC_DTIM_ID)
#elif (HWC_DTIM_UNIT == 1)
#define HWC_DTIM_INTNO (TAUFJ1I0_INTNO + HWC_DTIM_ID)
#else /*(HWC_DTIM_UNIT == 1) */
#error define HWC_UNIT 0 or 1.
#endif /* (HWC_DTIM_UNIT == 0) */
/*
* 割込み優先度
*/
#define HWC_DTIM_INTPRI 1
/*
* タイマクロック周波数(Hz)(16MHz)
*/
#define TIMER_CLOCK_HZ ((uint32) 16000000)
/*
* TAUJ関連レジスタ
*/
#define TAUJ_BASE(n) ((uint32) (0xffe50000U + (n * 0x1000U)))
#define TAUJTPS(n) (TAUJ_BASE(n) + 0x90U)
#define TAUJCDR(n, ch) (TAUJ_BASE(n) + (ch * 0x04U))
#define TAUJCNT(n, ch) (TAUJ_BASE(n) + 0x10U + (ch * 0x04U))
#define TAUJCMOR(n, ch) (TAUJ_BASE(n) + 0x80U + (ch * 0x04U))
#define TAUJCMUR(n, ch) (TAUJ_BASE(n) + 0x20U + (ch * 0x04U))
#define TAUJTS(n) (TAUJ_BASE(n) + 0x54U)
#define TAUJTT(n) (TAUJ_BASE(n) + 0x58U)
#define MCU_TAUJ_MASK_CK0 ((uint16) 0xfff0)
#define MCU_TAUJ_CK0_0 ((uint16) 0x0000) /* 分周なし */
#define MCU_TAUJ00_CMOR ((uint16) 0x0000)
#define MCU_TAUJ00_CMUR ((uint8) 0x01)
/*
* TAUJのユニット番号とチャネルから入力割込み番号への変換
*/
#define TAUJ_INTNO(n, ch) (n == 0)? ((uint32) ((TAUFJ0I0_INTNO + ch))) : ((uint32) (TAUFJ1I0_INTNO + ch))
/*
* 割込み要求のクリア
*/
LOCAL_INLINE void
HwcounterClearInterrupt(uint32 intno)
{
/* 割込み制御レジスタ */
uint32 eic_address = EIC_ADDRESS(intno);
/* 割込み要求ビットのクリア */
sil_wrh_mem((void *) eic_address,
sil_reh_mem((void *) eic_address) & ~EIRFn);
}
/*
* 割込み禁止/許可設定
*/
LOCAL_INLINE void
HwcounterDisableInterrupt(uint32 intno)
{
/* 割込み制御レジスタ */
uint32 eic_address = EIC_ADDRESS(intno);
/* 割込みマスクビットのセット */
sil_wrh_mem((void *) eic_address,
sil_reh_mem((void *) eic_address) | EIMKn);
}
LOCAL_INLINE void
HwcounterEnableInterrupt(uint32 intno)
{
/* 割込み制御レジスタ */
uint32 eic_address = EIC_ADDRESS(intno);
/* 割込みマスクビットのセット */
sil_wrh_mem((void *) eic_address,
sil_reh_mem((void *) eic_address) & ~EIMKn);
}
/*
* TAUJn タイマの動作開始/停止処理
*/
LOCAL_INLINE void
SetTimerStartTAUJ(uint8 n, uint8 ch)
{
/* タイマ開始処理 */
sil_wrb_mem((void *) TAUJTS(n), (1 << ch));
}
LOCAL_INLINE void
SetTimerStopTAUJ(uint8 n, uint8 ch)
{
/* タイマ停止処理 */
sil_wrb_mem((void *) TAUJTT(n), (1 << ch));
}
/*
* TAUJnハードウェアカウンタ現在ティック値取得
*/
LOCAL_INLINE TickType
GetCurrentTimeTAUJ(uint8 n, uint8 ch, TickType maxval)
{
TickType count;
TickType curr_time = 0U;
count = sil_rew_mem((void *) (TAUJCNT(n, ch)));
/* ダウンカウンタの為,現在チック値に変換 */
curr_time = maxval - count;
curr_time = (curr_time % maxval);
return(curr_time);
}
/* MAIN_HW_COUNTERの定義 */
extern void init_hwcounter_MAIN_HW_COUNTER(TickType maxval, TimeType nspertick);
extern void start_hwcounter_MAIN_HW_COUNTER(void);
extern void stop_hwcounter_MAIN_HW_COUNTER(void);
extern void set_hwcounter_MAIN_HW_COUNTER(TickType exprtick);
extern TickType get_hwcounter_MAIN_HW_COUNTER(void);
extern void cancel_hwcounter_MAIN_HW_COUNTER(void);
extern void trigger_hwcounter_MAIN_HW_COUNTER(void);
extern void int_clear_hwcounter_MAIN_HW_COUNTER(void);
extern void int_cancel_hwcounter_MAIN_HW_COUNTER(void);
extern void increment_hwcounter_MAIN_HW_COUNTER(void);
/*
* 10msと一致するティック値(サンプルプログラム用)
*/
#define TICK_FOR_10MS TIMER_CLOCK_HZ / 100
#endif /* TOPPERS_TARGET_HW_COUNTER_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: vasyslog.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* 可変数引数のシステムログライブラリ
*/
#include "t_syslog.h"
#include <stdarg.h>
#ifndef TOPPERS_OMIT_SYSLOG
void
syslog(uint32 prio, const char8 *format, ...)
{
SYSLOG syslog;
va_list ap;
uint32 i;
char8 c;
boolean lflag;
syslog.logtype = LOG_TYPE_COMMENT;
syslog.loginfo[0] = (sintptr) format;
i = 1U;
va_start(ap, format);
while (((c = *format++) != '\0') && (i < TMAX_LOGINFO)) {
if (c != '%') {
continue;
}
lflag = FALSE;
c = *format++;
while (('0' <= c) && (c <= '9')) {
c = *format++;
}
if (c == 'l') {
lflag = TRUE;
c = *format++;
}
switch (c) {
case 'd':
syslog.loginfo[i++] = (lflag != FALSE) ? (sintptr) va_arg(ap, sint32)
: (sintptr) va_arg(ap, sint32);
break;
case 'u':
case 'x':
case 'X':
syslog.loginfo[i++] = (lflag != FALSE) ? (sintptr) va_arg(ap, uint32)
: (sintptr) va_arg(ap, uint32);
break;
case 'p':
syslog.loginfo[i++] = (sintptr) va_arg(ap, void *);
break;
case 'c':
syslog.loginfo[i++] = (sintptr) va_arg(ap, sint32);
break;
case 's':
syslog.loginfo[i++] = (sintptr) va_arg(ap, const char8 *);
break;
case '\0':
format--;
break;
default:
/* 上記のケース以外の場合,処理は行わない */
break;
}
}
va_end(ap);
(void) syslog_wri_log(prio, &syslog);
}
#endif /* TOPPERS_OMIT_SYSLOG */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: scheduletable.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* スケジュールテーブル管理モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "scheduletable.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_STASCHTBLREL_ENTER
#define LOG_STASCHTBLREL_ENTER(schtblid, offset)
#endif /* LOG_STASCHTBLREL_ENTER */
#ifndef LOG_STASCHTBLREL_LEAVE
#define LOG_STASCHTBLREL_LEAVE(ercd)
#endif /* LOG_STASCHTBLREL_LEAVE */
#ifndef LOG_STASCHTBLABS_ENTER
#define LOG_STASCHTBLABS_ENTER(schtblid, start)
#endif /* LOG_STASCHTBLABS_ENTER */
#ifndef LOG_STASCHTBLABS_LEAVE
#define LOG_STASCHTBLABS_LEAVE(ercd)
#endif /* LOG_STASCHTBLABS_LEAVE */
#ifndef LOG_STPSCHTBL_ENTER
#define LOG_STPSCHTBL_ENTER(schtblid)
#endif /* LOG_STPSCHTBL_ENTER */
#ifndef LOG_STPSCHTBL_LEAVE
#define LOG_STPSCHTBL_LEAVE(ercd)
#endif /* LOG_STPSCHTBL_LEAVE */
#ifndef LOG_NXTSCHTBL_ENTER
#define LOG_NXTSCHTBL_ENTER(from, to)
#endif /* LOG_NXTSCHTBL_ENTER */
#ifndef LOG_NXTSCHTBL_LEAVE
#define LOG_NXTSCHTBL_LEAVE(ercd)
#endif /* LOG_NXTSCHTBL_LEAVE */
#ifndef LOG_GETSCHTBLST_ENTER
#define LOG_GETSCHTBLST_ENTER(schtblid)
#endif /* LOG_GETSCHTBLST_ENTER */
#ifndef LOG_GETSCHTBLST_LEAVE
#define LOG_GETSCHTBLST_LEAVE(ercd, p_status)
#endif /* LOG_GETSCHTBLST_LEAVE */
#ifndef LOG_SCHTBL_ENTER
#define LOG_SCHTBL_ENTER(p_schtblcb)
#endif /* LOG_SCHTBL_ENTER */
#ifndef LOG_SCHTBL_LEAVE
#define LOG_SCHTBL_LEAVE(p_schtblcb)
#endif /* LOG_SCHTBL_LEAVE */
/*
* スケジュールテーブルオブジェクトの初期化
*/
#ifdef TOPPERS_schtbl_initialize
void
schtbl_initialize(void)
{
ScheduleTableType i;
SCHTBLCB *p_schtblcb;
CNTCB *p_cntcb;
TickType staval;
for (i = 0U; i < tnum_scheduletable; i++) {
p_schtblcb = &(schtblcb_table[i]);
p_schtblcb->p_schtblinib = &(schtblinib_table[i]);
/*
* STOPPED状態にする時,p_nextschtblcb,p_prevschtblcbを初期化する
* RUNNING,NEXT状態にする時,expptindexを初期化する
*/
p_schtblcb->p_nextschtblcb = NULL;
p_schtblcb->p_prevschtblcb = NULL;
(p_schtblcb->cntexpinfo).expirefunc = &schtbl_expire;
if ((p_schtblcb->p_schtblinib->autosta & ((AppModeType) 1 << appmodeid)) != APPMODE_NONE) {
if (is_implschtbl(i)) {
p_schtblcb->status = SCHEDULETABLE_RUNNING_AND_SYNCHRONOUS;
}
else {
p_schtblcb->status = SCHEDULETABLE_RUNNING;
}
p_schtblcb->expptindex = EXPPTINDEX_INITIAL;
p_cntcb = p_schtblcb->p_schtblinib->p_cntcb;
staval = p_schtblcb->p_schtblinib->staval;
if (p_schtblcb->p_schtblinib->actatr == ABSOLUTE) {
/*
* 絶対時間の起動
* 満了時間が0の場合,次の周期の0のタイミングとなる
* (get_abstickに考慮済み)
*/
(p_schtblcb->cntexpinfo).expiretick = get_abstick(p_cntcb, staval);
}
else {
/* 相対時間の起動 */
(p_schtblcb->cntexpinfo).expiretick = get_reltick(p_cntcb, staval);
}
insert_cnt_expr_que(&(p_schtblcb->cntexpinfo), p_cntcb);
}
else {
p_schtblcb->status = SCHEDULETABLE_STOPPED;
queue_initialize(&(p_schtblcb->cntexpinfo.cntexpque));
}
}
}
#endif /* TOPPERS_schtbl_initialize */
/*
* 指定したスケジュールテーブルの開始(相対時間)
*/
#ifdef TOPPERS_StartScheduleTableRel
StatusType
StartScheduleTableRel(ScheduleTableType ScheduleTableID, TickType Offset)
{
StatusType ercd = E_OK;
SCHTBLCB *p_schtblcb;
CNTCB *p_cntcb;
LOG_STASCHTBLREL_ENTER(ScheduleTableID, Offset);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_STARTSCHEDULETABLEREL);
CHECK_ID(ScheduleTableID < tnum_scheduletable);
CHECK_ID(ScheduleTableID >= tnum_implscheduletable);
p_schtblcb = get_schtblcb(ScheduleTableID);
p_cntcb = p_schtblcb->p_schtblinib->p_cntcb;
CHECK_VALUE((Offset != 0U) &&
((p_cntcb->p_cntinib->maxval - p_schtblcb->p_schtblinib->p_exppt->offset) >= Offset));
x_nested_lock_os_int();
S_D_CHECK_STATE(p_schtblcb->status == SCHEDULETABLE_STOPPED);
p_schtblcb->status = SCHEDULETABLE_RUNNING;
p_schtblcb->expptindex = EXPPTINDEX_INITIAL;
p_schtblcb->cntexpinfo.expiretick = get_reltick(p_cntcb, Offset);
insert_cnt_expr_que(&(p_schtblcb->cntexpinfo), p_cntcb);
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_STASCHTBLREL_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.schtblid = ScheduleTableID;
temp_errorhook_par2.offset = Offset;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_StartScheduleTableRel);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_StartScheduleTableRel */
/*
* 指定したスケジュールテーブルの開始(絶対時間)
*/
#ifdef TOPPERS_StartScheduleTableAbs
StatusType
StartScheduleTableAbs(ScheduleTableType ScheduleTableID, TickType Start)
{
StatusType ercd = E_OK;
SCHTBLCB *p_schtblcb;
CNTCB *p_cntcb;
LOG_STASCHTBLABS_ENTER(ScheduleTableID, Start);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_STARTSCHEDULETABLEABS);
CHECK_ID(ScheduleTableID < tnum_scheduletable);
p_schtblcb = get_schtblcb(ScheduleTableID);
p_cntcb = p_schtblcb->p_schtblinib->p_cntcb;
CHECK_VALUE(p_cntcb->p_cntinib->maxval >= Start);
x_nested_lock_os_int();
S_D_CHECK_STATE(p_schtblcb->status == SCHEDULETABLE_STOPPED);
/* 暗黙同期の場合,同期動作状態で動作する */
if (is_implschtbl(ScheduleTableID)) {
p_schtblcb->status = SCHEDULETABLE_RUNNING_AND_SYNCHRONOUS;
}
else {
p_schtblcb->status = SCHEDULETABLE_RUNNING;
}
p_schtblcb->expptindex = EXPPTINDEX_INITIAL;
p_schtblcb->cntexpinfo.expiretick = get_abstick(p_cntcb, Start);
insert_cnt_expr_que(&(p_schtblcb->cntexpinfo), p_cntcb);
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_STASCHTBLABS_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.schtblid = ScheduleTableID;
temp_errorhook_par2.start = Start;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_StartScheduleTableAbs);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_StartScheduleTableAbs */
/*
* 指定したスケジュールテーブルの停止
*/
#ifdef TOPPERS_StopScheduleTable
StatusType
StopScheduleTable(ScheduleTableType ScheduleTableID)
{
StatusType ercd = E_OK;
SCHTBLCB *p_schtblcb, *p_nextcb;
LOG_STPSCHTBL_ENTER(ScheduleTableID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_STOPSCHEDULETABLE);
CHECK_ID(ScheduleTableID < tnum_scheduletable);
p_schtblcb = get_schtblcb(ScheduleTableID);
x_nested_lock_os_int();
S_D_CHECK_NOFUNC(p_schtblcb->status != SCHEDULETABLE_STOPPED);
/*
* 指定されたスケジュールテーブルがSCHEDULETABLE_NEXTの場合,
* 自分をNextにしたスケジュールテーブルから,自分を外す
*/
if (p_schtblcb->status == SCHEDULETABLE_NEXT) {
p_schtblcb->p_prevschtblcb->p_nextschtblcb = NULL;
p_schtblcb->p_prevschtblcb = NULL;
}
else {
/*
* Nextスケジュールテーブルが存在した場合,
* Nextスケジュールテーブルの予約をキャンセルする
*/
p_nextcb = p_schtblcb->p_nextschtblcb;
if (p_nextcb != NULL) {
p_nextcb->status = SCHEDULETABLE_STOPPED;
p_nextcb->p_prevschtblcb = NULL;
p_schtblcb->p_nextschtblcb = NULL;
}
/* カウンタ満了キューから既に登録した満了処理を削除 */
delete_cnt_expr_que(&(p_schtblcb->cntexpinfo),
p_schtblcb->p_schtblinib->p_cntcb);
}
p_schtblcb->status = SCHEDULETABLE_STOPPED;
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_STPSCHTBL_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.schtblid = ScheduleTableID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_StopScheduleTable);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_StopScheduleTable */
/*
* スケジュールテーブルの切替え
*/
#ifdef TOPPERS_NextScheduleTable
StatusType
NextScheduleTable(ScheduleTableType ScheduleTableID_From,
ScheduleTableType ScheduleTableID_To)
{
StatusType ercd = E_OK;
SCHTBLCB *p_curcb, *p_nextcb;
LOG_NXTSCHTBL_ENTER(ScheduleTableID_From, ScheduleTableID_To);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_NEXTSCHEDULETABLE);
CHECK_ID(ScheduleTableID_From < tnum_scheduletable);
CHECK_ID(ScheduleTableID_To < tnum_scheduletable);
CHECK_ID((ScheduleTableID_From < tnum_implscheduletable) ==
(ScheduleTableID_To < tnum_implscheduletable));
p_curcb = get_schtblcb(ScheduleTableID_From);
p_nextcb = get_schtblcb(ScheduleTableID_To);
CHECK_ID(p_curcb->p_schtblinib->p_cntcb == p_nextcb->p_schtblinib->p_cntcb);
x_nested_lock_os_int();
/* ScheduleTableID_Fromの状態チェック */
S_D_CHECK_NOFUNC((p_curcb->status & (SCHEDULETABLE_STOPPED | SCHEDULETABLE_NEXT)) == 0U);
/* ScheduleTableID_Toの状態チェック */
S_D_CHECK_STATE(p_nextcb->status == SCHEDULETABLE_STOPPED);
/*
* Currentに対して既にNextが存在した場合,
* これまでのNextに対してキャンセルする
*/
if (p_curcb->p_nextschtblcb != NULL) {
p_curcb->p_nextschtblcb->status = SCHEDULETABLE_STOPPED;
p_curcb->p_nextschtblcb->p_prevschtblcb = NULL;
}
p_curcb->p_nextschtblcb = p_nextcb;
p_nextcb->status = SCHEDULETABLE_NEXT;
p_nextcb->p_prevschtblcb = p_curcb;
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_NXTSCHTBL_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.schtblid_from = ScheduleTableID_From;
temp_errorhook_par2.schtblid_to = ScheduleTableID_To;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_NextScheduleTable);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_NextScheduleTable */
/*
* スケジュールテーブル状態の取得
*/
#ifdef TOPPERS_GetScheduleTableStatus
StatusType
GetScheduleTableStatus(ScheduleTableType ScheduleTableID,
ScheduleTableStatusRefType ScheduleStatus)
{
StatusType ercd = E_OK;
SCHTBLCB *p_schtblcb;
LOG_GETSCHTBLST_ENTER(ScheduleTableID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_GETSCHEDULETABLESTATUS);
CHECK_ID(ScheduleTableID < tnum_scheduletable);
CHECK_PARAM_POINTER(ScheduleStatus);
p_schtblcb = get_schtblcb(ScheduleTableID);
*ScheduleStatus = p_schtblcb->status;
exit_no_errorhook:
LOG_GETSCHTBLST_LEAVE(ercd, ScheduleStatus);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.schtblid = ScheduleTableID;
temp_errorhook_par2.p_schtblstate = ScheduleStatus;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetScheduleTableStatus);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetScheduleTableStatus */
/*
* スケジュール満了処理関数
*/
#ifdef TOPPERS_schtbl_expire
void
schtbl_expire(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb)
{
SCHTBLEXPINFO schtblexpinfo;
schtblexpinfo.p_schtblcb = (SCHTBLCB *) p_cntexpinfo;
schtbl_expiry_process(&schtblexpinfo, p_cntcb);
if (schtblexpinfo.p_schtblcb != NULL) {
insert_cnt_expr_que(&(schtblexpinfo.p_schtblcb->cntexpinfo), (CNTCB *) p_cntcb);
}
}
#endif /* TOPPERS_schtbl_expire */
/*
* 満了処理関数から各タイミング処理の実行
*/
#ifdef TOPPERS_schtbl_expiry_process
void
schtbl_expiry_process(SCHTBLEXPINFO *p_schtblexpinfo, const CNTCB *p_cntcb)
{
boolean loopcont = FALSE;
SCHTBLCB *p_schtblcb;
/*
* 設定した満了点は,すぐ満了する可能性があるので,
* 繰り返し情報によってループ処理
*/
do {
p_schtblcb = p_schtblexpinfo->p_schtblcb;
if (p_schtblcb->expptindex < p_schtblcb->p_schtblinib->tnum_exppt) {
/* 各満了点時 */
loopcont = schtbl_exppoint_process(p_schtblcb, p_cntcb);
}
else if (p_schtblcb->expptindex == p_schtblcb->p_schtblinib->tnum_exppt) {
/* 最終遅延処理 */
loopcont = schtbl_tail(p_schtblcb, p_schtblexpinfo, p_cntcb);
}
else {
/*
* 次スケジュールテーブルの開始時
* p_schtblcb->expptindex == EXPPTINDEX_INITIALしかあり得ない
*/
loopcont = schtbl_head(p_schtblcb, p_cntcb);
}
} while (loopcont != FALSE);
}
#endif /* TOPPERS_schtbl_expiry_process */
/*
* スケジュールテーブルの開始処理
*/
#ifdef TOPPERS_schtbl_head
boolean
schtbl_head(SCHTBLCB *p_schtblcb, const CNTCB *p_cntcb)
{
boolean loopcont;
const SCHTBLEXPPTCB *p_exppoint;
p_exppoint = &(p_schtblcb->p_schtblinib->p_exppt[EXPPTINDEX_TOP]);
if (p_exppoint->offset == 0U) {
/* 初期オフセット0の場合,今回満了処理内で1個目の満了点処理を行う */
loopcont = TRUE;
}
else {
loopcont = FALSE;
/* 次に起動すべき時間の選定 */
p_schtblcb->cntexpinfo.expiretick = add_tick(p_schtblcb->cntexpinfo.expiretick,
p_exppoint->offset, p_cntcb->p_cntinib->maxval2);
}
p_schtblcb->expptindex = EXPPTINDEX_TOP;
return(loopcont);
}
#endif /* TOPPERS_schtbl_head */
/*
* スケジュールテーブルの各満了点処理
*/
#ifdef TOPPERS_schtbl_exppoint_process
boolean
schtbl_exppoint_process(SCHTBLCB *p_schtblcb, const CNTCB *p_cntcb)
{
boolean loopcont = FALSE;
const SCHTBLEXPPTCB *p_exppoint;
const SCHTBLEXPPTCB *pp_exppoint;
uint8 index;
TickType currtime;
pp_exppoint = p_schtblcb->p_schtblinib->p_exppt;
index = p_schtblcb->expptindex;
p_exppoint = &(pp_exppoint[index]);
/* 満了処理の実行 */
LOG_SCHTBL_ENTER(p_schtblcb);
(p_exppoint->expptfnt)();
LOG_SCHTBL_LEAVE(p_schtblcb);
/* 現在時間の退避 */
currtime = p_exppoint->offset;
/* 次の満了点へ */
index++;
p_schtblcb->expptindex = index;
if (p_schtblcb->expptindex == p_schtblcb->p_schtblinib->tnum_exppt) {
/* 現在が周期の最後の満了点の場合 */
if (p_schtblcb->p_schtblinib->length == currtime) {
/*
* 単発スケジュールテーブル最終遅延値が0の場合,Nextが存在するかもしれないため,
* スケジュールテーブルの最後タイミング処理をする
*/
loopcont = TRUE;
}
else {
/* 最終遅延処理のため,満了時間の設定 */
p_schtblcb->cntexpinfo.expiretick = add_tick(p_schtblcb->cntexpinfo.expiretick,
(p_schtblcb->p_schtblinib->length - currtime), p_cntcb->p_cntinib->maxval2);
}
}
else {
p_exppoint = &(pp_exppoint[index]);
/* 次の満了点の満了時間の設定 */
p_schtblcb->cntexpinfo.expiretick = add_tick(p_schtblcb->cntexpinfo.expiretick,
(p_exppoint->offset - currtime), p_cntcb->p_cntinib->maxval2);
}
return(loopcont);
}
#endif /* TOPPERS_schtbl_exppoint_process */
/*
* スケジュールテーブルの終端処理
*/
#ifdef TOPPERS_schtbl_tail
boolean
schtbl_tail(SCHTBLCB *p_schtblcb, SCHTBLEXPINFO *p_schtblexpinfo, const CNTCB *p_cntcb)
{
boolean loopcont = FALSE;
SCHTBLCB *p_nextcb;
const SCHTBLEXPPTCB *p_exppoint;
/* 周期の最後にてNextが存在するかチェック */
if (p_schtblcb->p_nextschtblcb != NULL) {
p_nextcb = p_schtblcb->p_nextschtblcb;
/*
* スケジュールテーブルの切り替え
*
* 暗黙同期同士の切替を考慮し,状態の引継ぎが必要
* NextScheduleTableで同期方法チェックしているので,
* 同期方法の不整合がない
*/
p_nextcb->status = p_schtblcb->status;
p_nextcb->expptindex = EXPPTINDEX_INITIAL;
/* Nextの満了点設定基準は,Prevの満了時刻となる */
p_nextcb->cntexpinfo.expiretick = p_schtblcb->cntexpinfo.expiretick;
p_nextcb->p_prevschtblcb = NULL;
/* 今まで実行状態のスケジュールテーブルに対して終了処理 */
p_schtblcb->status = SCHEDULETABLE_STOPPED;
p_schtblcb->p_nextschtblcb = NULL;
/*
* 上流側よりNextの初期満了点をカウンタ満了キューに追加する時,
* 使用される
*/
p_schtblexpinfo->p_schtblcb = p_nextcb;
loopcont = TRUE;
}
else {
/* 周期制御の有無チェック */
if (p_schtblcb->p_schtblinib->repeat != FALSE) {
p_schtblcb->expptindex = EXPPTINDEX_TOP;
p_exppoint = &(p_schtblcb->p_schtblinib->p_exppt[EXPPTINDEX_TOP]);
if (p_exppoint->offset == 0U) {
/* 初期オフセット0の場合,今回満了処理内で1個目の満了点処理を行う */
loopcont = TRUE;
}
else {
/* 最終遅延処理のため,満了時間の設定 */
p_schtblcb->cntexpinfo.expiretick = add_tick(p_schtblcb->cntexpinfo.expiretick,
p_exppoint->offset, p_cntcb->p_cntinib->maxval2);
}
}
else {
/* 周期起動しないので,終了処理 */
p_schtblcb->status = SCHEDULETABLE_STOPPED;
p_schtblexpinfo->p_schtblcb = NULL;
p_schtblcb->p_prevschtblcb = NULL;
p_schtblcb->p_nextschtblcb = NULL;
}
}
return(loopcont);
}
#endif /* TOPPERS_schtbl_tail */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: trace_config.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* トレースログに関する設定
*/
#ifndef TOPPERS_TRACE_CONFIG_H
#define TOPPERS_TRACE_CONFIG_H
#ifdef TOPPERS_ENABLE_TRACE
/*
* 機能コードの読み込み
*/
#include "kernel_fncode.h"
/*
* トレースログバッファのサイズ
*/
#ifndef TCNT_TRACE_BUFFER
#define TCNT_TRACE_BUFFER UINT_C(8192)
#endif /* TCNT_TRACE_BUFFER */
/*
* トレース時刻の取得方法
*/
#ifndef GET_UTIM
#define GET_UTIM() (get_tim_utime())
#endif /* GET_UTIM */
#ifndef TOPPERS_MACRO_ONLY
/*
* トレースログのデータ構造
*
* システムログ機能のログ情報のデータ構造と同じものを用いる
*/
#include "t_syslog.h"
typedef SYSLOG TRACE;
typedef uint32 TraceModeType; /* サービスコールの動作モード */
#endif /* TOPPERS_MACRO_ONLY */
/*
* トレースモードの定義
*/
#define TRACE_STOP UINT_C(0x00) /* トレース停止 */
#define TRACE_RINGBUF UINT_C(0x01) /* リングバッファモード */
#define TRACE_AUTOSTOP UINT_C(0x02) /* 自動停止モード */
#define TRACE_CLEAR UINT_C(0x04) /* トレースログのクリア */
#ifndef TOPPERS_MACRO_ONLY
/*
* トレースログ機能の初期化
*
* トレースログ機能を初期化する.初期化ルーチンとして登録することを想
* 定している.引数により次の動作を行う
*
* TRACE_STOP:初期化のみでトレースは開始しない
* TRACE_RINGBUF:リングバッファモードでトレースを開始
* TRACE_AUTOSTOP:自動停止モードでトレースを開始
*/
extern void trace_initialize(uintptr exinf);
/*
* トレースログの開始
*
* トレースログの記録を開始/停止する.引数により次の動作を行う
*
* TRACE_STOP:トレースを停止
* TRACE_RINGBUF:リングバッファモードでトレースを開始
* TRACE_AUTOSTOP:自動停止モードでトレースを開始
* TRACE_CLEAR:トレースログをクリア
*/
extern StatusType trace_sta_log(TraceModeType mode);
/*
* トレースログの読出し
*/
extern StatusType trace_rea_log(TRACE *p_trace);
/*
* トレースログのダンプ(trace_dump.c)
*
* トレースログをダンプする.終了処理ルーチンとして登録することも想定
* している.引数として,ダンプ先となる文字出力関数へのポインタを渡す
* ターゲット依存の低レベル文字出力を利用する場合には,target_putcを渡
* す
*/
extern void trace_dump(void (*exinf)(char8 c));
/*
* トレースログを出力するためのライブラリ関数
*/
extern void trace_write_0(uint32 type);
extern void trace_write_1(uint32 type, const uintptr arg1);
extern void trace_write_2(uint32 type, uintptr arg1, uintptr arg2);
extern void trace_write_3(uint32 type, uintptr arg1, uintptr arg2, uintptr arg3);
extern void trace_write_4(uint32 type, uintptr arg1, uintptr arg2, uintptr arg3, uintptr arg4);
extern void trace_write_5(uint32 type, uintptr arg1, uintptr arg2, uintptr arg3, uintptr arg4, uintptr arg5);
/*
* トレースログを出力するためのマクロ
*/
#define trace_0(type) trace_write_0((type))
#define trace_1(type, arg1) trace_write_1((type), (arg1))
#define trace_2(type, arg1, arg2) trace_write_2((type), (arg1), (arg2))
#define trace_3(type, arg1, arg2, arg3) trace_write_3((type), (arg1), (arg2), (arg3))
#define trace_4(type, arg1, arg2, arg3, arg4) trace_write_4((type), (arg1), (arg2), (arg3), (arg4))
#define trace_5(type, arg1, arg2, arg3, arg4, arg5) trace_write_5((type), (arg1), (arg2), (arg3), (arg4), (arg5))
#endif /* TOPPERS_MACRO_ONLY */
/*
* トレースログ方法の設定
*/
/*
* 割込みサービスルーチンの前後
*/
#define LOG_ISR_ENTER(isrid) trace_1(LOG_TYPE_ISR | LOG_ENTER, (isrid))
#define LOG_ISR_LEAVE(isrid) trace_1(LOG_TYPE_ISR | LOG_LEAVE, (isrid))
/*
* アラームハンドラの前後
*/
#define LOG_ALM_ENTER(p_almcb) trace_1(LOG_TYPE_ALM | LOG_ENTER, (uintptr) (p_almcb))
#define LOG_ALM_LEAVE(p_almcb) trace_1(LOG_TYPE_ALM | LOG_LEAVE, (uintptr) (p_almcb))
/*
* スケジュールテーブル満了処理の前後
*/
#define LOG_SCHTBL_ENTER(p_schtblcb) trace_1(LOG_TYPE_SCHTBL | LOG_ENTER, (uintptr) (p_schtblcb))
#define LOG_SCHTBL_LEAVE(p_schtblcb) trace_1(LOG_TYPE_SCHTBL | LOG_LEAVE, (uintptr) (p_schtblcb))
/*
* タスクの状態変更
*/
#define LOG_TSKSTAT(p_tcb) trace_2(LOG_TYPE_TSKSTAT, (uintptr) (p_tcb), (uintptr) (p_tcb)->tstat)
/*
* ディスパッチャの前後
*/
#define LOG_DSP_ENTER(p_tcb) trace_1(LOG_TYPE_DSP | LOG_ENTER, (p_tcb))
#define LOG_DSP_LEAVE(p_tcb) trace_1(LOG_TYPE_DSP | LOG_LEAVE, (p_tcb))
/*
* ユーザーマーク
*/
#define LOG_TYPE_USER_MARK UINT_C(0x100)
#define LOG_USER_MARK(str) trace_1(LOG_TYPE_USER_MARK, &(str))
/*
* システムコール
*/
/*
* タスク管理機能
*/
#define LOG_ACTTSK_ENTER(tskid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_ACTIVATETASK, (uintptr) (tskid))
#define LOG_ACTTSK_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_ACTIVATETASK, (uintptr) (ercd))
#define LOG_TERTSK_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_TERMINATETASK)
#define LOG_TERTSK_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_TERMINATETASK, (uintptr) (ercd))
#define LOG_CHNTSK_ENTER(tskid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_CHAINTASK, (uintptr) (tskid))
#define LOG_CHNTSK_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_CHAINTASK, (uintptr) (ercd))
#define LOG_SCHED_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_SCHEDULE)
#define LOG_SCHED_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_SCHEDULE, (uintptr) (ercd))
#define LOG_GETTID_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_GETTASKID)
#define LOG_GETTID_LEAVE(ercd, p_tskid) trace_3(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETTASKID, (uintptr) (ercd), (((ercd) == E_OK) ? (uintptr) (*(p_tskid)) : (0U)))
#define LOG_GETTST_ENTER(tskid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_GETTASKSTATE, (uintptr) (tskid))
#define LOG_GETTST_LEAVE(ercd, p_state) trace_3(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETTASKSTATE, (uintptr) (ercd), (((ercd) == E_OK) ? (uintptr) (*(p_state)) : (0U)))
/*
* イベント機能
*/
#define LOG_SETEVT_ENTER(tskid, mask) trace_3(LOG_TYPE_SVC | LOG_ENTER, TFN_SETEVENT, (uintptr) (tskid), (uintptr) (mask))
#define LOG_SETEVT_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_SETEVENT, (uintptr) (ercd))
#define LOG_CLREVT_ENTER(p_runtsk, mask) trace_3(LOG_TYPE_SVC | LOG_ENTER, TFN_CLEAREVENT, (uintptr) (p_runtsk), (uintptr) (mask))
#define LOG_CLREVT_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_CLEAREVENT, (uintptr) (ercd))
#define LOG_GETEVT_ENTER(tskid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_GETEVENT, (uintptr) (tskid))
#define LOG_GETEVT_LEAVE(ercd, tskid, p_mask) trace_4(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETEVENT, (uintptr) (ercd), (uintptr) (tskid), (((ercd) == E_OK) ? (uintptr) (*(p_mask)) : (0U)))
#define LOG_WAIEVT_ENTER(p_runtsk, mask) trace_3(LOG_TYPE_SVC | LOG_ENTER, TFN_WAITEVENT, (uintptr) (p_runtsk), (uintptr) (mask))
#define LOG_WAIEVT_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_WAITEVENT, (uintptr) (ercd))
/*
* リソース機能
*/
#define LOG_GETRES_ENTER(resid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_GETRESOURCE, (uintptr) (resid))
#define LOG_GETRES_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETRESOURCE, (uintptr) (ercd))
#define LOG_RELRES_ENTER(resid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_RELEASERESOURCE, (uintptr) (resid))
#define LOG_RELRES_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_RELEASERESOURCE, (uintptr) (ercd))
/*
* アラーム機能
*/
#define LOG_GETALB_ENTER(almid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_GETALARMBASE, (uintptr) (almid))
#define LOG_GETALB_LEAVE(ercd, info) trace_5(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETALARMBASE, (uintptr) (ercd), (((ercd) == E_OK) ? ((info)->maxallowedvalue) : (0U)), (((ercd) == E_OK) ? ((info)->ticksperbase) : (0U)), (((ercd) == E_OK) ? ((info)->mincycle) : (0U)))
#define LOG_GETALM_ENTER(almid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_GETALARM, (uintptr) (almid))
#define LOG_GETALM_LEAVE(ercd, p_tick) trace_3(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETALARM, (uintptr) (ercd), (((ercd) == E_OK) ? (uintptr) (*(p_tick)) : (0U)))
#define LOG_SETREL_ENTER(almid, incr, cycle) trace_4(LOG_TYPE_SVC | LOG_ENTER, TFN_SETRELALARM, (uintptr) (almid), (uintptr) (incr), (uintptr) (cycle))
#define LOG_SETREL_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_SETRELALARM, (uintptr) (ercd))
#define LOG_SETABS_ENTER(almid, start, cycle) trace_4(LOG_TYPE_SVC | LOG_ENTER, TFN_SETABSALARM, (uintptr) (almid), (uintptr) (start), (uintptr) (cycle))
#define LOG_SETABS_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_SETABSALARM, (uintptr) (ercd))
#define LOG_CANALM_ENTER(almid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_CANCELALARM, (uintptr) (almid))
#define LOG_CANALM_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_CANCELALARM, (uintptr) (ercd))
/*
* カウンタ機能
*/
#define LOG_INCCNT_ENTER(cntid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_INCREMENTCOUNTER, (uintptr) (cntid))
#define LOG_INCCNT_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_INCREMENTCOUNTER, (uintptr) (ercd))
#define LOG_GETCNT_ENTER(cntid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_GETCOUNTERVALUE, (uintptr) (cntid))
#define LOG_GETCNT_LEAVE(ercd, p_val) trace_3(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETCOUNTERVALUE, (uintptr) (ercd), (((ercd) == E_OK) ? (uintptr) (*(p_val)) : (0U)))
#define LOG_GETEPS_ENTER(cntid, p_val) trace_3(LOG_TYPE_SVC | LOG_ENTER, TFN_GETELAPSEDVALUE, (uintptr) (cntid), (((p_val) == NULL) ? (0U) : *(p_val)))
#define LOG_GETEPS_LEAVE(ercd, p_val, p_eval) trace_4(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETELAPSEDVALUE, (uintptr) (ercd), (((ercd) == E_OK) ? (uintptr) (*(p_val)) : (0U)), (((ercd) == E_OK) ? (uintptr) (*(p_eval)) : (0U)))
/*
* スケジュールテーブル機能
*/
#define LOG_STASCHTBLREL_ENTER(schtblid, offset) trace_3(LOG_TYPE_SVC | LOG_ENTER, TFN_STARTSCHEDULETABLEREL, (uintptr) (schtblid), (uintptr) (offset))
#define LOG_STASCHTBLREL_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_STARTSCHEDULETABLEREL, (uintptr) (ercd))
#define LOG_STASCHTBLABS_ENTER(schtblid, start) trace_3(LOG_TYPE_SVC | LOG_ENTER, TFN_STARTSCHEDULETABLEABS, (uintptr) (schtblid), (uintptr) (start))
#define LOG_STASCHTBLABS_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_STARTSCHEDULETABLEABS, (uintptr) (ercd))
#define LOG_STPSCHTBL_ENTER(schtblid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_STOPSCHEDULETABLE, (uintptr) (schtblid))
#define LOG_STPSCHTBL_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_STOPSCHEDULETABLE, (uintptr) (ercd))
#define LOG_NXTSCHTBL_ENTER(from, to) trace_3(LOG_TYPE_SVC | LOG_ENTER, TFN_NEXTSCHEDULETABLE, (uintptr) (from), (uintptr) (to))
#define LOG_NXTSCHTBL_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_NEXTSCHEDULETABLE, (uintptr) (ercd))
#define LOG_GETSCHTBLST_ENTER(schtblid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_GETSCHEDULETABLESTATUS, (uintptr) (schtblid))
#define LOG_GETSCHTBLST_LEAVE(ercd, p_status) trace_3(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETSCHEDULETABLESTATUS, (uintptr) (ercd), (((ercd) == E_OK) ? (uintptr) (*(p_status)) : (0U)))
/*
* 割込み管理機能
*/
#define LOG_DISINT_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_DISABLEALLINTERRUPTS)
#define LOG_DISINT_LEAVE() trace_1(LOG_TYPE_SVC | LOG_LEAVE, TFN_DISABLEALLINTERRUPTS)
#define LOG_ENAINT_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_ENABLEALLINTERRUPTS)
#define LOG_ENAINT_LEAVE() trace_1(LOG_TYPE_SVC | LOG_LEAVE, TFN_ENABLEALLINTERRUPTS)
#define LOG_SUSALL_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_SUSPENDALLINTERRUPTS)
#define LOG_SUSALL_LEAVE() trace_1(LOG_TYPE_SVC | LOG_LEAVE, TFN_SUSPENDALLINTERRUPTS)
#define LOG_RSMALL_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_RESUMEALLINTERRUPTS)
#define LOG_RSMALL_LEAVE() trace_1(LOG_TYPE_SVC | LOG_LEAVE, TFN_RESUMEALLINTERRUPTS)
#define LOG_SUSOSI_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_SUSPENDOSINTERRUPTS)
#define LOG_SUSOSI_LEAVE() trace_1(LOG_TYPE_SVC | LOG_LEAVE, TFN_SUSPENDOSINTERRUPTS)
#define LOG_RSMOSI_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_RESUMEOSINTERRUPTS)
#define LOG_RSMOSI_LEAVE() trace_1(LOG_TYPE_SVC | LOG_LEAVE, TFN_RESUMEOSINTERRUPTS)
#define LOG_GETISRID_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_GETISRID)
#define LOG_GETISRID_LEAVE(isrid) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETISRID, (uintptr) (isrid))
#define LOG_DISINTSRC_ENTER(isrid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_DISABLEINTERRUPTSOURCE, (uintptr) (isrid))
#define LOG_DISINTSRC_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_DISABLEINTERRUPTSOURCE, (uintptr) (ercd))
#define LOG_ENAINTSRC_ENTER(isrid) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_ENABLEINTERRUPTSOURCE, (uintptr) (isrid))
#define LOG_ENAINTSRC_LEAVE(ercd) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_ENABLEINTERRUPTSOURCE, (uintptr) (ercd))
/*
* カーネルの初期化と終了処理
*/
#define LOG_STAOS_ENTER(mode)
#define LOG_STAOS_LEAVE()
#define LOG_STUTOS_ENTER(ercd) trace_2(LOG_TYPE_SVC | LOG_ENTER, TFN_SHUTDOWNOS, (uintptr) (ercd))
#define LOG_STUTOS_LEAVE()
#define LOG_GETAAM_ENTER() trace_1(LOG_TYPE_SVC | LOG_ENTER, TFN_GETACTIVEAPPLICATIONMODE)
#define LOG_GETAAM_LEAVE(mode) trace_2(LOG_TYPE_SVC | LOG_LEAVE, TFN_GETACTIVEAPPLICATIONMODE, (uintptr) (mode))
#define LOG_STAHOOK_ENTER() trace_0(LOG_TYPE_STAHOOK | LOG_ENTER)
#define LOG_STAHOOK_LEAVE() trace_0(LOG_TYPE_STAHOOK | LOG_LEAVE)
#define LOG_ERRHOOK_ENTER(ercd) trace_1(LOG_TYPE_ERRHOOK | LOG_ENTER, (uintptr) (ercd))
#define LOG_ERRHOOK_LEAVE() trace_0(LOG_TYPE_ERRHOOK | LOG_LEAVE)
#define LOG_PROHOOK_ENTER(ercd) trace_1(LOG_TYPE_PROHOOK | LOG_ENTER, (uintptr) (ercd))
#define LOG_PROHOOK_LEAVE(pret) trace_1(LOG_TYPE_PROHOOK | LOG_LEAVE, (uintptr) (pret))
#define LOG_SHUTHOOK_ENTER(ercd) trace_1(LOG_TYPE_SHUTHOOK | LOG_ENTER, (uintptr) (ercd))
#define LOG_SHUTHOOK_LEAVE() trace_0(LOG_TYPE_SHUTHOOK | LOG_LEAVE)
/*
* システムログ機能
*/
#define LOG_SYSLOG_WRI_LOG_LEAVE(ercd)
#define LOG_SYSLOG_REA_LOG_ENTER(p_syslog)
#define LOG_SYSLOG_REA_LOG_LEAVE(ercd, p_syslog)
#define LOG_SYSLOG_MSK_LOG_ENTER(lowmask)
#define LOG_SYSLOG_MSK_LOG_LEAVE(ercd)
#define LOG_SYSLOG_REF_LOG_ENTER(pk_rlog)
#define LOG_SYSLOG_REF_LOG_LEAVE(pk_rlog)
#endif /* TOPPERS_ENABLE_TRACE */
#endif /* TOPPERS_TRACE_CONFIG_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2019 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: prc_insn.h 911 2020-07-24 06:25:32Z nces-mtakada $
*/
/*
* プロセッサの特殊命令のインライン関数定義(V850用)
*/
#ifndef TOPPERS_PRC_INSN_H
#define TOPPERS_PRC_INSN_H
#ifndef TOPPERS_MACRO_ONLY
#define V850_MEMORY_CHANGED Asm("" ::: "memory");
#define SYNCM Asm("syncm");
LOCAL_INLINE uint32
current_psw(void)
{
volatile uint32 psw;
Asm(" ldsr r0,31 \n" /* Select CPU function grp */
"\t stsr 5 , %0 \n"
: "=r" (psw) :);
return(psw);
}
LOCAL_INLINE void
set_psw(uint32 psw)
{
Asm(" ldsr r0,31 \n" /* Select CPU function grp */
"\t ldsr %0 , 5 \n"
: : "r" (psw));
return;
}
LOCAL_INLINE void
set_psw_wo_fgs(uint32 psw)
{
Asm("\t ldsr %0 , 5 \n"
: : "r" (psw));
return;
}
LOCAL_INLINE void
disable_int(void)
{
Asm(" di");
}
LOCAL_INLINE void
enable_int(void)
{
Asm(" ei");
}
LOCAL_INLINE void
set_bit(uint8 bit_offset, uint32 addr)
{
uint32 any;
Asm("mov %1 , %0;"
"set1 %2 , 0[%0]" : "=r" (any) : "i" (addr), "i" (bit_offset));
}
LOCAL_INLINE void
clr_bit(uint8 bit_offset, uint32 addr)
{
uint32 any;
Asm("mov %1 , %0;"
"clr1 %2 , 0[%0]" : "=r" (any) : "i" (addr), "i" (bit_offset));
}
#ifdef __v850e2v3__
#elif defined(__v850e3v5__)
/*
* V850E3V5用の割込みコントローラ操作ルーチン
*/
LOCAL_INLINE void
set_pmr(uint16 pmr)
{
uint32 psw;
/* PMR must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
Asm("ldsr %0, sr11, 2" ::"r" (pmr));
set_psw_wo_fgs(psw);
}
LOCAL_INLINE uint16
get_ispr(void)
{
uint16 ispr;
Asm("stsr sr10, %0, 2" : "=r" (ispr) :);
return(ispr);
}
LOCAL_INLINE void
clear_ispr(void)
{
uint32 psw;
/* ISPR must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
Asm("ldsr %0, sr13, 2" ::"r" (1)); /* INTCFG = 1; ISPR を書き換え可能に */
Asm("ldsr %0, sr10, 2" ::"r" (0)); /* ISPR = 0 */
Asm("ldsr %0, sr13, 2" ::"r" (0)); /* INTCFG = 0; ISPR を書き換え禁止に(自動更新に) */
set_psw_wo_fgs(psw);
}
LOCAL_INLINE uint32
current_cpuid(void)
{
uint32 htcfg0_val;
Asm("stsr sr0, %0, 2":"=r"(htcfg0_val):);
return(((htcfg0_val >> 16) & 0x03));
}
LOCAL_INLINE void
set_intbp(uint32 intbp)
{
uint32 psw;
/* INTBP must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
Asm("\t ldsr %0, 4, 1 \n"
: : "r" (intbp));
set_psw_wo_fgs(psw);
return;
}
#else /* __v850e3v5__ */
#error please define ether __v850e2v3__ or __v850e3v5__
#endif /* __v850e2v3__ */
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_PRC_INSN_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: kernel_impl.h 739 2017-01-24 10:05:05Z nces-hibino $
*/
/*
* ATK2内部向け標準ヘッダファイル
*
* このヘッダファイルは,カーネルを構成するプログラムのソースファイル
* で必ずインクルードするべき標準ヘッダファイルである
*
* アセンブリ言語のソースファイルからこのファイルをインクルードする時
* は,TOPPERS_MACRO_ONLYを定義しておく
* これにより,マクロ定義以外を除くようになっている
*/
#ifndef TOPPERS_KERNEL_IMPL_H
#define TOPPERS_KERNEL_IMPL_H
#include "kernel_rename.h"
/*
* アプリケーションと共通のヘッダファイル
*/
#define OMIT_INCLUDE_OS_LCFG
#include "Os.h"
/* 無効ポインタ */
#ifndef NULL
#define NULL NULL_PTR
#endif /* NULL */
/*
* 型キャストを行うマクロの定義
*/
#ifndef CAST
#define CAST(type, val) ((type) (val))
#endif /* CAST */
#ifndef TOPPERS_MACRO_ONLY
/* 最適化するため,依存部再定義できる型 */
#ifndef OMIT_DATA_TYPE
/*
* カーネル内部のデータ型
*/
typedef uint32 InterruptNumberType; /* 割込み番号 */
typedef uint32 AttributeType; /* オブジェクトの属性 */
typedef sint32 PriorityType; /* 優先度 */
#endif /* OMIT_DATA_TYPE */
typedef void (*FunctionRefType)(void); /* プログラムの起動番地 */
typedef struct task_control_block TCB; /* TCB 解決のための宣言 */
#ifdef TOPPERS_ENABLE_TRACE
extern void log_dsp_enter(const TCB *p_tcb);
extern void log_dsp_leave(const TCB *p_tcb);
#endif
/*
* エラーフックOFF時,サービスID取得とパラメータ取得もOFFになる
*/
#ifdef CFG_USE_ERRORHOOK
#ifdef CFG_USE_PARAMETERACCESS
extern ErrorHook_Par temp_errorhook_par1;
extern ErrorHook_Par temp_errorhook_par2;
extern ErrorHook_Par temp_errorhook_par3;
#endif /* CFG_USE_PARAMETERACCESS */
#endif /* CFG_USE_ERRORHOOK */
/*
* OS内部からのShutdownOSの呼び出し
*/
extern void internal_shutdownos(StatusType ercd);
#ifdef CFG_USE_SHUTDOWNHOOK
extern void internal_call_shtdwnhk(StatusType ercd);
#endif /* CFG_USE_SHUTDOWNHOOK */
#endif /* TOPPERS_MACRO_ONLY */
/*
* ASSERTマクロ
*/
#ifndef NDEBUG
#define ASSERT(exp) do { \
if (!(exp)) { \
fatal_file_name = __FILE__; \
fatal_line_num = __LINE__; \
internal_shutdownos(E_OS_SYS_ASSERT_FATAL); \
} \
} while (0)
#define ASSERT_NO_REACHED do { \
fatal_file_name = __FILE__; \
fatal_line_num = __LINE__; \
internal_shutdownos(E_OS_SYS_ASSERT_FATAL); \
} while (0)
#else /* NDEBUG */
#define ASSERT(exp)
#define ASSERT_NO_REACHED
#endif /* NDEBUG */
/*
* ターゲット依存情報の定義
*/
#include "target_config.h"
/*
* すべての関数をコンパイルするための定義
*/
#ifdef ALLFUNC
#include "allfunc.h"
#endif /* ALLFUNC */
/*
* アプリケーションモード値の定義
*/
#define APPMODE_NONE ((AppModeType) 0) /* モードなし */
/*
* 実行中のコンテキスト(callevel_statの下位12ビット)の値の定義
* TCL_NULLの時に,本来の呼出下コンテキストが判別できなくなることに注意
*/
#define TCL_NULL UINT_C(0x0000) /* システムサービスを呼び出せない */
#define TCL_TASK UINT_C(0x0001) /* タスク */
#define TCL_ISR2 UINT_C(0x0002) /* C2ISR */
#define TCL_PROTECT UINT_C(0x0004) /* ProtectionHook */
#define TCL_PREPOST UINT_C(0x0008) /* PreTaskHook,PostTaskHook */
#define TCL_STARTUP UINT_C(0x0010) /* StartupHook */
#define TCL_SHUTDOWN UINT_C(0x0020) /* ShutdownHook */
#define TCL_ERROR UINT_C(0x0040) /* ErrorHook */
#define TCL_ALRMCBAK UINT_C(0x0080) /* Alarm CallBack routine */
#define TCLMASK UINT_C(0x0fff) /* コールレベルを示すビットのマスク */
/*
* システム状態 (callevel_statの上位4ビット)の値の定義
*/
#define TSYS_NULL UINT_C(0x0000) /* システム状態クリア */
#define TSYS_DISALLINT UINT_C(0x1000) /* DisableAllInterrupts発行中 */
#define TSYS_SUSALLINT UINT_C(0x2000) /* SuspendAllInterrupts発行中 */
#define TSYS_SUSOSINT UINT_C(0x4000) /* SuspendOSInterrupts発行中 */
#define TSYS_ISR1 UINT_C(0x8000) /* C1ISR起動済み */
#define TSYSMASK UINT_C(0xf000) /* システム状態を示すビットのマスク */
#ifdef CFG_USE_STACKMONITORING
#ifndef STACK_MAGIC_NUMBER
/*
* スタックモニタリング用マジックナンバーの定義
* ターゲット依存部の定義は優先される
*/
#define STACK_MAGIC_NUMBER 0x4E434553 /* NCESのASCIIコード(0x4E434553) */
#endif /* STACK_MAGIC_NUMBER */
#ifndef TOPPERS_ISTK_MAGIC_REGION
/* 割込みスタック用マジックナンバー領域取得マクロ */
#define TOPPERS_ISTK_MAGIC_REGION(stk, stksz) (stk)
#endif /* TOPPERS_ISTK_MAGIC_REGION */
#ifndef TOPPERS_TSTK_MAGIC_REGION
/* タスクスタック用マジックナンバー領域取得マクロ */
#ifndef USE_TSKINICTXB
#define TOPPERS_TSTK_MAGIC_REGION(p_tinib) ((StackType *) ((p_tinib)->stk))
#endif /* USE_TSKINICTXB */
#endif /* TOPPERS_TSTK_MAGIC_REGION */
#endif /* CFG_USE_STACKMONITORING */
/*
* callevel_statのビット操作
*/
#define ENTER_CALLEVEL(bit) (callevel_stat |= (bit))
#define LEAVE_CALLEVEL(bit) (callevel_stat &= (uint16) ~(uint32) (bit))
/*
* 各システムサービスを呼び出せる処理単位
*/
#define CALLEVEL_ACTIVATETASK (TCL_TASK | TCL_ISR2)
#define CALLEVEL_TERMINATETASK (TCL_TASK)
#define CALLEVEL_CHAINTASK (TCL_TASK)
#define CALLEVEL_SCHEDULE (TCL_TASK)
#define CALLEVEL_GETTASKID (TSYS_DISALLINT | TSYS_SUSALLINT | TSYS_SUSOSINT | TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PREPOST | TCL_PROTECT)
#define CALLEVEL_GETTASKSTATE (TSYS_DISALLINT | TSYS_SUSALLINT | TSYS_SUSOSINT | TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PREPOST)
#define CALLEVEL_GETRESOURCE (TCL_TASK | TCL_ISR2)
#define CALLEVEL_RELEASERESOURCE (TCL_TASK | TCL_ISR2)
#define CALLEVEL_SETEVENT (TCL_TASK | TCL_ISR2)
#define CALLEVEL_CLEAREVENT (TCL_TASK)
#define CALLEVEL_GETEVENT (TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PREPOST)
#define CALLEVEL_WAITEVENT (TCL_TASK)
#define CALLEVEL_GETALARMBASE (TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PREPOST)
#define CALLEVEL_GETALARM (TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PREPOST)
#define CALLEVEL_SETRELALARM (TCL_TASK | TCL_ISR2)
#define CALLEVEL_SETABSALARM (TCL_TASK | TCL_ISR2)
#define CALLEVEL_CANCELALARM (TCL_TASK | TCL_ISR2)
#define CALLEVEL_GETACTIVEAPPMODE (TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PREPOST | TCL_STARTUP | TCL_SHUTDOWN)
#define CALLEVEL_SHUTDOWNOS (TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_STARTUP)
#define CALLEVEL_GETISRID (TSYS_DISALLINT | TSYS_SUSALLINT | TSYS_SUSOSINT | TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PROTECT)
#define CALLEVEL_INCREMENTCOUNTER (TCL_TASK | TCL_ISR2)
#define CALLEVEL_GETCOUNTERVALUE (TCL_TASK | TCL_ISR2)
#define CALLEVEL_GETELAPSEDVALUE (TCL_TASK | TCL_ISR2)
#define CALLEVEL_STARTSCHEDULETABLEREL (TCL_TASK | TCL_ISR2)
#define CALLEVEL_STARTSCHEDULETABLEABS (TCL_TASK | TCL_ISR2)
#define CALLEVEL_STOPSCHEDULETABLE (TCL_TASK | TCL_ISR2)
#define CALLEVEL_NEXTSCHEDULETABLE (TCL_TASK | TCL_ISR2)
#define CALLEVEL_GETSCHEDULETABLESTATUS (TCL_TASK | TCL_ISR2)
#define CALLEVEL_DISABLEINTERRUPTSOURCE (TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PREPOST | TCL_STARTUP | TCL_SHUTDOWN | TCL_PROTECT | TSYS_DISALLINT | TSYS_SUSALLINT | TSYS_SUSOSINT)
#define CALLEVEL_ENABLEINTERRUPTSOURCE (TCL_TASK | TCL_ISR2 | TCL_ERROR | TCL_PREPOST | TCL_STARTUP | TCL_SHUTDOWN | TCL_PROTECT | TSYS_DISALLINT | TSYS_SUSALLINT | TSYS_SUSOSINT)
#define CALLEVEL_GETFAULTYCONTEXT (TCL_PROTECT)
/*
* その他の定数値(標準割込みモデル)
*/
#define TIPM_ENAALL UINT_C(0) /* 割込み優先度マスク全解除 */
/*
* オブジェクト属性の定義(標準割込みモデル)
*/
#define ENABLE UINT_C(0x01)
#define DISABLE UINT_C(0x00)
/*
* OS内部用無効なシステムサービスID
*/
#define OSServiceId_Invalid ((OSServiceIdType) 0xff)
/*
* ヘッダファイルを持たないモジュールの関数・変数の宣言
*/
#ifndef TOPPERS_MACRO_ONLY
#ifdef TOPPERS_StartOS
/*
* アプリケーションモードの数
*/
extern const AppModeType tnum_appmode;
#endif /* TOPPERS_StartOS */
/*
* OS実行制御のための変数(osctl_manage.c)
*/
extern uint16 callevel_stat; /* 実行中のコンテキスト */
extern AppModeType appmodeid; /* アプリケーションモードID */
/*
* カーネル動作状態フラグ
*/
extern boolean kerflg;
/*
* エラーフック呼び出しのための宣言(osctl.c)
*/
#ifdef CFG_USE_ERRORHOOK
extern void internal_call_errorhook(StatusType ercd, OSServiceIdType svcid);
#endif /* CFG_USE_ERRORHOOK */
/*
* ポストタスクフック/プレタスクフック
* スタックモニタリング機能の初期化/プロテクションフック呼び出しのための宣言(osctl.c)
*/
#ifdef CFG_USE_POSTTASKHOOK
extern void call_posttaskhook(void);
#endif /* CFG_USE_POSTTASKHOOK */
#ifdef CFG_USE_PRETASKHOOK
extern void call_pretaskhook(void);
#endif /* CFG_USE_PRETASKHOOK */
#ifdef CFG_USE_STACKMONITORING
extern void init_stack_magic_region(void);
#endif /* CFG_USE_STACKMONITORING */
extern void call_protectionhk_main(StatusType ercd);
/*
* 各モジュールの初期化(Os_Lcfg.c)
*/
extern void object_initialize(void);
/*
* 各モジュールの終了処理(Os_Lcfg.c)
*/
extern void object_terminate(void);
/*
* 非タスクコンテキスト用のスタック領域(Os_Lcfg.c)
*/
extern const MemorySizeType ostksz; /* スタック領域のサイズ(丸めた値) */
extern StackType * const ostk; /* スタック領域の先頭番地 */
#ifdef TOPPERS_OSTKPT
extern StackType * const ostkpt; /* スタックポインタの初期値 */
#endif /* TOPPERS_OSTKPT */
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_KERNEL_IMPL_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2013-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: kernel_inline_symbols.h 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* コンパイラ依存定義
*/
#ifndef KERNEL_INLINE_SYMBOL_H
#define KERNEL_INLINE_SYMBOL_H
/*
* 共通インクルードのInline関数のシンボル登録
*/
/* queue.h */
#pragma inline queue_initialize
#pragma inline queue_insert_prev
#pragma inline queue_insert_next
#pragma inline queue_delete
#pragma inline queue_delete_next
#pragma inline queue_empty
/*
* ターゲット非依存部のInline関数のシンボル登録
*/
/* counter.h */
#pragma inline add_tick
#pragma inline diff_tick
#pragma inline get_curval
/* task.c */
#pragma inline bitmap_search
#pragma inline primap_empty
#pragma inline primap_search
#pragma inline primap_set
#pragma inline primap_clear
/* t_syslog.h */
#pragma inline syslog
#pragma inline _syslog_0
#pragma inline _syslog_1
#pragma inline _syslog_2
#pragma inline _syslog_3
#pragma inline _syslog_4
#pragma inline _syslog_5
#pragma inline _syslog_6
#endif /* KERNEL_INLINE_SYMBOL_H */
<file_sep>
TOPPERS/ATK2-SC1(Release 1.4.2)
<ATK2-SC1 Readmeファイル>
本ファイルでは,ATK2-SC1 を使用する上で必要な情報を紹介します.
----------------------------------------------------------------------
TOPPERS ATK2
Toyohashi Open Platform for Embedded Real-Time Systems
Automotive Kernel Version 2
Copyright (C) 2011-2017 by Center for Embedded Computing Systems
Graduate School of Information Science, Nagoya Univ., JAPAN
Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
Copyright (C) 2011-2013 by Spansion LLC, USA
Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
Copyright (C) 2011-2017 by Witz Corporation
Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
上記著作権者は,以下の (1)〜(3)の条件を満たす場合に限り,本ドキュメ
ント(本ドキュメントを改変したものを含む.以下同じ)を使用・複製・改
変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
(1) 本ドキュメントを利用する場合には,上記の著作権表示,この利用条件
および下記の無保証規定が,そのままの形でドキュメント中に含まれて
いること.
(2) 本ドキュメントを改変する場合には,ドキュメントを改変した旨の記述
を,改変後のドキュメント中に含めること.ただし,改変後のドキュメ
ントが,TOPPERSプロジェクト指定の開発成果物である場合には,この限
りではない.
(3) 本ドキュメントの利用により直接的または間接的に生じるいかなる損害
からも,上記著作権者およびTOPPERSプロジェクトを免責すること.また,
本ドキュメントのユーザまたはエンドユーザからのいかなる理由に基づ
く請求からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
本ドキュメントは,AUTOSAR(AUTomotive Open System ARchitecture)仕様
に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するものではな
い.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利用する
者に対して,AUTOSARパートナーになることを求めている.
本ドキュメントは,無保証で提供されているものである.上記著作権者およ
びTOPPERSプロジェクトは,本ドキュメントに関して,特定の使用目的に対す
る適合性も含めて,いかなる保証も行わない.また,本ドキュメントの利用
により直接的または間接的に生じたいかなる損害に関しても,その責任を負
わない.
$Id: README.txt 761 2017-03-01 07:28:00Z witz-itoyo $
----------------------------------------------------------------------
ATK2-SC1は,「AUTOSAR R4.0 Rev 3」仕様に準拠した,スケーラビリティク
ラス1の機能を実装したリアルタイムカーネルです.
【ジェネレータのバージョンに関する注意】
ATK2-SC1 Release 1.4.0以降では,TOPPERS新世代カーネル用コンフィギュレー
タ(cfg)(ジェネレータと呼ぶ)の最新版(1.9.6)の機能を用いている.
1.9.4以前のバージョンでは動作しないので注意すること.
【最初に読むべきドキュメント】
ATK2-SC1のユーザーズマニュアルが,doc/user.txtにあります.ATK2-SC1を
使用する場合には,まずはこのドキュメントからお読み下さい.
【ファイルの閲覧にあたって】
ATK2-SC1のドキュメント(プレーンテキストファイル)およびソースファイル
を読む際には,TABを4に設定してください.
【利用条件】
ATK2-SC1の利用条件は,各ファイルの先頭に表示されているTOPPERSライセン
スです.TOPPERSライセンスに関するFAQが,以下のページにあります.
http://www.toppers.jp/faq/faq_ct12.html
【質問・バグレポート・意見等の送付先】
ATK2-SC1をより良いものにするためのご意見等を歓迎します.ATK2-SC1に関
する質問やバグレポート,ご意見等は,TOPPERSプロジェクトの会員はTOPPERS
開発者メーリングリスト(<EMAIL>)宛に,その他の方はTOPPERSユー
ザーズメーリングリスト(<EMAIL>)宛にお願いします.
TOPPERSユーザーズメーリングリストへの登録方法については,以下のページ
に説明があります.
http://www.toppers.jp/community.html
【ポーティングにあたって】
ATK2-SC1を,TOPPERSプロジェクトから公開することを前提に,未サポートの
ターゲットにポーティングされる場合には,あらかじめご相談くださると幸い
です.
以上
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2016 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: prc_config.c 557 2016-01-06 10:37:19Z ertl-honda $
*/
/*
* プロセッサ依存モジュール(V850用)
*/
#include "kernel_impl.h"
/*
* 例外(割込み/CPU例外)のネスト回数のカウント
* コンテキスト参照のために使用
*/
uint32 except_nest_cnt;
#ifdef CFG_USE_PROTECTIONHOOK
uint32 v850_cpu_exp_no;
uint32 v850_cpu_exp_pc;
uint32 v850_cpu_exp_sp;
#endif /* CFG_USE_PROTECTIONHOOK */
/*
* 現在の割込み優先度マスクの値(内部表現)
*/
uint8 current_iintpri;
/* 割り込み要求マスクテーブル */
const uint16 pmr_setting_tbl[] =
{
#if TNUM_INTPRI == 16
0xffff, /* ISR2 LEVEL -16 MASK */
0xfffe, /* ISR2 LEVEL -15 MASK */
0xfffc, /* ISR2 LEVEL -14 MASK */
0xfff8, /* ISR2 LEVEL -13 MASK */
0xfff0, /* ISR2 LEVEL -12 MASK */
0xffe0, /* ISR2 LEVEL -11 MASK */
0xffc0, /* ISR2 LEVEL -10 MASK */
0xff80, /* ISR2 LEVEL -9 MASK */
0xff00, /* ISR2 LEVEL -8 MASK */
0xfe00, /* ISR2 LEVEL -7 MASK */
0xfc00, /* ISR2 LEVEL -6 MASK */
0xf800, /* ISR2 LEVEL -5 MASK */
0xf000, /* ISR2 LEVEL -4 MASK */
0xe000, /* ISR2 LEVEL -3 MASK */
0xc000, /* ISR2 LEVEL -2 MASK */
0x8000, /* ISR2 LEVEL -1 MASK */
0x0000 /* Dummy */
#elif TNUM_INTPRI == 8
0x00ff, /* ISR2 LEVEL -8 MASK */
0x00fe, /* ISR2 LEVEL -7 MASK */
0x00fc, /* ISR2 LEVEL -6 MASK */
0x00f8, /* ISR2 LEVEL -5 MASK */
0x00f0, /* ISR2 LEVEL -4 MASK */
0x00e0, /* ISR2 LEVEL -3 MASK */
0x00c0, /* ISR2 LEVEL -2 MASK */
0x0080, /* ISR2 LEVEL -1 MASK */
0x0000 /* Dummy */
#else
#error TNUM_INTPRI is illegal.
#endif /* TNUM_INTPRI == 16 */
};
/*
* x_nested_lock_os_int()のネスト回数
*/
volatile uint8 nested_lock_os_int_cnt;
/*
* OS割込み禁止状態の時に割込み優先度マスクを保存する変数
*/
volatile uint16 current_intpri;
/*
* 起動時のハードウェア初期化
*/
void
prc_hardware_initialize(void)
{
}
#ifdef __v850e3v5__
extern const uint32 intbp_tbl[];
#endif /* __v850e3v5__ */
/*
* プロセッサ依存の初期化
*/
void
prc_initialize(void)
{
/*
* カーネル起動時は非タスクコンテキストとして動作させるため1に
*/
except_nest_cnt = 1U;
/*
* 割込み優先度マスクの初期値は最低優先度
*/
current_iintpri = INT_IPM(0);
#ifdef __v850e3v5__
/* テーブル参照方式のINTBPアドレス設定 */
set_intbp((uint32)intbp_tbl);
#endif /* __v850e3v5__ */
}
/*
* プロセッサ依存の終了処理
*/
void
prc_terminate(void)
{
/* 割り込み処理中で終了した場合を想定してISPRをクリアする */
clear_ispr();
/* 例外処理から終了した場合を想定してNP/EPビットをクリアする */
set_psw(current_psw() & ~(0x0080 | 0x0040));
}
/*
* 割込み要求ラインの属性の設定
*/
void
x_config_int(InterruptNumberType intno, AttributeType intatr, PriorityType intpri)
{
uint32 eic_address;
ASSERT(VALID_INTNO(intno));
eic_address = EIC_ADDRESS(intno);
/*
* 割込みのマスク
*
* 割込みを受け付けたまま,レベルトリガ/エッジトリガの設定や,割
* 込み優先度の設定を行うのは危険なため,割込み属性にかかわらず,
* 一旦マスクする.
*/
(void) x_disable_int(intno);
/*
* 割込み優先度の設定
*/
sil_wrh_mem((void *) eic_address,
((sil_reh_mem((void *) eic_address) & ~0x0f) | INT_IPM(intpri)));
#ifdef __v850e3v5__
/* テーブル参照方式 */
sil_wrh_mem((uint16 *) eic_address,
(sil_reh_mem((uint16 *) eic_address) | (1 << 6)));
#endif /* __v850e3v5__ */
if ((intatr & ENABLE) != 0U) {
/*
* 割込みのマスク解除
*/
(void) x_enable_int(intno);
}
}
#ifndef OMIT_DEFAULT_INT_HANDLER
/*
* 未定義の割込みが入った場合の処理
*/
void
default_int_handler(void)
{
target_fput_str("Unregistered Interrupt occurs.");
ASSERT(0);
}
#endif /* OMIT_DEFAULT_INT_HANDLER */
/*
* 無限ループ処理
* (デバッグ時の無限ループ到達確認用 / 最適化防止のためここで定義する)
*/
void
infinite_loop(void)
{
while (1) {
}
}
/*
* 特定の割込み要求ラインの有効/無効を制御可能かを調べる処理
*/
boolean
target_is_int_controllable(InterruptNumberType intno)
{
/*
* V850では全ての割込み要求ラインに対して
* 有効/無効を制御可能であるため,常にtrueを返す
*/
return(TRUE);
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: resource.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* リソース管理モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "task.h"
#include "interrupt.h"
#include "resource.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_GETRES_ENTER
#define LOG_GETRES_ENTER(resid)
#endif /* LOG_GETRES_ENTER */
#ifndef LOG_GETRES_LEAVE
#define LOG_GETRES_LEAVE(ercd)
#endif /* LOG_GETRES_LEAVE */
#ifndef LOG_RELRES_ENTER
#define LOG_RELRES_ENTER(resid)
#endif /* LOG_RELRES_ENTER */
#ifndef LOG_RELRES_LEAVE
#define LOG_RELRES_LEAVE(ercd)
#endif /* LOG_RELRES_LEAVE */
/*
* リソース管理機能の初期化
*/
#ifdef TOPPERS_resource_initialize
void
resource_initialize(void)
{
ResourceType i;
RESCB *p_rescb;
for (i = 0U; i < tnum_stdresource; i++) {
p_rescb = &(rescb_table[i]);
p_rescb->p_resinib = &(resinib_table[i]);
p_rescb->lockflg = FALSE;
}
}
#endif /* TOPPERS_resource_initialize */
/*
* リソースの獲得
*/
#ifdef TOPPERS_GetResource
StatusType
GetResource(ResourceType ResID)
{
StatusType ercd = E_OK;
PriorityType ceilpri, curpri;
RESCB *p_rescb;
LOG_GETRES_ENTER(ResID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_GETRESOURCE);
CHECK_ID(ResID < tnum_stdresource);
p_rescb = get_rescb(ResID);
ceilpri = p_rescb->p_resinib->ceilpri;
if (callevel_stat == TCL_TASK) {
CHECK_ACCESS(p_runtsk->p_tinib->inipri >= ceilpri);
x_nested_lock_os_int();
D_CHECK_ACCESS(p_rescb->lockflg == FALSE);
curpri = p_runtsk->curpri;
p_rescb->prevpri = curpri;
p_rescb->lockflg = TRUE;
p_rescb->p_prevrescb = p_runtsk->p_lastrescb;
p_runtsk->p_lastrescb = p_rescb;
if (ceilpri < curpri) {
p_runtsk->curpri = ceilpri;
if (ceilpri <= TPRI_MINISR) {
x_set_ipm(ceilpri);
}
}
}
else {
CHECK_ACCESS(GET_INTPRI(p_runisr) >= ceilpri);
x_nested_lock_os_int();
D_CHECK_ACCESS(p_rescb->lockflg == FALSE);
curpri = x_get_ipm();
p_rescb->prevpri = curpri;
p_rescb->lockflg = TRUE;
p_rescb->p_prevrescb = p_runisr->p_lastrescb;
p_runisr->p_lastrescb = p_rescb;
if (ceilpri < curpri) {
x_set_ipm(ceilpri);
}
}
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_GETRES_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.resid = ResID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetResource);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetResource */
/*
* リソースの返却
*/
#ifdef TOPPERS_ReleaseResource
StatusType
ReleaseResource(ResourceType ResID)
{
StatusType ercd = E_OK;
RESCB *p_rescb;
LOG_RELRES_ENTER(ResID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_RELEASERESOURCE);
CHECK_ID(ResID < tnum_stdresource);
p_rescb = get_rescb(ResID);
if (callevel_stat == TCL_TASK) {
CHECK_NOFUNC(p_runtsk->p_lastrescb == p_rescb);
x_nested_lock_os_int();
if (p_rescb->prevpri <= TPRI_MINISR) {
x_set_ipm(p_rescb->prevpri);
}
else {
if (p_runtsk->curpri <= TPRI_MINISR) {
x_set_ipm((PriorityType) TIPM_ENAALL);
}
}
p_runtsk->curpri = p_rescb->prevpri;
p_runtsk->p_lastrescb = p_rescb->p_prevrescb;
p_rescb->lockflg = FALSE;
if (p_runtsk->curpri > nextpri) {
preempt();
dispatch();
}
}
else {
CHECK_NOFUNC(p_runisr->p_lastrescb == p_rescb);
x_nested_lock_os_int();
x_set_ipm(p_rescb->prevpri);
p_runisr->p_lastrescb = p_rescb->p_prevrescb;
p_rescb->lockflg = FALSE;
}
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_RELRES_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.resid = ResID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_ReleaseResource);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_ReleaseResource */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2007-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: trace_dump.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* トレースログのダンプ
*/
#include "kernel_impl.h"
#include "task.h"
#include "alarm.h"
#include "scheduletable.h"
#include "log_output.h"
#include "Os_Lcfg.h"
#include "t_stdlib.h" /* atk2_strerror */
/*
* 処理単位の種別
*/
typedef enum {
PR_UNIT_TASK, /* タスク */
PR_UNIT_ALARM, /* アラーム満了処理 */
PR_UNIT_ISR, /* C2ISR */
PR_UNIT_SCHTBL, /* スケジュールテーブル満了処理 */
PR_UNIT_STA, /* スタートアップフック */
PR_UNIT_ERR, /* エラーフック */
PR_UNIT_PRO, /* プロテクションフック */
PR_UNIT_SHUT /* シャットダウンフック */
} PR_UNIT_TYPE;
/*
* 処理単位のID
*/
typedef struct {
PR_UNIT_TYPE type; /* 処理単位の種別 */
ObjectIDType id; /* 処理単位のID */
} OBJ_ID;
/* 内部関数のプロトタイプ宣言 */
static const char8 *trace_proret_str(ProtectionReturnType ret);
static const char8 *trace_schtblstatus_str(ScheduleTableStatusType status);
static const char8 *trace_task_state_str(TaskStateType state);
static uintptr trace_get_tskid(uintptr info);
static const char8 *trace_print_tskenter(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_tskleave(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_evententer(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_eventleave(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_resenter(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_resleave(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_almenter(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_almleave(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_schtblenter(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_schtblleave(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_intenter(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_intleave(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_sysenter(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_sysleave(const TRACE *trace, uintptr info[]);
static const char8 *trace_print_kerenter(const TRACE *trace, uintptr info[], void (*outputc)(char8 c));
static const char8 *trace_print_svcenter(const TRACE *trace, uintptr info[], void (*outputc)(char8 c));
static const char8 *trace_print_svcleave(const TRACE *trace, uintptr info[]);
static void trace_set_context(PR_UNIT_TYPE type, ObjectIDType id);
static void trace_push_context(PR_UNIT_TYPE type, ObjectIDType id);
static void trace_get_context(uintptr *p_obj_type_str, uintptr *p_id);
static void trace_pop_context(uintptr *p_obj_type_str, uintptr *p_id);
static void trace_change_context(PR_UNIT_TYPE type, ObjectIDType id);
static void trace_resume_context(void);
static void trace_print(const TRACE *p_trace, void (*outputc)(char8 c));
/*
* プロテクションフックの返り値を文字列変換
*/
static const char8 *
trace_proret_str(ProtectionReturnType ret)
{
const char8 *proretstr;
switch (ret) {
case PRO_IGNORE:
proretstr = "IGNORE";
break;
case PRO_SHUTDOWN:
proretstr = "SHUTDOWN";
break;
default:
proretstr = "";
break;
}
return(proretstr);
}
/*
* スケジュールテーブルの状態を文字列変換
*/
static const char8 *
trace_schtblstatus_str(ScheduleTableStatusType status)
{
const char8 *schtblstr;
switch (status) {
case SCHEDULETABLE_STOPPED:
schtblstr = "STOPPED";
break;
case SCHEDULETABLE_NEXT:
schtblstr = "NEXT";
break;
case SCHEDULETABLE_WAITING:
schtblstr = "WAITING";
break;
case SCHEDULETABLE_RUNNING:
schtblstr = "RUNNING";
break;
case SCHEDULETABLE_RUNNING_AND_SYNCHRONOUS:
schtblstr = "RUNNING_AND_SYNCHRONOUS";
break;
default:
schtblstr = "";
break;
}
return(schtblstr);
}
/*
* タスク状態を文字列変換
*/
static const char8 *
trace_task_state_str(TaskStateType state)
{
const char8 *taskstatstr;
switch (state) {
case SUSPENDED:
taskstatstr = "SUSPENDED";
break;
case RUNNING:
taskstatstr = "RUNNING";
break;
case READY:
taskstatstr = "READY";
break;
case WAITING:
taskstatstr = "WAITING";
break;
default:
taskstatstr = "unknown state";
break;
}
return(taskstatstr);
}
/*
* PR_UNIT_TYPEの処理単位種別に対応する文字列
*/
static const char8 *obj_type_to_str[] = {
"task",
"alarm",
"isr",
"schtbl",
"sta",
"err",
"pro",
"shut"
};
/*
* 2つの引数の大きい方を返す
*/
#define MAX(a, b) ((a) < (b) ? (b) : (a))
/*
* 処理単位のネストを管理するスタック
*/
static OBJ_ID context_stack[MAX(4U, 1U + TNUM_ISR2)];
/*
* タスクが実行しているアラーム満了処理,スケジュールテーブル満了処理
* を管理する
* アラーム満了処理はIncrementCounterによりネストする場合がある
* スケジュールテーブル満了処理のネストはない
*/
static OBJ_ID task_exec[TNUM_TASK][TNUM_ALARM + 1U];
/*
* タスクがアラーム満了処理,スケジュールテーブル満了処理を実行してい
* る場合の,task_exec[task_id][index]のindexを示す
* 満了処理を実行していない場合は-1にする
*/
static sint32 task_context_index[TNUM_TASK];
/*
* task_execのC2ISR版
*/
static OBJ_ID isr_exec[TNUM_ISR2][TNUM_ALARM + 1U];
/*
* task_context_indexのC2ISR版
*/
static sint32 isr_context_index[TNUM_ISR2];
/*
* context_stackの現在のインデックス(ネスト数)を示す
*/
static uint32 context_index;
/*
* tcbからタスクIDを取得
*/
static uintptr
trace_get_tskid(uintptr info)
{
TCB *p_tcb;
TaskType tskid;
p_tcb = (TCB *) info;
if (p_tcb == NULL) {
tskid = 0U;
}
else {
tskid = TSKID(p_tcb);
}
return((uintptr) tskid);
}
/*
* タスク管理 - 入口ログ
*/
static const char8 *
trace_print_tskenter(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_ACTIVATETASK:
info[0] = (uintptr) kernel_tskid_str((TaskType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to ActivateTask TaskID=%s(%d).";
break;
case TFN_TERMINATETASK:
tracemsg = "enter to TerminateTask.";
break;
case TFN_CHAINTASK:
info[0] = (uintptr) kernel_tskid_str((TaskType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to ChainTask TaskID=%s(%d).";
break;
case TFN_SCHEDULE:
tracemsg = "enter to Schedule.";
break;
default:
tracemsg = "unknown service call";
break;
}
return(tracemsg);
}
/*
* タスク管理 - 出口ログ
*/
static const char8 *
trace_print_tskleave(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_ACTIVATETASK:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from ActivateTask %s.";
break;
case TFN_TERMINATETASK:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from TerminateTask %s.";
break;
case TFN_CHAINTASK:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from ChainTask %s.";
break;
case TFN_SCHEDULE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from Schedule %s.";
break;
default:
tracemsg = "unknown tsk service call";
break;
}
return(tracemsg);
}
/*
* イベント機能 - 入口ログ
*/
static const char8 *
trace_print_evententer(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_SETEVENT:
info[0] = (uintptr) kernel_tskid_str((TaskType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
info[2] = (uintptr) kernel_evtid_str((TaskType) trace->loginfo[1], (EventMaskType) trace->loginfo[2]);
info[3] = trace->loginfo[2];
tracemsg = "enter to SetEvent TaskID=%s(%d)/Mask=%s(0x%x).";
break;
case TFN_CLEAREVENT:
info[0] = (uintptr) kernel_evtid_str((TaskType) trace_get_tskid(trace->loginfo[1]), (EventMaskType) trace->loginfo[2]);
info[1] = trace->loginfo[2];
tracemsg = "enter to ClearEvent Mask=%s(0x%x).";
break;
case TFN_GETEVENT:
info[0] = (uintptr) kernel_tskid_str((TaskType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to GetEvent TaskID=%s(%d).";
break;
case TFN_WAITEVENT:
info[0] = (uintptr) kernel_evtid_str((TaskType) trace_get_tskid(trace->loginfo[1]), (EventMaskType) trace->loginfo[2]);
info[1] = trace->loginfo[2];
tracemsg = "enter to WaitEvent Mask=%s(0x%x).";
break;
default:
tracemsg = "unknown service call";
break;
}
return(tracemsg);
}
/*
* イベント機能 - 出口ログ
*/
static const char8 *
trace_print_eventleave(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_SETEVENT:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from SetEvent %s.";
break;
case TFN_CLEAREVENT:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from ClearEvent %s.";
break;
case TFN_GETEVENT:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
/* 返り値がE_OKの場合のみ,有効値が入る */
if (trace->loginfo[1] == E_OK) {
info[1] = (uintptr) kernel_evtid_str((TaskType) trace->loginfo[2], (EventMaskType) trace->loginfo[3]);
info[2] = trace->loginfo[3];
tracemsg = "leave from GetEvent %s/Mask=%s(0x%x).";
}
else {
tracemsg = "leave from GetEvent %s.";
}
break;
case TFN_WAITEVENT:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from WaitEvent %s.";
break;
default:
tracemsg = "unknown servic call";
break;
}
return(tracemsg);
}
/*
* リソース機能 - 入口ログ
*/
static const char8 *
trace_print_resenter(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_GETRESOURCE:
info[0] = (uintptr) kernel_resid_str((ResourceType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to GetResource ResID=%s(%d).";
break;
case TFN_RELEASERESOURCE:
info[0] = (uintptr) kernel_resid_str((ResourceType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to ReleaseResource ResID=%s(%d).";
break;
default:
tracemsg = "unknown service call";
break;
}
return(tracemsg);
}
/*
* リソース機能 - 出口ログ
*/
static const char8 *
trace_print_resleave(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_GETRESOURCE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from GetResource %s.";
break;
case TFN_RELEASERESOURCE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from ReleaseResource %s.";
break;
default:
tracemsg = "unknown servic call";
break;
}
return(tracemsg);
}
/*
* アラーム機能 - 入口ログ
*/
static const char8 *
trace_print_almenter(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_GETALARMBASE:
info[0] = (uintptr) kernel_almid_str((AlarmType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to GetAlarmBase AlarmID=%s(%d).";
break;
case TFN_GETALARM:
info[0] = (uintptr) kernel_almid_str((AlarmType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to GetAlarm AlarmID=%s(%d).";
break;
case TFN_SETRELALARM:
info[0] = (uintptr) kernel_almid_str((AlarmType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
info[2] = trace->loginfo[2];
info[3] = trace->loginfo[3];
tracemsg = "enter to SetRelAlarm AlarmID=%s(%d)/increment=%d/cycle=%d.";
break;
case TFN_SETABSALARM:
info[0] = (uintptr) kernel_almid_str((AlarmType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
info[2] = trace->loginfo[2];
info[3] = trace->loginfo[3];
tracemsg = "enter to SetAbsAlarm AlarmID=%s(%d)/start=%d/cycle=%d.";
break;
case TFN_CANCELALARM:
info[0] = (uintptr) kernel_almid_str((AlarmType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to CancelAlarm AlarmID=%s(%d).";
break;
case TFN_INCREMENTCOUNTER:
info[0] = (uintptr) kernel_cntid_str((CounterType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to IncrementCounter CounterID=%s(%d).";
break;
case TFN_GETCOUNTERVALUE:
info[0] = (uintptr) kernel_cntid_str((CounterType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to GetCounterValue CounterID=%s(%d).";
break;
case TFN_GETELAPSEDVALUE:
info[0] = (uintptr) kernel_cntid_str((CounterType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
info[2] = trace->loginfo[2];
tracemsg = "enter to GetElapsedValue CounterID=%s(%d) Value=%d.";
break;
default:
tracemsg = "unknown service call";
break;
}
return(tracemsg);
}
/*
* アラーム機能 - 出口ログ
*/
static const char8 *
trace_print_almleave(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_GETALARMBASE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
/* 返り値がE_OKの場合のみ,有効値が入る */
if (trace->loginfo[1] == E_OK) {
info[1] = trace->loginfo[2];
info[2] = trace->loginfo[3];
info[3] = trace->loginfo[4];
tracemsg = "leave from GetAlarmBase %s/maxval=%d/tickbase=%d/mincyc=%d.";
}
else {
tracemsg = "leave from GetAlarmBase %s.";
}
break;
case TFN_GETALARM:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
/* 返り値がE_OKの場合のみ,有効値が入る */
if (trace->loginfo[1] == E_OK) {
info[1] = trace->loginfo[2];
tracemsg = "leave from GetAlarm %s/Tick=%d.";
}
else {
tracemsg = "leave from GetAlarm %s.";
}
break;
case TFN_SETRELALARM:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from SetRelAlarm %s.";
break;
case TFN_SETABSALARM:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from SetAbsAlarm %s.";
break;
case TFN_CANCELALARM:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from CancelAlarm %s.";
break;
case TFN_INCREMENTCOUNTER:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from IncrementCounter %s.";
break;
case TFN_GETCOUNTERVALUE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
/* 返り値がE_OKの場合のみ,有効値が入る */
if (trace->loginfo[1] == E_OK) {
info[1] = trace->loginfo[2];
tracemsg = "leave from GetCounterValue %s/Value=%d.";
}
else {
tracemsg = "leave from GetCounterValue %s.";
}
break;
case TFN_GETELAPSEDVALUE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
/* 返り値がE_OKの場合のみ,有効値が入る */
if (trace->loginfo[1] == E_OK) {
info[1] = trace->loginfo[2];
info[2] = trace->loginfo[3];
tracemsg = "leave from GetElapsedValue %s/Value=%d/ElapsedValue=%d.";
}
else {
tracemsg = "leave from GetElapsedValue %s.";
}
break;
default:
tracemsg = "unknown servic call";
break;
}
return(tracemsg);
}
/*
* スケジュールテーブル機能 - 入口ログ
*/
static const char8 *
trace_print_schtblenter(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_STARTSCHEDULETABLEREL:
info[0] = (uintptr) kernel_schtblid_str((ScheduleTableType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
info[2] = trace->loginfo[2];
tracemsg = "enter to StartScheduleTableRel SchtblID=%s(%d)/offset=%d.";
break;
case TFN_STARTSCHEDULETABLEABS:
info[0] = (uintptr) kernel_schtblid_str((ScheduleTableType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
info[2] = trace->loginfo[2];
tracemsg = "enter to StartScheduleTableAbs SchtblID=%s(%d)/start=%d.";
break;
case TFN_STOPSCHEDULETABLE:
info[0] = (uintptr) kernel_schtblid_str((ScheduleTableType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to StopScheduleTable SchtblID=%s(%d).";
break;
case TFN_NEXTSCHEDULETABLE:
info[0] = (uintptr) kernel_schtblid_str((ScheduleTableType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
info[2] = (uintptr) kernel_schtblid_str((ScheduleTableType) trace->loginfo[2]);
info[3] = trace->loginfo[2];
tracemsg = "enter to NextScheduleTable From_ID=%s(%d)/To_ID=%s(%d).";
break;
case TFN_GETSCHEDULETABLESTATUS:
info[0] = (uintptr) kernel_schtblid_str((ScheduleTableType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to GetScheduleTableStatus SchtblID=%s(%d).";
break;
default:
tracemsg = "unknown service call";
break;
}
return(tracemsg);
}
/*
* スケジュールテーブル - 出口ログ
*/
static const char8 *
trace_print_schtblleave(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_STARTSCHEDULETABLEREL:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from StartScheduleTableRel %s.";
break;
case TFN_STARTSCHEDULETABLEABS:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from StartScheduleTableAbs %s.";
break;
case TFN_STOPSCHEDULETABLE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from StopScheduleTable %s.";
break;
case TFN_NEXTSCHEDULETABLE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
tracemsg = "leave from NextScheduleTable %s.";
break;
case TFN_GETSCHEDULETABLESTATUS:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
/* 返り値がE_OKの場合のみ,有効値が入る */
if (trace->loginfo[1] == E_OK) {
info[1] = (uintptr) trace_schtblstatus_str((ScheduleTableStatusType) trace->loginfo[2]);
tracemsg = "leave from GetScheduleTableStatus %s/status=%s.";
}
else {
tracemsg = "leave from GetScheduleTableStatus %s.";
}
break;
default:
tracemsg = "unknown servic call";
break;
}
return(tracemsg);
}
/*
* 割込み管理機能 - 入口ログ
*/
static const char8 *
trace_print_intenter(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_DISABLEALLINTERRUPTS:
tracemsg = "enter to DisableAllInterrupts.";
break;
case TFN_SUSPENDALLINTERRUPTS:
tracemsg = "enter to SuspendAllInterrupts.";
break;
case TFN_SUSPENDOSINTERRUPTS:
tracemsg = "enter to SuspendOSInterrupts.";
break;
case TFN_ENABLEALLINTERRUPTS:
tracemsg = "enter to EnableAllInterrupts.";
break;
case TFN_RESUMEALLINTERRUPTS:
tracemsg = "enter to ResumeAllInterrupts.";
break;
case TFN_RESUMEOSINTERRUPTS:
tracemsg = "enter to ResumeOSInterrupts.";
break;
case TFN_GETISRID:
tracemsg = "enter to GetISRID.";
break;
default:
tracemsg = "unknown service call";
break;
}
return(tracemsg);
}
/*
* 割込み管理機能 - 出口ログ
*/
static const char8 *
trace_print_intleave(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_DISABLEALLINTERRUPTS:
tracemsg = "leave from DisableAllInterrupts.";
break;
case TFN_SUSPENDALLINTERRUPTS:
tracemsg = "leave from SuspendAllInterrupts.";
break;
case TFN_SUSPENDOSINTERRUPTS:
tracemsg = "leave from SuspendOSInterrupts.";
break;
case TFN_ENABLEALLINTERRUPTS:
tracemsg = "leave from EnableAllInterrupts.";
break;
case TFN_RESUMEALLINTERRUPTS:
tracemsg = "leave from ResumeAllInterrupts.";
break;
case TFN_RESUMEOSINTERRUPTS:
tracemsg = "leave from ResumeOSInterrupts.";
break;
case TFN_GETISRID:
info[0] = (uintptr) kernel_isrid_str((ISRType) trace->loginfo[1]);
info[1] = (const uintptr) trace->loginfo[1];
tracemsg = "leave from GetISRID id=%s(%d).";
break;
default:
tracemsg = "unknown servic call";
break;
}
return(tracemsg);
}
/*
* システム状態管理機能 - 入口ログ
*/
static const char8 *
trace_print_sysenter(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_GETTASKID:
tracemsg = "enter to GetTaskID.";
break;
case TFN_GETTASKSTATE:
info[0] = (uintptr) kernel_tskid_str((TaskType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "enter to GetTaskState TaskID=%s(%d).";
break;
case TFN_GETACTIVEAPPLICATIONMODE:
tracemsg = "enter to GetActiveApplicationMode.";
break;
default:
tracemsg = "unknown servic call";
break;
}
return(tracemsg);
}
/*
* システム状態管理機能 - 出口ログ
*/
static const char8 *
trace_print_sysleave(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_GETTASKID:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
/* 返り値がE_OKの場合のみ,有効値が入る */
if (trace->loginfo[1] == E_OK) {
info[1] = (uintptr) kernel_tskid_str(trace->loginfo[2]);
tracemsg = "leave from GetTaskID %s/TaskID=%s.";
}
else {
tracemsg = "leave from GetTaskID %s.";
}
break;
case TFN_GETTASKSTATE:
info[0] = (uintptr) atk2_strerror((StatusType) trace->loginfo[1]);
/* 返り値がE_OKの場合のみ,有効値が入る */
if (trace->loginfo[1] == E_OK) {
info[1] = (uintptr) trace_task_state_str((TaskStateType) trace->loginfo[2]);
tracemsg = "leave from GetTaskState %s/State=%s.";
}
else {
tracemsg = "leave from GetTaskState %s.";
}
break;
case TFN_GETACTIVEAPPLICATIONMODE:
info[0] = (uintptr) kernel_appid_str((AppModeType) trace->loginfo[1]);
info[1] = trace->loginfo[1];
tracemsg = "leave from GetActiveApplicationMode mode=%s(%d).";
break;
default:
tracemsg = "unknown servic call";
break;
}
return(tracemsg);
}
/*
* カーネルの初期化と終了処理
*/
static const char8 *
trace_print_kerenter(const TRACE *trace, uintptr info[], void (*outputc)(char8 c))
{
uint32 type;
const char8 *tracemsg;
uintptr traceinfo[TMAX_LOGINFO + 1U];
uint32 i;
type = (const uint32) trace->loginfo[0];
/* シャットダウン時にすべてのタスクがSUSPENDED状態となるようにする */
for (i = 0U; i < TNUM_TASK; i++) {
traceinfo[0] = (uintptr) i;
syslog_printf("task %d becomes SUSPENDED.\n", traceinfo, outputc);
traceinfo[0] = (uintptr) (trace->logtim);
syslog_printf("[%d] ", traceinfo, outputc);
}
if (type == TFN_SHUTDOWNOS) {
info[0] = trace->loginfo[1];
tracemsg = "enter to ShutdownOS Error=%d.";
}
else {
tracemsg = "unknown service call";
}
return(tracemsg);
}
/*
* システムコールの入口ログ(LOG_TYPE_SVC|ENTER)
*/
static const char8 *
trace_print_svcenter(const TRACE *trace, uintptr info[], void (*outputc)(char8 c))
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
/*タスク管理 */
case TFN_ACTIVATETASK:
case TFN_TERMINATETASK:
case TFN_CHAINTASK:
case TFN_SCHEDULE:
tracemsg = trace_print_tskenter(trace, info);
break;
/* イベント機能 */
case TFN_SETEVENT:
case TFN_CLEAREVENT:
case TFN_GETEVENT:
case TFN_WAITEVENT:
tracemsg = trace_print_evententer(trace, info);
break;
/* リソース機能 */
case TFN_RELEASERESOURCE:
case TFN_GETRESOURCE:
tracemsg = trace_print_resenter(trace, info);
break;
/* アラーム機能 */
case TFN_GETALARMBASE:
case TFN_GETALARM:
case TFN_SETRELALARM:
case TFN_SETABSALARM:
case TFN_CANCELALARM:
case TFN_INCREMENTCOUNTER:
case TFN_GETCOUNTERVALUE:
case TFN_GETELAPSEDVALUE:
tracemsg = trace_print_almenter(trace, info);
break;
/* スケジュールテーブル機能 */
case TFN_STARTSCHEDULETABLEREL:
case TFN_STARTSCHEDULETABLEABS:
case TFN_STOPSCHEDULETABLE:
case TFN_NEXTSCHEDULETABLE:
case TFN_GETSCHEDULETABLESTATUS:
tracemsg = trace_print_schtblenter(trace, info);
break;
/* 割込み管理機能 */
case TFN_DISABLEALLINTERRUPTS:
case TFN_SUSPENDALLINTERRUPTS:
case TFN_SUSPENDOSINTERRUPTS:
case TFN_ENABLEALLINTERRUPTS:
case TFN_RESUMEALLINTERRUPTS:
case TFN_RESUMEOSINTERRUPTS:
case TFN_GETISRID:
tracemsg = trace_print_intenter(trace, info);
break;
/* システム状態管理機能 */
case TFN_GETTASKID:
case TFN_GETTASKSTATE:
case TFN_GETACTIVEAPPLICATIONMODE:
tracemsg = trace_print_sysenter(trace, info);
break;
/* カーネルの初期化と終了処理 */
case TFN_SHUTDOWNOS:
tracemsg = trace_print_kerenter(trace, info, outputc);
break;
default:
tracemsg = "unknown LOG_TYPE_SVC|ENTER service call";
break;
}
return(tracemsg);
}
/*
* システムコールの出口ログ(LOG_TYPE_SVC|LEAVE)
*/
static const char8 *
trace_print_svcleave(const TRACE *trace, uintptr info[])
{
uint32 type;
const char8 *tracemsg;
type = (const uint32) trace->loginfo[0];
switch (type) {
case TFN_ACTIVATETASK:
case TFN_TERMINATETASK:
case TFN_CHAINTASK:
case TFN_SCHEDULE:
/* タスク管理 */
tracemsg = trace_print_tskleave(trace, info);
break;
/* イベント機能 */
case TFN_SETEVENT:
case TFN_CLEAREVENT:
case TFN_GETEVENT:
case TFN_WAITEVENT:
tracemsg = trace_print_eventleave(trace, info);
break;
/* リソース機能 */
case TFN_RELEASERESOURCE:
case TFN_GETRESOURCE:
tracemsg = trace_print_resleave(trace, info);
break;
/* アラーム機能 */
case TFN_GETALARMBASE:
case TFN_GETALARM:
case TFN_SETRELALARM:
case TFN_SETABSALARM:
case TFN_CANCELALARM:
case TFN_INCREMENTCOUNTER:
case TFN_GETCOUNTERVALUE:
case TFN_GETELAPSEDVALUE:
tracemsg = trace_print_almleave(trace, info);
break;
/* スケジュールテーブル機能 */
case TFN_STARTSCHEDULETABLEREL:
case TFN_STARTSCHEDULETABLEABS:
case TFN_STOPSCHEDULETABLE:
case TFN_NEXTSCHEDULETABLE:
case TFN_GETSCHEDULETABLESTATUS:
tracemsg = trace_print_schtblleave(trace, info);
break;
/* 割込み管理機能 */
case TFN_DISABLEALLINTERRUPTS:
case TFN_SUSPENDALLINTERRUPTS:
case TFN_SUSPENDOSINTERRUPTS:
case TFN_ENABLEALLINTERRUPTS:
case TFN_RESUMEALLINTERRUPTS:
case TFN_RESUMEOSINTERRUPTS:
case TFN_GETISRID:
tracemsg = trace_print_intleave(trace, info);
break;
/* システム状態管理機能 */
case TFN_GETTASKID:
case TFN_GETTASKSTATE:
case TFN_GETACTIVEAPPLICATIONMODE:
tracemsg = trace_print_sysleave(trace, info);
break;
default:
tracemsg = "unknown LOG_TYPE_SVC|LEAVE servic call";
break;
}
return(tracemsg);
}
/*
* 処理単位を切り替える
* 通常はtrace_push_contextから呼ばれるが,
* trace_push_contextを経由しない場合もある(タスク,スタートアップフック)
*/
static void
trace_set_context(PR_UNIT_TYPE type, ObjectIDType id)
{
context_stack[context_index].type = type;
context_stack[context_index].id = id;
}
/*
* 処理単位スタックにtype, idで指定される処理単位をプッシュする
*/
static void
trace_push_context(PR_UNIT_TYPE type, ObjectIDType id)
{
context_index++;
trace_set_context(type, id);
}
/*
* 現在の処理単位を返す
* p_obj_type_strには処理単位種別の文字列を入れる
* p_idには処理単位のIDを入れる
* タスク,C2ISR実行中の場合で,アラーム満了処理,
* スケジュールテーブル満了処理を行なっている場合は,それらを
* 現在の処理単位として返す
*/
static void
trace_get_context(uintptr *p_obj_type_str, uintptr *p_id)
{
PR_UNIT_TYPE type;
ObjectIDType id;
sint32 index;
type = context_stack[context_index].type;
id = context_stack[context_index].id;
if (type == PR_UNIT_TASK) {
index = task_context_index[id];
if (index >= 0) {
id = task_exec[id][index].id;
type = task_exec[id][index].type;
}
}
else if (type == PR_UNIT_ISR) {
index = isr_context_index[id];
if (index >= 0) {
id = isr_exec[id][index].id;
type = isr_exec[id][index].type;
}
}
else {
/* typeが上記以外の場合,処理は行わない */
}
*p_obj_type_str = (const uintptr) obj_type_to_str[type];
*p_id = (uintptr) id;
}
/*
* trace_push_contextでプッシュした処理単位をポップ(取り除く)する
* 1つ前の処理単位を返す
*/
static void
trace_pop_context(uintptr *p_obj_type_str, uintptr *p_id)
{
context_index--;
trace_get_context(p_obj_type_str, p_id);
}
/*
* タスク,C2ISR実行中にアラーム満了処理,スケジュールテーブ
* ル満了処理が発生した場合に,現在の処理単位をそれらの満了処理にする
*/
static void
trace_change_context(PR_UNIT_TYPE type, ObjectIDType id)
{
sint32 index;
TaskType tskid;
ISRType isrid;
if (context_stack[context_index].type == PR_UNIT_TASK) {
tskid = context_stack[context_index].id;
task_context_index[tskid]++;
index = task_context_index[tskid];
task_exec[tskid][index].id = id;
task_exec[tskid][index].type = type;
}
else if (context_stack[context_index].type == PR_UNIT_ISR) {
isrid = context_stack[context_index].id;
isr_context_index[isrid]++;
index = isr_context_index[isrid];
isr_exec[isrid][index].id = id;
isr_exec[isrid][index].type = type;
}
else {
/* ここには来ない.万が一来た場合,以降のログ内容が未保証となる */
}
}
/*
* タスク,C2ISR実行中のアラーム満了処理,スケジュールテーブ
* ル満了処理の終了時に呼び出し,処理単位を戻す
*/
static void
trace_resume_context(void)
{
TaskType tskid;
ISRType isrid;
if (context_stack[context_index].type == PR_UNIT_TASK) {
tskid = context_stack[context_index].id;
task_context_index[tskid]--;
}
else if (context_stack[context_index].type == PR_UNIT_ISR) {
isrid = context_stack[context_index].id;
isr_context_index[isrid]--;
}
else {
/* ここには来ない.万が一来た場合,以降のログ内容が未保証となる */
}
}
/*
* トレースログの表示
*/
static void
trace_print(const TRACE *p_trace, void (*outputc)(char8 c))
{
uintptr traceinfo[TMAX_LOGINFO + 1U];
const char8 *tracemsg;
uint32 i;
TaskType tskid;
AlarmType almid;
ISRType isrid;
ScheduleTableType schtblid;
traceinfo[0] = (uintptr) (p_trace->logtim);
syslog_printf("[%d] ", traceinfo, outputc);
switch (p_trace->logtype) {
/* C2ISRの開始 */
case LOG_TYPE_ISR | LOG_ENTER:
isrid = p_trace->loginfo[0];
trace_push_context(PR_UNIT_ISR, isrid);
traceinfo[0] = (uintptr) isrid;
tracemsg = "enter to isr %d.";
break;
/* C2ISRの終了 */
case LOG_TYPE_ISR | LOG_LEAVE:
isrid = p_trace->loginfo[0];
traceinfo[0] = (uintptr) isrid;
trace_pop_context(&(traceinfo[1]), &(traceinfo[2]));
tracemsg = "leave from isr %d, context is %s %d.";
break;
/* アラーム満了処理の開始 */
case LOG_TYPE_ALM | LOG_ENTER:
almid = (uintptr) (((ALMCB *) (p_trace->loginfo[0])) - almcb_table);
trace_change_context(PR_UNIT_ALARM, almid);
traceinfo[0] = (uintptr) almid;
tracemsg = "enter to alarm %d.";
break;
/* アラーム満了処理の終了 */
case LOG_TYPE_ALM | LOG_LEAVE:
almid = (uintptr) (((ALMCB *) (p_trace->loginfo[0])) - almcb_table);
trace_resume_context();
traceinfo[0] = (uintptr) almid;
trace_get_context(&(traceinfo[1]), &(traceinfo[2]));
tracemsg = "leave from alarm %d, context is %s %d.";
break;
/* スケジュールテーブル満了処理の開始 */
case LOG_TYPE_SCHTBL | LOG_ENTER:
schtblid = (uintptr) (((SCHTBLCB *) (p_trace->loginfo[0])) - schtblcb_table);
trace_change_context(PR_UNIT_SCHTBL, schtblid);
traceinfo[0] = (uintptr) schtblid;
tracemsg = "enter to scheduletable %d.";
break;
/* スケジュールテーブル満了処理の終了 */
case LOG_TYPE_SCHTBL | LOG_LEAVE:
schtblid = (uintptr) (((SCHTBLCB *) (p_trace->loginfo[0])) - schtblcb_table);
trace_resume_context();
traceinfo[0] = (uintptr) schtblid;
trace_get_context(&(traceinfo[1]), &(traceinfo[2]));
tracemsg = "leave from scheduletable %d, context is %s %d.";
break;
/* スタートアップフックの開始 */
case LOG_TYPE_STAHOOK | LOG_ENTER:
trace_set_context(PR_UNIT_STA, 0U);
tracemsg = "enter to startup hook.";
break;
/* スタートアップフックの終了 */
case LOG_TYPE_STAHOOK | LOG_LEAVE:
tracemsg = "leave from startup hook.";
break;
/* エラーフックの開始 */
case LOG_TYPE_ERRHOOK | LOG_ENTER:
trace_push_context(PR_UNIT_ERR, 0U);
traceinfo[0] = (uintptr) atk2_strerror((StatusType) p_trace->loginfo[0]);
tracemsg = "enter to error hook ercd=%s.";
break;
/* エラーフックの終了 */
case LOG_TYPE_ERRHOOK | LOG_LEAVE:
trace_pop_context(&(traceinfo[0]), &(traceinfo[1]));
tracemsg = "leave from error hook, context is %s %d.";
break;
/* プロテクションフックの開始 */
case LOG_TYPE_PROHOOK | LOG_ENTER:
trace_push_context(PR_UNIT_PRO, 0U);
traceinfo[0] = (uintptr) atk2_strerror((StatusType) p_trace->loginfo[0]);
tracemsg = "enter to protection hook ercd=%s.";
break;
/* プロテクションフックの終了 */
case LOG_TYPE_PROHOOK | LOG_LEAVE:
traceinfo[0] = (uintptr) trace_proret_str((ProtectionReturnType) p_trace->loginfo[0]);
trace_pop_context(&(traceinfo[1]), &(traceinfo[2]));
tracemsg = "leave from protection hook ercd=%s, context is %s %d.";
break;
/* シャットダウンフックの開始 */
case LOG_TYPE_SHUTHOOK | LOG_ENTER:
trace_push_context(PR_UNIT_SHUT, 0U);
traceinfo[0] = (uintptr) atk2_strerror((StatusType) p_trace->loginfo[0]);
tracemsg = "enter to shutdown hook ercd=%s.";
break;
/* シャットダウンフックの終了 */
case LOG_TYPE_SHUTHOOK | LOG_LEAVE:
trace_pop_context(&(traceinfo[0]), &(traceinfo[1]));
tracemsg = "leave from shutdown hook.";
break;
/* タスク状態の変化 */
case LOG_TYPE_TSKSTAT:
traceinfo[0] = trace_get_tskid(p_trace->loginfo[0]);
traceinfo[1] = (uintptr) trace_task_state_str((TaskStateType) p_trace->loginfo[1]);
tracemsg = "task %d becomes %s.";
break;
/* ディスパッチャの入口 */
case LOG_TYPE_DSP | LOG_ENTER:
traceinfo[0] = trace_get_tskid(p_trace->loginfo[0]);
tracemsg = "dispatch from task %d.";
break;
/* ディスパッチャの出口 */
case LOG_TYPE_DSP | LOG_LEAVE:
tskid = (TaskType) trace_get_tskid(p_trace->loginfo[0]);
traceinfo[0] = (uintptr) tskid;
trace_set_context(PR_UNIT_TASK, tskid);
/* 満了処理をしているかもしれないので,現在の処理単位を取得する */
trace_get_context(&(traceinfo[1]), &(traceinfo[2]));
if (traceinfo[1] != (const uintptr) obj_type_to_str[PR_UNIT_TASK]) {
tracemsg = "dispatch to task %d, executing %s %d.";
}
else {
tracemsg = "dispatch to task %d.";
}
break;
/* システムサービスの入口 */
case LOG_TYPE_SVC | LOG_ENTER:
tracemsg = trace_print_svcenter(p_trace, traceinfo, outputc);
break;
/* システムサービスの出口 */
case LOG_TYPE_SVC | LOG_LEAVE:
tracemsg = trace_print_svcleave(p_trace, traceinfo);
break;
case LOG_TYPE_COMMENT:
for (i = 1U; i < TMAX_LOGINFO; i++) {
traceinfo[i - 1U] = p_trace->loginfo[i];
}
tracemsg = (const char8 *) (p_trace->loginfo[0]);
break;
case LOG_TYPE_ASSERT:
traceinfo[0] = p_trace->loginfo[0];
traceinfo[1] = p_trace->loginfo[1];
traceinfo[2] = p_trace->loginfo[2];
tracemsg = "%s:%u: Assertion '%s' failed.";
break;
case LOG_TYPE_USER_MARK:
traceinfo[0] = p_trace->loginfo[0];
tracemsg = "user mark=%s.";
break;
default:
traceinfo[0] = p_trace->logtype;
tracemsg = "unknown trace log type: %d.";
break;
}
syslog_printf(tracemsg, traceinfo, outputc);
(*outputc)('\n');
}
/*
* トレースログのダンプ
*/
void
trace_dump(void (*exinf)(char8 c))
{
TRACE trace;
void (*outputc)(char8 c);
uint32 i;
for (i = 0U; i < TNUM_TASK; i++) {
task_context_index[i] = -1;
}
for (i = 0U; i < TNUM_ISR2; i++) {
isr_context_index[i] = -1;
}
outputc = exinf;
while (trace_rea_log(&trace) == E_OK) {
trace_print(&trace, outputc);
}
syslog(LOG_NOTICE, "sizeof TRACE=%d", sizeof(TRACE));
}
<file_sep>#!python
# -*- coding: utf-8 -*-
#
# TOPPERS ATK2
# Toyohashi Open Platform for Embedded Real-Time Systems
# Automotive Kernel Version 2
#
# Copyright (C) 2013-2014 by Center for Embedded Computing Systems
# Graduate School of Information Science, Nagoya Univ., JAPAN
# Copyright (C) 2013-2014 by FUJI SOFT INCORPORATED, JAPAN
# Copyright (C) 2013-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
# Copyright (C) 2013-2014 by Renesas Electronics Corporation, JAPAN
# Copyright (C) 2013-2014 by <NAME> Inc., JAPAN
# Copyright (C) 2013-2014 by TOSHIBA CORPORATION, JAPAN
# Copyright (C) 2013-2014 by Witz Corporation, JAPAN
#
# 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
# ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
# 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
# (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
# 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
# スコード中に含まれていること.
# (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
# 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
# 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
# の無保証規定を掲載すること.
# (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
# 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
# と.
# (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
# 作権表示,この利用条件および下記の無保証規定を掲載すること.
# (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
# 報告すること.
# (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
# 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
# また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
# 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
# 免責すること.
#
# 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
# 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
# はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
# 用する者に対して,AUTOSARパートナーになることを求めている.
#
# 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
# よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
# に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
# アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
# の責任を負わない.
#
# $Id: post_cfg.py 663 2016-06-30 07:19:44Z ertl-honda $
#
import subprocess
import os
import sys
import re # for regular expression
import shutil
import os.path
from System import Threading
# set relative path from top proj
proj_rel_dir = "../"
# call definition file
common.Source(proj_rel_dir + "def.py")
# path
src_abs_path = os.path.abspath(proj_rel_dir + SRCDIR)
# call common file
common.Source(src_abs_path + "/arch/ccrh/common.py")
#
# convert map file
#
inputfile = open("./DefaultBuild/cfg.map")
outputfile = open("cfg1_out.syms", 'w')
r = re.compile("^\s+([0-9a-f]+)\s+[0-9a-f]+\s+\w+\s+,\w+\s+\*\s+")
line = inputfile.readline()
pre_line = line
while line:
line = line.replace('\r\n','') #delete newline
m = r.search(line)
if m:
outputfile.write(m.group(1) + " T " + pre_line + "\n")
pre_line = line
line = inputfile.readline()
inputfile.close()
outputfile.close()
# remove Os_Lcfg.c
if os.path.isfile('Os_Lcfg.c'):
os.remove('Os_Lcfg.c')
#
# Execute cfg path 2
#
# make command
cfg_command = cfg + " --pass 2 " + "--kernel " + CFG_KERNEL
cfg_command += " --api-table " + cfg_api_table
cfg_command += " " + cfg_cfg1_def_tables + cfg_includes
cfg_command += " -T " + cfg_tf
cfg_command += " --ini-file " + cfg_ini_file
cfg_command += " " + cfg_input_str
print cfg_command
# build stop
def BuildStop():
build.Stop()
# Execute
try:
output = subprocess.check_output(cfg_command, stderr=subprocess.STDOUT,)
except subprocess.CalledProcessError, e:
print "ERROR!! : ", e.output
thread = Threading.Thread(Threading.ThreadStart(BuildStop))
thread.IsBackground = True
thread.Start()
sys.exit()
output.replace('\r','')
print output
#
# mov Os_Cfg_tmp.h Os_Cfg.h
#
import filecmp
if not os.path.isfile(r'Os_Cfg.h'):
print "Rename Os_Cfg_tmp.h to Os_Cfg.h"
shutil.move("Os_Cfg_tmp.h", "Os_Cfg.h")
else:
print "compare Os_Cfg_tmp.h and Os_Cfg.h"
if not filecmp.cmp(r'Os_Cfg_tmp.h', r'Os_Cfg.h'):
print "Rename Os_Cfg_tmp.h to Os_Cfg.h"
shutil.move("Os_Cfg_tmp.h", "Os_Cfg.h")
else:
print "Delete Os_Cfg_tmp.h"
os.remove("Os_Cfg_tmp.h")
#
# Execute cfg path 3
#
# make command
cfg_command = cfg + " --pass 3 " + "--kernel " + CFG_KERNEL
cfg_command += " --api-table " + cfg_api_table
cfg_command += " " + cfg_cfg1_def_tables + cfg_includes
cfg_command += " --rom-image cfg1_out.srec --symbol-table cfg1_out.syms"
cfg_command += " -T " + cfg_offset_tf
cfg_command += " --ini-file " + cfg_ini_file
cfg_command += " " + cfg_input_str
print cfg_command
# Execute
try:
output = subprocess.check_output(cfg_command, stderr=subprocess.STDOUT,)
except subprocess.CalledProcessError, e:
print "ERROR!! : ", e.output
thread = Threading.Thread(Threading.ThreadStart(BuildStop))
thread.IsBackground = True
thread.Start()
sys.exit()
output.replace('\r','')
print output
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2015 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: target_config.c 716 2017-01-19 01:02:05Z ertl-honda $
*/
/*
* ターゲット依存モジュール(HSBRH850F1K用)
*/
#include "kernel_impl.h"
#include "v850_gcc/uart_rlin.h"
#include "v850_gcc/prc_sil.h"
#include "target_sysmod.h"
#ifdef ENABLE_RETURN_MAIN
#include "interrupt.h"
#endif /* ENABLE_RETURN_MAIN */
#ifdef TOPPERS_ENABLE_TRACE
#include "logtrace/trace_config.h"
#endif /* TOPPERS_ENABLE_TRACE */
/*
* 文字列の出力
*/
void
target_fput_str(const char8 *c)
{
while (*c != '\0') {
uart_putc(*c);
c++;
}
uart_putc('\n');
}
void
hsbrh850f1k_led_output(uint8 pattern)
{
uint16 wk;
pattern = ~pattern;
wk = sil_reh_mem((void *) P(8));
wk &= ~LED_P8_MASK;
wk |= (pattern & LED_P8_MASK);
sil_wrh_mem((void *) P(8), wk);
}
/*
* ポートの初期設定
*/
void
target_port_initialize(void)
{
uint16 wk;
/*
* PORT8(LED)
*/
/* PM8 設定 */
wk = sil_reh_mem((void *) PM(8));
wk &= ~LED_P8_MASK;
wk |= (LED_PM8_INIT & LED_P8_MASK);
sil_wrh_mem((void *) PM(8), wk);
/* P8 設定 */
wk = sil_reh_mem((void *) P(8));
wk &= ~LED_P8_MASK;
wk |= (LED_P8_INIT & LED_P8_MASK);
sil_wrh_mem((void *) P(8), wk);
/*
* PORT10(RLIN31)
*/
/* PFC10 設定 */
wk = sil_reh_mem((void *) PFC(10));
wk &= ~RLIN31_P10_MASK;
wk |= (RLIN31_PFC10_INIT & RLIN31_P10_MASK);
sil_wrh_mem((void *) PFC(10), wk);
/* PMC10 設定 */
wk = sil_reh_mem((void *) PMC(10));
wk &= ~RLIN31_P10_MASK;
wk |= (RLIN31_PMC10_INIT & RLIN31_P10_MASK);
sil_wrh_mem((void *) PMC(10), wk);
/* PM10 設定 */
wk = sil_reh_mem((void *) PM(10));
wk &= ~RLIN31_P10_MASK;
wk |= (RLIN31_PM10_INIT & RLIN31_P10_MASK);
sil_wrh_mem((void *) PM(10), wk);
/* PIBC10 設定 */
wk = sil_reh_mem((void *) PIBC(10));
wk &= ~RLIN31_P10_MASK;
wk |= (RLIN31_PIBC10_INIT & RLIN31_P10_MASK);
sil_wrh_mem((void *) PIBC(10), wk);
}
/*
* クロック関係の初期化
*/
void
target_clock_initialize(void)
{
uint32 errcnt = 0;
/* Init Main Clock */
if (EnableMainOSC(MHz(MAINOSC_CLOCK_MHZ)) != UC_SUCCESS) {
errcnt++;
}
/* Init PLL */
if (EnablePLL() != UC_SUCCESS) {
errcnt++;
}
/* Set PPLLCLK Clock */
if (SetClockSelection(CKSC_PPLLCLKS_CTL, CKSC_PPLLCLKS_ACT,
PNO_CtrlProt1, 0x03, /* PPLLOUT */
0, 0, 0) != UC_SUCCESS) {
errcnt++;
}
/* Set CPU Clock */
if (SetClockSelection(CKSC_CPUCLKS_CTL, CKSC_CPUCLKS_ACT,
PNO_CtrlProt1, 0x03, /* CPLLOUT */
CKSC_CPUCLKD_CTL, CKSC_CPUCLKD_ACT,
0x11 /* 120Mhz */) != UC_SUCCESS) {
errcnt++;
}
/* Set TAUJ Clock */
if (SetClockSelection(CKSC_ATAUJS_CTL, CKSC_ATAUJS_ACT,
PNO_CtrlProt0, 0x02, /* MainOSC */
CKSC_ATAUJD_CTL, CKSC_ATAUJD_ACT,
0x01) != UC_SUCCESS) {
errcnt++;
}
/* Set RLIN Clock */
if (SetClockSelection(CKSC_ILINS_CTL, CKSC_ILINS_ACT,
PNO_CtrlProt1, 0x02, /* MainOSC */
CKSC_ILIND_CTL, CKSC_ILIND_ACT,
0x01) != UC_SUCCESS) {
errcnt++;
}
if (errcnt > 0) {
infinite_loop();
}
}
/*
* ターゲット依存のハードウェアの初期化
* スターアップルーチンから呼び出される.
*/
void
target_hardware_initialize(void)
{
/* クロックの初期設定 */
target_clock_initialize();
/* ポートの初期設定 */
target_port_initialize();
}
/*
* ターゲット依存の初期化
*/
void
target_initialize(void)
{
/*
* V850依存の初期化
*/
prc_initialize();
#ifdef TOPPERS_ENABLE_TRACE
/*
* トレースログ機能の初期化
*/
trace_initialize((uintptr) (TRACE_AUTOSTOP));
#endif /* TOPPERS_ENABLE_TRACE */
}
/*
* ターゲット依存の終了処理
*/
void
target_exit(void)
{
#ifdef TOPPERS_ENABLE_TRACE
/*
* トレースログのダンプ
*/
trace_dump(target_fput_log);
#endif /* TOPPERS_ENABLE_TRACE */
#ifndef ENABLE_RETURN_MAIN
/*
* シャットダウン処理の出力
*/
target_fput_str("Kernel Exit...");
#else
target_fput_str("Kernel Shutdown...");
#endif /* ENABLE_RETURN_MAIN */
/*
* FL-850/F1K依存の終了処理
*/
prc_terminate();
#ifdef ENABLE_RETURN_MAIN
kerflg = FALSE;
except_nest_cnt = 0U;
nested_lock_os_int_cnt = 0U;
sus_all_cnt = 0U;
sus_all_cnt_ctx = 0U;
sus_os_cnt = 0U;
sus_os_cnt_ctx = 0U;
/* スタックポインタの初期化とmain()の呼び出し */
return_main();
#endif /* ENABLE_RETURN_MAIN */
infinite_loop();
}
/*
* ターゲット依存の文字出力
*/
void
target_fput_log(char8 c)
{
if (c == '\n') {
uart_putc('\r');
}
uart_putc(c);
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: osctl_manage.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* OS管理モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "interrupt.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_GETAAM_ENTER
#define LOG_GETAAM_ENTER()
#endif /* LOG_GETAAM_ENTER */
#ifndef LOG_GETAAM_LEAVE
#define LOG_GETAAM_LEAVE(mode)
#endif /* LOG_GETAAM_LEAVE */
#ifndef LOG_STAOS_ENTER
#define LOG_STAOS_ENTER(mode)
#endif /* LOG_STAOS_ENTER */
#ifndef LOG_STAOS_LEAVE
#define LOG_STAOS_LEAVE()
#endif /* LOG_STAOS_LEAVE */
#ifndef LOG_STAHOOK_ENTER
#define LOG_STAHOOK_ENTER()
#endif /* LOG_STAHOOK_ENTER */
#ifndef LOG_STAHOOK_LEAVE
#define LOG_STAHOOK_LEAVE()
#endif /* LOG_STAHOOK_LEAVE */
#ifdef TOPPERS_StartOS
/*
* OS実行制御のための変数
*/
uint16 callevel_stat = 0U; /* 実行中のコンテキスト */
AppModeType appmodeid; /* アプリケーションモードID */
/*
* カーネル動作状態フラグ
*/
boolean kerflg = FALSE;
/*
* ファイル名,行番号の参照用の変数
*/
const char8 *fatal_file_name = NULL; /* ファイル名 */
sint32 fatal_line_num = 0; /* 行番号 */
/*
* OSの起動
*/
void
StartOS(AppModeType Mode)
{
LOG_STAOS_ENTER(Mode);
#ifdef CFG_USE_EXTENDEDSTATUS
if (kerflg != FALSE) {
/* OS起動中はエラーフックを呼ぶ */
#ifdef CFG_USE_ERRORHOOK
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.mode = Mode;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(E_OS_ACCESS, OSServiceId_StartOS);
x_nested_unlock_os_int();
#endif /* CFG_USE_ERRORHOOK */
}
else {
#endif /* CFG_USE_EXTENDEDSTATUS */
/* 全割込み禁止状態に移行 */
x_lock_all_int();
#ifdef CFG_USE_STACKMONITORING
/*
* スタックモニタリング機能の初期化
* スタックモニタリング機能のためのマジックナンバー領域の初期化
*/
init_stack_magic_region();
#endif /* CFG_USE_STACKMONITORING */
/* アプリケーションモードの設定 */
appmodeid = Mode;
/* ターゲット依存の初期化 */
target_initialize();
/* 各モジュールの初期化 */
object_initialize();
callevel_stat = TCL_NULL;
/* カーネル動作中 */
kerflg = TRUE;
/*
* Modeが不正であった場合,OSシャットダウンを行う
* この時,スタートアップフックは呼び出されない
*/
if (Mode >= tnum_appmode) {
/*
* internal_shutdownosを呼ぶ前にOS割込み禁止状態へ
* 全割込み禁止状態解除
*/
x_nested_lock_os_int();
x_unlock_all_int();
internal_shutdownos(E_OS_MODE);
}
#ifdef CFG_USE_STARTUPHOOK
/* OS割込み禁止状態にし,全割込み禁止状態解除 */
x_nested_lock_os_int();
x_unlock_all_int();
ENTER_CALLEVEL(TCL_STARTUP);
LOG_STAHOOK_ENTER();
StartupHook();
LOG_STAHOOK_LEAVE();
LEAVE_CALLEVEL(TCL_STARTUP);
/* 元の割込みマスク優先度と全割込み禁止状態に */
x_lock_all_int();
x_nested_unlock_os_int();
#endif /* CFG_USE_STARTUPHOOK */
ENTER_CALLEVEL(TCL_TASK);
LOG_STAOS_LEAVE();
start_dispatch();
ASSERT_NO_REACHED;
#ifdef CFG_USE_EXTENDEDSTATUS
}
#endif /* CFG_USE_EXTENDEDSTATUS */
}
#endif /* TOPPERS_StartOS */
/*
* 現在のアプリケーションモードの取得
*/
#ifdef TOPPERS_GetActiveApplicationMode
AppModeType
GetActiveApplicationMode(void)
{
AppModeType appmode;
#if defined(CFG_USE_EXTENDEDSTATUS) || defined(CFG_USE_ERRORHOOK)
StatusType ercd;
#endif /* CFG_USE_EXTENDEDSTATUS || CFG_USE_ERRORHOOK */
LOG_GETAAM_ENTER();
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_GETACTIVEAPPMODE);
appmode = appmodeid;
exit_finish:
LOG_GETAAM_LEAVE(appmode);
return(appmode);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
/*
* エラー発生時はINVALID_APPMODETYPEが返るが,エラーが発生したのか実行中の
* C2ISRが存在しないのか区別するため,エラーフックを呼ぶ
*/
call_errorhook(ercd, OSServiceId_GetActiveApplicationMode);
x_nested_unlock_os_int();
#endif /* CFG_USE_ERRORHOOK */
exit_no_errorhook:
appmode = INVALID_APPMODETYPE;
goto exit_finish;
}
#endif /* TOPPERS_GetActiveApplicationMode */
/*
* OSの終了
*/
#ifdef TOPPERS_ShutdownOS
void
ShutdownOS(StatusType Error)
{
StatusType ercd = Error;
/*
* 不正な処理単位から呼び出した場合も,ErrorをE_OS_SHUTDOWN_FATALとして
* ShutdownOSを呼び出したものとして,シャットダウン処理を行う
*/
if (((callevel_stat & TCLMASK) | (CALLEVEL_SHUTDOWNOS)) != (CALLEVEL_SHUTDOWNOS)) {
ercd = E_OS_SHUTDOWN_FATAL;
}
/*
* OSで定義されていないエラーコードが指定された場合,ErrorをE_OS_SHUTDOWN_FATALとして
* ShutdownOSを呼び出したものとして,シャットダウン処理を行う
*/
if (ercd > ERRCODE_NUM) {
ercd = E_OS_SHUTDOWN_FATAL;
}
internal_shutdownos(ercd);
}
#endif /* TOPPERS_ShutdownOS */
/*
* 保護違反を起こした処理単位の取得
*/
#ifdef TOPPERS_GetFaultyContext
FaultyContextType
GetFaultyContext(void)
{
FaultyContextType faultycontext = FC_INVALID;
#ifdef CFG_USE_PROTECTIONHOOK
if ((callevel_stat & CALLEVEL_GETFAULTYCONTEXT) != 0U) {
/* C1ISR以外で発生 */
if ((callevel_stat & TSYS_ISR1) == 0U) {
/* フック中に発生 */
if ((callevel_stat & (TCL_ERROR | TCL_PREPOST | TCL_STARTUP | TCL_SHUTDOWN)) != 0U) {
/* システム定義フック中に発生 */
faultycontext = FC_SYSTEM_HOOK;
}
else if ((callevel_stat & TCL_ISR2) != 0U) {
if ((callevel_stat & TCL_ALRMCBAK) == 0U) {
faultycontext = FC_C2ISR;
}
}
else if ((callevel_stat & TCL_TASK) != 0U) {
if ((callevel_stat & TCL_ALRMCBAK) == 0U) {
faultycontext = FC_TASK;
}
}
else {
/* 上記以外の場合,処理は行わない(戻り値:FC_INVALID) */
}
}
}
#endif /* CFG_USE_PROTECTIONHOOK */
return(faultycontext);
}
#endif /* TOPPERS_GetFaultyContext */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2015 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: Platform_Types.h 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* AUTOSAR platform types header file
*/
#ifndef TOPPERS_PLATFORM_TYPES_H
#define TOPPERS_PLATFORM_TYPES_H
/*
* Symbol definitions - general
*/
#define CPU_TYPE_8 UINT_C(8)
#define CPU_TYPE_16 UINT_C(16)
#define CPU_TYPE_32 UINT_C(32)
#define MSB_FIRST UINT_C(0)
#define LSB_FIRST UINT_C(1)
#define HIGH_BYTE_FIRST UINT_C(0)
#define LOW_BYTE_FIRST UINT_C(1)
#ifndef TRUE
#define TRUE UINT_C(1)
#endif /* TRUE */
#ifndef FALSE
#define FALSE UINT_C(0)
#endif /* FALSE */
/*
* Symbol definitions - platform
*/
#define CPU_TYPE (CPU_TYPE_32)
#define CPU_BIT_ORDER (MSB_FIRST)
#define CPU_BYTE_ORDER (LOW_BYTE_FIRST)
/*
* Stack definitions - platform
*/
#define DEFINE_VAR_STACK(type, var) type __attribute__((aligned(4))) var
/*
* Type definitions
*/
#ifndef TOPPERS_MACRO_ONLY
#include <stdint.h>
typedef unsigned char boolean;
typedef char char8;
typedef unsigned char uint8;
typedef signed char sint8;
typedef unsigned short uint16;
typedef signed short sint16;
typedef unsigned int uint32;
typedef signed int sint32;
typedef unsigned long long uint64;
typedef signed long long sint64;
typedef unsigned long uint8_least;
typedef unsigned long uint16_least;
typedef unsigned long uint32_least;
typedef signed long sint8_least;
typedef signed long sint16_least;
typedef signed long sint32_least;
typedef float float32;
typedef double float64;
typedef uint32 uintptr; /* ポインタを格納できる符号無し整数 */
typedef sint32 sintptr; /* ポインタを格納できる符号付き整数 */
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_PLATFORM_TYPES_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2016 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: rh850_f1h.h 717 2017-01-19 01:03:12Z ertl-honda $
*/
/*
* RH850/F1Hのハードウェア資源の定義
*/
#ifndef TOPPERS_RH850_F1H_H
#define TOPPERS_RH850_F1H_H
#define _RH850G3M_
/*
* 保護コマンドレジスタ
*/
#define PROTCMD0 0xFFF80000
#define PROTCMD1 0xFFF88000
#define CLMA0PCMD 0xFFF8C010
#define CLMA1PCMD 0xFFF8D010
#define CLMA2PCMD 0xFFF8E010
#define PROTCMDCLMA 0xFFF8C200
#define JPPCMD0 0xFFC204C0
#define PPCMD0 0xFFC14C00
#define PPCMD1 0xFFC14C04
#define PPCMD2 0xFFC14C08
#define PPCMD3 0xFFC14C0C
#define PPCMD8 0xFFC14C20
#define PPCMD9 0xFFC14C24
#define PPCMD10 0xFFC14C28
#define PPCMD11 0xFFC14C2C
#define PPCMD12 0xFFC14C30
#define PPCMD13 0xFFC14C34
#define PPCMD18 0xFFC14C48
#define PPCMD19 0xFFC14C4C
#define PPCMD20 0xFFC14C50
#define PPCMD21 0xFFC14C54
#define PPCMD22 0xFFC14C58
#define PROTCMDCVM 0xFFF83200
#define FLMDPCMD 0xFFA00004
/*
* 保護ステータスレジスタ
*/
#define PROTS0 0xFFF80004
#define PROTS1 0xFFF88004
#define CLMA0PS 0xFFF8C014
#define CLMA1PS 0xFFF8D014
#define CLMA2PS 0xFFF8E014
#define PROTSCLMA 0xFFF8C204
#define JPPROTS0 0xFFC204B0
#define PPROTS0 0xFFC14B00
#define PPROTS1 0xFFC14B04
#define PPROTS2 0xFFC14B08
#define PPROTS3 0xFFC14B0C
#define PPROTS8 0xFFC14B20
#define PPROTS9 0xFFC14B24
#define PPROTS10 0xFFC14B28
#define PPROTS11 0xFFC14B2C
#define PPROTS12 0xFFC14B30
#define PPROTS13 0xFFC14B34
#define PPROTS18 0xFFC14B48
#define PPROTS19 0xFFC14B4C
#define PPROTS20 0xFFC14B50
#define PPROTS21 0xFFC14B54
#define PPROTS22 0xFFC14B58
#define PROTSCVM 0xFFF83204
#define FLMDPS 0xFFA00008
/*
* 保護コマンドレジスタの番号
*/
#define PNO_CtrlProt0 0
#define PNO_CtrlProt1 1
#define PNO_ClkMonitorCtrlProt0 2
#define PNO_ClkMonitorCtrlProt1 3
#define PNO_ClkMonitorCtrlProt2 4
#define PNO_ClkMonitorTestProt 5
#define PNO_PortProt0 6
#define PNO_PortProt0_0 7
#define PNO_PortProt0_1 8
#define PNO_PortProt0_2 9
#define PNO_PortProt0_3 10
#define PNO_PortProt0_8 11
#define PNO_PortProt1_9 12
#define PNO_PortProt1_10 13
#define PNO_PortProt1_11 14
#define PNO_PortProt1_12 15
#define PNO_PortProt1_13 16
#define PNO_PortProt1_18 17
#define PNO_PortProt1_19 18
#define PNO_PortProt1_20 19
#define PNO_PortProt1_21 20
#define PNO_PortProt1_22 21
#define PNO_CoreVMonitorProt 22
#define PNO_SelfProgProt 23
/*
* PORTレジスタ
*/
#define PORT_BASE UINT_C(0xffc10000)
/* 端子機能設定 (USE)*/
#define PMC(n) ((PORT_BASE) +0x0400 + (n * 0x04U)) /* ポート・モード・コントロール・レジスタ */
#define PMCSR(n) ((PORT_BASE) +0x0900 + (n * 0x04U)) /* ポート・モード・コントロール・セット/リセット・レジスタ */
#define PIPC(n) ((PORT_BASE) +0x4200 + (n * 0x04U)) /* ポートIP コントロール・レジスタ */
#define PM(n) ((PORT_BASE) +0x0300 + (n * 0x04U)) /* ポート・モード・レジスタ */
#define PMSR(n) ((PORT_BASE) +0x0800 + (n * 0x04U)) /* ポート・モード・セット/リセット・レジスタ */
#define PIBC(n) ((PORT_BASE) +0x4000 + (n * 0x04U)) /* ポート入力バッファ・コントロール・レジスタ */
#define PFC(n) ((PORT_BASE) +0x0500 + (n * 0x04U)) /* ポート機能コントロール・レジスタ */
#define PFCE(n) ((PORT_BASE) +0x0600 + (n * 0x04U)) /* ポート機能コントロール拡張・レジスタ */
#define PFCAE(n) ((PORT_BASE) +0x0A00 + (n * 0x04U)) /* ポート機能コントロール追加拡張・レジスタ */
/* 端子データ入力/出力 (USE)*/
#define PBDC(n) ((PORT_BASE) +0x4100 + (n * 0x04U)) /* ポート双方向コントロール・レジスタ */
#define PPR(n) ((PORT_BASE) +0x0200 + (n * 0x04U)) /* ポート端子リード・レジスタ */
#define P(n) ((PORT_BASE) +0x0000 + (n * 0x04U)) /* ポート・レジスタ */
#define PNOT(n) ((PORT_BASE) +0x0700 + (n * 0x04U)) /* ポート・ノット・レジスタ */
#define PSR(n) ((PORT_BASE) +0x0100 + (n * 0x04U)) /* ポート・セット/リセット・レジスタ */
#define RLN3xBASE 0xffce2040
#define RLN3xLWBR_B 0x00000001
#define RLN3xLBRP01_H 0x00000002
#define RLN3xLBRP0_B 0x00000002
#define RLN3xLBRP1_B 0x00000003
#define RLN3xLSTC_B 0x00000004
#define RLN3xLMD_B 0x00000008
#define RLN3xLBFC_B 0x00000009
#define RLN3xLSC_B 0x0000000a
#define RLN3xLWUP_B 0x0000000b
#define RLN3xLIE_B 0x0000000c
#define RLN3xLEDE_B 0x0000000d
#define RLN3xLCUC_B 0x0000000e
#define RLN3xLTRC_B 0x00000010
#define RLN3xLMST_B 0x00000011
#define RLN3xLST_B 0x00000012
#define RLN3xLEST_B 0x00000013
#define RLN3xLDFC_B 0x00000014
#define RLN3xLIDB_B 0x00000015
#define RLN3xLCBR_B 0x00000016
#define RLN3xLUDB0_B 0x00000017
#define RLN3xLDBR1_B 0x00000018
#define RLN3xLDBR2_B 0x00000019
#define RLN3xLDBR3_B 0x0000001a
#define RLN3xLDBR4_B 0x0000001b
#define RLN3xLDBR5_B 0x0000001c
#define RLN3xLDBR6_B 0x0000001d
#define RLN3xLDBR7_B 0x0000001e
#define RLN3xLDBR8_B 0x0000001f
#define RLN3xLUOER_B 0x00000020
#define RLN3xLUOR1_B 0x00000021
#define RLN3xLUTDR_H 0x00000024
#define RLN3xLUTDRL_B 0x00000024
#define RLN3xLUTDRH_B 0x00000025
#define RLN3xLURDR_H 0x00000026
#define RLN3xLURDRL_B 0x00000026
#define RLN3xLURDRH_B 0x00000027
#define RLN3xLUWTDR_H 0x00000028
#define RLN3xLUWTDRL_B 0x00000028
#define RLN3xLUWTDRH_B 0x00000029
/*
* OSTM
*/
#if 0
#define OSTM_IRQ UINT_C(147)
#define OSTM0_BASE 0xFFD70000
#define OSTM1_BASE 0xFFD70100
#define OSTM2_BASE 0xFFD70200
#define OSTM3_BASE 0xFFD70300
#define OSTM4_BASE 0xFFD70400
#define OSTM5_BASE 0xFFD71000
#define OSTM6_BASE 0xFFD71100
#define OSTM7_BASE 0xFFD71200
#define OSTM8_BASE 0xFFD71300
#define OSTM9_BASE 0xFFD71400
#define OSTM_CMP_W 0x00
#define OSTM_CNT_W 0x04
#define OSTM_TE 0x10
#define OSTM_TS_B 0x14
#define OSTM_TT_B 0x18
#define OSTM_CTL_B 0x20
#endif
/*
* PLL関連のレジスタと定義
*/
/* Main OSC */
#define MOSCE 0xfff81100
#define MOSCS 0xfff81104
#define MOSCC 0xfff81108
#define MOSCST 0xfff8110c
#define MOSCSTPM 0xfff81118
/* Sub OSC */
#define SOSCE 0xfff81200
#define SOSCS 0xfff81204
#define SOSCST 0xfff8120C
/* PLL */
#define PLL0E 0xfff89000
#define PLL0S 0xfff89004
#define PLL0C 0xfff89008
#define PLL1E 0xfff89100
#define PLL1S 0xfff89104
#define PLL1C 0xfff89108
#define CKSC_CPUCLKS_CTL 0xfff8a000
#define CKSC_CPUCLKS_ACT 0xfff8a008
#define CKSC_CPUCLKD_CTL 0xfff8a100
#define CKSC_CPUCLKD_ACT 0xfff8a108
#define CKSC_ILINS_CTL 0xfff8a400
#define CKSC_ILINS_ACT 0xfff8a408
#define CKSC_ILIND_CTL 0xfff8a800
#define CKSC_ILIND_ACT 0xfff8a808
#define CKSC_ATAUJS_CTL 0xfff82100
#define CKSC_ATAUJS_ACT 0xfff82108
#define CKSC_ATAUJD_CTL 0xfff82200
#define CKSC_ATAUJD_ACT 0xfff82208
#define MHz(n) ((n) * 1000 * 1000)
#define CLK_MHz(num) (num * 1000 * 1000)
/* xxxS Register (USE) */
#define CLK_S_STPACK 0x08
#define CLK_S_CLKEN 0x04
#define CLK_S_CLKACT 0x02
#define CLK_S_CLKSTAB 0x01
/* Return Parameter */
#define UC_SUCCESS 0
#define UC_ERROR 1
#define UC_INVALIDPARAM 2
#define UC_PROTREGERROR 3
#define UC_CLKSTATUSERR 4
#define UC_CLKNOTENABLE 5
#define UC_CLKNOTACTIVE 6
#define UC_CLKNOTSTAB 7
/*
* RLIN3
*/
#define RLIN30_BASE 0xffce2000
#define RLIN31_BASE 0xffce2040
#define RLIN32_BASE 0xffce2080
#define RLIN33_BASE 0xffce20c0
#define RLIN34_BASE 0xffce2100
#define RLIN35_BASE 0xffce2140
/*
* INTC
*/
#define INTC1_BASE 0xFFFEEA00
#define INTC2_BASE 0xFFFFB000
#define INTC2_EIC 0x040
#define INTC2_EIBD 0x880
#define INTC2_INTNO_OFFSET 32
/* intno は unsigned を想定 */
#define EIC_ADDRESS(intno) (intno <= 31)? (INTC1_BASE + (intno * 2)) : (INTC2_BASE + INTC2_EIC + ((intno - INTC2_INTNO_OFFSET) * 2))
#define INTC_HAS_IBD
#define IBD_ADDRESS(intno) (intno <= 31)? (0xFFFEEB00 + (intno * 4)) : (0xFFFFB880 + ((intno - INTC2_INTNO_OFFSET) * 4))
#define TMIN_INTNO UINT_C(0)
#define TMAX_INTNO UINT_C(350)
#define TNUM_INT UINT_C(351)
/*
* INTNO
*/
#define RLIN30_TX_INTNO UINT_C(34)
#define RLIN30_RX_INTNO UINT_C(35)
#define RLIN30_ER_INTNO UINT_C(36)
#define RLIN31_TX_INTNO UINT_C(121)
#define RLIN31_RX_INTNO UINT_C(122)
#define RLIN31_ER_INTNO UINT_C(123)
#define RLIN35_TX_INTNO UINT_C(237)
#define RLIN35_RX_INTNO UINT_C(238)
#define RLIN35_ER_INTNO UINT_C(239)
#define TAUFJ0I0_INTNO UINT_C(80)
#define TAUFJ0I1_INTNO UINT_C(81)
#define TAUFJ0I2_INTNO UINT_C(82)
#define TAUFJ0I3_INTNO UINT_C(83)
#define TAUFJ1I0_INTNO UINT_C(168)
#define TAUFJ1I1_INTNO UINT_C(169)
#define TAUFJ1I2_INTNO UINT_C(170)
#define TAUFJ1I3_INTNO UINT_C(171)
/*
* PE間割込みレジスタ
*/
#define IPIR_CH0 0xfffeec80
#define IPIR_CH1 0xfffeec84
#define IPIR_CH2 0xfffeec88
#define IPIR_CH3 0xfffeec8c
#define IPIC_ADDR(ch) (IPIR_CH0 + ch * 4)
#ifndef TOPPERS_MACRO_ONLY
extern uint32 EnableSubOSC(void);
extern uint32 EnableMainOSC(uint32 clk_in);
extern uint32 EnablePLL0(void);
extern uint32 EnablePLL1(void);
extern uint32 SetClockSelection(uint32 s_control, uint32 s_status, uint8 regno, uint16 sel,
uint32 d_control, uint32 d_status, uint8 divider);
extern void raise_ipir(uint8 ch);
#endif /* TOPPERS_MACRO_ONLY */
#include "v850.h"
#endif /* TOPPERS_RH850_F1H_H */
<file_sep>#!ruby -Ke
if ARGV.size != 1 then
puts "Argment Error!"
exit
end
while str = STDIN.gets
if /^.*\.data\s+[\dabcdef]+\s+[\dabcdef]+\s+([\dabcdef]+)\s+.*/ =~ str
command = 'v850-elf-objcopy -R .bss ' + ARGV[0]
puts command
system(command)
command = 'v850-elf-objcopy --change-section-vma .data=0x' + $1 + ' ' + ARGV[0]
puts command
system(command)
exit(0)
end
end
<file_sep>#!ruby -Ku
#
# ABREX
# AUTOSAR BSW and RTE XML Generator
#
# Copyright (C) 2013-2016 by Center for Embedded Computing Systems
# Graduate School of Information Science, Nagoya Univ., JAPAN
# Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
# Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
# Copyright (C) 2013-2016 by FUJI SOFT INCORPORATED, JAPAN
# Copyright (C) 2014-2016 by NEC Communication Systems, Ltd., JAPAN
# Copyright (C) 2013-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
# Copyright (C) 2013-2014 by Renesas Electronics Corporation, JAPAN
# Copyright (C) 2014-2016 by SCSK Corporation, JAPAN
# Copyright (C) 2013-2016 by Sunny Giken Inc., JAPAN
# Copyright (C) 2015-2016 by SUZUKI MOTOR CORPORATION
# Copyright (C) 2013-2016 by TOSHIBA CORPORATION, JAPAN
# Copyright (C) 2013-2016 by Witz Corporation
#
# 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
# ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
# 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
# (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
# 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
# スコード中に含まれていること.
# (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
# 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
# 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
# の無保証規定を掲載すること.
# (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
# 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
# と.
# (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
# 作権表示,この利用条件および下記の無保証規定を掲載すること.
# (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
# 報告すること.
# (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
# 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
# また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
# 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
# 免責すること.
#
# 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
# 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
# はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
# 用する者に対して,AUTOSARパートナーになることを求めている.
#
# 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
# よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
# に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
# アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
# の責任を負わない.
#
# $Id: abrex.rb 785 2017-03-07 08:45:46Z nces-mtakada $
#
if ($0 == __FILE__)
TOOL_ROOT = File.expand_path(File.dirname(__FILE__) + "/")
$LOAD_PATH.unshift(TOOL_ROOT)
end
require "pp"
require "yaml"
require "optparse"
require "kconv.rb"
require "rexml/document.rb"
include REXML
######################################################################
# 定数定義
######################################################################
VERSION = "1.1.1"
VER_INFO = " Generated by ABREX Ver. #{VERSION} "
XML_ROOT_PATH = "/AUTOSAR/EcucDefs/"
XML_EDITION = "4.2.0"
XML_SNAME = "SHORT-NAME"
XML_PARAM = "PARAMETER-VALUES"
XML_REFER = "REFERENCE-VALUES"
XML_SUB = "SUB-CONTAINERS"
XML_AUTOSAR_FIXED_ATT = {"xmlns" => "http://autosar.org/schema/r4.0",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation" => "http://autosar.org/schema/r4.0 AUTOSAR_4-0-3_STRICT.xsd"}
# パラメータデータ型種別格納ハッシュ
# (これ以外はすべてECUC-NUMERICAL-PARAM-VALUE)
XML_VALUE_TYPE = {"ECUC-REFERENCE-DEF" => "ECUC-REFERENCE-VALUE",
"ECUC-FOREIGN-REFERENCE-DEF" => "ECUC-REFERENCE-VALUE",
"ECUC-SYMBOLIC-NAME-REFERENCE-DEF" => "ECUC-REFERENCE-VALUE",
"ECUC-INSTANCE-REFERENCE-DEF" => "ECUC-INSTANCE-REFERENCE-VALUE",
"ECUC-CHOICE-REFERENCE-DEF" => "ECUC-CHOICE-REFERENCE-DEF",
"ECUC-ENUMERATION-PARAM-DEF" => "ECUC-TEXTUAL-PARAM-VALUE",
"ECUC-STRING-PARAM-DEF" => "ECUC-TEXTUAL-PARAM-VALUE",
"ECUC-MULTILINE-STRING-PARAM-DEF" => "ECUC-TEXTUAL-PARAM-VALUE",
"ECUC-FUNCTION-NAME-DEF" => "ECUC-TEXTUAL-PARAM-VALUE",
"ECUC-LINKER-SYMBOL-DEF" => "ECUC-TEXTUAL-PARAM-VALUE"}
# インスタンス参照型の特別コンテナ
XML_INSTANCE_REF_CONTAINER = {"EcucPartitionSoftwareComponentInstanceRef" =>
{"CONTEXT-ELEMENT-REF" => "ROOT-SW-COMPOSITION-PROTOTYPE",
"TARGET-REF" => "SW-COMPONENT-PROTOTYPE"}}
######################################################################
# YAML → XML 実行機能
######################################################################
def YamlToXml(aArgData, sEcuExtractRef, bVerbose)
# 各パラメータのデータ型定義(-pオプションで生成したものを使用する)
sFileName = "#{TOOL_ROOT}/param_info.yaml"
if (!File.exist?(sFileName))
abort("#{sFileName} not found !!")
end
hParamInfo = YAML.load_file(sFileName)
# ハッシュでない(YAMLでない)場合エラー
if (!hParamInfo.is_a?(Hash))
abort("not YAML file !! [#{sFileName}]")
end
# 外部参照先のデータ型格納ハッシュを分離
$hForeignRefType = hParamInfo.delete(:FOREIGN_REF_TYPE)
# 選択型のコンテナ格納配列を分離
$aChoiceContainer = hParamInfo.delete(:ECUC_CHOICE_CONTAINER_DEF)
# インスタンス参照先のデータ型を保持
$aInstanceRefType = hParamInfo["ECUC-INSTANCE-REFERENCE-DEF"]
# コンテナ名変換テーブル
$hEcuc = {}
$hDest = {}
hParamInfo.each{|sType, aParam|
aParam.each{|sName|
if (XML_VALUE_TYPE.has_key?(sType))
$hEcuc[sName] = XML_VALUE_TYPE[sType]
else
$hEcuc[sName] = "ECUC-NUMERICAL-PARAM-VALUE"
end
$hDest[sName] = sType
}
}
# 参照型のパラメータ一覧
$hReferenceParam = hParamInfo["ECUC-REFERENCE-DEF"] + hParamInfo["ECUC-FOREIGN-REFERENCE-DEF"] + hParamInfo["ECUC-SYMBOLIC-NAME-REFERENCE-DEF"] + hParamInfo["ECUC-INSTANCE-REFERENCE-DEF"]
# 与えられた全YAMLをマージする
hYaml = {}
sArxmlName = nil
aArgData.each{|sFileName|
# ファイルが存在しない場合エラー
if (!File.exist?(sFileName))
abort("Argument error !! [#{sFileName}]")
end
# 出力ファイル名作成(複数ある場合,最初のファイル名を採用する)
if (File.extname(sFileName) == ".yaml")
if (sArxmlName.nil?())
sArxmlName = File.dirname(sFileName) + "/" + File.basename(sFileName, ".yaml") + ".arxml"
end
else
abort("not YAML file name !! [#{sFileName}]")
end
hTmpData = YAML.load(File.read(sFileName).toutf8())
# ハッシュでない(YAMLでない)場合エラー
if (!hTmpData.is_a?(Hash))
abort("not YAML file !! [#{sFileName}]")
end
# 読み込んだデータをマージしていく
YamlToXml_merge_hash(hYaml, hTmpData)
}
cXmlInfo = Document.new()
cXmlInfo.add(XMLDecl.new("1.0", "UTF-8"))
REXML::Comment.new(VER_INFO, cXmlInfo)
cXmlAutosar = cXmlInfo.add_element("AUTOSAR", XML_AUTOSAR_FIXED_ATT)
cXmlArPackages = cXmlAutosar.add_element("AR-PACKAGES")
# IMPLEMENTATION-DATA-TYPE格納ハッシュを分離して先に登録
hImplDataType = hYaml.delete("IMPLEMENTATION-DATA-TYPE")
if (!hImplDataType.nil?())
cXmlArPackage = cXmlArPackages.add_element("AR-PACKAGE")
cXmlArPackage.add_element(XML_SNAME).add_text("ImplementationDataTypes")
cXmlElements = cXmlArPackage.add_element("ELEMENTS")
hImplDataType.each{|sShortName, hData|
cXmlEcucModuleConfVal = cXmlElements.add_element("IMPLEMENTATION-DATA-TYPE")
cXmlEcucModuleConfVal.add_element(XML_SNAME).add_text(sShortName)
cXmlEcucModuleConfVal.add_element("CATEGORY").add_text(hData["CATEGORY"])
}
end
aModulePaths = []
hYaml.each{|sPackageName, hPackageData|
cXmlArPackage = cXmlArPackages.add_element("AR-PACKAGE")
cXmlArPackage.add_element(XML_SNAME).add_text(sPackageName)
cXmlElements = cXmlArPackage.add_element("ELEMENTS")
hPackageData.each{|sEcucModuleName, hEcucModuleData|
aModulePaths.push("/#{sPackageName}/#{sEcucModuleName}")
cXmlEcucModuleConfVal = cXmlElements.add_element("ECUC-MODULE-CONFIGURATION-VALUES")
cXmlEcucModuleConfVal.add_element(XML_SNAME).add_text(sEcucModuleName)
if (hEcucModuleData.has_key?("DefinitionRef"))
sEcuModuleDefinitionRef = hEcucModuleData["DefinitionRef"].dup
hEcucModuleData.delete("DefinitionRef")
else
if ( bVerbose == true )
puts("This #{sEcucModuleName} is not defined for 'DefinitionRef'.")
end
sEcuModuleDefinitionRef = sEcucModuleName
end
cXmlEcucModuleConfVal.add_element("DEFINITION-REF", {"DEST" => "ECUC-MODULE-DEF"}).add_text(XML_ROOT_PATH + sEcuModuleDefinitionRef)
cXmlEcucModuleConfVal.add_element("ECUC-DEF-EDITION").add_text(XML_EDITION)
cXmlEcucModuleConfVal.add_element("IMPLEMENTATION-CONFIG-VARIANT").add_text("VARIANT-PRE-COMPILE")
cXmlContainers = cXmlEcucModuleConfVal.add_element("CONTAINERS")
# 各パラメータ用コンテナを作成する
hEcucModuleData.each{|sShortName, hParamInfo|
# DefinitionRef補完
if (!hParamInfo.has_key?("DefinitionRef"))
hParamInfo["DefinitionRef"] = sShortName
end
cContainer = YamlToXml_make_container(sShortName, hParamInfo, XML_ROOT_PATH + sEcuModuleDefinitionRef)
cXmlContainers.add_element(cContainer)
}
}
}
# ECU-EXTRACT-REF指定がある場合、<ECUC-VALUE-COLLECTION>を追加する
if (!sEcuExtractRef.nil?())
cXmlArPackage = cXmlArPackages.add_element("AR-PACKAGE")
cXmlArPackage.add_element(XML_SNAME).add_text("EcucValueCollection")
cXmlElements = cXmlArPackage.add_element("ELEMENTS")
cXmlEcucValueCollection = cXmlElements.add_element("ECUC-VALUE-COLLECTION")
cXmlEcucValueCollection.add_element(XML_SNAME).add_text("EcucValueCollection")
cXmlEcucValueCollection.add_element("ECU-EXTRACT-REF", {"DEST" => "SYSTEM"}).add_text(sEcuExtractRef)
cXmlEcucValues = cXmlEcucValueCollection.add_element("ECUC-VALUES")
aModulePaths.each{|sPath|
cTemp = cXmlEcucValues.add_element("ECUC-MODULE-CONFIGURATION-VALUES-REF-CONDITIONAL")
cTemp.add_element("ECUC-MODULE-CONFIGURATION-VALUES-REF", {"DEST" => "ECUC-MODULE-CONFIGURATION-VALUES"}).add_text(sPath)
}
end
# XML文字列生成
sXmlCode = String.new()
cXmlInfo.write(sXmlCode, 2, false)
# XML宣言の属性のコーテーションをダブルに出来ない(?)ため,ここで置換する
sXmlCode.gsub!("'", "\"")
# ダブルコーテーションが"に変換されるのを抑止できない(?)ため,ここで置換する
sXmlCode.gsub!(""", "\"")
# 値を定義する部分だけインデントを入れないように出来ない(?)ため,ここで置換する
sXmlCode.gsub!(/>\n[\s]+([\w\.\[\]\(\)\+-\/\*~&;\s]*?)\n[\s]+</, ">\\1<")
# インデントをタブに出来ない(?)ため,ここで置換する
sXmlCode.gsub!(" ", "\t")
# ファイル出力
#puts(sXmlCode)
File.open(sArxmlName, "w") {|io|
io.puts(sXmlCode)
}
puts("Generated #{sArxmlName}")
end
# ハッシュマージ関数
def YamlToXml_merge_hash(hBase, hAdd)
hAdd.each{|sKey, xVal|
# 追加先にキーが存在しなければ,そのまま追加するのみ
if (!hBase.has_key?(sKey))
hBase[sKey] = xVal
# 同じキーで値が違う場合
elsif (hBase[sKey] != hAdd[sKey])
# ハッシュ同士であれば,再帰で追加
if (hBase[sKey].is_a?(Hash) && hAdd[sKey].is_a?(Hash))
YamlToXml_merge_hash(hBase[sKey], hAdd[sKey])
# 追加先が配列であれば,配列に合わせて追加
elsif (hBase[sKey].is_a?(Array))
if (hAdd[sKey].is_a?(Array))
hBase[sKey].concat(hAdd[sKey])
else
hBase[sKey].push(hAdd[sKey])
end
# 追加先が配列でなければ,配列にしてから追加
elsif (hAdd[sKey].is_a?(Array))
hBase[sKey] = [hBase[sKey]]
hBase[sKey].concat(hAdd[sKey])
# どちらも配列でない場合,配列として両方をマージ
else
hBase[sKey] = [hBase[sKey]]
hBase[sKey].push(hAdd[sKey])
end
else
# 同じパラメータの場合,何もしない
end
}
end
# コンテナ作成関数
def YamlToXml_make_container(sShortName, hParamInfo, sPath)
# 一律"ECUC-CONTAINER-VALUE"を入れた状態で初期化
cContainer = Element.new().add_element("ECUC-CONTAINER-VALUE")
# ショートネーム追加
cContainer.add_element(XML_SNAME).add_text(sShortName)
# コンテナまでのパス追加
if ($aChoiceContainer.include?(hParamInfo["DefinitionRef"]))
cContainer.add_element("DEFINITION-REF", {"DEST" => "ECUC-CHOICE-CONTAINER-DEF"}).add_text("#{sPath}/#{hParamInfo["DefinitionRef"]}")
else
cContainer.add_element("DEFINITION-REF", {"DEST" => "ECUC-PARAM-CONF-CONTAINER-DEF"}).add_text("#{sPath}/#{hParamInfo["DefinitionRef"]}")
end
# 各パラメータ設定(パラメータが無い場合は不要)
hCheck= {}
if (hParamInfo.size() != 1)
hCheck[XML_PARAM] = false
hCheck[XML_REFER] = false
hCheck[XML_SUB] = false
# まず参照型,サブコンテナ以外を生成(AUTOSARスキーマ制約)
hParamInfo.each{|sParamName, sahValue|
if ((sParamName == "DefinitionRef") || (sahValue.is_a?(Hash)))
next
end
# 参照型,サブコンテナ以外のパラメータ
if (!$hReferenceParam.include?(sParamName))
# パラメータ名チェック
if (!$hEcuc.has_key?(sParamName) || !$hDest.has_key?(sParamName))
abort("Unknown parameter: #{sParamName}")
end
if (hCheck[XML_PARAM] == false)
cContainer.add_element(XML_PARAM)
hCheck[XML_PARAM] = true
end
# 多重度*対応
aTemp = []
if (sahValue.is_a?(Array))
aTemp = sahValue
else
aTemp.push(sahValue)
end
aTemp.each{|sVal|
cParamContainer_ = Element.new()
cParamContainer = cParamContainer_.add_element($hEcuc[sParamName])
cParamContainer.add_element("DEFINITION-REF", {"DEST" => $hDest[sParamName]}).add_text("#{sPath}/#{hParamInfo["DefinitionRef"]}/#{sParamName}")
cParamContainer.add_element("VALUE").add_text(sVal.to_s())
cContainer.elements[XML_PARAM].add_element(cParamContainer)
}
end
}
# 次に参照型を生成(AUTOSARスキーマ制約)
hParamInfo.each{|sParamName, sahValue|
if ((sParamName == "DefinitionRef") || (sahValue.is_a?(Hash)))
next
end
# インスタンス参照型の場合
if ($aInstanceRefType.include?(sParamName))
if (!sahValue.is_a?(Array))
abort("#{sParamName} must be Array !!")
end
# 未サポートコンテナは生成できないためエラーとする
if (!XML_INSTANCE_REF_CONTAINER.has_key?(sParamName))
abort("#{sParamName} is not supported !!")
end
if (hCheck[XML_REFER] == false)
cContainer.add_element(XML_REFER)
hCheck[XML_REFER] = true
end
# 多重度*対応(2次元配列かチェック)
aTemp = []
if (sahValue[0].is_a?(Array))
aTemp = sahValue
else
aTemp.push(sahValue)
end
aTemp.each{|aVal|
cParamContainer_ = Element.new()
cParamContainer = cParamContainer_.add_element($hEcuc[sParamName])
cParamContainer.add_element("DEFINITION-REF", {"DEST" => $hDest[sParamName]}).add_text("#{sPath}/#{hParamInfo["DefinitionRef"]}/#{sParamName}")
cInstanceRef = cParamContainer.add_element("VALUE-IREF")
aVal.each{|hVal|
XML_INSTANCE_REF_CONTAINER[sParamName].each{|sParam, sDest|
if (hVal.has_key?(sParam))
cInstanceRef.add_element(sParam, {"DEST" => sDest}).add_text(hVal[sParam].to_s())
end
}
}
cContainer.elements[XML_REFER].add_element(cParamContainer)
}
# 参照型の場合
elsif ($hReferenceParam.include?(sParamName))
if (hCheck[XML_REFER] == false)
cContainer.add_element(XML_REFER)
hCheck[XML_REFER] = true
end
# 多重度*対応
aTemp = []
if (sahValue.is_a?(Array))
aTemp = sahValue
else
aTemp.push(sahValue)
end
aTemp.each{|sVal|
cParamContainer_ = Element.new()
cParamContainer = cParamContainer_.add_element($hEcuc[sParamName])
cParamContainer.add_element("DEFINITION-REF", {"DEST" => $hDest[sParamName]}).add_text("#{sPath}/#{hParamInfo["DefinitionRef"]}/#{sParamName}")
if (!$hForeignRefType.nil? && $hForeignRefType.has_key?(sParamName))
cParamContainer.add_element("VALUE-REF", {"DEST" => $hForeignRefType[sParamName]}).add_text(sVal.to_s())
else
cParamContainer.add_element("VALUE-REF", {"DEST" => "ECUC-CONTAINER-VALUE"}).add_text(sVal.to_s())
end
cContainer.elements[XML_REFER].add_element(cParamContainer)
}
end
}
# 最後にサブコンテナを生成
hParamInfo.each{|sParamName, sahValue|
if ((sParamName == "DefinitionRef") || (!sahValue.is_a?(Hash)))
next
end
if (hCheck[XML_SUB] == false)
cContainer.add_element(XML_SUB)
hCheck[XML_SUB] = true
end
# DefinitionRef補完
if (!sahValue.has_key?("DefinitionRef"))
sahValue["DefinitionRef"] = sParamName
end
# 再帰でサブコンテナを作成する
cContainer.elements[XML_SUB].add_element(YamlToXml_make_container(sParamName, sahValue, "#{sPath}/#{hParamInfo["DefinitionRef"]}"))
}
end
return cContainer
end
######################################################################
# XML → YAML 実行機能
######################################################################
def XmlToYaml(sFirstFile, aExtraFile)
aExtraFile.unshift(sFirstFile)
aExtraFile.each{|sFileName|
# ファイルが存在しない場合エラー
if (!File.exist?(sFileName))
abort("Argument error !! [#{sFileName}]")
end
# 出力ファイル名作成
if (File.extname(sFileName) == ".arxml")
sYamlName = File.dirname(sFileName) + "/" + File.basename(sFileName, ".arxml") + ".yaml"
else
abort("not ARXML file !! [#{sFileName}]")
end
# XMLライブラリでの読み込み
cXmlData = REXML::Document.new(open(sFileName))
hResult = {}
cXmlData.elements.each("AUTOSAR/AR-PACKAGES/AR-PACKAGE"){|cElement1|
cElement1.elements.each("ELEMENTS/ECUC-MODULE-CONFIGURATION-VALUES"){|cElement2|
sPackageName = cElement1.elements["SHORT-NAME"].text()
if (!hResult.has_key?(sPackageName))
hResult[sPackageName] = {}
end
sModuleName = cElement2.elements["SHORT-NAME"].text()
hResult[sPackageName][sModuleName] = {}
cElement2.elements.each("CONTAINERS/ECUC-CONTAINER-VALUE"){|cElement3|
XmlToYaml_parse_parameter(cElement3, hResult[sPackageName][sModuleName])
}
}
}
# YAMLファイル出力
open(sYamlName, "w") do |io|
YAML.dump(hResult, io)
end
# YAML整形処理
# ・先頭の区切り文字削除
# ・コーテーションの削除
# ・配列のインデント整列
sFileData = File.read(sYamlName)
sFileData.gsub!(/^---$/, "")
sFileData.gsub!("'", "")
sFileData.gsub!(/^(\s+)-(\s.*)$/, "\\1 -\\2")
File.write(sYamlName, sFileData)
puts("Generated #{sYamlName}")
}
end
# コンテナパース関数
def XmlToYaml_parse_parameter(cElement, hTarget)
sParamShortName = cElement.elements["SHORT-NAME"].text()
sParamDefName = cElement.elements["DEFINITION-REF"].text().split("/")[-1]
hTarget[sParamShortName] = {}
if (sParamShortName != sParamDefName)
hTarget[sParamShortName]["DefinitionRef"] = sParamDefName
end
# パラメータ
cElement.elements.each("PARAMETER-VALUES"){|cElementC|
["ECUC-NUMERICAL-PARAM-VALUE", "ECUC-TEXTUAL-PARAM-VALUE"].each{|sParamValue|
cElementC.elements.each(sParamValue){|cElementG|
sName = cElementG.elements["DEFINITION-REF"].text().split("/")[-1]
sValue = cElementG.elements["VALUE"].text()
# 複数多重度対応
if (hTarget[sParamShortName].has_key?(sName))
if (hTarget[sParamShortName][sName].is_a?(Array))
# 既に複数ある場合は配列に追加
hTarget[sParamShortName][sName].push(sValue)
else
# 1つだけ定義されていた場合は配列に変更
sTemp = hTarget[sParamShortName][sName]
hTarget[sParamShortName][sName] = [sTemp, sValue]
end
else
hTarget[sParamShortName][sName] = sValue
end
}
}
}
# 参照,外部参照,選択参照
cElement.elements.each("REFERENCE-VALUES/ECUC-REFERENCE-VALUE"){|cElementC|
sName = cElementC.elements["DEFINITION-REF"].text().split("/")[-1]
if (cElementC.elements["VALUE-REF"].nil?)
abort("<VALUE> is not found in '#{sParamShortName}'")
end
sValue = cElementC.elements["VALUE-REF"].text()
# 複数多重度対応
if (hTarget[sParamShortName].has_key?(sName))
if (hTarget[sParamShortName][sName].is_a?(Array))
# 既に複数ある場合は配列に追加
hTarget[sParamShortName][sName].push(sValue)
else
# 1つだけ定義されていた場合は配列に変更
sTemp = hTarget[sParamShortName][sName]
hTarget[sParamShortName][sName] = [sTemp, sValue]
end
else
hTarget[sParamShortName][sName] = sValue
end
}
# インスタンス参照
cElement.elements.each("REFERENCE-VALUES/ECUC-INSTANCE-REFERENCE-VALUE"){|cElementC|
sName = cElementC.elements["DEFINITION-REF"].text().split("/")[-1]
hTarget[sParamShortName][sName] = []
hTarget[sParamShortName][sName].push({"CONTEXT-ELEMENT-REF" => cElementC.elements["VALUE-IREF"].elements["CONTEXT-ELEMENT-REF"].text()})
hTarget[sParamShortName][sName].push({"TARGET-REF" => cElementC.elements["VALUE-IREF"].elements["TARGET-REF"].text()})
}
# サブコンテナ(再帰呼出し)
cElement.elements.each("SUB-CONTAINERS/ECUC-CONTAINER-VALUE"){|cElementC|
XmlToYaml_parse_parameter(cElementC, hTarget[sParamShortName])
}
end
######################################################################
# AUTOSARパラメータ情報ファイル作成
######################################################################
def MakeParamInfo(sFileName)
# ファイルが存在しない場合エラー
if (!File.exist?(sFileName))
abort("Argument error !! [#{sFileName}]")
end
sParamFileName = File.dirname(sFileName) + "/param_info.yaml"
# 読み込み対象モジュール
aTargetModule = ["Rte", "Os", "Com", "PduR", "CanTp", "CanIf", "Can", "EcuC", "EcuM", "WdgM", "WdgIf", "Wdg", "Dem"]
# XMLライブラリでの読み込み
cXmlData = REXML::Document.new(open(sFileName))
# 外部参照先のデータ型格納ハッシュ
$hForeignRefType = {}
# 選択型のコンテナ格納配列
$aChoiceContainer = []
# パース結果格納ハッシュ初期化(NCES仕様コンテナは予め設定)
sNcesContainer = <<-EOS
ECUC-ENUMERATION-PARAM-DEF:
- OsMemorySectionInitialize
- OsIsrInterruptSource
- OsInterCoreInterruptInterruptSource
- OsSpinlockLockMethod
- WdgTriggerMode
- WdgTimeoutReaction
ECUC-INTEGER-PARAM-DEF:
- OsMasterCoreId
- OsHookStackSize
- OsHookStackCoreAssignment
- OsOsStackSize
- OsOsStackCoreAssignment
- OsNonTrustedHookStackSize
- OsNonTrustedHookStackCoreAssignment
- OsTaskStackSize
- OsTaskSystemStackSize
- OsIsrInterruptNumber
- OsIsrInterruptPriority
- OsIsrStackSize
- OsTrustedFunctionStackSize
- OsInterCoreInterruptStackSize
- OsMemoryRegionSize
- OsMemoryRegionStartAddress
- OsMemoryAreaSize
- OsStandardMemoryCoreAssignment
- OsIsrMaxFrequency
- WdgWindowOpenRate
ECUC-STRING-PARAM-DEF:
- OsIncludeFileName
- OsMemoryRegionName
- OsMemoryAreaStartAddress
- OsMemorySectionName
- OsMemoryModuleName
- OsLinkSectionName
- OsIocPrimitiveDataType
- OsIocIncludeFile
- OsHookStackStartAddress
- OsOsStackStartAddress
- OsNonTrustedHookStackStartAddress
- OsTaskStackStartAddress
- OsTaskSystemStackStartAddress
- OsInterCoreInterruptStackStartAddress
ECUC-BOOLEAN-PARAM-DEF:
- OsMemoryRegionWriteable
- OsMemoryAreaWriteable
- OsMemoryAreaReadable
- OsMemoryAreaExecutable
- OsMemoryAreaCacheable
- OsMemoryAreaDevice
- OsMemorySectionWriteable
- OsMemorySectionReadable
- OsMemorySectionExecutable
- OsMemorySectionShort
- OsMemorySectionCacheable
- OsMemorySectionDevice
- OsMemorySectionExport
- OsMemoryModuleExport
- OsTaskOsInterruptLockMonitor
- OsTaskResourceLockMonitor
ECUC-REFERENCE-DEF:
- OsStandardMemoryRomRegionRef
- OsStandardMemoryRamRegionRef
- OsAppStandardMemoryRomRegionRef
- OsAppStandardMemoryRamRegionRef
- OsMemorySectionMemoryRegionRef
- OsLinkSectionMemoryRegionRef
- OsResourceLinkedResourceRef
- OsCounterIsrRef
- OsAppMemorySectionRef
- OsAppMemoryModuleRef
- OsAppMemoryAreaRef
- OsAppInterCoreInterruptRef
- OsInterCoreInterruptAccessingApplication
- OsInterCoreInterruptResourceRef
- WdgMOsCounterRef
- OsSystemCycleTimeWindowRef
ECUC-FLOAT-PARAM-DEF:
- OsSystemCycleTime
- OsSystemCycleTimeWindowStart
- OsSystemCycleTimeWindowLength
- OsOsInterruptLockBudget
- OsResourceLockBudget
- OsTrustedFunctionExecutionBudget
- WdgTimeout
- WdgTriggerInterruptPeriod
EOS
$hResult = YAML.load(sNcesContainer)
cXmlData.elements.each("AUTOSAR/AR-PACKAGES/AR-PACKAGE/AR-PACKAGES/AR-PACKAGE/ELEMENTS/ECUC-MODULE-DEF"){|cElement1|
# 対象モジュールのみを処理する
if (!aTargetModule.include?(cElement1.elements["SHORT-NAME"].text()))
next
end
cElement1.elements.each("CONTAINERS/ECUC-PARAM-CONF-CONTAINER-DEF"){|cElement2|
MakeParamInfo_parse_parameter(cElement2)
}
}
# パラメータ名でソートと重複除去
hResultSort = {}
$hResult.each{|sType, aParam|
hResultSort[sType] = aParam.uniq().sort()
}
# 外部参照先のデータ型格納ハッシュを結合
if (!$hForeignRefType.empty?())
hResultSort[:FOREIGN_REF_TYPE] = $hForeignRefType
end
# 選択型のコンテナ格納配列を追加
if (!$aChoiceContainer.empty?())
hResultSort[:ECUC_CHOICE_CONTAINER_DEF] = $aChoiceContainer
end
# RteSoftwareComponentInstanceRefは外部参照とインスタンス参照の
# 両方に含まれるが,外部参照として扱う
hResultSort["ECUC-INSTANCE-REFERENCE-DEF"].delete("RteSoftwareComponentInstanceRef")
# YAMLファイル出力
open(sParamFileName, "w") do |io|
YAML.dump(hResultSort, io)
end
puts("Generated #{sParamFileName}")
end
# サブコンテナ再帰パース関数
def MakeParamInfo_parse_sub_container(cElement)
# "ECUC-PARAM-CONF-CONTAINER-DEF"が登場するまで再帰する
cElement.elements.each{|cElementC|
# CHOICEはさらにネストする
if (cElementC.name == "ECUC-CHOICE-CONTAINER-DEF")
$aChoiceContainer.push(cElementC.elements[XML_SNAME].text())
MakeParamInfo_parse_sub_container(cElementC)
elsif (cElementC.name == "ECUC-PARAM-CONF-CONTAINER-DEF")
MakeParamInfo_parse_parameter(cElementC)
else
MakeParamInfo_parse_sub_container(cElementC)
end
}
end
# コンテナパース関数
def MakeParamInfo_parse_parameter(cElement)
# パラメータ
cElement.elements.each("PARAMETERS"){|cElementC|
cElementC.elements.each{|cElementG|
# 初出のデータ型処理
if (!$hResult.has_key?(cElementG.name))
$hResult[cElementG.name] = []
end
# 取得したパラメータ名を格納する
$hResult[cElementG.name].push(cElementG.elements["SHORT-NAME"].text())
}
}
# 参照
cElement.elements.each("REFERENCES/ECUC-REFERENCE-DEF"){|cElementC|
$hResult["ECUC-REFERENCE-DEF"].push(cElementC.elements["SHORT-NAME"].text())
}
# 外部参照
cElement.elements.each("REFERENCES/ECUC-FOREIGN-REFERENCE-DEF"){|cElementC|
# 初出のデータ型処理
if (!$hResult.has_key?("ECUC-FOREIGN-REFERENCE-DEF"))
$hResult["ECUC-FOREIGN-REFERENCE-DEF"] = []
end
$hResult["ECUC-FOREIGN-REFERENCE-DEF"].push(cElementC.elements["SHORT-NAME"].text())
$hForeignRefType[cElementC.elements["SHORT-NAME"].text()] = cElementC.elements["DESTINATION-TYPE"].text()
}
# 選択参照
cElement.elements.each("REFERENCES/ECUC-CHOICE-REFERENCE-DEF"){|cElementC|
# 初出のデータ型処理
if (!$hResult.has_key?("ECUC-CHOICE-REFERENCE-DEF"))
$hResult["ECUC-CHOICE-REFERENCE-DEF"] = []
end
$hResult["ECUC-CHOICE-REFERENCE-DEF"].push(cElementC.elements["SHORT-NAME"].text())
}
# シンボル参照
cElement.elements.each("REFERENCES/ECUC-SYMBOLIC-NAME-REFERENCE-DEF"){|cElementC|
# 初出のデータ型処理
if (!$hResult.has_key?("ECUC-SYMBOLIC-NAME-REFERENCE-DEF"))
$hResult["ECUC-SYMBOLIC-NAME-REFERENCE-DEF"] = []
end
$hResult["ECUC-SYMBOLIC-NAME-REFERENCE-DEF"].push(cElementC.elements["SHORT-NAME"].text())
}
# インスタンス参照
cElement.elements.each("REFERENCES/ECUC-INSTANCE-REFERENCE-DEF"){|cElementC|
# 初出のデータ型処理
if (!$hResult.has_key?("ECUC-INSTANCE-REFERENCE-DEF"))
$hResult["ECUC-INSTANCE-REFERENCE-DEF"] = []
end
$hResult["ECUC-INSTANCE-REFERENCE-DEF"].push(cElementC.elements["SHORT-NAME"].text())
}
# サブコンテナ(再帰呼出し)
cElement.elements.each("SUB-CONTAINERS"){|cElementC|
MakeParamInfo_parse_sub_container(cElementC)
}
end
######################################################################
# ジェネレータ用csvファイルの生成
######################################################################
def MakeCsv(sFileName, sTargetModule)
# ファイルが存在しない場合エラー
if (!File.exist?(sFileName))
abort("Argument error !! [#{sFileName}]")
end
sCsvFileName = File.dirname(sFileName) + "/" + sTargetModule + ".csv"
# XMLライブラリでの読み込み
cXmlData = REXML::Document.new(open(sFileName))
$hResult = {}
$sNowContainer = ""
cXmlData.elements.each("AUTOSAR/AR-PACKAGES/AR-PACKAGE/AR-PACKAGES/AR-PACKAGE/ELEMENTS/ECUC-MODULE-DEF"){|cElement1|
# 対象モジュールのみを処理する
if (cElement1.elements["SHORT-NAME"].text() != sTargetModule)
next
end
cElement1.elements.each("CONTAINERS/ECUC-PARAM-CONF-CONTAINER-DEF"){|cElement2|
$sContainer = cElement2.elements["SHORT-NAME"].text()
$hResult[$sContainer] = MakeCsv_add_parameter_info(cElement2, nil)
MakeCsv_parse_parameter(cElement2)
}
}
sModulePath = "/AUTOSAR/EcucDefs/#{sTargetModule}"
sCsvData = "#{sModulePath},,,1\n"
hDataTypeTable = {"ECUC-REFERENCE-DEF" => "REF",
"ECUC-FOREIGN-REFERENCE-DEF" => "REF",
"ECUC-CHOICE-REFERENCE-DEF" => "REF",
"ECUC-SYMBOLIC-NAME-REFERENCE-DEF" => "REF",
"ECUC-INSTANCE-REFERENCE-DEF" => "REF",
"ECUC-BOOLEAN-PARAM-DEF" => "BOOLEAN",
"ECUC-INTEGER-PARAM-DEF" => "INT",
"ECUC-FUNCTION-NAME-DEF" => "FUNCTION",
"ECUC-ENUMERATION-PARAM-DEF" => "ENUM",
"ECUC-STRING-PARAM-DEF" => "STRING",
"ECUC-FLOAT-PARAM-DEF" => "FLOAT",
"ECUC-LINKER-SYMBOL-DEF" => "STRING",
nil => ""}
$hResult.each{|sParam, aInfo|
if (!hDataTypeTable.has_key?(aInfo[0]))
abort("[#{__FILE__}] #{__LINE__}: #{aInfo[0]}")
end
if ((aInfo[1] == "1") && (aInfo[2] == "1"))
sCsvData += "#{sModulePath}/#{sParam},#{sParam.split("/")[-1]},#{hDataTypeTable[aInfo[0]]},1\n"
else
sCsvData += "#{sModulePath}/#{sParam},#{sParam.split("/")[-1]},#{hDataTypeTable[aInfo[0]]},#{aInfo[1]},#{aInfo[2]}\n"
end
}
File.open(sCsvFileName, "w") {|io|
io.puts(sCsvData)
}
puts("Generated #{sCsvFileName}")
end
# パラメータ情報追加関数
def MakeCsv_add_parameter_info(cElement, sName = cElement.name)
# パラメータ毎に,型・多重度下限,上限の情報を取得
sLower = nil
if (!cElement.elements["LOWER-MULTIPLICITY"].nil?)
sLower = cElement.elements["LOWER-MULTIPLICITY"].text()
else
abort("[#{__FILE__}] #{__LINE__}")
end
sUpper = nil
if (!cElement.elements["UPPER-MULTIPLICITY"].nil?)
sUpper = cElement.elements["UPPER-MULTIPLICITY"].text()
elsif (!cElement.elements["UPPER-MULTIPLICITY-INFINITE"].nil? && (cElement.elements["UPPER-MULTIPLICITY-INFINITE"].text() == "true"))
sUpper = "*"
else
abort("[#{__FILE__}] #{__LINE__}")
end
return [sName, sLower, sUpper]
end
# サブコンテナ再帰パース関数
def MakeCsv_parse_sub_container(cElement)
# "ECUC-PARAM-CONF-CONTAINER-DEF"が登場するまで再帰する
cElement.elements.each{|cElementC|
# CHOICEはさらにネストする
if (cElementC.name == "ECUC-CHOICE-CONTAINER-DEF")
$sContainer += "/#{cElementC.elements["SHORT-NAME"].text()}"
$hResult[$sContainer] = MakeCsv_add_parameter_info(cElementC, nil)
MakeCsv_parse_sub_container(cElementC)
aTemp = $sContainer.split("/")
aTemp.pop()
$sContainer = aTemp.join("/")
elsif (cElementC.name == "ECUC-PARAM-CONF-CONTAINER-DEF")
$sContainer += "/#{cElementC.elements["SHORT-NAME"].text()}"
$hResult[$sContainer] = MakeCsv_add_parameter_info(cElementC, nil)
MakeCsv_parse_parameter(cElementC)
aTemp = $sContainer.split("/")
aTemp.pop()
$sContainer = aTemp.join("/")
else
MakeCsv_parse_sub_container(cElementC)
end
}
end
# コンテナパース関数
def MakeCsv_parse_parameter(cElement)
# パラメータ
cElement.elements.each("PARAMETERS"){|cElementC|
cElementC.elements.each{|cElementG|
sParamName = "#{$sContainer}/#{cElementG.elements["SHORT-NAME"].text()}"
$hResult[sParamName] = MakeCsv_add_parameter_info(cElementG)
}
}
# 参照
cElement.elements.each("REFERENCES/ECUC-REFERENCE-DEF"){|cElementC|
sParamName = "#{$sContainer}/#{cElementC.elements["SHORT-NAME"].text()}"
$hResult[sParamName] = MakeCsv_add_parameter_info(cElementC)
}
# 外部参照
cElement.elements.each("REFERENCES/ECUC-FOREIGN-REFERENCE-DEF"){|cElementC|
sParamName = "#{$sContainer}/#{cElementC.elements["SHORT-NAME"].text()}"
$hResult[sParamName] = MakeCsv_add_parameter_info(cElementC)
}
# 選択参照
cElement.elements.each("REFERENCES/ECUC-CHOICE-REFERENCE-DEF"){|cElementC|
sParamName = "#{$sContainer}/#{cElementC.elements["SHORT-NAME"].text()}"
$hResult[sParamName] = MakeCsv_add_parameter_info(cElementC)
}
# シンボルネーム参照
cElement.elements.each("REFERENCES/ECUC-SYMBOLIC-NAME-REFERENCE-DEF"){|cElementC|
sParamName = "#{$sContainer}/#{cElementC.elements["SHORT-NAME"].text()}"
$hResult[sParamName] = MakeCsv_add_parameter_info(cElementC)
}
# インスタンス参照
cElement.elements.each("REFERENCES/ECUC-INSTANCE-REFERENCE-DEF"){|cElementC|
sParamName = "#{$sContainer}/#{cElementC.elements["SHORT-NAME"].text()}"
$hResult[sParamName] = MakeCsv_add_parameter_info(cElementC)
}
# サブコンテナ(再帰呼出し)
cElement.elements.each("SUB-CONTAINERS"){|cElementC|
MakeCsv_parse_sub_container(cElementC)
}
end
######################################################################
# オプション処理
######################################################################
lMode = :YamlToXml
sEcuExtractRef = nil
cOpt = OptionParser.new(banner="Usage: abrex.rb [options]... [yaml|xml files]...", 18)
cOpt.version = VERSION
sOptData = nil
sBswName = nil
bVerbose = nil
cOpt.on("-i XML_FILE", "ARXML to YAML conversion") {|xVal|
sOptData = xVal
lMode = :XmlToYaml
}
cOpt.on("-p XML_FILE", "Generate 'param_info.yaml' from AUTOSAR Ecu Configuration Parameters file") {|xVal|
sOptData = xVal
lMode = :MakeParamInfo
}
cOpt.on("-c XML_FILE", "Generate '{BSW_NAME}.csv' from AUTOSAR Ecu Configuration Parameters file") {|xVal|
sOptData = xVal
lMode = :MakeCsv
}
cOpt.on("-b BSW_NAME", "set a BSW Module Name (for '-c' additional optipn)") {|xVal|
sBswName = xVal
lMode = :MakeCsv
}
cOpt.on("-e ECU-EXTRACT-REF", "set a ECU-EXTRACT-REF path if <ECUC-VALUE-COLLECTION> is needed") {|xVal|
sEcuExtractRef = xVal
lMode = :YamlToXml
}
cOpt.on("-v", "--version", "show version information"){
puts(cOpt.ver())
exit(1)
}
cOpt.on("-V", "--verbose", "Show the warning on as conversion is running."){|boolean|
bVerbose = boolean
}
cOpt.on("-h", "--help", "show help (this)"){
puts(cOpt.help())
exit(1)
}
begin
aArgData = cOpt.parse(ARGV)
rescue OptionParser::ParseError
puts(cOpt.help())
exit(1)
end
if (((lMode == :YamlToXml) && aArgData.empty?()) ||
((lMode != :YamlToXml) && sOptData.nil?()))
puts(cOpt.help())
exit(1)
end
if ((lMode == :MakeCsv) && sBswName.nil?())
puts(cOpt.help())
exit(1)
end
######################################################################
# オプションに従って各処理を実行
######################################################################
case lMode
when :YamlToXml
YamlToXml(aArgData, sEcuExtractRef, bVerbose)
when :XmlToYaml
XmlToYaml(sOptData, aArgData)
when :MakeParamInfo
MakeParamInfo(sOptData)
when :MakeCsv
MakeCsv(sOptData, sBswName)
end
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2011-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: Os.h 739 2017-01-24 10:05:05Z nces-hibino $
*/
/*
* ATK2 OSヘッダファイル
*
* ATK2がサポートするシステムサービスの宣言と,必要なデー
* タ型,定数,マクロの定義を含むヘッダファイル
*
* アセンブリ言語のソースファイルからこのファイルをインクルードする時
* は,TOPPERS_MACRO_ONLYを定義しておく
* これにより,マクロ定義以外を除くようになっている
*
* このファイルをインクルードする前にインクルードしておくべきファイル
* はない
*/
#ifndef TOPPERS_OS_H
#define TOPPERS_OS_H
/*
* 共通のデータ型・定数・マクロ
*/
#include "Std_Types.h"
#include "MemMap.h"
#include "Rte_Os_Type.h"
#if !defined(TOPPERS_CFG1_OUT) && !defined(OMIT_INCLUDE_OS_CFG)
#include "Os_Cfg.h"
#endif
/*
* ターゲット依存部
*/
#include "target_kernel.h"
#ifndef TOPPERS_MACRO_ONLY
/*
* データ型の定義
*/
/*
* オブジェクト番号の型定義
*/
typedef uint8 TaskStateType; /* タスク状態 */
typedef uint32 EventMaskType; /* イベントマスク */
typedef uint32 TickType; /* カウンタ値(ティック)*/
typedef uint32 AppModeType; /* アプリケーションモード */
typedef uint8 OSServiceIdType; /* システムサービスID */
typedef uint8 ScheduleTableStatusType; /* スケジュールテーブル状態 */
typedef uint8 ProtectionReturnType; /* プロテクションフックからの返り値 */
typedef uintptr MemorySizeType; /* メモリ領域サイズ */
typedef struct {
TickType maxallowedvalue; /* カウンタ指定の最大値 */
TickType ticksperbase; /* OSでは使用せず,ユーザが自由に使用する値 */
TickType mincycle; /* サイクル指定の最小値 */
} AlarmBaseType;
/*
* 最適化するため,依存部再定義できる型
*/
#ifndef OMIT_DATA_TYPE
typedef uint32 TimeType; /* 時間 */
typedef uint32 AlarmType; /* アラームID */
typedef uint32 ResourceType; /* リソースID */
typedef uint32 TaskType; /* タスクID */
typedef uint32 ISRType; /* ISR ID */
typedef uint32 CounterType; /* カウンタID */
typedef uint32 ScheduleTableType; /* スケジュールテーブルID */
typedef float32 PhysicalTimeType; /* (ティックから時間に換算用)時間 */
#endif /* OMIT_DATA_TYPE */
typedef AlarmBaseType * AlarmBaseRefType;
typedef TaskType * TaskRefType;
typedef TaskStateType * TaskStateRefType;
typedef EventMaskType * EventMaskRefType;
typedef TickType * TickRefType;
typedef ScheduleTableStatusType * ScheduleTableStatusRefType;
/*
* 保護違反を起こした処理単位の型
*/
typedef uint8 FaultyContextType;
/*
* OSオブジェクト宣言用のマクロ
*/
#define DeclareTask(TaskIdentifier)
#define DeclareResource(ResourceIdentifier)
#define DeclareEvent(EventIdentifier)
#define DeclareAlarm(AlarmIdentifier)
/*
* メインルーチン定義用のマクロ
*/
#define TASK(TaskName) void TaskMain ## TaskName(void)
#define ISR(ISRName) void ISRMain ## ISRName(void)
#ifndef C1ISR
#define C1ISR(ISRName) void C1ISRMain ## ISRName(void)
#endif /* C1ISR */
#define ALARMCALLBACK(AlarmCallBackName) \
void AlarmMain ## AlarmCallBackName(void)
/*
* メモリ領域確保のための型定義
*/
#ifndef TOPPERS_STK_T
#define TOPPERS_STK_T sintptr
#endif /* TOPPERS_STK_T */
typedef TOPPERS_STK_T StackType; /* スタック領域を確保するための型 */
/*
* システムサービスパラメータ取得のための定義
*/
typedef union {
TaskType tskid;
TaskRefType p_tskid;
TaskStateRefType p_stat;
ResourceType resid;
EventMaskType mask;
EventMaskRefType p_mask;
AlarmType almid;
AlarmBaseRefType p_info;
TickRefType p_tick;
TickRefType p_val;
TickRefType p_eval;
TickType incr;
TickType cycle;
TickType start;
AppModeType mode;
CounterType cntid;
ScheduleTableType schtblid;
TickType offset;
ScheduleTableType schtblid_from;
ScheduleTableType schtblid_to;
ScheduleTableStatusRefType p_schtblstate;
ISRType isrid;
} ErrorHook_Par;
/*
* メモリ領域確保のためのマクロ
*
* 以下のTOPPERS_COUNT_SZとTOPPERS_ROUND_SZの定義は,unitが2の巾乗であ
* ることを仮定している.
*/
#ifndef TOPPERS_COUNT_SZ
#define TOPPERS_COUNT_SZ(sz, unit) ((((sz) + (unit)) - (1U)) / (unit))
#endif /* TOPPERS_COUNT_SZ */
#ifndef TOPPERS_ROUND_SZ
#define TOPPERS_ROUND_SZ(sz, unit) ((((sz) + (unit)) - (1U)) & (~((unit) - (1U))))
#endif /* TOPPERS_ROUND_SZ */
#define COUNT_STK_T(sz) (TOPPERS_COUNT_SZ((sz), sizeof(StackType)))
#define ROUND_STK_T(sz) (TOPPERS_ROUND_SZ((sz), sizeof(StackType)))
/*
* システムサービスAPIの宣言
*/
/*
* OS管理
*/
extern AppModeType GetActiveApplicationMode(void);
extern void StartOS(AppModeType Mode);
extern void ShutdownOS(StatusType Error);
extern FaultyContextType GetFaultyContext(void);
/*
* タスク管理
*/
extern StatusType ActivateTask(TaskType TaskID);
extern StatusType TerminateTask(void);
extern StatusType ChainTask(TaskType TaskID);
extern StatusType Schedule(void);
extern StatusType GetTaskID(TaskRefType TaskID);
extern StatusType GetTaskState(TaskType TaskID, TaskStateRefType State);
/*
* 割込み管理
*/
extern void EnableAllInterrupts(void);
extern void DisableAllInterrupts(void);
extern void ResumeAllInterrupts(void);
extern void SuspendAllInterrupts(void);
extern void ResumeOSInterrupts(void);
extern void SuspendOSInterrupts(void);
extern ISRType GetISRID(void);
extern StatusType DisableInterruptSource(ISRType DisableISR);
extern StatusType EnableInterruptSource(ISRType EnableISR);
/*
* イベント管理
*/
extern StatusType SetEvent(TaskType TaskID, EventMaskType Mask);
extern StatusType ClearEvent(EventMaskType Mask);
extern StatusType GetEvent(TaskType TaskID, EventMaskRefType Event);
extern StatusType WaitEvent(EventMaskType Mask);
/*
* リソース管理
*/
extern StatusType GetResource(ResourceType ResID);
extern StatusType ReleaseResource(ResourceType ResID);
/*
* カウンタ制御
*/
extern StatusType IncrementCounter(CounterType CounterID);
/*
* ソフトウェアフリーランタイマ制御
*/
extern StatusType GetCounterValue(CounterType CounterID, TickRefType Value);
extern StatusType GetElapsedValue(CounterType CounterID, TickRefType Value, TickRefType ElapsedValue);
/*
* アラーム制御
*/
extern StatusType GetAlarmBase(AlarmType AlarmID, AlarmBaseRefType Info);
extern StatusType GetAlarm(AlarmType AlarmID, TickRefType Tick);
extern StatusType SetRelAlarm(AlarmType AlarmID, TickType increment, TickType cycle);
extern StatusType SetAbsAlarm(AlarmType AlarmID, TickType start, TickType cycle);
extern StatusType CancelAlarm(AlarmType AlarmID);
/*
* スケジュールテーブル制御
*/
extern StatusType StartScheduleTableRel(ScheduleTableType ScheduleTableID, TickType Offset);
extern StatusType StartScheduleTableAbs(ScheduleTableType ScheduleTableID, TickType Start);
extern StatusType StopScheduleTable(ScheduleTableType ScheduleTableID);
extern StatusType NextScheduleTable(ScheduleTableType ScheduleTableID_From, ScheduleTableType ScheduleTableID_To);
extern StatusType GetScheduleTableStatus(ScheduleTableType ScheduleTableID, ScheduleTableStatusRefType ScheduleStatus);
#if !defined(TOPPERS_CFG1_OUT) && !defined(OMIT_INCLUDE_OS_CFG) && !defined(OMIT_INCLUDE_OS_LCFG)
#include "Os_Lcfg.h"
#endif
/*
* フックルーチン
*/
#ifdef CFG_USE_ERRORHOOK
extern void ErrorHook(StatusType Error);
#endif /* CFG_USE_ERRORHOOK */
#ifdef CFG_USE_PRETASKHOOK
extern void PreTaskHook(void);
#endif /* CFG_USE_PRETASKHOOK */
#ifdef CFG_USE_POSTTASKHOOK
extern void PostTaskHook(void);
#endif /* CFG_USE_POSTTASKHOOK */
#ifdef CFG_USE_STARTUPHOOK
extern void StartupHook(void);
#endif /* CFG_USE_STARTUPHOOK */
#ifdef CFG_USE_SHUTDOWNHOOK
extern void ShutdownHook(StatusType Error);
#endif /* CFG_USE_SHUTDOWNHOOK */
#ifdef CFG_USE_PROTECTIONHOOK
extern ProtectionReturnType ProtectionHook(StatusType FatalError);
#endif /* CFG_USE_PROTECTIONHOOK */
/*
* ファイル名,行番号の参照用の変数
*/
extern const char8 *kernel_fatal_file_name; /* ファイル名 */
extern sint32 kernel_fatal_line_num; /* 行番号 */
#endif /* TOPPERS_MACRO_ONLY */
/*
* OSのエラーコード
*/
#define E_OS_ACCESS UINT_C(1)
#define E_OS_CALLEVEL UINT_C(2)
#define E_OS_ID UINT_C(3)
#define E_OS_LIMIT UINT_C(4)
#define E_OS_NOFUNC UINT_C(5)
#define E_OS_RESOURCE UINT_C(6)
#define E_OS_STATE UINT_C(7)
#define E_OS_VALUE UINT_C(8)
#define E_OS_SERVICEID UINT_C(9)
#define E_OS_ILLEGAL_ADDRESS UINT_C(10)
#define E_OS_MISSINGEND UINT_C(11)
#define E_OS_DISABLEDINT UINT_C(12)
#define E_OS_STACKFAULT UINT_C(13)
#define E_OS_PROTECTION_MEMORY UINT_C(14)
#define E_OS_PROTECTION_TIME_TASK UINT_C(15)
#define E_OS_PROTECTION_TIME_ISR UINT_C(16)
#define E_OS_PROTECTION_ARRIVAL_TASK UINT_C(17)
#define E_OS_PROTECTION_ARRIVAL_ISR UINT_C(18)
#define E_OS_PROTECTION_LOCKED_RESOURCE UINT_C(19)
#define E_OS_PROTECTION_LOCKED_OSINT UINT_C(20)
#define E_OS_PROTECTION_LOCKED_ALLINT UINT_C(21)
#define E_OS_PROTECTION_EXCEPTION UINT_C(22)
#define E_OS_PROTECTION_FATAL UINT_C(23)
#define E_OS_MODE UINT_C(24)
#define E_OS_SHUTDOWN_FATAL UINT_C(25)
#define E_OS_PARAM_POINTER UINT_C(26)
#define E_OS_SYS_ASSERT_FATAL UINT_C(27)
#define E_OS_STACKINSUFFICIENT UINT_C(28)
#define E_OS_CORE UINT_C(29)
#define E_OS_SPINLOCK UINT_C(30)
#define E_OS_INTERFERENCE_DEADLOCK UINT_C(31)
#define E_OS_NESTING_DEADLOCK UINT_C(32)
#define E_OS_SHUTDOWN_OTHER_CORE UINT_C(33)
#define E_OS_TIMEINSUFFICIENT UINT_C(34)
#define E_OS_PROTECTION_TIMEWINDOW UINT_C(35)
#define E_OS_PROTECTION_COUNT_ISR UINT_C(36)
/* AUTOSAR仕様R4.0.3との互換性考慮 */
#define OS_E_PARAM_POINTER E_OS_PARAM_POINTER
#define ERRCODE_NUM UINT_C(36) /* エラーコード数 */
/*
* その他の定数値
*/
#define UINT32_INVALID UINT_C(0xffffffff)
#define UINT8_INVALID UINT_C(0xff)
#define SUSPENDED ((TaskStateType) 0) /* 休止状態 */
#define RUNNING ((TaskStateType) 1) /* 実行状態 */
#define READY ((TaskStateType) 2) /* 実行可能状態 */
#define WAITING ((TaskStateType) 3) /* 待ち状態 */
/*
* 最適化するため,依存部での再定義が必要
*/
#ifndef OMIT_DATA_TYPE
#define INVALID_TASK ((TaskType) UINT32_INVALID)
#define INVALID_ISR ((ISRType) UINT32_INVALID)
#endif /* OMIT_DATA_TYPE */
#define INVALID_APPMODETYPE ((AppModeType) UINT32_INVALID)
/*
* スケジュールテーブルのステータス定義
*/
#define SCHEDULETABLE_STOPPED ((ScheduleTableStatusType) 0x01)
#define SCHEDULETABLE_NEXT ((ScheduleTableStatusType) 0x02)
#define SCHEDULETABLE_WAITING ((ScheduleTableStatusType) 0x04)
#define SCHEDULETABLE_RUNNING ((ScheduleTableStatusType) 0x08)
#define SCHEDULETABLE_RUNNING_AND_SYNCHRONOUS ((ScheduleTableStatusType) 0x10)
/*
* システムサービスID
*/
#define OSServiceId_GetISRID ((OSServiceIdType) 0x01)
#define OSServiceId_StartScheduleTableRel ((OSServiceIdType) 0x07)
#define OSServiceId_StartScheduleTableAbs ((OSServiceIdType) 0x08)
#define OSServiceId_StopScheduleTable ((OSServiceIdType) 0x09)
#define OSServiceId_NextScheduleTable ((OSServiceIdType) 0x0a)
#define OSServiceId_GetScheduleTableStatus ((OSServiceIdType) 0x0e)
#define OSServiceId_IncrementCounter ((OSServiceIdType) 0x0f)
#define OSServiceId_GetCounterValue ((OSServiceIdType) 0x10)
#define OSServiceId_GetElapsedValue ((OSServiceIdType) 0x11)
#define OSServiceId_EnableInterruptSource ((OSServiceIdType) 0xa0)
#define OSServiceId_DisableInterruptSource ((OSServiceIdType) 0xa1)
#define OSServiceId_TaskMissingEnd ((OSServiceIdType) 0xaf)
#define OSServiceId_ISRMissingEnd ((OSServiceIdType) 0xb0)
#define OSServiceId_HookMissingEnd ((OSServiceIdType) 0xb1)
#define OSServiceId_ActivateTask ((OSServiceIdType) 0xe0)
#define OSServiceId_TerminateTask ((OSServiceIdType) 0xe1)
#define OSServiceId_ChainTask ((OSServiceIdType) 0xe2)
#define OSServiceId_Schedule ((OSServiceIdType) 0xe3)
#define OSServiceId_GetTaskID ((OSServiceIdType) 0xe4)
#define OSServiceId_GetTaskState ((OSServiceIdType) 0xe5)
#define OSServiceId_EnableAllInterrupts ((OSServiceIdType) 0xe6)
#define OSServiceId_DisableAllInterrupts ((OSServiceIdType) 0xe7)
#define OSServiceId_ResumeAllInterrupts ((OSServiceIdType) 0xe8)
#define OSServiceId_SuspendAllInterrupts ((OSServiceIdType) 0xe9)
#define OSServiceId_ResumeOSInterrupts ((OSServiceIdType) 0xea)
#define OSServiceId_SuspendOSInterrupts ((OSServiceIdType) 0xeb)
#define OSServiceId_GetResource ((OSServiceIdType) 0xec)
#define OSServiceId_ReleaseResource ((OSServiceIdType) 0xed)
#define OSServiceId_SetEvent ((OSServiceIdType) 0xee)
#define OSServiceId_ClearEvent ((OSServiceIdType) 0xef)
#define OSServiceId_GetEvent ((OSServiceIdType) 0xf0)
#define OSServiceId_WaitEvent ((OSServiceIdType) 0xf1)
#define OSServiceId_GetAlarmBase ((OSServiceIdType) 0xf2)
#define OSServiceId_GetAlarm ((OSServiceIdType) 0xf3)
#define OSServiceId_SetRelAlarm ((OSServiceIdType) 0xf4)
#define OSServiceId_SetAbsAlarm ((OSServiceIdType) 0xf5)
#define OSServiceId_CancelAlarm ((OSServiceIdType) 0xf6)
#define OSServiceId_GetActiveApplicationMode ((OSServiceIdType) 0xf7)
#define OSServiceId_StartOS ((OSServiceIdType) 0xf8)
#define OSServiceId_ShutdownOS ((OSServiceIdType) 0xf9)
/*
* 保護違反を起こした処理単位の定義
*/
#define FC_INVALID UINT_C(0x00) /* 保護違反を起こした処理単位が特定できない */
#define FC_TASK UINT_C(0x01) /* 保護違反を起こした処理単位がタスク */
#define FC_C2ISR UINT_C(0x02) /* 保護違反を起こした処理単位がC2ISR */
#define FC_SYSTEM_HOOK UINT_C(0x03) /* 保護違反を起こした処理単位がシステム定義のフック */
/*
* システムサービスパラメータ取得のための定義
*/
#ifndef TOPPERS_MACRO_ONLY
/*
* エラーフックOFF時,サービスID取得とパラメータ取得もOFFになる
*/
#ifdef CFG_USE_ERRORHOOK
#ifdef CFG_USE_GETSERVICEID
extern OSServiceIdType errorhook_svcid;
#endif /* CFG_USE_GETSERVICEID */
#ifdef CFG_USE_PARAMETERACCESS
extern ErrorHook_Par errorhook_par1;
extern ErrorHook_Par errorhook_par2;
extern ErrorHook_Par errorhook_par3;
#endif /* CFG_USE_PARAMETERACCESS */
#endif /* CFG_USE_ERRORHOOK */
#endif /* TOPPERS_MACRO_ONLY */
/*
* エラーフックOFF時,サービスID取得とパラメータ取得もOFFになる
*/
#ifdef CFG_USE_ERRORHOOK
/*
* マクロの定義
*/
#ifdef CFG_USE_GETSERVICEID
#define OSErrorGetServiceId() (errorhook_svcid)
#endif /* CFG_USE_GETSERVICEID */
/*
* エラーを引き起こしたシステムサービスID
*/
#ifdef CFG_USE_PARAMETERACCESS
#define OSError_StartOS_Mode() (errorhook_par1.mode)
#define OSError_ActivateTask_TaskID() (errorhook_par1.tskid)
#define OSError_ChainTask_TaskID() (errorhook_par1.tskid)
#define OSError_GetTaskID_TaskID() (errorhook_par1.p_tskid)
#define OSError_GetTaskState_TaskID() (errorhook_par1.tskid)
#define OSError_GetTaskState_State() (errorhook_par2.p_stat)
#define OSError_GetResource_ResID() (errorhook_par1.resid)
#define OSError_ReleaseResource_ResID() (errorhook_par1.resid)
#define OSError_SetEvent_TaskID() (errorhook_par1.tskid)
#define OSError_SetEvent_Mask() (errorhook_par2.mask)
#define OSError_ClearEvent_Mask() (errorhook_par1.mask)
#define OSError_GetEvent_TaskID() (errorhook_par1.tskid)
#define OSError_GetEvent_Event() (errorhook_par2.p_mask)
#define OSError_WaitEvent_Mask() (errorhook_par1.mask)
#define OSError_GetAlarmBase_AlarmID() (errorhook_par1.almid)
#define OSError_GetAlarmBase_Info() (errorhook_par2.p_info)
#define OSError_GetAlarm_AlarmID() (errorhook_par1.almid)
#define OSError_GetAlarm_Tick() (errorhook_par2.p_tick)
#define OSError_SetRelAlarm_AlarmID() (errorhook_par1.almid)
#define OSError_SetRelAlarm_increment() (errorhook_par2.incr)
#define OSError_SetRelAlarm_cycle() (errorhook_par3.cycle)
#define OSError_SetAbsAlarm_AlarmID() (errorhook_par1.almid)
#define OSError_SetAbsAlarm_start() (errorhook_par2.start)
#define OSError_SetAbsAlarm_cycle() (errorhook_par3.cycle)
#define OSError_CancelAlarm_AlarmID() (errorhook_par1.almid)
#define OSError_IncrementCounter_CounterID() (errorhook_par1.cntid)
#define OSError_GetCounterValue_CounterID() (errorhook_par1.cntid)
#define OSError_GetCounterValue_Value() (errorhook_par2.p_val)
#define OSError_GetElapsedValue_CounterID() (errorhook_par1.cntid)
#define OSError_GetElapsedValue_Value() (errorhook_par2.p_val)
#define OSError_GetElapsedValue_ElapsedValue() (errorhook_par3.p_eval)
#define OSError_StartScheduleTableRel_ScheduleTableID() (errorhook_par1.schtblid)
#define OSError_StartScheduleTableRel_Offset() (errorhook_par2.offset)
#define OSError_StartScheduleTableAbs_ScheduleTableID() (errorhook_par1.schtblid)
#define OSError_StartScheduleTableAbs_Start() (errorhook_par2.start)
#define OSError_StopScheduleTable_ScheduleTableID() (errorhook_par1.schtblid)
#define OSError_NextScheduleTable_ScheduleTableID_From() (errorhook_par1.schtblid_from)
#define OSError_NextScheduleTable_ScheduleTableID_To() (errorhook_par2.schtblid_to)
#define OSError_GetScheduleTableStatus_ScheduleTableID() (errorhook_par1.schtblid)
#define OSError_GetScheduleTableStatus_ScheduleStatus() (errorhook_par2.p_schtblstate)
#define OSError_DisableInterruptSource_DisableISR() (errorhook_par1.isrid)
#define OSError_EnableInterruptSource_EnableISR() (errorhook_par1.isrid)
#endif /* CFG_USE_PARAMETERACCESS */
#endif /* CFG_USE_ERRORHOOK */
/*
* プロテクションフック関係のマクロ
*/
#define PRO_IGNORE UINT_C(0x00)
#define PRO_SHUTDOWN UINT_C(0x01)
/*
* バージョン情報
*/
#define OS_SW_MAJOR_VERSION UINT_C(1) /* サプライヤーバージョン */
#define OS_SW_MINOR_VERSION UINT_C(4)
#define OS_SW_PATCH_VERSION UINT_C(2)
#define OS_AR_RELEASE_MAJOR_VERSION UINT_C(4) /* AUTOSARリリースバージョン */
#define OS_AR_RELEASE_MINOR_VERSION UINT_C(0)
#define OS_AR_RELEASE_REVISION_VERSION UINT_C(3)
#define TKERNEL_NAME "TOPPERS/ATK2-SC1" /* カーネル名称(独自仕様) */
#endif /* TOPPERS_OS_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: v850e2_fx4.h 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* V850E2/Fx4のハードウェア資源の定義
*/
#ifndef TOPPERS_V850E2_FX4_H
#define TOPPERS_V850E2_FX4_H
#if defined(V850FG4) || defined(V850FL4)
#define _V850E2M_
#elif defined(V850FG4_L)
#define _V850E2S_
#endif /* V850FG4 */
/*
* PORTレジスタ
*/
#define PORT_BASE UINT_C(0xff400000)
/* 端子機能設定 */
#define PMC(n) ((PORT_BASE) +0x0400 + (n * 0x04U)) /* ポート・モード・コントロール・レジスタ */
#define PMCSR(n) ((PORT_BASE) +0x0900 + (n * 0x04U)) /* ポート・モード・コントロール・セット/リセット・レジスタ */
#define PIPC(n) ((PORT_BASE) +0x4200 + (n * 0x04U)) /* ポートIP コントロール・レジスタ */
#define PM(n) ((PORT_BASE) +0x0300 + (n * 0x04U)) /* ポート・モード・レジスタ */
#define PMSR(n) ((PORT_BASE) +0x0800 + (n * 0x04U)) /* ポート・モード・セット/リセット・レジスタ */
#define PIBC(n) ((PORT_BASE) +0x4000 + (n * 0x04U)) /* ポート入力バッファ・コントロール・レジスタ */
#define PFC(n) ((PORT_BASE) +0x0500 + (n * 0x04U)) /* ポート機能コントロール・レジスタ */
#define PFCE(n) ((PORT_BASE) +0x0600 + (n * 0x04U)) /* ポート機能コントロール・レジスタ */
/* 端子データ入力/出力 */
#define PBDC(n) ((PORT_BASE) +0x4100 + (n * 0x04U)) /* ポート双方向コントロール・レジスタ */
#define PPR(n) ((PORT_BASE) +0x0200 + (n * 0x04U)) /* ポート端子リード・レジスタ */
#define P(n) ((PORT_BASE) +0x0000 + (n * 0x04U)) /* ポート・レジスタ */
#define PNOT(n) ((PORT_BASE) +0x0700 + (n * 0x04U)) /* ポート・ノット・レジスタ */
#define PSR(n) ((PORT_BASE) +0x0100 + (n * 0x04U)) /* ポート・セット/リセット・レジスタ */
#define FCLA27CTL1 0xff416244 /* UARTE3フィルタレジスタ */
#define FCLA27CTL3 0xff41624c
#define FCLA7CTL0 0xff415040
#define FCLA0CTL2 0xff414008
#define FCLA0CTL4 0xff414010
/*
* PLL関連のレジスタと定義
*/
#define MOSCC 0xff421018
#define MOSCE 0xff421010
#define MOSCS 0xff421014
#define MOSCST 0xff42101c
#define OCDIDH 0xff470008
#define OCDIDL 0xff470000
#define OCDIDM 0xff470004
#define OPBT0 0xff47000c
#define OSCWUFMSK 0xff4201a4
#define SOSCE 0xff421020
#define SOSCS 0xff421024
#define SOSCST 0xff42102c
#define CKSC_0_BASE 0xff426000
#define CKSC_0(n) (CKSC_0_BASE + (0x10 * n))
#define CKSC_1_BASE 0xff42a000
#define CKSC_1(n) (CKSC_1_BASE + (0x10 * n))
#define CKSC_A_BASE 0xff422000
#define CKSC_A(n) (CKSC_A_BASE + (0x10 * n))
#define CSCSTAT_0_BASE 0xff426000
#define CSCSTAT_0(n) (CSCSTAT_0_BASE + (0x10 * n)) + 4
#define CSCSTAT_1_BASE 0xff42a000
#define CSCSTAT_1(n) (CSCSTAT_1_BASE + (0x10 * n)) + 4
#define CSCSTAT_A_BASE 0xff422000
#define CSCSTAT_A(n) (CSCSTAT_A_BASE + (0x10 * n)) + 4
#define PLLE_BASE 0xff425000
#define PLLE(n) (PLLE_BASE + (0x10 * n))
#define PLLS_BASE 0xff425004
#define PLLS(n) (PLLS_BASE + (0x10 * n))
#define PLLC_BASE 0xff425008
#define PLLC(n) (PLLC_BASE + (0x10 * n))
#define PLLST_BASE 0xff42500c
#define PLLST(n) (PLLST_BASE + (0x10 * n))
#define MHz(n) ((n) * 1000 * 1000)
#define CLK_MHz(num) (num * 1000 * 1000)
/* CKSC_000 CPU, CPU SubSystem */
#define HIGH_SPEED_INTOSC_DIV2 0x08
#define HIGH_SPEED_INTOSC_DIV4 0x09
#define HIGH_SPEED_INTOSC_DIV8 0x0A
#define HIGH_SPEED_INTOSC_DIV32 0x0B
#define MAINOSC_DIV1 0x0C
#define PLL0_DIV1 0x14
#define PLL0_DIV2 0x15
#define PLL0_DIV3 0x16
#define PLL0_DIV4 0x17
#define PLL0_DIV5 0x18
#define PLL0_DIV6 0x19
#define PLL0_DIV8 0x1A
#define PLL0_DIV10 0x1B
#define INTOSC_AUTOSELECT 0x3A
/* CKSC_A03 TAUJ0:PCLK */
#define LOW_SPEED_INTOSC_DIV1 0x01
#define HIGH_SPEED_INTOSC_DIV1 0x07
#define SUBOSC 0x12
#define NO_CLOCKSELECT 0x00
#define PROT_PLLE 2 /* Fx4 Setting */
#define PROT_CKSC0 0
#define PROT_CKSC1 1
#define PROT_MOSCE 2
#define PROT_SOSCE 2
#define PROT_ROSCE 2
#define PROT_CKSCA 2
/* xxxS Register */
#define CLK_S_STPACK 0x08
#define CLK_S_CLKEN 0x04
#define CLK_S_CLKACT 0x02
#define CLK_S_CLKSTAB 0x01
/* PLL P-Value */
#define PDIV0R5_200TO400 0x0 /* Div 0.5, 200-400MHz Output */
#define PDIV1R0_100TO200 0x1 /* Div 1.0, 100-200MHz Output */
#define PDIV2R0_050TO100 0x2 /* Div 2.0, 50-100MHz Output */
#define PDIV4R0_025TO050 0x3 /* Div 4.0, 25- 50MHz Output */
#define UC_SUCCESS 0
#define UC_ERROR 1
#define UC_INVALIDPARAM 2
#define UC_PROTREGERROR 3
#define UC_CLKSTATUSERR 4
#define UC_CLKNOTENABLE 5
#define UC_CLKNOTACTIVE 6
#define UC_CLKNOTSTAB 7
#ifndef TOPPERS_MACRO_ONLY
extern uint32 EnableSubOSC(void);
extern uint32 EnableMainOSC(uint32 clk_in);
extern uint32 SetPLL(uint32 pllno, uint32 mhz, uint32 *outclk);
extern uint32 set_clock_selection(uint32 control, uint32 status, uint8 regno, uint16 sel);
#endif /* TOPPERS_MACRO_ONLY */
/*
* Interval Timer(TAUA0)
*/
#define TAUA0_BASE UINT_C(0xFF808000) /* TAUA0 */
#define TAUA0_IRQ UINT_C(20) /* TAUA0 */
#define TAUA1_IRQ UINT_C(21) /* TAUA1 */
#define TAUA2_IRQ UINT_C(22) /* TAUA2 */
#define TAUA3_IRQ UINT_C(23) /* TAUA3 */
#define TAUA4_IRQ UINT_C(24) /* TAUA4 */
#define TAUA5_IRQ UINT_C(25) /* TAUA5 */
#define TAUA6_IRQ UINT_C(26) /* TAUA6 */
#define TAUA7_IRQ UINT_C(27) /* TAUA7 */
#define TAUA8_IRQ UINT_C(28) /* TAUA8 */
#define TAUA9_IRQ UINT_C(29) /* TAUA9 */
#define TAUA10_IRQ UINT_C(30) /* TAUA10 */
#define TAUA11_IRQ UINT_C(31) /* TAUA11 */
#define TAUA12_IRQ UINT_C(32) /* TAUA12 */
#define TAUA13_IRQ UINT_C(33) /* TAUA13 */
#define TAUA14_IRQ UINT_C(34) /* TAUA14 */
#define TAUA15_IRQ UINT_C(35) /* TAUA15 */
#define TAUA_CH0 0
#define TAUA_CH1 1
#define TAUA_CH2 2
#define TAUA_CH3 3
#define TAUA_CH4 4
#define TAUA_CH5 5
#define TAUA_CH6 6
#define TAUA_CH7 7
#define TAUA_CH8 8
#define TAUA_CH9 9
#define TAUA_CH10 10
#define TAUA_CH11 11
#define TAUA_CH12 12
#define TAUA_CH13 13
#define TAUA_CH14 14
#define TAUA_CH15 15
/*
* TAUA0 Timer ハードウェア定義
*/
/*
* レジスタ
*/
/* TAUA0 プリスケーラ・レジスタ */
#define TAUA0TPS (TAUA0_BASE + 0x240U) /* プリスケーラ・クロック選択レジス */
#define TAUA0BRS (TAUA0_BASE + 0x244U) /* プリスケーラ・ボー・レート設定レジスタ */
/* TAUA0 制御レジスタ */
#define TAUA0CDR(CH) (TAUA0_BASE + (CH * 4U)) /* データ・レジスタ */
#define TAUA0CNT(CH) (TAUA0_BASE + (0x80U + (CH * 4U))) /* カウンタ・レジスタ */
#define TAUA0CMOR(CH) (TAUA0_BASE + (0x200U + (CH * 4U))) /* モードOS レジスタ */
#define TAUA0CMUR(CH) (TAUA0_BASE + (0xC0 + (CH * 4U))) /* モード・ユーザ・レジスタ */
#define TAUA0CSR(CH) (TAUA0_BASE + (0x140U + (CH * 4U))) /* ステータス・レジスタ */
#define TATA0CSC(CH) (TAUA0_BASE + (0x180U + (CH * 4U))) /* ステータス・クリア・トリガ・レジスタ */
#define TAUA0TS (TAUA0_BASE + 0x1C4U) /* スタート・トリガ・レジスタ */
#define TAUA0TE (TAUA0_BASE + 0x1C0U) /* 許可ステータス・レジスタ */
#define TAUA0TT (TAUA0_BASE + 0x1C8U) /* ストップ・トリガ・レジスタ */
/* TAUA0 出力レジスタ */
#define TAUA0TOE (TAUA0_BASE + 0x5CU) /* 出力許可レジスタ */
#define TAUA0TO (TAUA0_BASE + 0x58U) /* 出力レジスタ */
#define TAUA0TOM (TAUA0_BASE + 0x248U) /* 出力モード・レジスタ */
#define TAUA0TOC (TAUA0_BASE + 0x24CU) /* 出力コンフィギュレーション・レジスタ */
#define TAUA0TOL (TAUA0_BASE + 0x40U) /* 出力アクティブ・レベル・レジスタ */
#define TAUA0TDE (TAUA0_BASE + 0x250U) /* デッド・タイム出力許可レジスタ */
#define TAUA0TDM (TAUA0_BASE + 0x254U) /* デッド・タイム出力モード・レジスタ */
#define TAUA0TDL (TAUA0_BASE + 0x54U) /* デッド・タイム出力レベル・レジスタ */
#define TAUA0TRO (TAUA0_BASE + 0x4CU) /* リアルタイム出力レジスタ */
#define TAUA0TRE (TAUA0_BASE + 0x258U) /* リアルタイム出力許可レジスタ */
#define TAUA0TRC (TAUA0_BASE + 0x25CU) /* リアルタイム出力制御レジスタ */
#define TAUA0TME (TAUA0_BASE + 0x50U) /* 変調出力許可レジスタ */
/* TAUA0 リロード・データ・レジスタ */
#define TAUA0RDE (TAUA0_BASE + 0x260U) /* リロード・データ許可レジスタ */
#define TAUA0RDM (TAUA0_BASE + 0x264U) /* リロード・データ・モード・レジスタ */
#define TAUA0RDS (TAUA0_BASE + 0x268U) /* リロード・データ制御CH 選択・リロード・データ制御CH 選択 */
#define TAUA0RDC (TAUA0_BASE + 0x26CU) /* リロード・データ制御レジスタ */
#define TAUA0RDT (TAUA0_BASE + 0x44U) /* リロード・データ・トリガ・レジスタ */
#define TAUA0RSF (TAUA0_BASE + 0x48U) /* リロード・ステータス・レジスタ */
#define MCU_TAUA0_MASK_CK0 ((uint16) 0x000f)
#define MCU_TAUA0_CK0 ((uint16) 0x0000)
#define MCU_TAUA00_CMOR ((uint16) 0x0001)
#define MCU_TAUA00_CMUR ((uint8) 0x01)
#define MCU_TAUA00_DI ((uint16) 0x0080)
#define MCU_TAUA00_EI ((uint16) 0x0000)
#define MCU_TAUA00_MASK_ENB ((uint16) 0x0001)
#define MCU_TIMER_STOP ((uint8) 0x0)
#define MCU_TIMER_START ((uint8) 0x1)
#define ICTAUA0_BASE 0xffff6028 /* チャンネル0割り込み */
#define ICTAUA0I(CH) (ICTAUA0_BASE + (CH * 0x02))
/*
* TAUA0 マスク定義
*/
#define TAUA0_MASK_BIT 0x0xfffe /* bit0 = TAUA0 */
/*
* OSTM
*/
#define OSTM_IRQ UINT_C(147)
#define OSTM0_BASE 0xFF800000
#define OSTM_CMP_W (0xFF800000 + 0x00)
#define OSTM_CNT_W (0xFF800000 + 0x04)
#define OSTM_TE (0xFF800000 + 0x10)
#define OSTM_TS_B (0xFF800000 + 0x14)
#define OSTM_TT_B (0xFF800000 + 0x18)
#define OSTM_CTL_B (0xFF800000 + 0x20)
/*
* UARTE
*/
#define URTE3_BASE UINT_C(0xff5f0000)
#define URTE5_BASE UINT_C(0xff610000)
#define URTE10_BASE UINT_C(0xff660000)
#define URTEnCTL0 (UARTE_BASE + 0x00U)
#define URTEnCTL1 (UARTE_BASE + 0x20U)
#define URTEnCTL2 (UARTE_BASE + 0x24U)
#define URTEnTRG (UARTE_BASE + 0x04U)
#define URTEnSTR0 (UARTE_BASE + 0x08U)
#define URTEnSTR1 (UARTE_BASE + 0x0cU)
#define URTEnSTC (UARTE_BASE + 0x10U)
#define URTEnRX (UARTE_BASE + 0x14U)
#define URTEnTX (UARTE_BASE + 0x18U)
#define URTEnEMU (UARTE_BASE + 0x34U)
#define INTLMA3IT 0xffff618C /* 転送完了 */
#define INTLMA3IR 0xffff618A /* 受信完了 */
#define INTLMA5IT 0xffff61C4 /* UART5 RX */
#define INTLMA5IR 0xffff61C6 /* UART5 TX */
#define INTLMA10IT 0xffff6204 /* UART10 TX */
#define INTLMA10IR 0xffff6202 /* UART10 RX */
#define URTE3_INTNO UINT_C(197)
#define URTE5_INTNO UINT_C(226)
#ifndef URTE10_INTNO
#define URTE10_INTNO UINT_C(249)
#endif /* URTE10_INTNO */
/*
* TAUJ
*/
#ifdef V850FG4
#define TAUFJ0I0_INTNO 135
#define TAUFJ0I1_INTNO 136
#define TAUFJ0I2_INTNO 137
#define TAUFJ0I3_INTNO 138
#define TAUFJ1I0_INTNO 139
#define TAUFJ1I1_INTNO 140
#define TAUFJ1I2_INTNO 141
#define TAUFJ1I3_INTNO 142
#elif defined(V850FG4_L)
#define TAUFJ0I0_INTNO 78
#define TAUFJ0I1_INTNO 79
#define TAUFJ0I2_INTNO 80
#define TAUFJ0I3_INTNO 81
#endif /* V850FG4 */
/*
* TAUJ関連レジスタ
*/
#define TAUJ_BASE(n) ((uint32) (0xff811000U + (n * 0x1000U)))
#define TAUJTPS(n) (TAUJ_BASE(n) + 0x90U)
#define TAUJCDR(n, ch) (TAUJ_BASE(n) + (ch * 0x04U))
#define TAUJCNT(n, ch) (TAUJ_BASE(n) + 0x10U + (ch * 0x04U))
#define TAUJCMOR(n, ch) (TAUJ_BASE(n) + 0x80U + (ch * 0x04U))
#define TAUJCMUR(n, ch) (TAUJ_BASE(n) + 0x20U + (ch * 0x04U))
#define TAUJTS(n) (TAUJ_BASE(n) + 0x54U)
#define TAUJTT(n) (TAUJ_BASE(n) + 0x58U)
/*
* INT
*/
#define EIC_BASE UINT_C(0xffff6000)
#define EIC_ADDRESS(intno) (EIC_BASE + (intno * 2))
#define PMR UINT_C(0xFFFF6448)
#define ISPR_H UINT_C(0xFFFF6440)
#define ISPC_H UINT_C(0xffff6450)
#define TMIN_INTNO UINT_C(0)
#define TMAX_INTNO UINT_C(255)
#define TNUM_INT UINT_C(256)
#include "v850.h"
#endif /* TOPPERS_V850E2_FX4_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2011-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: allfunc.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* すべての関数をコンパイルするための定義
*/
#ifndef TOPPERS_ALLFUNC_H
#define TOPPERS_ALLFUNC_H
/* alarm.c */
#define TOPPERS_alarm_initialize
#define TOPPERS_GetAlarmBase
#define TOPPERS_GetAlarm
#define TOPPERS_SetRelAlarm
#define TOPPERS_SetAbsAlarm
#define TOPPERS_CancelAlarm
#define TOPPERS_alarm_expire
/* counter_manage.c */
#define TOPPERS_IncrementCounter
#define TOPPERS_GetCounterValue
#define TOPPERS_GetElapsedValue
#define TOPPERS_notify_hardware_counter
#define TOPPERS_incr_counter_action
/* counter.c */
#define TOPPERS_insert_cnt_expr_que
#define TOPPERS_delete_cnt_expr_que
#define TOPPERS_counter_initialize
#define TOPPERS_counter_terminate
#define TOPPERS_get_reltick
#define TOPPERS_get_abstick
#define TOPPERS_expire_process
/* event.c */
#define TOPPERS_SetEvent
#define TOPPERS_ClearEvent
#define TOPPERS_GetEvent
#define TOPPERS_WaitEvent
#define TOPPERS_set_event_action
/* interrupt.c */
#define TOPPERS_interrupt_initialize
#define TOPPERS_release_interrupts
#define TOPPERS_exit_isr2
/* interrupt_manage.c */
#define TOPPERS_DisableAllInterrupts
#define TOPPERS_EnableAllInterrupts
#define TOPPERS_SuspendAllInterrupts
#define TOPPERS_ResumeAllInterrupts
#define TOPPERS_SuspendOSInterrupts
#define TOPPERS_ResumeOSInterrupts
#define TOPPERS_GetISRID
#define TOPPERS_DisableInterruptSource
#define TOPPERS_EnableInterruptSource
/* osctl.c */
#define TOPPERS_internal_call_errorhook
#define TOPPERS_call_posttaskhook
#define TOPPERS_call_pretaskhook
#define TOPPERS_call_protectionhk_main
#define TOPPERS_init_stack_magic_region
#define TOPPERS_internal_shutdownos
#define TOPPERS_internal_call_shtdwnhk
/* osctl_manage.c */
#define TOPPERS_StartOS
#define TOPPERS_GetActiveApplicationMode
#define TOPPERS_ShutdownOS
#define TOPPERS_GetFaultyContext
/* resource.c */
#define TOPPERS_resource_initialize
#define TOPPERS_GetResource
#define TOPPERS_ReleaseResource
/* scheduletable.c */
#define TOPPERS_schtbl_initialize
#define TOPPERS_StartScheduleTableRel
#define TOPPERS_StartScheduleTableAbs
#define TOPPERS_StopScheduleTable
#define TOPPERS_NextScheduleTable
#define TOPPERS_GetScheduleTableStatus
#define TOPPERS_schtbl_expire
#define TOPPERS_schtbl_expiry_process
#define TOPPERS_schtbl_head
#define TOPPERS_schtbl_exppoint_process
#define TOPPERS_schtbl_tail
/* task.c */
#define TOPPERS_task_initialize
#define TOPPERS_search_schedtsk
#define TOPPERS_make_runnable
#define TOPPERS_make_non_runnable
#define TOPPERS_make_active
#define TOPPERS_preempt
#define TOPPERS_suspend
#define TOPPERS_exit_task
/* task_manage.c */
#define TOPPERS_ActivateTask
#define TOPPERS_TerminateTask
#define TOPPERS_ChainTask
#define TOPPERS_Schedule
#define TOPPERS_GetTaskID
#define TOPPERS_GetTaskState
#define TOPPERS_activate_task_action
#endif /* TOPPERS_ALLFUNC_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: interrupt.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* 割込み制御モジュール
*/
#include "kernel_impl.h"
#include "interrupt.h"
#ifdef TOPPERS_interrupt_initialize
/*
* 実行中のC2ISR
*/
ISRCB *p_runisr;
/*
* 割込み管理機能内部で使用する変数の定義
*/
/*
* SuspendAllInterrupts のネスト回数
*/
uint8 sus_all_cnt = 0U;
/*
* SuspendOSInterrupts のネスト回数
*/
uint8 sus_os_cnt = 0U;
/*
* 割込み管理機能の初期化
*/
#ifndef OMIT_INITIALIZE_INTERRUPT
void
interrupt_initialize(void)
{
ISRType i;
InterruptNumberType j;
ISRCB *p_isrcb;
const INTINIB *p_intinib;
p_runisr = NULL;
sus_all_cnt = 0U;
sus_os_cnt = 0U;
for (i = 0U; i < tnum_isr2; i++) {
p_isrcb = &(isrcb_table[i]);
p_isrcb->p_intinib = &(intinib_table[i]);
p_isrcb->p_lastrescb = NULL;
}
for (j = 0U; j < tnum_intno; j++) {
p_intinib = &(intinib_table[j]);
x_config_int(p_intinib->intno, p_intinib->intatr, p_intinib->intpri);
}
}
#endif /* OMIT_INITIALIZE_INTERRUPT */
#endif /* TOPPERS_interrupt_initialize */
/*
* 割込み禁止の解除
*/
#ifdef TOPPERS_release_interrupts
void
release_interrupts(OSServiceIdType serviceId)
{
#ifdef CFG_USE_ERRORHOOK
boolean call_error_hook = FALSE;
#endif /* CFG_USE_ERRORHOOK */
if (sus_os_cnt > 0U) {
sus_os_cnt = 0U;
LEAVE_CALLEVEL(TSYS_SUSOSINT);
x_nested_unlock_os_int();
#ifdef CFG_USE_ERRORHOOK
call_error_hook = TRUE;
#endif /* CFG_USE_ERRORHOOK */
}
if (sus_all_cnt > 0U) {
sus_all_cnt = 0U;
LEAVE_CALLEVEL(TSYS_SUSALLINT);
ASSERT((callevel_stat & TSYS_DISALLINT) == TSYS_NULL);
x_unlock_all_int();
#ifdef CFG_USE_ERRORHOOK
call_error_hook = TRUE;
#endif /* CFG_USE_ERRORHOOK */
}
/* C2ISRの場合のみDisAllを解除する */
if (serviceId == OSServiceId_ISRMissingEnd) {
if ((callevel_stat & TSYS_DISALLINT) != TSYS_NULL) {
LEAVE_CALLEVEL(TSYS_DISALLINT);
x_unlock_all_int();
#ifdef CFG_USE_ERRORHOOK
call_error_hook = TRUE;
#endif /* CFG_USE_ERRORHOOK */
}
}
#ifdef CFG_USE_ERRORHOOK
if ((serviceId != OSServiceId_Invalid) && (call_error_hook != FALSE)) {
call_errorhook(E_OS_DISABLEDINT, serviceId);
}
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_release_interrupts */
/*
* C2ISR終了時のチェック関数
*/
#ifdef TOPPERS_exit_isr2
LOCAL_INLINE void
release_isrresources(ISRCB *p_isrcb)
{
/* OS割込み禁止状態以上で来るはず */
if (p_isrcb->p_lastrescb != NULL) {
do {
x_set_ipm(p_isrcb->p_lastrescb->prevpri);
p_isrcb->p_lastrescb->lockflg = FALSE;
p_isrcb->p_lastrescb = p_isrcb->p_lastrescb->p_prevrescb;
} while (p_isrcb->p_lastrescb != NULL);
#ifdef CFG_USE_ERRORHOOK
call_errorhook(E_OS_RESOURCE, OSServiceId_ISRMissingEnd);
#endif /* CFG_USE_ERRORHOOK */
}
}
void
exit_isr2(void)
{
x_nested_lock_os_int();
release_interrupts(OSServiceId_ISRMissingEnd);
/* リソース確保状態の場合 */
release_isrresources(p_runisr);
x_nested_unlock_os_int();
}
#endif /* TOPPERS_exit_isr2 */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: interrupt_manage.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* 割込み管理モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "interrupt.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_DISINT_ENTER
#define LOG_DISINT_ENTER()
#endif /* LOG_DISINT_ENTER */
#ifndef LOG_DISINT_LEAVE
#define LOG_DISINT_LEAVE()
#endif /* LOG_DISINT_LEAVE */
#ifndef LOG_ENAINT_ENTER
#define LOG_ENAINT_ENTER()
#endif /* LOG_ENAINT_ENTER */
#ifndef LOG_ENAINT_LEAVE
#define LOG_ENAINT_LEAVE()
#endif /* LOG_ENAINT_LEAVE */
#ifndef LOG_SUSALL_ENTER
#define LOG_SUSALL_ENTER()
#endif /* LOG_SUSALL_ENTER */
#ifndef LOG_SUSALL_LEAVE
#define LOG_SUSALL_LEAVE()
#endif /* LOG_SUSALL_LEAVE */
#ifndef LOG_RSMALL_ENTER
#define LOG_RSMALL_ENTER()
#endif /* LOG_RSMALL_ENTER */
#ifndef LOG_RSMALL_LEAVE
#define LOG_RSMALL_LEAVE()
#endif /* LOG_RSMALL_LEAVE */
#ifndef LOG_SUSOSI_ENTER
#define LOG_SUSOSI_ENTER()
#endif /* LOG_SUSOSI_ENTER */
#ifndef LOG_SUSOSI_LEAVE
#define LOG_SUSOSI_LEAVE()
#endif /* LOG_SUSOSI_LEAVE */
#ifndef LOG_RSMOSI_ENTER
#define LOG_RSMOSI_ENTER()
#endif /* LOG_RSMOSI_ENTER */
#ifndef LOG_RSMOSI_LEAVE
#define LOG_RSMOSI_LEAVE()
#endif /* LOG_RSMOSI_LEAVE */
#ifndef LOG_GETISRID_ENTER
#define LOG_GETISRID_ENTER()
#endif /* LOG_GETISRID_ENTER */
#ifndef LOG_GETISRID_LEAVE
#define LOG_GETISRID_LEAVE(ercd)
#endif /* LOG_GETISRID_LEAVE */
#ifndef LOG_DISINTSRC_ENTER
#define LOG_DISINTSRC_ENTER(isrid)
#endif /* LOG_DISINTSRC_ENTER */
#ifndef LOG_DISINTSRC_LEAVE
#define LOG_DISINTSRC_LEAVE(ercd)
#endif /* LOG_DISINTSRC_LEAVE */
#ifndef LOG_ENAINTSRC_ENTER
#define LOG_ENAINTSRC_ENTER(isrid)
#endif /* LOG_ENAINTSRC_ENTER */
#ifndef LOG_ENAINTSRC_LEAVE
#define LOG_ENAINTSRC_LEAVE(ercd)
#endif /* LOG_ENAINTSRC_LEAVE */
/*
* すべての割込みの禁止(高速簡易版)
* 全割込み禁止状態へ移行
*/
#ifdef TOPPERS_DisableAllInterrupts
#ifndef OMIT_STANDARD_DISALLINT
void
DisableAllInterrupts(void)
{
LOG_DISINT_ENTER();
if ((callevel_stat & (TSYS_DISALLINT | TSYS_SUSALLINT | TSYS_SUSOSINT)) == TSYS_NULL) {
x_lock_all_int();
ENTER_CALLEVEL(TSYS_DISALLINT);
}
LOG_DISINT_LEAVE();
}
#endif /* OMIT_STANDARD_DISALLINT */
#endif /* TOPPERS_DisableAllInterrupts */
/*
* すべての割込みの許可(高速簡易版)
* 全割込み禁止状態を解除する
*/
#ifdef TOPPERS_EnableAllInterrupts
#ifndef OMIT_STANDARD_DISALLINT
void
EnableAllInterrupts(void)
{
LOG_ENAINT_ENTER();
if ((callevel_stat & (TSYS_SUSALLINT | TSYS_SUSOSINT)) == TSYS_NULL) {
if ((callevel_stat & TSYS_DISALLINT) != TSYS_NULL) {
LEAVE_CALLEVEL(TSYS_DISALLINT);
x_unlock_all_int();
}
}
LOG_ENAINT_LEAVE();
}
#endif /* OMIT_STANDARD_DISALLINT */
#endif /* TOPPERS_EnableAllInterrupts */
/*
* 全割込み禁止
* CPU全ての割込みが対象の割込み禁止(ネストカウント有り)
*/
#ifdef TOPPERS_SuspendAllInterrupts
void
SuspendAllInterrupts(void)
{
#ifdef CFG_USE_ERRORHOOK
StatusType ercd;
#endif /* CFG_USE_ERRORHOOK */
LOG_SUSALL_ENTER();
S_N_CHECK_DISALLINT();
/* ネスト回数の上限値超過 */
S_N_CHECK_LIMIT(sus_all_cnt != UINT8_INVALID);
if (sus_all_cnt == 0U) {
x_lock_all_int();
ENTER_CALLEVEL(TSYS_SUSALLINT);
}
sus_all_cnt++;
exit_no_errorhook:
LOG_SUSALL_LEAVE();
return;
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
if (kerflg != FALSE) {
x_nested_lock_os_int();
call_errorhook(ercd, OSServiceId_SuspendAllInterrupts);
x_nested_unlock_os_int();
goto exit_no_errorhook;
}
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_SuspendAllInterrupts */
/*
* 全割込み禁止解除
* CPU全ての割込みが対象の割込み許可(ネストカウント有り)
*/
#ifdef TOPPERS_ResumeAllInterrupts
void
ResumeAllInterrupts(void)
{
#ifdef CFG_USE_ERRORHOOK
StatusType ercd;
#endif /* CFG_USE_ERRORHOOK */
LOG_RSMALL_ENTER();
S_N_CHECK_DISALLINT();
S_N_CHECK_STATE(sus_all_cnt != 0U);
sus_all_cnt--;
if (sus_all_cnt == 0U) {
LEAVE_CALLEVEL(TSYS_SUSALLINT);
x_unlock_all_int();
}
exit_no_errorhook:
LOG_RSMALL_LEAVE();
return;
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
if (kerflg != FALSE) {
x_nested_lock_os_int();
call_errorhook(ercd, OSServiceId_ResumeAllInterrupts);
x_nested_unlock_os_int();
goto exit_no_errorhook;
}
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_ResumeAllInterrupts */
/*
* OS割込みの禁止
* C2ISRが対象の割込み禁止(ネストカウント有り)
*/
#ifdef TOPPERS_SuspendOSInterrupts
void
SuspendOSInterrupts(void)
{
#ifdef CFG_USE_ERRORHOOK
StatusType ercd;
#endif /* CFG_USE_ERRORHOOK */
LOG_SUSOSI_ENTER();
if ((callevel_stat & (TCL_PROTECT | TCL_PREPOST | TCL_STARTUP | TCL_SHUTDOWN | TCL_ERROR | TCL_ALRMCBAK | TSYS_ISR1)) == TCL_NULL) {
S_N_CHECK_DISALLINT();
/* ネスト回数の上限値超過 */
S_N_CHECK_LIMIT(sus_os_cnt != UINT8_INVALID);
if (sus_os_cnt == 0U) {
x_nested_lock_os_int();
ENTER_CALLEVEL(TSYS_SUSOSINT);
}
sus_os_cnt++;
}
exit_no_errorhook:
LOG_SUSOSI_LEAVE();
return;
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
call_errorhook(ercd, OSServiceId_SuspendOSInterrupts);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_SuspendOSInterrupts */
/*
* OS割込み禁止解除
* C2ISRが対象の割込み許可(ネストカウント有り)
*/
#ifdef TOPPERS_ResumeOSInterrupts
void
ResumeOSInterrupts(void)
{
#ifdef CFG_USE_ERRORHOOK
StatusType ercd;
#endif /* CFG_USE_ERRORHOOK */
LOG_RSMOSI_ENTER();
if ((callevel_stat & (TCL_PROTECT | TCL_PREPOST | TCL_STARTUP | TCL_SHUTDOWN | TCL_ERROR | TCL_ALRMCBAK | TSYS_ISR1)) == TCL_NULL) {
S_N_CHECK_DISALLINT();
S_N_CHECK_STATE(sus_os_cnt != 0U);
sus_os_cnt--;
if (sus_os_cnt == 0U) {
LEAVE_CALLEVEL(TSYS_SUSOSINT);
x_nested_unlock_os_int();
}
}
exit_no_errorhook:
LOG_RSMOSI_LEAVE();
return;
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
call_errorhook(ercd, OSServiceId_ResumeOSInterrupts);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_ResumeOSInterrupts */
/*
* C2ISR IDの取得
*/
#ifdef TOPPERS_GetISRID
ISRType
GetISRID(void)
{
ISRType isrid;
#if defined(CFG_USE_EXTENDEDSTATUS) || defined(CFG_USE_ERRORHOOK)
StatusType ercd;
#endif /* CFG_USE_EXTENDEDSTATUS || CFG_USE_ERRORHOOK */
LOG_GETISRID_ENTER();
CHECK_CALLEVEL(CALLEVEL_GETISRID);
isrid = (p_runisr == NULL) ? INVALID_ISR : ISR2ID(p_runisr);
exit_finish:
LOG_GETISRID_LEAVE(isrid);
return(isrid);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
/*
* エラー発生時はINVALID_ISRIDが返るが,エラーが発生したのか実行中の
* C2ISRが存在しないのか区別するため,エラーフックを呼ぶ
*/
call_errorhook(ercd, OSServiceId_GetISRID);
x_nested_unlock_os_int();
#endif /* CFG_USE_ERRORHOOK */
exit_no_errorhook:
isrid = INVALID_ISR;
goto exit_finish;
}
#endif /* TOPPERS_GetISRID */
/*
* 割込みの禁止
*/
#ifdef TOPPERS_DisableInterruptSource
StatusType
DisableInterruptSource(ISRType DisableISR)
{
ISRCB *p_isrcb;
StatusType ercd;
LOG_DISINTSRC_ENTER(DisableISR);
CHECK_CALLEVEL(CALLEVEL_DISABLEINTERRUPTSOURCE);
CHECK_ID(DisableISR < tnum_isr2);
p_isrcb = get_isrcb(DisableISR);
CHECK_NOFUNC(target_is_int_controllable(p_isrcb->p_intinib->intno) != FALSE);
x_disable_int(GET_INTNO(p_isrcb));
ercd = E_OK;
exit_no_errorhook:
LOG_DISINTSRC_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.isrid = DisableISR;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_DisableInterruptSource);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_DisableInterruptSource */
/*
* 割込みの許可
*/
#ifdef TOPPERS_EnableInterruptSource
StatusType
EnableInterruptSource(ISRType EnableISR)
{
ISRCB *p_isrcb;
StatusType ercd;
LOG_ENAINTSRC_ENTER(EnableISR);
CHECK_CALLEVEL(CALLEVEL_ENABLEINTERRUPTSOURCE);
CHECK_ID(EnableISR < tnum_isr2);
p_isrcb = get_isrcb(EnableISR);
CHECK_NOFUNC(target_is_int_controllable(p_isrcb->p_intinib->intno) != FALSE);
x_enable_int(GET_INTNO(p_isrcb));
ercd = E_OK;
exit_no_errorhook:
LOG_ENAINTSRC_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.isrid = EnableISR;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_EnableInterruptSource);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_EnableInterruptSource */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: taua_timer.c 540 2015-12-29 01:00:01Z ertl-honda $
*/
/*
* タイマドライバ(TAUA0 Timer)
*/
#include "kernel_impl.h"
#include "target_timer.h"
#include "taua_timer.h"
#include "Os_Lcfg.h"
/*
* 現在のシステム時刻(単位: ミリ秒)
*
* 厳密には,前のタイムティックのシステム時刻
*/
SystemTimeMsType current_time;
/*
* 内部関数プロトタイプ宣言
*/
ISR(target_timer_hdr);
/*
* マイクロ秒単位での時刻を取得
*/
SystemTimeUsType
get_tim_utime(void)
{
SystemTimeUsType utime;
SystemTimeMsType mtime;
TickType clock1, clock2;
boolean ireq;
SIL_PRE_LOC;
SIL_LOC_INT();
mtime = current_time;
clock1 = target_timer_get_current();
ireq = target_timer_probe_int();
clock2 = target_timer_get_current();
SIL_UNL_INT();
utime = ((SystemTimeUsType) mtime) * 1000U;
if ((ireq != FALSE) && (clock2 >= clock1)) {
/*
* 割込みが入っており,clock2の方がclock1の方が大きいまたは等しい場合は,
* current_time が割込みにより更新されていないかつ,clock1はオーバフロー後
* の値であるため,utimeに1m追加する.clock1の読み込み,割込みのチェック,
* clock2の読み込みが1μs以下で実行可能なプロセッサも存在するため,等号付き
* で比較している.
*/
utime += 1000U;
}
utime += TO_USEC(clock1);
return(utime);
}
SystemTime100NsType
get_tim_100ntime(void)
{
SystemTime100NsType ntime;
SystemTimeMsType mtime;
TickType clock1, clock2;
boolean ireq;
SIL_PRE_LOC;
SIL_LOC_INT();
mtime = current_time;
clock1 = target_timer_get_current();
ireq = target_timer_probe_int();
clock2 = target_timer_get_current();
SIL_UNL_INT();
ntime = ((SystemTime100NsType) mtime) * 10000U;
if ((ireq != FALSE) && (clock2 >= clock1)) {
/*
* 割込みが入っており,clock2の方がclock1の方が大きいまたは等しい場合は,
* current_time が割込みにより更新されていないかつ,clock1はオーバフロー後
* の値であるため,utimeに1m追加する.clock1の読み込み,割込みのチェック,
* clock2の読み込みが1μs以下で実行可能なプロセッサも存在するため,等号付き
* で比較している.
*/
ntime += 10000U;
}
ntime += TO_100NSEC(clock1);
return(ntime);
}
/*
* タイマの起動処理
*
* タイマはタイマ0を使用
*/
void
target_timer_initialize(void)
{
uint16 wk;
current_time = 0U;
wk = sil_reh_mem((void *) TAUA0TPS);
wk &= ~MCU_TAUA0_MASK_CK0;
wk |= MCU_TAUA0_CK0;
sil_wrh_mem((void *) TAUA0TPS, wk); /* Set prescaler value for CK0 */
sil_wrh_mem((void *) TAUA0CMOR(0), MCU_TAUA00_CMOR); /* インターバルタイマとして使用 */
sil_wrb_mem((void *) TAUA0CMUR(0), MCU_TAUA00_CMUR);
sil_wrh_mem((void *) TAUA0CDR(0), TIMER_CLOCK); /* 1ms */
wk = sil_reh_mem((void *) TAUA0TE);
wk |= 0x0001; /* TAUT0チャンネル0許可 */
sil_wrh_mem((void *) TAUA0TS, wk); /* カウンタ動作を許可 */
}
/*
* タイマの停止処理
*/
void
target_timer_terminate(void)
{
uint16 wk;
/* タイマ停止 */
wk = sil_reh_mem((void *) TAUA0TE);
wk &= ~0x0001; /* チャンネル0停止 */
sil_wrh_mem((void *) TAUA0TT, wk); /* カウンタ動作停止 */
/* 割込みの禁止とクリア */
x_disable_int(TAUA0_IRQ);
x_clear_int(TAUA0_IRQ);
}
/*
* target_timer.arxmlを使用しない場合の対処
*/
#ifndef SysTimerCnt
#define SysTimerCnt UINT_C(0)
#endif /* SysTimerCnt */
/*
* タイマ割込みハンドラ
*/
ISR(target_timer_hdr)
{
StatusType ercd;
/* current_timeを更新する */
current_time++;
/*
* カウンタ加算通知処理実行
*/
ercd = IncrementCounter(SysTimerCnt);
/* エラーリターンの場合はシャットダウン */
if (ercd != E_OK) {
ShutdownOS(ercd);
}
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2011-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by <NAME> Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: kernel_fncode.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
#ifndef TOPPERS_KERNEL_FNCODE_H
#define TOPPERS_KERNEL_FNCODE_H
#define TMAX_SVCID UINT_C(36)
#define TFN_STARTOS UINT_C(0)
#define TFN_SHUTDOWNOS UINT_C(1)
#define TFN_ACTIVATETASK UINT_C(2)
#define TFN_TERMINATETASK UINT_C(3)
#define TFN_CHAINTASK UINT_C(4)
#define TFN_SCHEDULE UINT_C(5)
#define TFN_GETTASKID UINT_C(6)
#define TFN_GETTASKSTATE UINT_C(7)
#define TFN_ENABLEALLINTERRUPTS UINT_C(8)
#define TFN_DISABLEALLINTERRUPTS UINT_C(9)
#define TFN_RESUMEALLINTERRUPTS UINT_C(10)
#define TFN_SUSPENDALLINTERRUPTS UINT_C(11)
#define TFN_RESUMEOSINTERRUPTS UINT_C(12)
#define TFN_SUSPENDOSINTERRUPTS UINT_C(13)
#define TFN_GETISRID UINT_C(14)
#define TFN_GETRESOURCE UINT_C(15)
#define TFN_RELEASERESOURCE UINT_C(16)
#define TFN_SETEVENT UINT_C(17)
#define TFN_CLEAREVENT UINT_C(18)
#define TFN_GETEVENT UINT_C(19)
#define TFN_WAITEVENT UINT_C(20)
#define TFN_GETALARMBASE UINT_C(21)
#define TFN_GETALARM UINT_C(22)
#define TFN_SETRELALARM UINT_C(23)
#define TFN_SETABSALARM UINT_C(24)
#define TFN_CANCELALARM UINT_C(25)
#define TFN_INCREMENTCOUNTER UINT_C(26)
#define TFN_GETCOUNTERVALUE UINT_C(27)
#define TFN_GETELAPSEDVALUE UINT_C(28)
#define TFN_GETACTIVEAPPLICATIONMODE UINT_C(29)
#define TFN_STARTSCHEDULETABLEREL UINT_C(30)
#define TFN_STARTSCHEDULETABLEABS UINT_C(31)
#define TFN_STOPSCHEDULETABLE UINT_C(32)
#define TFN_NEXTSCHEDULETABLE UINT_C(33)
#define TFN_GETSCHEDULETABLESTATUS UINT_C(34)
#define TFN_DISABLEINTERRUPTSOURCE UINT_C(35)
#define TFN_ENABLEINTERRUPTSOURCE UINT_C(36)
#endif /* TOPPERS_KERNEL_FNCODE_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: prc_config.h 832 2017-09-23 02:18:28Z ertl-honda $
*/
/*
* プロセッサ依存モジュール(V850用)
*
* このインクルードファイルは,target_config.h(または,そこからインク
* ルードされるファイル)のみからインクルードされる.他のファイルから
* 直接インクルードしてはならない
*/
#ifndef TOPPERS_PRC_CONFIG_H
#define TOPPERS_PRC_CONFIG_H
#include "prc_sil.h"
/*
* エラーチェック方法の指定
*/
#ifndef CHECK_STKSZ_ALIGN
#define CHECK_STKSZ_ALIGN 4 /* スタックサイズのアライン単位 */
#endif /* CHECK_STKSZ_ALIGN */
#ifndef CHECK_FUNC_ALIGN
#define CHECK_FUNC_ALIGN 2 /* 関数のアライン単位 */
#endif /* CHECK_FUNC_ALIGN */
#define CHECK_FUNC_NONNULL /* 関数の非NULLチェック */
#ifndef CHECK_STACK_ALIGN
#define CHECK_STACK_ALIGN 4 /* スタック領域のアライン単位 */
#endif /* CHECK_STACK_ALIGN */
#define CHECK_STACK_NONNULL /* スタック領域の非NULLチェック */
#define call_errorhook(ercd, svcid) stack_change_and_call_func_2((void *) &internal_call_errorhook, (ercd), (svcid))
#define call_shutdownhook(ercd) stack_change_and_call_func_1((void *) &internal_call_shtdwnhk, ((uint32) (ercd)))
/*
* 割込み番号の範囲の判定
*/
#if TMIN_INTNO == 0
#define VALID_INTNO(intno) ((intno) <= (InterruptNumberType) (TMAX_INTNO))
#else /* TMIN_INTNO != 0 */
#define VALID_INTNO(intno) (((InterruptNumberType) (TMIN_INTNO) <= (intno)) && ((intno) <= (InterruptNumberType) (TMAX_INTNO)))
#endif /* TMIN_INTNO == 0 */
#ifndef TOPPERS_MACRO_ONLY
/*
* 非タスクコンテキスト用のスタック開始アドレス設定マクロ
*/
#define TOPPERS_OSTKPT(stk, stksz) ((StackType *) ((sint8 *) (stk) + (stksz)))
/*
* プロセッサの特殊命令のインライン関数定義
*/
#include <prc_insn.h>
/*
* TOPPERS標準割込み処理モデルの実現
*/
/*
* 例外(割込み/CPU例外)のネスト回数のカウント
*
* コンテキスト参照のために使用
*/
extern uint32 except_nest_cnt;
/*
* カーネル管理内(カテゴリ2)の割込みを禁止するためのPMRの設定値
*/
extern const uint16 pmr_isr2_mask;
/*
* カーネル管理外(カテゴリ1)の割込みとなる優先度のPMRのビット
*/
extern const uint16 pmr_isr1_mask;
/*
* 現在の割込み優先度の値(内部表現)
*/
extern uint8 current_iintpri;
/*
* 割り込み要求マスクテーブル(PMRへの設定値)
*/
extern const uint16 pmr_setting_tbl[];
/*
* 無限ループ処理
*/
extern void infinite_loop(void) NoReturn;
/*
* 割込み優先度の内部表現と外部表現の変更
*/
#ifndef TOPPERS_MACRO_ONLY
#define EXT_IPM(iipm) ((PriorityType) (iipm - (TNUM_INTPRI))) /* 内部表現を外部表現に */
#define INT_IPM(ipm) ((uint32) (ipm + (TNUM_INTPRI))) /* 外部表現を内部表現に */
#else /* TOPPERS_MACRO_ONLY */
#define EXT_IPM(iipm) (iipm - (TNUM_INTPRI)) /* 内部表現を外部表現に */
#define INT_IPM(ipm) (ipm + (TNUM_INTPRI)) /* 外部表現を内部表現に */
#endif /* TOPPERS_MACRO_ONLY */
/*
* 全割込み禁止状態への移行
*/
LOCAL_INLINE void
x_lock_all_int(void)
{
disable_int();
}
/*
* 全割込み禁止状態の解除
*/
LOCAL_INLINE void
x_unlock_all_int(void)
{
enable_int();
}
/*
* x_nested_lock_os_int()のネスト回数
* アクセスの順序が変化しないよう,volatile を指定
*/
extern volatile uint8 nested_lock_os_int_cnt;
/*
* OS割込み禁止
* API実行時に呼び出される
* 割込み優先度マスクがISR2の優先度マスクの範囲より高い状態で呼び出される
* ことはない(ISR1から呼び出されることはない)
*/
LOCAL_INLINE void
x_nested_lock_os_int(void)
{
/*
* 一段目なら割込みの禁止レベルに設定割込み優先度マスクの値を保存
*/
if (nested_lock_os_int_cnt == 0U) {
set_pmr(pmr_isr2_mask); /* OS割り込み禁止に設定 */
}
nested_lock_os_int_cnt++;
V850_MEMORY_CHANGED
}
/*
* OS割込み解除
* API実行時に呼び出される
* 割込み優先度マスクがISR2の優先度マスクの範囲より高い状態で呼び出される
* ことはない(ISR1から呼び出されることはない)
*/
LOCAL_INLINE void
x_nested_unlock_os_int(void)
{
V850_MEMORY_CHANGED
ASSERT(nested_lock_os_int_cnt > 0U);
nested_lock_os_int_cnt--;
/*
* 一番外側なら割込み優先度マスクを更新
*/
if (nested_lock_os_int_cnt == 0U) {
set_pmr(pmr_setting_tbl[current_iintpri]);
}
}
/*
* (モデル上の)割込み優先度マスクの設定
*
* 本OSでは次の二点が成り立つ
* * OS割込み禁止状態で呼び出される
* * OS割込み禁止時の優先度より高い値は指定されない
* OS割込み禁止はPMRで実現されており,ここでPMRを変更すると,OS割込み禁止
* が解除される場合があるため,内部変数(current_iintpri) の変更のみを行う.
* 優先度マスクの変更は,APIの出口で呼び出される,x_nested_unlock_os_int()
* で実施される.
*/
LOCAL_INLINE void
x_set_ipm(PriorityType intpri)
{
ASSERT(nested_lock_os_int_cnt > 0U);
current_iintpri = INT_IPM(intpri);
}
/*
* (モデル上の)割込み優先度マスクの参照
*
* 本OSでは次の点が成り立つ
* * OS割込み禁止状態で呼び出される
*/
LOCAL_INLINE PriorityType
x_get_ipm(void)
{
ASSERT(nested_lock_os_int_cnt > 0U);
return(EXT_IPM(current_iintpri));
}
/*
* 割込み要求禁止フラグのセット
*
* 割込み属性が設定されていない割込み要求ラインに対して割込み要求禁止
* フラグをクリアしようとした場合には,falseを返す.
*/
LOCAL_INLINE boolean
x_disable_int(InterruptNumberType intno)
{
uint32 eic_address = EIC_ADDRESS(intno);
if (!VALID_INTNO(intno)) {
return(FALSE);
}
/* 割込みの禁止(7bit目をセット) */
sil_wrh_mem((void *) eic_address,
sil_reh_mem((void *) eic_address) | (0x01U << 7));
return(TRUE);
}
/*
* 割込み要求禁止フラグの解除
*
* 割込み属性が設定されていない割込み要求ラインに対して割込み要求禁止
* フラグをクリアしようとした場合には,falseを返す.
*/
LOCAL_INLINE boolean
x_enable_int(InterruptNumberType intno)
{
uint32 eic_address = EIC_ADDRESS(intno);
if (!VALID_INTNO(intno)) {
return(FALSE);
}
/* 7bit目をクリア */
sil_wrh_mem((void *) eic_address,
sil_reh_mem((void *) eic_address) & ~(0x01U << 7));
return(TRUE);
}
/*
* 割込み要求のクリア
*/
LOCAL_INLINE boolean
x_clear_int(InterruptNumberType intno)
{
uint32 eic_address = EIC_ADDRESS(intno);
if (!VALID_INTNO(intno)) {
return(FALSE);
}
/* 割込みのクリア(12bit目をクリア) */
sil_wrh_mem((void *) eic_address,
sil_reh_mem((void *) eic_address) & ~(0x01U << 12));
return(TRUE);
}
/*
* 割込み要求のチェック
*/
LOCAL_INLINE boolean
x_probe_int(InterruptNumberType intno)
{
uint32 eic_address = EIC_ADDRESS(intno);
uint16 tmp;
if (!VALID_INTNO(intno)) {
return(FALSE);
}
tmp = sil_reh_mem((void *) (eic_address));
return((tmp & 0x1000) != 0);
}
/*
* 割込み要求ラインの属性の設定
*/
extern void x_config_int(InterruptNumberType intno, AttributeType intatr, PriorityType intpri);
/*
* 割込みハンドラの入り口で必要なIRC操作
*/
LOCAL_INLINE void
i_begin_int(InterruptNumberType intno)
{
}
/*
* 割込みハンドラの出口で必要なIRC操作
*/
LOCAL_INLINE void
i_end_int(InterruptNumberType intno)
{
}
/*
* 未定義の割込みが入った場合の処理
*/
extern void default_int_handler(void);
/*
* 起動時のハードウェアの初期化
*/
extern void prc_hardware_initialize(void);
/*
* プロセッサ依存の初期化
*/
extern void prc_initialize(void);
/*
* プロセッサ依存の終了時処理
*/
extern void prc_terminate(void);
/*
* タスクディスパッチャ
*/
/*
* 最高優先順位タスクへのディスパッチ(prc_support.S)
*
* dispatch は,タスクコンテキストから呼び出されたサービスコール処理
* 内で,OS割込み禁止状態で呼び出さなければならない
*/
extern void dispatch(void);
/*
* ディスパッチャの動作開始(prc_support.S)
*
* start_dispatchは,カーネル起動時に呼び出すべきもので,すべての割込
* みを禁止した状態(全割込み禁止状態と同等の状態)で呼び出さなければ
* ならない
*/
extern void start_dispatch(void) NoReturn;
/*
* 現在のコンテキストを捨ててディスパッチ(prc_support.S)
*
* exit_and_dispatch は,OS割込み禁止状態で呼び出さなければならない
*/
extern void exit_and_dispatch(void) NoReturn;
/*
* タスクコンテキストブロックの定義
*/
typedef struct task_context_block {
void *sp; /* スタックポインタ */
FunctionRefType pc; /* プログラムカウンタ */
} TSKCTXB;
/*
* タスクコンテキストの初期化
*
* タスクが休止状態から実行できる状態に移行する時に呼ばれる.この時点
* でスタック領域を使ってはならない
*
* activate_contextを,インライン関数ではなくマクロ定義としているのは,
* この時点ではTCBが定義されていないためである
*/
extern void start_r(void);
#define activate_context(p_tcb) do { \
(p_tcb)->tskctxb.sp = (void *) ((char8 *) ((p_tcb)->p_tinib->stk) \
+ (p_tcb)->p_tinib->stksz); \
(p_tcb)->tskctxb.pc = (FunctionRefType) start_r; \
} while (0)
/* 引数の型はハードウェアが扱えるサイズ(uint32)と同サイズを使用 */
extern void stack_change_and_call_func_1(void *func, uint32 arg1);
extern void stack_change_and_call_func_2(void *func, uint8 arg1, uint8 arg2);
#ifdef ENABLE_RETURN_MAIN
/*
* AKTSP用のmain()へのリターンコード(prc_support.S)
*/
extern void return_main(void);
#endif /* ENABLE_RETURN_MAIN */
/*
* 特定の割込み要求ラインの有効/無効を制御可能かを調べる処理
*/
extern boolean target_is_int_controllable(InterruptNumberType intno);
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_PRC_CONFIG_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: log_output.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* システムログのフォーマット出力
*/
#include "log_output.h"
/*
* 数値を文字列に変換時,uintptr型の数値の最大文字数
* 8進数,10進数,16進数へ変換を想定
* 動作例:
* 2Byteの場合:16進数:FFFF →4文字
* :10進数:65535 →5文字
* : 8進数:177777→6文字
* →CONVERT_BUFLENは最大の6文字を返す
* 計算パラメータ:
* 8U:1バイトのビット数
* 2U:3で割った際の余り1ビット,または2ビット分を含めるための補正値
* 3U:10進数へ変換時,最大3ビットで1文字になる
* (4ビットだと2桁数字になるため)
* 計算例:
* 2Byteの場合
* ビット数は2 * 8U = 16bit
* 単純に3で割ると,16 / 3 = 5となり,余り1ビット分の文字数が
* 切り捨てられてしまう
* 3で割る前に2ビット分足すことで,切捨てを防ぐ
* (16 + 2) / 3 = 6文字
*/
#define CONVERT_BUFLEN (((sizeof(uintptr) * 8U) + 2U) / 3U)
/*
* 数値を文字列に変換
*/
static void
convert(uintptr val, uint32 radix, const char8 *radchar,
uint32 width, boolean minus, boolean padzero, void (*outputc)(char8 c))
{
char8 buf[CONVERT_BUFLEN];
uint32 i, j;
i = 0U;
do {
buf[i++] = radchar[val % radix];
val /= radix;
} while ((i < CONVERT_BUFLEN) && (val != 0U));
if ((minus != FALSE) && (width > 0U)) {
width -= 1U;
}
if ((minus != FALSE) && (padzero != FALSE)) {
(*outputc)('-');
}
for (j = i; j < width; j++) {
(*outputc)((char8) ((padzero != FALSE) ? '0' : ' '));
}
if ((minus != FALSE) && (padzero == FALSE)) {
(*outputc)('-');
}
while (i > 0U) {
(*outputc)(buf[--i]);
}
}
/*
* 文字列整形出力
*/
static const char8 raddec[] = "0123456789";
static const char8 radhex[] = "0123456789abcdef";
static const char8 radHEX[] = "0123456789ABCDEF";
void
syslog_printf(const char8 *format, const uintptr *p_args, void (*outputc)(char8 c))
{
char8 c;
uint32 width;
boolean padzero;
sintptr val;
const char8 *str;
while ((c = *format++) != '\0') {
if (c != '%') {
(*outputc)(c);
continue;
}
width = 0U;
padzero = FALSE;
if ((c = *format++) == '0') {
padzero = TRUE;
c = *format++;
}
while (('0' <= c) && (c <= '9')) {
width = (width * 10U) + (c - '0');
c = *format++;
}
if (c == 'l') {
c = *format++;
}
switch (c) {
case 'd':
val = (sintptr) (*p_args++);
if (val >= 0) {
convert((uintptr) val, 10U, raddec,
width, FALSE, padzero, outputc);
}
else {
convert((uintptr) (-val), 10U, raddec,
width, TRUE, padzero, outputc);
}
break;
case 'u':
val = (sintptr) (*p_args++);
convert((uintptr) val, 10U, raddec, width, FALSE, padzero, outputc);
break;
case 'x':
case 'p':
val = (sintptr) (*p_args++);
convert((uintptr) val, 16U, radhex, width, FALSE, padzero, outputc);
break;
case 'X':
val = (sintptr) (*p_args++);
convert((uintptr) val, 16U, radHEX, width, FALSE, padzero, outputc);
break;
case 'c':
(*outputc)((char8) (uintptr) (*p_args++));
break;
case 's':
str = (const char8 *) (*p_args++);
while ((c = *str++) != '\0') {
(*outputc)(c);
}
break;
case '%':
(*outputc)('%');
break;
case '\0':
format--;
break;
default:
/* 上記のケース以外の場合,処理は行わない */
break;
}
}
}
/*
* ログ情報の出力
*/
void
syslog_print(const SYSLOG *p_syslog, void (*outputc)(char8 c))
{
switch (p_syslog->logtype) {
case LOG_TYPE_COMMENT:
syslog_printf((const char8 *) (p_syslog->loginfo[0]),
&(p_syslog->loginfo[1]), outputc);
break;
case LOG_TYPE_ASSERT:
syslog_printf("%s:%u: Assertion '%s' failed.",
&(p_syslog->loginfo[0]), outputc);
break;
default:
/* 上記のケース以外の場合,出力は行わない */
break;
}
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: t_syslog.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* システムログ出力を行うための定義
*
* システムログサービスは,システムのログ情報を出力するためのサービス
* である
* カーネルからのログ情報の出力にも用いるため,内部で待ち状態にはいる
* ことはない
*
* ログ情報は,カーネル内のログバッファに書き込むか,低レベルの文字出
* 力関数を用いて出力する
* どちらを使うかは,拡張サービスコールで切り換えることができる
*
* ログバッファ領域がオーバフローした場合には,古いログ情報を消して上
* 書きする
*
* アセンブリ言語のソースファイルからこのファイルをインクルードする時
* は,TOPPERS_MACRO_ONLYを定義しておくことで,マクロ定義以外の記述を
* 除くことができる
*/
#ifndef TOPPERS_T_SYSLOG_H
#define TOPPERS_T_SYSLOG_H
#include "Os.h"
/*
* ログ情報の種別の定義
*/
#define LOG_TYPE_COMMENT UINT_C(0x01) /* コメント */
#define LOG_TYPE_ASSERT UINT_C(0x02) /* アサーションの失敗 */
#define LOG_TYPE_ISR UINT_C(0x11) /* 割込みサービスルーチン */
#define LOG_TYPE_ALM UINT_C(0x12) /* アラームハンドラ */
#define LOG_TYPE_TSKSTAT UINT_C(0x13) /* タスク状態変化 */
#define LOG_TYPE_DSP UINT_C(0x14) /* ディスパッチャ */
#define LOG_TYPE_SVC UINT_C(0x15) /* サービスコール */
#define LOG_TYPE_SCHTBL UINT_C(0x16) /* スケジュールテーブル満了処理 */
#define LOG_TYPE_STAHOOK UINT_C(0x17) /* スタートアップフック */
#define LOG_TYPE_ERRHOOK UINT_C(0x18) /* エラーフック */
#define LOG_TYPE_PROHOOK UINT_C(0x19) /* プロテクションフック */
#define LOG_TYPE_SHUTHOOK UINT_C(0x1a) /* シャットダウンフック */
#define LOG_TYPE_STAHOOKOSAP UINT_C(0x1b) /* OSAPスタートアップフック */
#define LOG_TYPE_ERRHOOKOSAP UINT_C(0x1c) /* OSAPエラーフック */
#define LOG_TYPE_SHUTHOOKOSAP UINT_C(0x1d) /* OSAPシャットダウンフック */
#define LOG_TYPE_TFN UINT_C(0x1e) /* 信頼関数 */
#define LOG_ENTER UINT_C(0x00) /* 入口/開始 */
#define LOG_LEAVE UINT_C(0x80) /* 出口/終了 */
/*
* ログ情報の重要度の定義
*/
#define LOG_EMERG UINT_C(0) /* シャットダウンに値するエラー */
#define LOG_ALERT UINT_C(1)
#define LOG_CRIT UINT_C(2)
#define LOG_ERROR UINT_C(3) /* システムエラー */
#define LOG_WARNING UINT_C(4) /* 警告メッセージ */
#define LOG_NOTICE UINT_C(5)
#define LOG_INFO UINT_C(6)
#define LOG_DEBUG UINT_C(7) /* デバッグ用メッセージ */
#ifndef TOPPERS_MACRO_ONLY
/*
* ログ出力用データ型
*/
typedef uint32 ObjectIDType; /* オブジェクトのID番号 */
/*
* ログ情報のデータ構造
*/
#define TMAX_LOGINFO UINT_C(6)
typedef struct {
uint32 logtype; /* ログ情報の種別 */
SystemTimeMsType logtim; /* ログ時刻 */
uintptr loginfo[TMAX_LOGINFO]; /* その他のログ情報 */
} SYSLOG;
/*
* ログ情報の重要度のビットマップを作るためのマクロ
*/
#define LOG_MASK(prio) (1U << (prio))
#define LOG_UPTO(prio) ((((uint32) 1) << ((prio) + 1U)) - 1U)
#ifndef TOPPERS_OMIT_SYSLOG
/*
* ログ情報を出力するためのライブラリ関数(syslog.c)
*/
extern StatusType syslog_wri_log(uint32 prio, const SYSLOG *p_syslog);
LOCAL_INLINE void
_syslog_1(uint32 prio, uint32 type, uintptr arg1)
{
SYSLOG syslog;
syslog.logtype = type;
syslog.loginfo[0] = arg1;
(void) syslog_wri_log(prio, &syslog);
}
LOCAL_INLINE void
_syslog_2(uint32 prio, uint32 type, uintptr arg1, uintptr arg2)
{
SYSLOG syslog;
syslog.logtype = type;
syslog.loginfo[0] = arg1;
syslog.loginfo[1] = arg2;
(void) syslog_wri_log(prio, &syslog);
}
LOCAL_INLINE void
_syslog_3(uint32 prio, uint32 type, uintptr arg1, uintptr arg2,
uintptr arg3)
{
SYSLOG syslog;
syslog.logtype = type;
syslog.loginfo[0] = arg1;
syslog.loginfo[1] = arg2;
syslog.loginfo[2] = arg3;
(void) syslog_wri_log(prio, &syslog);
}
LOCAL_INLINE void
_syslog_4(uint32 prio, uint32 type, uintptr arg1, uintptr arg2,
uintptr arg3, uintptr arg4)
{
SYSLOG syslog;
syslog.logtype = type;
syslog.loginfo[0] = arg1;
syslog.loginfo[1] = arg2;
syslog.loginfo[2] = arg3;
syslog.loginfo[3] = arg4;
(void) syslog_wri_log(prio, &syslog);
}
LOCAL_INLINE void
_syslog_5(uint32 prio, uint32 type, uintptr arg1, uintptr arg2,
uintptr arg3, uintptr arg4, uintptr arg5)
{
SYSLOG syslog;
syslog.logtype = type;
syslog.loginfo[0] = arg1;
syslog.loginfo[1] = arg2;
syslog.loginfo[2] = arg3;
syslog.loginfo[3] = arg4;
syslog.loginfo[4] = arg5;
(void) syslog_wri_log(prio, &syslog);
}
LOCAL_INLINE void
_syslog_6(uint32 prio, uint32 type, uintptr arg1, uintptr arg2,
uintptr arg3, uintptr arg4, uintptr arg5, uintptr arg6)
{
SYSLOG syslog;
syslog.logtype = type;
syslog.loginfo[0] = arg1;
syslog.loginfo[1] = arg2;
syslog.loginfo[2] = arg3;
syslog.loginfo[3] = arg4;
syslog.loginfo[4] = arg5;
syslog.loginfo[5] = arg6;
(void) syslog_wri_log(prio, &syslog);
}
/*
* ログ情報(コメント)を出力するためのライブラリ関数(vasyslog.c)
*/
extern void syslog(uint32 prio, const char8 *format, ...);
#else /* TOPPERS_OMIT_SYSLOG */
/*
* システムログ出力を抑止する場合
*/
LOCAL_INLINE void
_syslog_1(uint32 prio, uint32 type, uintptr arg1)
{
}
LOCAL_INLINE void
_syslog_2(uint32 prio, uint32 type, uintptr arg1, uintptr arg2)
{
}
LOCAL_INLINE void
_syslog_3(uint32 prio, uint32 type, uintptr arg1, uintptr arg2,
uintptr arg3)
{
}
LOCAL_INLINE void
_syslog_4(uint32 prio, uint32 type, uintptr arg1, uintptr arg2,
uintptr arg3, uintptr arg4)
{
}
LOCAL_INLINE void
_syslog_5(uint32 prio, uint32 type, uintptr arg1, uintptr arg2,
uintptr arg3, uintptr arg4, uintptr arg5)
{
}
LOCAL_INLINE void
_syslog_6(uint32 prio, uint32 type, uintptr arg1, uintptr arg2,
uintptr arg3, uintptr arg4, uintptr arg5, uintptr arg6)
{
}
LOCAL_INLINE void
syslog(uint32 prio, const char8 *format, ...)
{
}
#endif /* TOPPERS_OMIT_SYSLOG */
/*
* ログ情報(コメント)を出力するためのマクロ
*
* formatおよび後続の引数から作成したメッセージを,重大度prioでログ情
* 報として出力するためのマクロ
* arg1〜argnはuintptr型にキャストするため,uintptr型に型変換できる任
* 意の型でよい
*/
#define syslog_0(prio, format) \
_syslog_1((prio), LOG_TYPE_COMMENT, (uintptr) (format))
#define syslog_1(prio, format, arg1) \
_syslog_2((prio), LOG_TYPE_COMMENT, (uintptr) (format), \
(uintptr) (arg1))
#define syslog_2(prio, format, arg1, arg2) \
_syslog_3((prio), LOG_TYPE_COMMENT, (uintptr) (format), \
(uintptr) (arg1), (uintptr) (arg2))
#define syslog_3(prio, format, arg1, arg2, arg3) \
_syslog_4((prio), LOG_TYPE_COMMENT, (uintptr) (format), \
(uintptr) (arg1), (uintptr) (arg2), (uintptr) (arg3))
#define syslog_4(prio, format, arg1, arg2, arg3, arg4) \
_syslog_5((prio), LOG_TYPE_COMMENT, (uintptr) (format), \
(uintptr) (arg1), (uintptr) (arg2), (uintptr) (arg3), \
(uintptr) (arg4))
#define syslog_5(prio, format, arg1, arg2, arg3, arg4, arg5) \
_syslog_6((prio), LOG_TYPE_COMMENT, (uintptr) (format), \
(uintptr) (arg1), (uintptr) (arg2), (uintptr) (arg3), \
(uintptr) (arg4), (uintptr) (arg5))
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_T_SYSLOG_H */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2005-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2011-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: syslog.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* システムログ機能
*/
/*
* AUTOSAR共通のデータ型・定数・マクロ
*/
#include "Std_Types.h"
#include "t_syslog.h"
#include "log_output.h"
#include "target_sysmod.h"
#include "syslog.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_SYSLOG_WRI_LOG_ENTER
#define LOG_SYSLOG_WRI_LOG_ENTER(prio, p_syslog)
#endif /* LOG_SYSLOG_WRI_LOG_ENTER */
#ifndef LOG_SYSLOG_WRI_LOG_LEAVE
#define LOG_SYSLOG_WRI_LOG_LEAVE(ercd)
#endif /* LOG_SYSLOG_WRI_LOG_LEAVE */
#ifndef LOG_SYSLOG_MSK_LOG_ENTER
#define LOG_SYSLOG_MSK_LOG_ENTER(lowmask)
#endif /* LOG_SYSLOG_MSK_LOG_ENTER */
#ifndef LOG_SYSLOG_MSK_LOG_LEAVE
#define LOG_SYSLOG_MSK_LOG_LEAVE(ercd)
#endif /* LOG_SYSLOG_MSK_LOG_LEAVE */
/*
* 出力すべきログ情報の重要度(ビットマップ)
*/
static uint32 syslog_lowmask_not; /* 低レベル出力すべき重要度(反転)*/
/*
* システムログ機能の初期化
*/
void
syslog_initialize(void)
{
syslog_lowmask_not = 0U;
}
/*
* ログ情報の出力
*
* CPUロック状態や実行コンテキストによらず動作できるように実装してある
*/
StatusType
syslog_wri_log(uint32 prio, const SYSLOG *p_syslog)
{
SIL_PRE_LOC;
LOG_SYSLOG_WRI_LOG_ENTER(prio, p_syslog);
SIL_LOC_INT();
/*
* 低レベル出力
*/
if (((~syslog_lowmask_not) & LOG_MASK(prio)) != 0U) {
syslog_print(p_syslog, &target_fput_log);
(*target_fput_log)('\n');
}
SIL_UNL_INT();
LOG_SYSLOG_WRI_LOG_LEAVE(E_OK);
return(E_OK);
}
/*
* 出力すべきログ情報の重要度の設定
*/
StatusType
syslog_msk_log(uint32 lowmask)
{
LOG_SYSLOG_MSK_LOG_ENTER(lowmask);
syslog_lowmask_not = ~lowmask;
LOG_SYSLOG_MSK_LOG_LEAVE(E_OK);
return(E_OK);
}
<file_sep>#!python
# -*- coding: utf-8 -*-
#
# TOPPERS ATK2
# Toyohashi Open Platform for Embedded Real-Time Systems
# Automotive Kernel Version 2
#
# Copyright (C) 2013-2014 by Center for Embedded Computing Systems
# Graduate School of Information Science, Nagoya Univ., JAPAN
# Copyright (C) 2013-2014 by FUJI SOFT INCORPORATED, JAPAN
# Copyright (C) 2013-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
# Copyright (C) 2013-2014 by Renesas Electronics Corporation, JAPAN
# Copyright (C) 2013-2014 by <NAME> Inc., JAPAN
# Copyright (C) 2013-2014 by TOSHIBA CORPORATION, JAPAN
# Copyright (C) 2013-2014 by Witz Corporation, JAPAN
#
# 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
# ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
# 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
# (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
# 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
# スコード中に含まれていること.
# (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
# 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
# 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
# の無保証規定を掲載すること.
# (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
# 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
# と.
# (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
# 作権表示,この利用条件および下記の無保証規定を掲載すること.
# (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
# 報告すること.
# (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
# 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
# また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
# 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
# 免責すること.
#
# 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
# 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
# はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
# 用する者に対して,AUTOSARパートナーになることを求めている.
#
# 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
# よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
# に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
# アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
# の責任を負わない.
#
# $Id: configure.py 551 2015-12-30 12:52:19Z ertl-honda $
#
import os.path
import os
os.chdir(os.path.dirname(project.Path))
# set relative path from top proj
proj_rel_dir = ""
# call definition file
common.Source("./def.py")
# path
src_abs_path = os.path.abspath(SRCDIR)
# call common file
common.Source(src_abs_path + "/arch/ccrh/configure_body.py")
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2014 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* @(#) $Id: ostm.c 540 2015-12-29 01:00:01Z ertl-honda $
*/
#include "kernel_impl.h"
#include "target_timer.h"
#include "ostm.h"
#include "Os_Lcfg.h"
/*
* 現在のシステム時刻(単位: ミリ秒)
*
* 厳密には,前のタイムティックのシステム時刻
*/
SystemTimeMsType current_time;
/*
* 内部関数プロトタイプ宣言
*/
ISR(target_timer_hdr);
/*
* マイクロ秒単位での時刻を取得
*/
SystemTimeUsType
get_tim_utime(void)
{
SystemTimeUsType utime;
SystemTimeMsType mtime;
TickType clock1, clock2;
boolean ireq;
SIL_PRE_LOC;
SIL_LOC_INT();
mtime = current_time;
clock1 = target_timer_get_current();
ireq = target_timer_probe_int();
clock2 = target_timer_get_current();
SIL_UNL_INT();
utime = ((SystemTimeUsType) mtime) * 1000U;
if ((ireq != FALSE) && (clock2 >= clock1)) {
/*
* 割込みが入っており,clock2の方がclock1の方が大きいまたは等しい場合は,
* current_time が割込みにより更新されていないかつ,clock1はオーバフロー後
* の値であるため,utimeに1m追加する.clock1の読み込み,割込みのチェック,
* clock2の読み込みが1μs以下で実行可能なプロセッサも存在するため,等号付き
* で比較している.
*/
utime += 1000U;
}
utime += TO_USEC(clock1);
return(utime);
}
/*
* OSTMの初期化
*/
void
target_timer_initialize(void)
{
/* 停止 */
sil_wrb_mem((void *) (OSTM_TT_B), 0x01);
/* インターバル・タイマ・モード */
sil_wrb_mem((void *) (OSTM_CTL_B), 0x00);
/* コンペアレジスタの設定 */
sil_wrw_mem((void *) (OSTM_CMP_W), TIMER_CLOCK);
/* スタート */
sil_wrb_mem((void *) (OSTM_TS_B), 0x01);
}
/*
* OSTMの停止
*/
void
target_timer_terminate(void)
{
/* 停止 */
sil_wrb_mem((void *) (OSTM_TT_B), 0x01);
/* 割込みの禁止とクリア */
x_disable_int(OSTM_IRQ);
x_clear_int(OSTM_IRQ);
}
/*
* target_timer.arxmlを使用しない場合の対処
*/
#ifndef SysTimerCnt
#define SysTimerCnt UINT_C(0)
#endif /* SysTimerCnt */
/*
* タイマ割込みハンドラ
*/
ISR(target_timer_hdr)
{
StatusType ercd;
/* current_timeを更新する */
current_time++;
/*
* カウンタ加算通知処理実行
*/
ercd = IncrementCounter(SysTimerCnt);
/* エラーリターンの場合はシャットダウン */
if (ercd != E_OK) {
ShutdownOS(ercd);
}
}
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: counter_manage.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* カウンタ管理モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "counter.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_INCCNT_ENTER
#define LOG_INCCNT_ENTER(cntid)
#endif /* LOG_INCCNT_ENTER */
#ifndef LOG_INCCNT_LEAVE
#define LOG_INCCNT_LEAVE(ercd)
#endif /* LOG_INCCNT_LEAVE */
#ifndef LOG_GETCNT_ENTER
#define LOG_GETCNT_ENTER(cntid)
#endif /* LOG_GETCNT_ENTER */
#ifndef LOG_GETCNT_LEAVE
#define LOG_GETCNT_LEAVE(ercd, p_val)
#endif /* LOG_GETCNT_LEAVE */
#ifndef LOG_GETEPS_ENTER
#define LOG_GETEPS_ENTER(cntid, p_val)
#endif /* LOG_GETEPS_ENTER */
#ifndef LOG_GETEPS_LEAVE
#define LOG_GETEPS_LEAVE(ercd, p_val, p_eval)
#endif /* LOG_GETEPS_LEAVE */
/*
* カウンタのインクリメント
*/
#ifdef TOPPERS_IncrementCounter
StatusType
IncrementCounter(CounterType CounterID)
{
StatusType ercd = E_OK;
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_INCREMENTCOUNTER);
CHECK_ID(CounterID < tnum_counter);
CHECK_ID(CounterID >= tnum_hardcounter);
x_nested_lock_os_int();
/*
* カウンタのインクリメント
* エラーの場合はincr_counter_actionでエラーフック呼び出しているので,
* ここでは,エラーフックを呼び出さない
*/
ercd = incr_counter_action(CounterID);
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.cntid = CounterID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_IncrementCounter);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_IncrementCounter */
/*
* カウンタ値の参照
*/
#ifdef TOPPERS_GetCounterValue
StatusType
GetCounterValue(CounterType CounterID, TickRefType Value)
{
StatusType ercd = E_OK;
CNTCB *p_cntcb;
TickType curval;
LOG_GETCNT_ENTER(CounterID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_GETCOUNTERVALUE);
CHECK_ID(CounterID < tnum_counter);
CHECK_PARAM_POINTER(Value);
p_cntcb = get_cntcb(CounterID);
/*
* 内部処理のため,コンフィギュレーション設定値の2倍+1までカウント
* アップするのでカウンタ値が設定値よりも大きい場合は設定値を減算する
*
* *Value を直接操作してもよいが,局所変数がレジスタに割当てられること
* による速度を期待している
*/
x_nested_lock_os_int();
curval = get_curval(p_cntcb, CounterID);
x_nested_unlock_os_int();
if (curval > p_cntcb->p_cntinib->maxval) {
curval -= (p_cntcb->p_cntinib->maxval + 1U);
}
*Value = curval;
exit_no_errorhook:
LOG_GETCNT_LEAVE(ercd, Value);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.cntid = CounterID;
temp_errorhook_par2.p_val = Value;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetCounterValue);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetCounterValue */
/*
* 経過カウンタ値の参照
*/
#ifdef TOPPERS_GetElapsedValue
StatusType
GetElapsedValue(CounterType CounterID, TickRefType Value, TickRefType ElapsedValue)
{
StatusType ercd = E_OK;
CNTCB *p_cntcb;
TickType curval;
LOG_GETEPS_ENTER(CounterID, Value);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_GETELAPSEDVALUE);
CHECK_ID(CounterID < tnum_counter);
CHECK_PARAM_POINTER(Value);
CHECK_PARAM_POINTER(ElapsedValue);
p_cntcb = get_cntcb(CounterID);
CHECK_VALUE(*Value <= p_cntcb->p_cntinib->maxval);
/*
* 内部処理のため,コンフィギュレーション設定値の2倍+1までカウント
* アップするのでカウンタ値が設定値よりも大きい場合は設定値を減算する
*/
x_nested_lock_os_int();
curval = get_curval(p_cntcb, CounterID);
x_nested_unlock_os_int();
if (curval > p_cntcb->p_cntinib->maxval) {
curval -= (p_cntcb->p_cntinib->maxval + 1U);
}
*ElapsedValue = diff_tick(curval, *Value, p_cntcb->p_cntinib->maxval);
*Value = curval;
exit_no_errorhook:
LOG_GETEPS_LEAVE(ercd, Value, ElapsedValue);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.cntid = CounterID;
temp_errorhook_par2.p_val = Value;
temp_errorhook_par3.p_eval = ElapsedValue;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetElapsedValue);
x_nested_unlock_os_int();
goto exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetElapsedValue */
/*
* ハードウェアカウンタ満了処理
*
* 割込みルーチンより実行される
*/
#ifdef TOPPERS_notify_hardware_counter
void
notify_hardware_counter(CounterType cntid)
{
CNTCB *p_cntcb;
p_cntcb = get_cntcb(cntid);
/* カウンタ満了処理中はOS割込みを禁止 */
x_nested_lock_os_int();
/*
* ハードウェアカウンタに対応するC2ISRが起動した際に,
* 割込み要求のクリア処理を実行する
*/
(hwcntinib_table[cntid].intclear)();
expire_process(p_cntcb, cntid);
x_nested_unlock_os_int();
}
#endif /* TOPPERS_notify_hardware_counter */
/*
* カウンタのインクリメント
*
* 条件:割込み禁止状態で呼ばれる
*/
#ifdef TOPPERS_incr_counter_action
StatusType
incr_counter_action(CounterType CounterID)
{
StatusType ercd = E_OK;
TickType newval;
CNTCB *p_cntcb;
LOG_INCCNT_ENTER(CounterID);
p_cntcb = get_cntcb(CounterID);
/*
* カウンタが操作中(IncrementCounterのネスト)の場合エラー
* ※独自仕様
*/
D_CHECK_STATE(p_cntcb->cstat == CS_NULL);
p_cntcb->cstat = CS_DOING;
newval = add_tick(p_cntcb->curval, 1U, p_cntcb->p_cntinib->maxval2);
p_cntcb->curval = newval;
expire_process(p_cntcb, CounterID);
p_cntcb->cstat = CS_NULL;
d_exit_no_errorhook:
LOG_INCCNT_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.cntid = CounterID;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_IncrementCounter);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_incr_counter_action */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: event.c 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* イベント管理モジュール
*/
#include "kernel_impl.h"
#include "check.h"
#include "task.h"
/*
* トレースログマクロのデフォルト定義
*/
#ifndef LOG_TSKSTAT
#define LOG_TSKSTAT(p_tcb)
#endif /* LOG_TSKSTAT */
#ifndef LOG_SETEVT_ENTER
#define LOG_SETEVT_ENTER(tskid, mask)
#endif /* LOG_SETEVT_ENTER */
#ifndef LOG_SETEVT_LEAVE
#define LOG_SETEVT_LEAVE(ercd)
#endif /* LOG_SETEVT_LEAVE */
#ifndef LOG_CLREVT_ENTER
#define LOG_CLREVT_ENTER(p_runtsk, mask)
#endif /* LOG_CLREVT_ENTER */
#ifndef LOG_CLREVT_LEAVE
#define LOG_CLREVT_LEAVE(ercd)
#endif /* LOG_CLREVT_LEAVE */
#ifndef LOG_GETEVT_ENTER
#define LOG_GETEVT_ENTER(tskid)
#endif /* LOG_GETEVT_ENTER */
#ifndef LOG_GETEVT_LEAVE
#define LOG_GETEVT_LEAVE(ercd, tskid, p_mask)
#endif /* LOG_GETEVT_LEAVE */
#ifndef LOG_WAIEVT_ENTER
#define LOG_WAIEVT_ENTER(p_runtsk, mask)
#endif /* LOG_WAIEVT_ENTER */
#ifndef LOG_WAIEVT_LEAVE
#define LOG_WAIEVT_LEAVE(ercd)
#endif /* LOG_WAIEVT_LEAVE */
/*
* イベントのセット
*/
#ifdef TOPPERS_SetEvent
StatusType
SetEvent(TaskType TaskID, EventMaskType Mask)
{
StatusType ercd = E_OK;
TCB *p_tcb;
LOG_SETEVT_ENTER(TaskID, Mask);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_SETEVENT);
CHECK_ID(TaskID < tnum_task);
CHECK_ACCESS(TaskID < tnum_exttask);
p_tcb = get_tcb(TaskID);
x_nested_lock_os_int();
D_CHECK_STATE(p_tcb->tstat != SUSPENDED);
p_tcb->curevt |= Mask;
if ((p_tcb->curevt & p_tcb->waievt) != EVTMASK_NONE) {
p_tcb->waievt = EVTMASK_NONE;
if ((make_runnable(p_tcb) != FALSE) && (callevel_stat == TCL_TASK)) {
dispatch();
}
}
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_SETEVT_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.tskid = TaskID;
temp_errorhook_par2.mask = Mask;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_SetEvent);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_SetEvent */
/*
* イベントのクリア
*/
#ifdef TOPPERS_ClearEvent
StatusType
ClearEvent(EventMaskType Mask)
{
StatusType ercd = E_OK;
LOG_CLREVT_ENTER(p_runtsk, Mask);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_CLEAREVENT);
CHECK_ACCESS(TSKID(p_runtsk) < tnum_exttask);
x_nested_lock_os_int();
p_runtsk->curevt &= ~Mask;
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_CLREVT_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.mask = Mask;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_ClearEvent);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_ClearEvent */
/*
* イベントの状態参照
*/
#ifdef TOPPERS_GetEvent
StatusType
GetEvent(TaskType TaskID, EventMaskRefType Event)
{
StatusType ercd = E_OK;
TCB *p_tcb;
LOG_GETEVT_ENTER(TaskID);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_GETEVENT);
CHECK_ID(TaskID < tnum_task);
CHECK_ACCESS(TaskID < tnum_exttask);
CHECK_PARAM_POINTER(Event);
p_tcb = get_tcb(TaskID);
x_nested_lock_os_int();
/* 対象タスクが休止状態の場合はエラーとする */
D_CHECK_STATE((p_tcb->tstat != SUSPENDED) || (p_tcb == p_runtsk));
*Event = p_tcb->curevt;
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_GETEVT_LEAVE(ercd, TaskID, Event);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.tskid = TaskID;
temp_errorhook_par2.p_mask = Event;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_GetEvent);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_GetEvent */
/*
* イベント待ち
*/
#ifdef TOPPERS_WaitEvent
StatusType
WaitEvent(EventMaskType Mask)
{
StatusType ercd = E_OK;
LOG_WAIEVT_ENTER(p_runtsk, Mask);
CHECK_DISABLEDINT();
CHECK_CALLEVEL(CALLEVEL_WAITEVENT);
CHECK_ACCESS(TSKID(p_runtsk) < tnum_exttask);
CHECK_RESOURCE(p_runtsk->p_lastrescb == NULL);
x_nested_lock_os_int();
if ((p_runtsk->curevt & Mask) == EVTMASK_NONE) {
p_runtsk->curpri = p_runtsk->p_tinib->inipri;
p_runtsk->tstat = WAITING;
LOG_TSKSTAT(p_runtsk);
p_runtsk->waievt = Mask;
make_non_runnable();
dispatch();
p_runtsk->curpri = p_runtsk->p_tinib->exepri;
}
d_exit_no_errorhook:
x_nested_unlock_os_int();
exit_no_errorhook:
LOG_WAIEVT_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
exit_errorhook:
x_nested_lock_os_int();
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.mask = Mask;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_WaitEvent);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_WaitEvent */
/*
* 満了処理専用イベントのセット
*
* 条件:OS割込み禁止状態で呼ばれる
*/
#ifdef TOPPERS_set_event_action
StatusType
set_event_action(TaskType TaskID, EventMaskType Mask)
{
StatusType ercd;
TCB *p_tcb;
LOG_SETEVT_ENTER(TaskID, Mask);
p_tcb = get_tcb(TaskID);
D_CHECK_STATE(p_tcb->tstat != SUSPENDED);
ercd = E_OK;
p_tcb->curevt |= Mask;
if ((p_tcb->curevt & p_tcb->waievt) != EVTMASK_NONE) {
p_tcb->waievt = EVTMASK_NONE;
(void) make_runnable(p_tcb);
}
d_exit_no_errorhook:
LOG_SETEVT_LEAVE(ercd);
return(ercd);
#ifdef CFG_USE_ERRORHOOK
d_exit_errorhook:
#ifdef CFG_USE_PARAMETERACCESS
temp_errorhook_par1.tskid = TaskID;
temp_errorhook_par2.mask = Mask;
#endif /* CFG_USE_PARAMETERACCESS */
call_errorhook(ercd, OSServiceId_SetEvent);
goto d_exit_no_errorhook;
#endif /* CFG_USE_ERRORHOOK */
}
#endif /* TOPPERS_set_event_action */
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
* Toyohashi Univ. of Technology, JAPAN
* Copyright (C) 2004-2017 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2011-2017 by FUJI SOFT INCORPORATED, JAPAN
* Copyright (C) 2011-2013 by Spansion LLC, USA
* Copyright (C) 2011-2017 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2011-2016 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2011-2016 by Sunny Giken Inc., JAPAN
* Copyright (C) 2011-2017 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2004-2017 by Witz Corporation
* Copyright (C) 2014-2016 by AISIN COMCRUISE Co., Ltd., JAPAN
* Copyright (C) 2014-2016 by eSOL Co.,Ltd., JAPAN
* Copyright (C) 2014-2017 by SCSK Corporation, JAPAN
* Copyright (C) 2015-2017 by SUZUKI MOTOR CORPORATION
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: alarm.h 727 2017-01-23 09:27:59Z witz-itoyo $
*/
/*
* アラーム機能
*/
#ifndef TOPPERS_ALARM_H
#define TOPPERS_ALARM_H
#include "counter.h"
/*
* アラームIDからアラーム管理ブロックを取り出すためのマクロ
*/
#define get_almcb(almid) (&(almcb_table[(almid)]))
/*
* アラーム初期化ブロック
*/
typedef struct alarm_initialization_block {
CNTCB *p_cntcb; /* 駆動カウンタ管理ブロックのポインタ */
FunctionRefType action; /* アラーム満了アクション */
AppModeType autosta; /* 起動するモード */
TickType almval; /* expire するティック値 */
TickType cycle; /* アラームの周期 */
AttributeType actatr; /* 満了アクション・自動起動の属性 */
} ALMINIB;
/*
* アラーム管理ブロック
*/
typedef struct alarm_control_block {
CNTEXPINFO cntexpinfo; /* カウンタ満了情報(構造体の先頭に入る必要) */
const ALMINIB *p_alminib; /* アラーム初期化ブロックポインタ */
TickType cycle; /* アラームの周期 */
} ALMCB;
/*
* アラーム数を保持する変数の宣言(Os_Lcfg.c)
*/
extern const AlarmType tnum_alarm; /* アラームの数 */
/*
* アラーム初期化ブロックのエリア(Os_Lcfg.c)
*/
extern const ALMINIB alminib_table[];
/*
* アラーム管理ブロックのエリア(Os_Lcfg.c)
*/
extern ALMCB almcb_table[];
/*
* アラーム機能の初期化
*/
extern void alarm_initialize(void);
/*
* アラーム満了アクション処理用関数
*/
extern void alarm_expire(CNTEXPINFO *p_cntexpinfo, CNTCB *p_cntcb);
#endif /* TOPPERS_ALARM_H */
<file_sep>#!python
# -*- coding: utf-8 -*-
#
# TOPPERS ATK2
# Toyohashi Open Platform for Embedded Real-Time Systems
# Automotive Kernel Version 2
#
# Copyright (C) 2013-2021 by Center for Embedded Computing Systems
# Graduate School of Information Science, Nagoya Univ., JAPAN
# Copyright (C) 2013-2021 by FUJI SOFT INCORPORATED, JAPAN
# Copyright (C) 2013-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
# Copyright (C) 2013-2014 by Renesas Electronics Corporation, JAPAN
# Copyright (C) 2013-2014 by <NAME> Inc., JAPAN
# Copyright (C) 2013-2014 by TOSHIBA CORPORATION, JAPAN
# Copyright (C) 2013-2014 by Witz Corporation, JAPAN
#
# 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
# ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
# 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
# (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
# 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
# スコード中に含まれていること.
# (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
# 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
# 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
# の無保証規定を掲載すること.
# (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
# 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
# と.
# (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
# 作権表示,この利用条件および下記の無保証規定を掲載すること.
# (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
# 報告すること.
# (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
# 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
# また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
# 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
# 免責すること.
#
# 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
# 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
# はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
# 用する者に対して,AUTOSARパートナーになることを求めている.
#
# 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
# よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
# に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
# アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
# の責任を負わない.
#
# $Id: common.py 929 2021-01-06 08:51:23Z nces-mtakada $
#
#
# variable definition
#
INCLUDES = []
CFG1_DEF_TABLES = []
#
# set cfg and cfg kernel param
#
CFG = SRCDIR + "cfg/cfg/cfg.exe"
CFG_KERNEL = "atk2"
#
# files for each project
#
app_files = []
app_configuration_files = ['Os_Lcfg_asm.asm', 'Os_Lcfg.c']
app_sysmod_files = ['sysmod/banner.c', 'sysmod/serial.c', 'sysmod/syslog.c']
app_library_files = ['library/log_output.c', 'library/strerror.c', 'library/t_perror.c', 'library/vasyslog.c']
kernel_kernel_files = ['kernel/alarm.c','kernel/counter.c','kernel/counter_manage.c','kernel/event.c','kernel/interrupt.c','kernel/interrupt_manage.c','kernel/osctl.c','kernel/osctl_manage.c','kernel/resource.c','kernel/scheduletable.c','kernel/task.c','kernel/task_manage.c']
cfg_files = []
cfg_configuration_files = ['cfg1_out.c']
#
# pre/postbuiled file
#
cfg_pre_python_files = ['arch/ccrh/pre_cfg.py']
cfg_post_python_files = ['arch/ccrh/post_cfg.py']
atk2_sc1_post_python_files = ['arch/ccrh/post_atk2.py']
#
# cubesuite+ depend files
#
atk2_sc1_rel_includes = [".","cfg"]
cfg_rel_includes = [".."]
kernel_rel_includes = ["..","..\cfg"]
#
# library
#
#atk2_sc1_lib_includes = []
atk2_sc1_lib_files = [r'kernel\%BuildModeName%\kernel']
#
# cx define
#
kernel_define = ['ALLFUNC', 'TOPPERS_LABEL_ASM']
#
# cx additional option
# -Xno_warning=20177 : Suppress warnings no refer label(exit_no_errorhooh, d_exit_no_errorhook)
kernel_c_addopt = ['-Xno_warning=20177']
# -Xno_warning=50013 : Use r1 register as source register
kernel_asm_addopt = ['-Xno_warning=50013']
#
# Set cfg path and srdir path
#
cfg = proj_rel_dir + CFG
srcdir = proj_rel_dir + SRCDIR
#
# soucre target file
#
execfile(srcdir + "target/" + TARGET + "/target.py")
#
# merge files
#
app_files.append(statup_file)
app_files = app_files + app_sysmod_files + app_library_files
kernel_files = kernel_kernel_files + kernel_target_files + kernel_arch_files
#
# Set include path and cfg1_def_table
#
INCLUDES = USER_INCLUDE + ["", "arch", "include", "kernel", "arch", "sysmod", "library"] + INCLUDES
CFG1_DEF_TABLES = ["kernel/kernel_def.csv"] + CFG1_DEF_TABLES
API_TABLE = "kernel/kernel.csv"
INI_FILE = "kernel/kernel.ini"
CFG_TF = "target/" + TARGET + "/target.tf"
CFG_OFFSET_TF = "target/" + TARGET + "/target_offset.tf"
CFG_CHECK_TF = "target/" + TARGET + "/target_check.tf"
#
# cfg input files
#
cfg_rel_files = []
cfg_input_str = ""
for cfg_filename in CFGNAME:
cfg_rel_file = cfg_filename + '.arxml'
cfg_list = [proj_rel_dir + cfg_rel_file]
for inc_path in INCLUDES:
cfg_list = cfg_list + [src_abs_path + '/' + inc_path + '/' + cfg_rel_file]
flg = 0
for cfg_rel_file in cfg_list:
if os.path.exists(cfg_rel_file):
cfg_rel_files.append(cfg_rel_file)
flg = 1
break
if flg == 0:
print "WARNING!! : Not Exist %s" % cfg_filename
cfg_input_str = " ".join(cfg_rel_files)
#
# make cfg include path
#
cfg_includes = ""
for include in INCLUDES:
cfg_includes = cfg_includes + " -I" + srcdir + include
#
# make cfg1_def_table
#
cfg_cfg1_def_tables = ""
for cfg1_def_table in CFG1_DEF_TABLES:
cfg_cfg1_def_tables = cfg_cfg1_def_tables + " --cfg1-def-table " + srcdir + cfg1_def_table
#
# Set api_table
#
cfg_api_table = srcdir + API_TABLE
#
# Set ini_file
#
cfg_ini_file = srcdir + INI_FILE
#
# Set tf
#
cfg_tf = srcdir + CFG_TF
#
# Set offset tf
#
cfg_offset_tf = srcdir + CFG_OFFSET_TF
#
# Set check tf
#
cfg_check_tf = srcdir + CFG_CHECK_TF
#
#
# Functions
#
#
import re
#
# Set Cx Includes
#
def SetCxIncludes(inputstr, include_list, rel_include_list, relpath):
cx_includes = ""
for include in rel_include_list:
include_list.append(relpath + include)
for include in include_list:
cx_includes = cx_includes + include + "\n"
cx_includes = cx_includes.replace('/', r'\\')
pattern_pre = r'(\s\<AdditionalIncludePaths-0\>)[\s\S]+?(\</AdditionalIncludePaths-0\>)'
pattern_post = r'\1' + cx_includes + r'\2'
inputstr = re.sub (pattern_pre, pattern_post, inputstr)
return inputstr
#
# ChangeSetItemXml
#
def ChangeItemXml(inputstr, xml_pattern, newitemstr):
pattern_pre = r'<' + xml_pattern + r'>[\s\S]+?</' + xml_pattern + '>'
pattern_post = '<' + xml_pattern + '>' + newitemstr + '</' + xml_pattern + '>'
inputstr = re.sub (pattern_pre, pattern_post, inputstr)
return inputstr
#
# NewSetItemXml
#
def NewSetItemXml(inputstr, xml_pattern, newitemstr):
pattern_pre = r'\<' + xml_pattern + r' /\>'
pattern_post = r'<' + xml_pattern + r'>' + newitemstr + '</' + xml_pattern + r'>'
inputstr = re.sub (pattern_pre, pattern_post, inputstr)
return inputstr
#
# NewSetItemXmlOnce
#
def NewSetItemXmlOnce(inputstr, xml_pattern, newitemstr):
pattern_pre = r'\<' + xml_pattern + r' /\>'
pattern_post = r'<' + xml_pattern + r'>' + newitemstr + '</' + xml_pattern + r'>'
inputstr = re.sub (pattern_pre, pattern_post, inputstr, 1)
return inputstr
#
# New set Cx Include
#
def NewSetCxIncludes(inputstr, include_list, rel_include_list, relpath):
cx_includes = ""
for include in rel_include_list:
include_list.append(relpath + include)
for include in include_list:
cx_includes = cx_includes + include + "\n"
cx_includes = cx_includes.replace('/', r'\\')
return NewSetItemXml(inputstr, 'AdditionalIncludePaths-0', cx_includes)
def NewSetCCRHIncludes(inputstr, include_list, rel_include_list, relpath):
ccrh_includes = ""
for include in rel_include_list:
include_list.append(relpath + include)
for include in include_list:
ccrh_includes = ccrh_includes + include + "\n"
ccrh_includes = ccrh_includes.replace('/', r'\\')
return NewSetItemXml(inputstr, 'COptionI-0', ccrh_includes)
#
# New set library Include
#
def NewSetLibIncludes(inputstr, include_list, rel_include_list, relpath):
lib_includes = ""
for include in rel_include_list:
include_list.append(relpath + include)
for include in include_list:
lib_includes = lib_includes + include + "\n"
lib_includes = lib_includes.replace('/', r'\\')
return NewSetItemXml(inputstr, 'AdditionalLibraryPaths-0', lib_includes)
#
# New set library files
#
def NewSetLibFiles(inputstr, file_list):
lib_files = ""
for file in file_list:
lib_files = lib_files + file + "\n"
lib_files = lib_files.replace('/', r'\\')
return NewSetItemXml(inputstr, 'LinkOptionLibrary-0', lib_files)
#
# New set prebuild
#
def NewSetPrebuild(inputstr, rel_command_list, relpath):
command_str = ''
for command in rel_command_list:
command_str = command_str + relpath + command
command_str = r'#!python\ncommon.Source("' + command_str + r'")\n'
return NewSetItemXml(inputstr, 'PreBuildCommands-0', command_str)
#
# New set postbuild
#
def NewSetPostbuild(inputstr, rel_command_list, relpath):
command_str = ''
for command in rel_command_list:
command_str = command_str + relpath + command
command_str = r'#!python\ncommon.Source("' + command_str + r'")\n'
return NewSetItemXml(inputstr, 'PostBuildCommands-0', command_str)
#
# New set Define
#
def NewSetDefine(inputstr, define_list):
define_str = ''
for define in define_list:
define_str = define_str + define + '\n'
return NewSetItemXml(inputstr, 'COptionD-0', define_str)
#
# New set additional options
#
def NewSetCAddOpt(inputstr, option_list):
option_str = ''
for option in option_list:
option_str = option_str + option + ' '
return NewSetItemXmlOnce(inputstr, 'COptionOtherAdditionalOptions-0', option_str)
def NewSetAsmAddOpt(inputstr, option_list):
option_str = ''
for option in option_list:
option_str = option_str + option + ' '
return NewSetItemXmlOnce(inputstr, 'AsmOptionOtherAdditionalOptions-0', option_str)
#
# Set target file relative path
#
def SetTargetFileRelativePath(inputstr, file_list, relpath):
relpath_win = re.sub(r'/',r'\\\\', relpath)
for file_path in file_list:
file_path = re.sub(r'/',r'\\\\',file_path)
pattern_pre = r'(\s\<RelativePath\>).+?' + file_path + r'(\</RelativePath\>)'
pattern_post = r'\1' + relpath_win + file_path + r'\2'
inputstr = re.sub (pattern_pre, pattern_post, inputstr)
return inputstr
#
# Set python file relative path
#
def SetPythonFileRelativePath(inputstr, file_list, relpath):
for file_path in file_list:
pattern_pre = r'".+?' + file_path + r'"'
pattern_post = r'"' + relpath + file_path + r'"'
inputstr = re.sub (pattern_pre, pattern_post, inputstr)
return inputstr
def ReadFile(filename):
f = open(filename, "r")
str = f.read()
f.close()
return str
def WriteFile(filename, str):
f = open(filename, "w")
str = re.sub (u'\uFEFF', '', str) ## Delete BOM
f.write(str)
f.close()
def WriteFile_B(filename, str):
f = open(filename, "wb")
f.write(str)
f.close()
<file_sep>/*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2016 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: rh850_f1l.c 559 2016-01-09 01:21:54Z ertl-honda $
*/
#include "kernel_impl.h"
#include "rh850_f1l.h"
#include "Os.h"
#include "prc_sil.h"
/*******************************************************************************************/
/* Outline : Write protected register */
/* Argument : Register address */
/* Register data */
/* Register No */
/* Return value : 0: write success / 1: write error */
/* Description : Write protected register */
/* */
/*******************************************************************************************/
static uint32
write_protected_reg(uint32 addr, uint32 data, uint8 regno)
{
uint8 wk;
const uint32 cmd_reg[19] = {
PROTCMD0, PROTCMD1, CLMA0PCMD, CLMA1PCMD, CLMA2PCMD, PROTCMDCLMA,
JPPCMD0, PPCMD0, PPCMD1, PPCMD2, PPCMD8,
PPCMD9, PPCMD10, PPCMD11, PPCMD12, PPCMD18, PPCMD20,
PROTCMDCVM, FLMDPCMD
};
const uint32 s_reg[19] = {
PROTS0, PROTS1, CLMA0PS, CLMA1PS, CLMA2PS, PROTSCLMA,
JPPROTS0, PPROTS0, PPROTS1, PPROTS2, PPROTS8,
PPROTS9, PPROTS10, PPROTS11, PPROTS12, PPROTS18, PPROTS20,
PROTSCVM, FLMDPS
};
SIL_PRE_LOC;
if (regno > 19) {
return(UC_INVALIDPARAM);
}
SIL_LOC_INT();
sil_wrw_mem((void *) cmd_reg[regno], 0xA5);
sil_wrw_mem((void *) addr, data);
sil_wrw_mem((void *) addr, ~data);
sil_wrw_mem((void *) addr, data);
SIL_UNL_INT();
wk = sil_rew_mem((void *) s_reg[regno]);
wk &= 0x01;
return((wk == 0) ? UC_SUCCESS : UC_PROTREGERROR);
} /* write_protected_reg */
/*******************************************************************************************/
/* Outline : Sub Oscillator enable */
/* Argument : - */
/* Return value : 0: successfly set / 1: set error */
/* Description : Sub Oscillator register setting */
/* */
/*******************************************************************************************/
uint32
EnableSubOSC(void)
{
/* stop SubOSC */
if (write_protected_reg(SOSCE, 0x00, PNO_CtrlProt0) != UC_SUCCESS) {
return(UC_ERROR);
}
/* Wait inactive */
while (((sil_rew_mem((void *) SOSCS)) & CLK_S_CLKEN) != 0) {
}
/* start SubOSC */
if (write_protected_reg(SOSCE, 0x01, PNO_CtrlProt0) != UC_SUCCESS) return(UC_ERROR);
/* Wait stabilization */
while (((sil_rew_mem((void *) SOSCS)) & CLK_S_CLKEN) == 0) {
}
return(UC_SUCCESS);
} /* EnableSubOSC */
/*******************************************************************************************/
/* Outline : Main Oscillator enable */
/* Argument : Main Cscillator frequency(Hz) */
/* Return value : 0: successfly set / 1: set error */
/* Description : Main Oscillator register setting */
/* */
/*******************************************************************************************/
uint32
EnableMainOSC(uint32 clk_in)
{
uint8 ampsel;
/* stop MainOSC */
if (write_protected_reg(MOSCE, 0x02, PNO_CtrlProt0) != UC_SUCCESS) {
return(UC_ERROR);
}
if (clk_in == CLK_MHz(8)) {
ampsel = 0x03;
}
else if (CLK_MHz(8) < clk_in && clk_in <= CLK_MHz(16)) {
ampsel = 0x02;
}
else if (CLK_MHz(16) < clk_in && clk_in <= CLK_MHz(20)) {
ampsel = 0x01;
}
else if (CLK_MHz(20) < clk_in && clk_in <= CLK_MHz(24)) {
ampsel = 0x00;
}
else {
return(UC_INVALIDPARAM);
}
/* Wait inactive */
while (((sil_rew_mem((void *) MOSCS)) & CLK_S_CLKEN) != 0) {
}
sil_wrw_mem((void *) MOSCC, 0x00 | ampsel); /* Normal stabilization time mode */
sil_wrw_mem((void *) MOSCST, 0x00FF); /* stabilization time -> Max */
/* MainOSC start */
if (write_protected_reg(MOSCE, 0x01, PNO_CtrlProt0) != UC_SUCCESS) {
return(UC_ERROR);
}
/* Wait stabilization */
while (((sil_rew_mem((void *) MOSCS)) & CLK_S_CLKEN) == 0) {
}
return(UC_SUCCESS);
} /* EnableMainOSC */
/*******************************************************************************************/
/* Outline : PLL enable */
/* Argument : none */
/* Return value : 0: successfly set / 1: set error */
/* Description : PLL register setting */
/* */
/*******************************************************************************************/
uint32
EnablePLL(void)
{
/* stop PLL */
if (write_protected_reg(PLLE, 0x02, PNO_CtrlProt1) != UC_SUCCESS) {
return(UC_ERROR);
}
sil_wrw_mem((void *) PLLC, (PLLC_OUTBSEL << 16) | ((PLLC_mr - 1) << 11) | ((PLLC_par >> 1) << 8) | (PLLC_nr - 1));
/* start PLL */
if (write_protected_reg(PLLE, 0x01, PNO_CtrlProt1) != UC_SUCCESS) {
return(UC_ERROR);
}
/* Wait stabilization */
while (((sil_rew_mem((void *) PLLS)) & CLK_S_CLKEN) == 0) {
}
return(UC_SUCCESS);
} /* EnablePLL */
/*******************************************************************************************/
/* Outline : Clock switcher setting */
/* Argument : Selector Control reginster address */
/* Selector Status reginster address */
/* Register No */
/* Select No */
/* Divider Control reginster address */
/* Divider Status reginster address */
/* divider */
/* Return value : 0: successfly set / 1: set error */
/* Description : Select clock source of CKSCLK_mn */
/* */
/*******************************************************************************************/
uint32
SetClockSelection(uint32 s_control, uint32 s_status, uint8 regno, uint16 sel,
uint32 d_control, uint32 d_status, uint8 divider)
{
/* Set Selector */
if (write_protected_reg(s_control, sel, regno) != UC_SUCCESS) {
return(UC_ERROR);
}
/* Set Divider */
if (d_control != 0) {
if (write_protected_reg(d_control, divider, regno) != UC_SUCCESS) {
return(UC_ERROR);
}
}
/* Wait untile enable */
while (sil_rew_mem((void *) s_control) != sil_rew_mem((void *) s_status)) {
}
if (d_control != 0) {
while (sil_rew_mem((void *) d_control) != sil_rew_mem((void *) d_status)) {
}
}
return(UC_SUCCESS);
}
<file_sep>#
# TOPPERS ATK2
# Toyohashi Open Platform for Embedded Real-Time Systems
# Automotive Kernel Version 2
#
# Copyright (C) 2012-2014 by Center for Embedded Computing Systems
# Graduate School of Information Science, Nagoya Univ., JAPAN
# Copyright (C) 2012-2014 by FUJI SOFT INCORPORATED, JAPAN
# Copyright (C) 2012-2013 by Spansion LLC, USA
# Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
# Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
# Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
# Copyright (C) 2012-2014 by <NAME> Inc., JAPAN
# Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
# Copyright (C) 2012-2014 by Witz Corporation, JAPAN
#
# 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
# ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
# 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
# (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
# 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
# スコード中に含まれていること.
# (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
# 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
# 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
# の無保証規定を掲載すること.
# (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
# 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
# と.
# (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
# 作権表示,この利用条件および下記の無保証規定を掲載すること.
# (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
# 報告すること.
# (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
# 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
# また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
# 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
# 免責すること.
#
# 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
# 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
# はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
# 用する者に対して,AUTOSARパートナーになることを求めている.
#
# 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
# よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
# に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
# アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
# の責任を負わない.
#
# $Id: Makefile.prc 911 2020-07-24 06:25:32Z nces-mtakada $
#
#
# Makefile のプロセッサ依存部(V850用)
#
#
# プロセッサ名,開発環境名の定義
#
PRC = v850
TOOL = gcc
#
# プロセッサ依存部ディレクトリ名の定義
#
PRCDIR = $(SRCDIR)/arch/$(PRC)_$(TOOL)
#
# コンパイルオプション
#
INCLUDES := $(INCLUDES) -I$(PRCDIR) -I$(SRCDIR)/arch/$(TOOL)
COPTS := $(COPTS) -mdisable-callt -mno-app-regs -mtda=0
CDEFS := $(CDEFS) -DTOPPERS_LABEL_ASM
LIBS := $(LIBS) -lgcc -lc
#LDFLAGS := $(LDFLAGS) -Wl,-S # for CuteSuite+ debugger
LDFLAGS := $(LDFLAGS)
#
# アーキテクチャの切り替え
#
ifeq ($(ARCH),V850E2V3)
COPTS := $(COPTS) -mv850e2v3 -D__v850e2v3__ -Wa,-mno-bcond17
KERNEL_ASMOBJS := $(KERNEL_ASMOBJS) Os_Lcfg_asm.o
endif
ifeq ($(ARCH),V850E3V5)
COPTS := $(COPTS) -mv850e3v5
endif
#
# コアタイプ(実装)による切り替え
#
ifeq ($(CORETYPE),RH850G3K)
COPTS := $(COPTS) -msoft-float
endif
ifeq ($(CORETYPE),RH850G3M)
ifeq ($(USE_HARD_FLOAT),true)
COPTS := $(COPTS) -mhard-float -DTOPPERS_USE_HFLOAT
else
COPTS := $(COPTS) -msoft-float
endif
endif
#
# カーネルに関する定義
#
KERNEL_DIR := $(KERNEL_DIR) $(PRCDIR)
KERNEL_ASMOBJS := $(KERNEL_ASMOBJS) prc_support.o
KERNEL_COBJS := $(KERNEL_COBJS) prc_config.o
#
# スタートアップモジュールに関する定義
#
# リンカスクリプトに「STARTUP(start.o)」を記述したため,スタートアップモジュー
# ルの名前をHIDDEN_OBJSに定義する.また,LDFLAGSに-nostdlibを追加している.
#
HIDDEN_OBJS = start.o
$(HIDDEN_OBJS): %.o: %.S
$(CC) -c $(CFLAGS) $(KERNEL_CFLAGS) $<
$(HIDDEN_OBJS:.o=.d): %.d: %.S
@$(PERL) $(SRCDIR)/utils/makedep -C $(CC) \
-O "$(CFLAGS) $(KERNEL_CFLAGS)" $< >> Makefile.depend
LDFLAGS := -nostdlib $(LDFLAGS)
#
# 依存関係の定義
#
cfg1_out.c: $(PRCDIR)/prc_def.csv
Os_Lcfg.timestamp: $(PRCDIR)/prc.tf
$(OBJFILE): $(PRCDIR)/prc_check.tf
offset.h: $(PRCDIR)/prc_offset.tf
#
# ジェネレータ関係の変数の定義
#
CFG_TABS := $(CFG_TABS) --cfg1-def-table $(PRCDIR)/prc_def.csv
CFG2_OUT := Os_Lcfg_asm.S
#
# CS+用に変換
#
cs: $(OBJFILE)
v850-elf-objdump.exe -h $(OBJFILE) | $(SRCDIR)/arch/v850_gcc/conv2cs+.rb $(OBJFILE)
|
261892578d04c5f3fd5fce37474012437896af08
|
[
"SQL",
"Ruby",
"INI",
"Python",
"Text",
"C"
] | 70 |
INI
|
mikoto2000/athrill_skip_clock_bugfix_test_project
|
3759204392ea694877dbf255cb851904f49ddfc8
|
1f37eb50de7429c028b7c66866893ea917a2f208
|
refs/heads/master
|
<repo_name>kardi31/ap<file_sep>/application/modules/order/models/Doctrine/BasePayment.php
<?php
/**
* Order_Model_Doctrine_BasePayment
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property integer $id
* @property string $status
* @property string $error_status
* @property string $desc
* @property string $client_ip
* @property string $trans_id
* @property string $ts
* @property integer $status_id
* @property integer $payment_type_id
* @property Order_Model_Doctrine_OrderStatus $Status
* @property Order_Model_Doctrine_PaymentType $PaymentType
* @property Order_Model_Doctrine_Order $Order
*
* @package Admi
* @subpackage Order
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class Order_Model_Doctrine_BasePayment extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('order_payment');
$this->hasColumn('id', 'integer', 4, array(
'primary' => true,
'autoincrement' => true,
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('status', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('error_status', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('desc', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('client_ip', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('trans_id', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('ts', 'string', 128, array(
'type' => 'string',
'length' => '128',
));
$this->hasColumn('status_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('payment_type_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->option('type', 'MyISAM');
$this->option('collate', 'utf8_general_ci');
$this->option('charset', 'utf8');
}
public function setUp()
{
parent::setUp();
$this->hasOne('Order_Model_Doctrine_OrderStatus as Status', array(
'local' => 'status_id',
'foreign' => 'id'));
$this->hasOne('Order_Model_Doctrine_PaymentType as PaymentType', array(
'local' => 'payment_type_id',
'foreign' => 'id'));
$this->hasOne('Order_Model_Doctrine_Order as Order', array(
'local' => 'id',
'foreign' => 'payment_id'));
$timestampable0 = new Doctrine_Template_Timestampable();
$softdelete0 = new Doctrine_Template_SoftDelete();
$this->actAs($timestampable0);
$this->actAs($softdelete0);
}
}<file_sep>/application/modules/order/library/DataTables/Coupon.php
<?php
/**
* Order_DataTables_Coupon
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Coupon extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Order_DataTables_Adapter_Coupon';
}
}
<file_sep>/application/modules/testimonial/models/Doctrine/TestimonialTranslationTable.php
<?php
/**
* Testimonial_Model_Doctrine_TestimonialTranslationTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Testimonial_Model_Doctrine_TestimonialTranslationTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Testimonial_Model_Doctrine_TestimonialTranslationTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Testimonial_Model_Doctrine_TestimonialTranslation');
}
}<file_sep>/application/modules/order/models/Doctrine/BaseDelivery.php
<?php
/**
* Order_Model_Doctrine_BaseDelivery
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property integer $id
* @property integer $delivery_type_id
* @property integer $delivery_address_id
* @property decimal $delivery_cost
* @property integer $status_id
* @property Order_Model_Doctrine_OrderStatus $Status
* @property Order_Model_Doctrine_DeliveryType $DeliveryType
* @property Order_Model_Doctrine_DeliveryAddress $DeliveryAddress
* @property Order_Model_Doctrine_Order $Order
*
* @package Admi
* @subpackage Order
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class Order_Model_Doctrine_BaseDelivery extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('order_delivery');
$this->hasColumn('id', 'integer', 4, array(
'primary' => true,
'autoincrement' => true,
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('delivery_type_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('delivery_address_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('delivery_cost', 'decimal', null, array(
'type' => 'decimal',
));
$this->hasColumn('status_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->option('type', 'MyISAM');
$this->option('collate', 'utf8_general_ci');
$this->option('charset', 'utf8');
}
public function setUp()
{
parent::setUp();
$this->hasOne('Order_Model_Doctrine_OrderStatus as Status', array(
'local' => 'status_id',
'foreign' => 'id'));
$this->hasOne('Order_Model_Doctrine_DeliveryType as DeliveryType', array(
'local' => 'delivery_type_id',
'foreign' => 'id'));
$this->hasOne('Order_Model_Doctrine_DeliveryAddress as DeliveryAddress', array(
'local' => 'delivery_address_id',
'foreign' => 'id'));
$this->hasOne('Order_Model_Doctrine_Order as Order', array(
'local' => 'id',
'foreign' => 'delivery_id'));
$timestampable0 = new Doctrine_Template_Timestampable();
$softdelete0 = new Doctrine_Template_SoftDelete();
$this->actAs($timestampable0);
$this->actAs($softdelete0);
}
}<file_sep>/application/modules/location/controllers/AdminController.php
<?php
/**
* Location_AdminController
*
* @author <NAME> <<EMAIL>>
*/
class Location_AdminController extends MF_Controller_Action {
public static $itemCountPerPage = 15;
public function listLocationAction() {
}
public function listLocationDataAction() {
$i18nService = $this->_service->getService('Default_Service_I18n');
$table = Doctrine_Core::getTable('Location_Model_Doctrine_Location');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Location_DataTables_Location',
'columns' => array('xt.title'),
'searchFields' => array('xt.title')
));
$results = $dataTables->getResult();
$language = $i18nService->getAdminLanguage();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result->Translation[$language->getId()]->title;
$row[] = $result->Translation[$language->getId()]->city;
$row[] = MF_Text::timeFormat($result->created_at, 'H:i d/m/Y');
$options = '<a href="' . $this->view->adminUrl('edit-location', 'location', array('id' => $result->id)) . '" title="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-location', 'location', array('id' => $result->id)) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addLocationAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$i18nService = $this->_service->getService('Default_Service_I18n');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$categoryService = $this->_service->getService('Location_Service_Category');
$translator = $this->_service->get('translate');
$adminLanguage = $i18nService->getAdminLanguage();
$form = $locationService->getLocationForm();
$metatagsForm = $metatagService->getMetatagsSubForm();
$form->addSubForm($metatagsForm, 'metatags');
$form->getElement('category_id')->setMultiOptions($categoryService->getTargetCategorySelectOptions(true,$adminLanguage->getId()));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
if($metatags = $metatagService->saveMetatagsFromArray(null, $values, array('title' => 'title', 'description' => 'content', 'keywords' => 'content'))) {
$values['metatag_id'] = $metatags->getId();
}
$location = $locationService->saveLocationFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('edit-location', 'location', array('id' => $location->getId())));
} catch(Exception $e) {
var_dump($e->getMessage());exit;
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$languages = $i18nService->getLanguageList();
$this->view->assign('adminLanguage', $adminLanguage);
$this->view->assign('languages', $languages);
$this->view->assign('form', $form);
}
public function editLocationAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$i18nService = $this->_service->getService('Default_Service_I18n');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$categoryService = $this->_service->getService('Location_Service_Category');
$translator = $this->_service->get('translate');
if(!$location = $locationService->getLocation($this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Location not found');
}
$adminLanguage = $i18nService->getAdminLanguage();
$form = $locationService->getLocationForm($location);
$metatagsForm = $metatagService->getMetatagsSubForm($location->get('Metatags'));
$form->addSubForm($metatagsForm, 'metatags');
$form->getElement('category_id')->setMultiOptions($categoryService->getTargetCategorySelectOptions(true,$adminLanguage->getId()));
$form->getElement('category_id')->setValue($location['Category']['id']);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
if($metatags = $metatagService->saveMetatagsFromArray($location->get('Metatags'), $values, array('title' => 'title', 'description' => 'content', 'keywords' => 'content'))) {
$values['metatag_id'] = $metatags->getId();
}
$location = $locationService->savelocationFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-location', 'location'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$languages = $i18nService->getLanguageList();
$this->view->assign('adminLanguage', $adminLanguage);
$this->view->assign('languages', $languages);
$this->view->assign('location', $location);
$this->view->assign('form', $form);
}
public function removeLocationAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$metatagTranslationService = $this->_service->getService('Default_Service_MetatagTranslation');
$photoService = $this->_service->getService('Media_Service_Photo');
if($location = $locationService->getLocation($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$metatag = $metatagService->getMetatag((int) $location['metatag_id']);
$photoRoot = $location->get('PhotoRoot');
$photoService->removePhoto($photoRoot);
$locationService->removeLocation($location);
$metatagService->removeMetatag($metatag);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-location', 'location'));
} catch(Exception $e) {
var_dump($e->getMessage());exit;
$this->_service->get('Logger')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-location', 'location'));
}
// ajax actions
public function addLocationPhotoAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$photoService = $this->_service->getService('Media_Service_Photo');
if(!$location = $locationService->getLocation((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Location not found');
}
$options = $this->getInvokeArg('bootstrap')->getOptions();
if(!array_key_exists('domain', $options)) {
throw new Zend_Controller_Action_Exception('Domain string not set');
}
$href = $this->getRequest()->getParam('hrefs');
if(is_string($href) && strlen($href)) {
$path = str_replace("http://" . $options['domain'], "", urldecode($href));
$filePath = urldecode($options['publicDir'] . $path);
if(file_exists($filePath)) {
$pathinfo = pathinfo($filePath);
$slug = MF_Text::createSlug($pathinfo['basename']);
$name = MF_Text::createUniqueFilename($slug, $photoService->photosDir);
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$root = $location->get('PhotoRoot');
if(!$root || $root->isInProxyState()) {
$photo = $photoService->createPhoto($filePath, $name, $pathinfo['filename'], array_keys(Location_Model_Doctrine_Location::getLocationPhotoDimensions()), false, false);
} else {
$photo = $photoService->clearPhoto($root);
$photo = $photoService->updatePhoto($root, $filePath, null, $name, $pathinfo['filename'], array_keys(Location_Model_Doctrine_Location::getLocationPhotoDimensions()), false);
}
$location->set('PhotoRoot', $photo);
$location->save();
$this->_service->get('doctrine')->getCurrentConnection()->commit();
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$list = '';
$locationPhotos = new Doctrine_Collection('Media_Model_Doctrine_Photo');
$root = $location->get('PhotoRoot');
if($root && !$root->isInProxyState()) {
$locationPhotos->add($root);
$list = $this->view->partial('admin/location-main-photo.phtml', 'location', array('photos' => $locationPhotos, 'location' => $location));
}
$this->_helper->json(array(
'status' => 'success',
'body' => $list,
'id' => $location->getId()
));
}
public function editLocationPhotoAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$photoService = $this->_service->getService('Media_Service_Photo');
$i18nService = $this->_service->getService('Default_Service_I18n');
$translator = $this->_service->get('translate');
$adminLanguage = $i18nService->getAdminLanguage();
if(!$location = $locationService->getLocation((int) $this->getRequest()->getParam('location-id'))) {
throw new Zend_Controller_Action_Exception('Location not found');
}
if(!$photo = $photoService->getPhoto((int) $this->getRequest()->getParam('id'))) {
$this->view->messages()->add($translator->translate('First you have to choose picture'), 'error');
$this->_helper->redirector->gotoUrl($this->view->adminUrl('edit-location', 'location', array('id' => $location->getId())));
}
$form = $photoService->getPhotoForm($photo);
$form->setAction($this->view->adminUrl('edit-location-photo', 'location', array('location-id' => $location->getId(), 'id' => $photo->getId())));
$photosDir = $photoService->photosDir;
$offsetDir = realpath($photosDir . DIRECTORY_SEPARATOR . $photo->getOffset());
if(strlen($photo->getFilename()) > 0 && file_exists($offsetDir . DIRECTORY_SEPARATOR . $photo->getFilename())) {
list($width, $height) = getimagesize($offsetDir . DIRECTORY_SEPARATOR . $photo->getFilename());
$this->view->assign('imgDimensions', array('width' => $width, 'height' => $height));
}
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$photo = $photoService->saveFromArray($values);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
if($this->getRequest()->getParam('saveOnly') == '1')
$this->_helper->redirector->gotoUrl($this->view->adminUrl('edit-location-photo', 'location', array('id' => $location->getId(), 'photo' => $photo->getId())));
$this->_helper->redirector->gotoUrl($this->view->adminUrl('edit-location', 'location', array('id' => $location->getId())));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('Logger')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('location', $location);
$this->view->assign('photo', $photo);
$this->view->assign('dimensions', Location_Model_Doctrine_Location::getLocationPhotoDimensions());
$this->view->assign('form', $form);
}
public function removeLocationPhotoAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$photoService = $this->_service->getService('Media_Service_Photo');
if(!$location = $locationService->getLocation((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Location not found');
}
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
if($root = $location->get('PhotoRoot')) {
if($root && !$root->isInProxyState()) {
$photo = $photoService->updatePhoto($root);
$photo->setOffset(null);
$photo->setFilename(null);
$photo->setTitle(null);
$photo->save();
}
}
$this->_service->get('doctrine')->getCurrentConnection()->commit();
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
$list = '';
$locationPhotos = new Doctrine_Collection('Media_Model_Doctrine_Photo');
$root = $location->get('PhotoRoot');
if($root && !$root->isInProxyState()) {
$locationPhotos->add($root);
$list = $this->view->partial('admin/location-main-photo.phtml', 'location', array('photos' => $locationPhotos, 'location' => $location));
}
$this->_helper->json(array(
'status' => 'success',
'body' => $list,
'id' => $location->getId()
));
}
public function refreshSponsoredLocationAction() {
$locationService = $this->_service->getService('Location_Service_Location');
if(!$location = $locationService->getLocation((int) $this->getRequest()->getParam('location-id'))) {
throw new Zend_Controller_Action_Exception('Location not found');
}
$locationService->refreshSponsoredLocation($location);
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-location', 'location'));
$this->_helper->viewRenderer->setNoRender();
}
/* category */
public function listCategoryAction() {
}
public function listCategoryDataAction() {
$i18nService = $this->_service->getService('Default_Service_I18n');
$table = Doctrine_Core::getTable('Location_Model_Doctrine_Category');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Location_DataTables_Category',
'columns' => array('xt.title', 'x.created_at'),
'searchFields' => array('xt.title')
));
$results = $dataTables->getResult();
$language = $i18nService->getAdminLanguage();
$rows = array();
foreach($results as $result) {
$row = array();
//$row['DT_RowId'] = $result->id;
$row[] = $result->Translation[$language->getId()]->title;
$options = '<a href="' . $this->view->adminUrl('edit-category', 'location', array('id' => $result->id)) . '" title="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-category', 'location', array('id' => $result->id)) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addCategoryAction() {
$categoryService = $this->_service->getService('Location_Service_Category');
$i18nService = $this->_service->getService('Default_Service_I18n');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$translator = $this->_service->get('translate');
$adminLanguage = $i18nService->getAdminLanguage();
$form = $categoryService->getCategoryForm();
$metatagsForm = $metatagService->getMetatagsSubForm();
$form->addSubForm($metatagsForm, 'metatags');
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
if($metatags = $metatagService->saveMetatagsFromArray(null, $values, array('title' => 'title'))) {
$values['metatag_id'] = $metatags->getId();
}
$category = $categoryService->saveCategoryFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-category', 'location'));
} catch(Exception $e) {
var_dump($e->getMessage());exit;
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$languages = $i18nService->getLanguageList();
$this->view->assign('adminLanguage', $adminLanguage);
$this->view->assign('languages', $languages);
$this->view->assign('form', $form);
}
public function editCategoryAction() {
$categoryService = $this->_service->getService('Location_Service_Category');
$i18nService = $this->_service->getService('Default_Service_I18n');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$translator = $this->_service->get('translate');
if(!$category = $categoryService->getCategory($this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Category not found');
}
$adminLanguage = $i18nService->getAdminLanguage();
$form = $categoryService->getCategoryForm($category);
$metatagsForm = $metatagService->getMetatagsSubForm($category->get('Metatags'));
$form->addSubForm($metatagsForm, 'metatags');
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$category = $categoryService->saveCategoryFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-category', 'location'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$languages = $i18nService->getLanguageList();
$this->view->assign('adminLanguage', $adminLanguage);
$this->view->assign('languages', $languages);
$this->view->assign('location', $location);
$this->view->assign('form', $form);
}
public function removeCategoryAction() {
$categoryService = $this->_service->getService('Location_Service_Category');
if($category = $categoryService->getCategory($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$categoryService->removeCategory($category);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-category', 'location'));
} catch(Exception $e) {
$this->_service->get('Logger')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-category', 'location'));
}
}
<file_sep>/application/modules/order/models/Doctrine/OrderTable.php
<?php
/**
* Order_Model_Doctrine_OrderTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Order_Model_Doctrine_OrderTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Order_Model_Doctrine_OrderTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Order_Model_Doctrine_Order');
}
public function getFullOrderQuery() {
$q = $this->createQuery('o')
->addSelect('o.*')
->addSelect('u.*')
->addSelect('pr.*')
->addSelect('i.*')
->addSelect('d.*')
->addSelect('da.*')
->addSelect('prod.*')
->addSelect('tr.*')
->leftJoin('o.Delivery d')
->leftJoin('d.DeliveryAddress da')
->leftJoin('o.User u')
->leftJoin('u.Profile pr')
->leftJoin('o.Items i')
->leftJoin('i.Product prod')
->leftJoin('prod.Translation tr')
;
return $q;
}
}<file_sep>/application/modules/order/library/DataTables/Delivery.php
<?php
/**
* Order_DataTables_Delivery
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Delivery extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Order_DataTables_Adapter_Delivery';
}
}
<file_sep>/application/modules/affilateprogram/forms/Partner.php
<?php
/**
* Affilateprogram_Form_Partner
*
* @author <NAME> <<EMAIL>>
*/
class Affilateprogram_Form_Partner extends Admin_Form {
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$name = $this->createElement('text', 'name');
$name->setLabel('Name');
$name->setRequired(true);
$name->setDecorators(self::$textDecorators);
$name->setAttrib('class', 'span8');
$discount = $this->createElement('text', 'discount');
$discount->setLabel('Discount in %');
$discount->setRequired(true);
$discount->setDecorators(self::$textDecorators);
$discount->setAttrib('class', 'span8');
$comission = $this->createElement('text', 'comission');
$comission->setLabel('Comission in %');
$comission->setRequired(true);
$comission->setDecorators(self::$textDecorators);
$comission->setAttrib('class', 'span8');
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Save');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$id,
$name,
$discount,
$comission,
$submit
));
}
}
<file_sep>/application/modules/order/controllers/IndexController.php
<?php
/**
* Order_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class Order_IndexController extends MF_Controller_Action {
public function indexAction() {
}
}
<file_sep>/application/modules/order/models/Doctrine/Payment.php
<?php
/**
* Order_Model_Doctrine_Payment
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package Admi
* @subpackage Order
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Order_Model_Doctrine_Payment extends Order_Model_Doctrine_BasePayment
{
public function getId() {
return $this->_get('id');
}
public function getTs() {
return $this->_get('ts');
}
public function getStatus() {
return $this->_get('status');
}
public function setStatus($status) {
$this->_set('status', $status);
}
public function getStatusId() {
return $this->_get('status_id');
}
public function setStatusId($statusId) {
$this->_set('status_id', $statusId);
}
public function setErrorStatus($errorStatus) {
$this->_set('error_status', $errorStatus);
}
public function getTransId() {
return $this->_get('trans_id');
}
public function setTransId($transId) {
$this->_set('trans_id', $transId);
}
public function setTs($ts) {
$this->_set('ts', $ts);
}
public function getDesc() {
return $this->_get('desc');
}
public function setDesc($desc) {
$this->_set('desc', $desc);
}
}<file_sep>/application/modules/league/forms/PersonalData.php
<?php
class Order_Form_PersonalData extends Admin_Form
{
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$date = $this->createElement('text', 'date');
$date->setDecorators(self::$textDecorators);
$date->setAttrib('class', 'span8 date');
for($j=1;$j<5;$j++):
${'time'.$j} = $this->createElement('text', 'team'.$j);
${'time'.$j}->setDecorators(self::$textDecorators);
${'time'.$j}->setAttrib('class', 'span8 time');
$this->addElement(${'time'.$j});
endfor;
for($i=1;$i<=10;$i++):
${'team'.$i} = $this->createElement('select', 'team'.$i);
${'team'.$i}->setDecorators(User_BootstrapForm::$bootstrapElementDecorators);
${'team'.$i}->setAttrib('class', 'span8');
$this->addElement(${'team'.$j});
endfor;
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Save');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$submit
));
}
}<file_sep>/application/modules/tournament/models/Doctrine/PlayerTable.php
<?php
/**
* Tournament_Model_Doctrine_PlayerTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Tournament_Model_Doctrine_PlayerTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Tournament_Model_Doctrine_PlayerTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Tournament_Model_Doctrine_Player');
}
}<file_sep>/application/modules/order/library/DataTables/DeliveryType.php
<?php
/**
* Order_DataTables_DeliveryType
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_DeliveryType extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Order_DataTables_Adapter_DeliveryType';
}
}
<file_sep>/application/modules/testimonial/services/Testimonial.php
<?php
/**
* Testimonial_Service_Testimonial
*
* @author <NAME> <<EMAIL>>
*/
class Testimonial_Service_Testimonial extends MF_Service_ServiceAbstract {
protected $testimonialTable;
public static $testimonialItemCountPerPage = 5;
public static function getTestimonialItemCountPerPage(){
return self::$testimonialItemCountPerPage;
}
public function init() {
$this->testimonialTable = Doctrine_Core::getTable('Testimonial_Model_Doctrine_Testimonial');
}
public function getTestimonial($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->testimonialTable->findOneBy($field, $id, $hydrationMode);
}
public function getTestimonialForm(Testimonial_Model_Doctrine_Testimonial $testimonial = null) {
$form = new Testimonial_Form_Testimonial();
if(null != $testimonial) {
$form->populate($testimonial->toArray());
$i18nService = MF_Service_ServiceBroker::getInstance()->getService('Default_Service_I18n');
$languages = $i18nService->getLanguageList();
foreach($languages as $language) {
$i18nSubform = $form->translations->getSubForm($language);
if($i18nSubform) {;
$i18nSubform->getElement('description')->setValue($testimonial->Translation[$language]->description);
}
}
}
return $form;
}
public function saveTestimonialFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$testimonial = $this->testimonialTable->getProxy($values['id'])) {
$testimonial = $this->testimonialTable->getRecord();
}
$i18nService = MF_Service_ServiceBroker::getInstance()->getService('Default_Service_I18n');
$testimonial->fromArray($values);
$languages = $i18nService->getLanguageList();
foreach($languages as $language) {
if(is_array($values['translations'][$language])) {
$testimonial->Translation[$language]->description = $values['translations'][$language]['description'];
}
}
$testimonial->save();
if(isset($values['parent_id'])) {
$parent = $this->getTestimonial((int) $values['parent_id']);
$testimonial->getNode()->insertAsLastChildOf($parent);
}
return $testimonial;
}
public function getTestimonialTree() {
return $this->testimonialTable->getTree();
}
public function getTestimonialRoot() {
return $this->getTestimonialTree()->fetchRoot();
}
public function createTestimonialRoot() {
$testimonial = $this->testimonialTable->getRecord();
$testimonial->save();
$tree = $this->getTestimonialTree();
$tree->createRoot($testimonial);
return $testimonial;
}
public function moveTestimonial($testimonial, $mode) {
switch($mode) {
case 'up':
$prevSibling = $testimonial->getNode()->getPrevSibling();
if($prevSibling->getNode()->isRoot()) {
throw new Exception('Cannot move category on root level');
}
$testimonial->getNode()->moveAsPrevSiblingOf($prevSibling);
break;
case 'down':
$nextSibling = $testimonial->getNode()->getNextSibling();
if($nextSibling->getNode()->isRoot()) {
throw new Exception('Cannot move category on root level');
}
$testimonial->getNode()->moveAsNextSiblingOf($nextSibling);
break;
}
}
public function getPublicTestimonials($language, $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->testimonialTable->getTestimonialQuery();
$q->andWhere('tt.lang = ?', $language);
$q->andWhere('t.status = ?', 1);
$q->addOrderBy('t.lft ASC');
return $q->execute(array(), $hydrationMode);
}
public function getTestimonialsPaginationQuery($language) {
$q = $this->testimonialTable->getTestimonialQuery();
$q->andWhere('tt.lang = ?', $language);
$q->andWhere('t.status = ?', 1);
$q->addOrderBy('t.lft ASC');
return $q;
}
public function removeTestimonial(Testimonial_Model_Doctrine_Testimonial $testimonial) {
$testimonial->getNode()->delete();
$testimonial->delete();
}
public function refreshStatusTestimonial($testimonial){
if ($testimonial->isStatus()):
$testimonial->setStatus(0);
else:
$testimonial->setStatus(1);
endif;
$testimonial->save();
}
}
<file_sep>/application/modules/order/controllers/CartController.php
<?php
/**
* Order_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class Order_CartController extends MF_Controller_Action {
public function miniCartAction(){
$this->_helper->layout->disableLayout();
$cartService = $this->_service->getService('Order_Service_Cart');
$cart = $cartService->getCart();
$cartItems = $cart->get('Product_Model_Doctrine_Product');
$this->view->assign('cartItems', $cartItems);
$this->view->assign('cart', $cart);
}
public function cartAction() {
$cartService = $this->_service->getService('Order_Service_Cart');
$productService = $this->_service->getService('Product_Service_Product');
$couponService = $this->_service->getService('Order_Service_Coupon');
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
$translator = $this->_service->get('translate');
$form = $cartService->getDiscountCodeForm();
$form->getElement('discount_code')->setAttrib('placeholder', $translator->translate('Enter a coupon code'));
$cart = $cartService->getCart();
$items = $cart->get('Product_Model_Doctrine_Product');
$productsIds = array();
foreach($items as $productId=>$item):
$productsIds[] = $productId;
endforeach;
if($productsIds):
$products = $productService->getPreSortedProductCart($productsIds);
endif;
$user = $this->_helper->user();
if($user):
$userDiscount = $user['Discount']->toArray();
$userGroups = $user->get("Groups");
endif;
$userGroupDiscounts = array();
foreach($userGroups as $userGroup):
$userGroupDiscounts[] = $userGroup['Discount']->toArray();
endforeach;
if (isset($_COOKIE["reference_number"])):
$partner = $affilateProgramService->getPartner($_COOKIE["reference_number"], 'reference_number');
endif;
$count = $cart->count();
$totalPrice = 0;
foreach($products as $product):
foreach($items as $id=>$item):
if($product->getId() == $id):
$arrayDiscounts = array($product['Discount'], $product['Producer']['Discount'], $userDiscount);
foreach($userGroupDiscounts as $userGroupDiscount):
$arrayDiscounts[] = $userGroupDiscount;
endforeach;
$flag = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$flag = $flag['flag'];
if($flag || $product['promotion']):
if($product['promotion']):
if($flag):
$price = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$price = $price['price'];
$totalPrice += $price*$item[""]['count'];
else:
$totalPrice += $product['promotion_price']*$item[""]['count'];
endif;
elseif($flag):
$price = MF_Discount::getPriceWithDiscount($product['price'], $arrayDiscounts);
$price = $price['price'];
$totalPrice += $price*$item[""]['count'];
endif;
else:
$totalPrice += $product['price']*$item[""]['count'];
endif;
endif;
endforeach;
endforeach;
$noCouponPrice = $totalPrice;
if (isset($_COOKIE["discount_code"])):
$coupon = $couponService->getCoupon($_COOKIE["discount_code"], 'code');
if ($coupon->getType() == "percent"):
$totalPrice = $totalPrice - ($coupon->getAmount()*$totalPrice/100);
$couponAmount = $coupon->getAmount()."%";
elseif ($coupon->getType() == "amount"):
$totalPrice = $totalPrice - $coupon->getAmount();
$couponAmount = $coupon->getAmount()." zł";
endif;
endif;
if ($partner):
$discountPartner = ($totalPrice*$partner->getDiscount())/100;
endif;
$this->view->assign('userDiscount', $userDiscount);
$this->view->assign('userGroupDiscounts', $userGroupDiscounts);
$this->view->assign('items', $items);
$this->view->assign('count', $count);
$this->view->assign('products', $products);
$this->view->assign('totalPrice', $totalPrice);
$this->view->assign('noCouponPrice', $noCouponPrice);
$this->view->assign('coupon', $coupon);
$this->view->assign('partner', $partner);
$this->view->assign('discountPartner', $discountPartner);
$this->view->assign('form', $form);
$this->view->assign('hideSlider', true);
$this->view->assign('coupon',$coupon);
$this->_helper->actionStack('layout', 'index', 'default');
}
public function checkoutAction() {
$cartService = $this->_service->getService('Order_Service_Cart');
$productService = $this->_service->getService('Product_Service_Product');
$couponService = $this->_service->getService('Order_Service_Coupon');
$orderService = $this->_service->getService('Order_Service_Order');
$deliveryTypeService = $this->_service->getService('Order_Service_DeliveryType');
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
$userService = $this->_service->getService('User_Service_User');
$locationService = $this->_service->getService('Default_Service_Location');
$auth = $this->_service->getService('User_Service_Auth');
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
$translator = $this->_service->get('translate');
$loginForm = new User_Form_Login();
$loginForm->setElementDecorators(User_BootstrapForm::$bootstrapElementDecorators);
//$loginForm->getElement('remember')->setDecorators(User_BootstrapForm::$bootstrapSubmitDecorators);
$loginForm->getElement('submit')->setAttrib('class','button_type_5 m_bottom_10 m_right_20 tr_all color_blue transparent fs_medium r_corners');
$loginForm->getElement('submit')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$loginForm->getElement('username')->setAttrib('class', 'r_corners color_grey w_full fw_light');
$loginForm->getElement('username')->setAttrib('placeholder', 'Email');
$loginForm->getElement('username')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$loginForm->getElement('password')->setAttrib('class', 'r_corners color_grey w_full fw_light');
$loginForm->getElement('password')->setAttrib('placeholder', $translator->translate('Password'));
$loginForm->getElement('password')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$loginForm->getElement('remember')->setAttrib('class','d_none');
$loginForm->getElement('remember')->removeDecorator(array('ElementWrapper','Wrapper','Label','DtDdWrapper','Description'));
$orderForm = $userService->getOrderForm();
//$orderForm->getElement('province')->setMultiOptions($locationService->getProvinceSelectOptions());
$orderForm->getElement('country')->setMultiOptions($locationService->getCountrySelectOptions());
$orderForm->getElement('country')->setValue('Poland');
$orderForm->getElement('name')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('name')->setAttrib('placeholder', 'np. <NAME>');
$orderForm->getElement('name')->setAttrib('class', 'r_corners fw_light color_grey w_full');
$orderForm->getElement('country')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('country')->setAttrib('class', 'bg_light select_title r_corners fw_light color_grey');
$orderForm->getElement('postal_code')->setAttrib('placeholder', 'np. 56-200');
$orderForm->getElement('postal_code')->setAttrib('class', 'r_corners fw_light color_grey w_full fe_width_1');
$orderForm->getElement('postal_code')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('address')->setAttrib('placeholder', 'np. Śliska 25');
$orderForm->getElement('address')->setAttrib('class', 'r_corners fw_light color_grey w_full');
$orderForm->getElement('address')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('city')->setAttrib('placeholder', 'np. Wrocław');
$orderForm->getElement('city')->setAttrib('class', 'r_corners fw_light color_grey w_full');
$orderForm->getElement('city')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('contact_email')->setAttrib('placeholder', 'np. <EMAIL>');
$orderForm->getElement('contact_email')->setAttrib('class', 'r_corners fw_light color_grey fe_width_2 w_xs_full');
$orderForm->getElement('contact_email')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('contact_number')->setAttrib('placeholder', 'np. 500300600');
$orderForm->getElement('contact_number')->setAttrib('class', 'r_corners fw_light color_grey fe_width_2 w_xs_full');
$orderForm->getElement('contact_number')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('attention')->setAttrib('class', 'height_2 h_max_100');
$orderForm->getElement('invoice')->setAttrib('class', 'm_right_10 m_top_8 m_xs_top_0 d_none');
$orderForm->getElement('invoice')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('invoice_company_name')->setAttrib('placeholder', 'np. Microsoft sp.z o.o.');
$orderForm->getElement('invoice_company_name')->setAttrib('class', 'r_corners fw_light color_grey w_xs_full');
$orderForm->getElement('invoice_company_name')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('invoice_city')->setAttrib('placeholder', 'np. Poznań');
$orderForm->getElement('invoice_city')->setAttrib('class', 'r_corners fw_light color_grey w_xs_full');
$orderForm->getElement('invoice_city')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('invoice_address')->setAttrib('placeholder', 'np. Krakowska 25');
$orderForm->getElement('invoice_address')->setAttrib('class', 'r_corners fw_light color_grey w_xs_full');
$orderForm->getElement('invoice_address')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('invoice_postal_code')->setAttrib('placeholder', 'np. Microsoft sp.z o.o.');
$orderForm->getElement('invoice_postal_code')->setAttrib('class', 'r_corners fw_light color_grey w_xs_full fe_width_1');
$orderForm->getElement('invoice_postal_code')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
$orderForm->getElement('invoice_nip')->setAttrib('placeholder', 'np. 2998033475');
$orderForm->getElement('invoice_nip')->setAttrib('class', 'r_corners fw_light color_grey w_xs_full');
$orderForm->getElement('invoice_nip')->removeDecorator(array('ElementWrapper','Wrapper','Label'));
//$orderForm->getElement('delivery_type_id')->getDeco();
$orderForm->getElement('delivery_type_id')->setMultiOptions($deliveryTypeService->getTargetDeliveryTypeSelectOptionsSorted());
$orderForm->getElement('delivery_type_id')->setAttrib('class','d_inline_m m_right_15 m_bottom_3 fw_light');
$orderForm->getElement('delivery_type_id')->removeDecorator(array('HtmlTag'));
$orderForm->getElement('payment_type_id')->setMultiOptions($paymentTypeService->getTargetPaymentTypeRadioOptions());
$options = $this->getFrontController()->getParam('bootstrap')->getOptions();
$contactEmail = $options['reply_email'];
$cart = $cartService->getCart();
$user = $this->_helper->user();
if($user):
$userDiscount = $user['Discount']->toArray();
$userGroups = $user->get("Groups");
endif;
$userGroupDiscounts = array();
foreach($userGroups as $userGroup):
$userGroupDiscounts[] = $userGroup['Discount']->toArray();
endforeach;
if ($user){
$orderForm->removeElement('contact_email');
}
if($this->getRequest()->isPost()) {
$dataPost = $this->getRequest()->getParams();
if ($dataPost['type'] == 'order-form'){
if ($dataPost['other_address'] == 1 || $dataPost['other_address'] == NULL):
$orderForm->getElement('name')->setRequired();
$orderForm->getElement('city')->setRequired();
$orderForm->getElement('address')->setRequired();
$orderForm->getElement('postal_code')->setRequired();
$address = true;
endif;
if ($dataPost['delivery_type_id']):
$deliveryType = $deliveryTypeService->getDeliveryType($dataPost['delivery_type_id']);
if ($deliveryType->getType() == "przelew"){
$orderForm->getElement('payment_type_id')->setRequired();
}
endif;
if ($dataPost['invoice']):
$orderForm->getElement('invoice_company_name')->setRequired();
$orderForm->getElement('invoice_city')->setRequired();
$orderForm->getElement('invoice_address')->setRequired();
$orderForm->getElement('invoice_postal_code')->setRequired();
$orderForm->getElement('invoice_nip')->setRequired();
$address = true;
endif;
if($orderForm->isValid($this->getRequest()->getPost()) && $cart->get('Product_Model_Doctrine_Product') != NULL) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $orderForm->getValues();
if ($user){
$values['user_id'] = $user->getId();
}
$items = $cart->get('Product_Model_Doctrine_Product');
$productsIds = array();
foreach($items as $productId=>$item):
$productsIds[] = $productId;
endforeach;
if($productsIds):
$products = $productService->getPreSortedProductCart($productsIds);
endif;
// check availability
foreach($products as $product):
foreach($items as $id=>$item):
if($product->getId() == $id):
if ($product->getAvailability() < $item[""]['count']):
throw new Order_Model_ProductAvailabilityExistsException($product->Translation[$this->view->language]->name);
endif;
endif;
endforeach;
endforeach;
// end check availability
//payment
if ($deliveryType->getType() == "przelew" && $values['payment_type_id'] != NULL){
$valuesPayment = $values;
$valuesPayment['status_id'] = 3;
$payment = $orderService->savePaymentFromArray($valuesPayment);
}
if ($deliveryType->getId() == 9 && $values['payment_type_id'] != NULL){
$valuesPayment = $values;
$valuesPayment['status_id'] = 8;
$payment = $orderService->savePaymentFromArray($valuesPayment);
}
// endpayment
// address
if ($address):
$deliveryAddress = $orderService->saveDeliveryAddressFromArray($values);
endif;
// address
// delivery
$valuesDelivery = $values;
$valuesDelivery['status_id'] = "2";
if ($deliveryAddress){
$valuesDelivery['delivery_address_id'] = $deliveryAddress->getId();
}
$delivery = $orderService->saveDeliveryFromArray($valuesDelivery);
// end delivery
// invoice
if ($values['invoice'] == 1){
$invoice = $orderService->saveInvoiceFromArray($values);
}
// end invoice
// calculate sum
if (isset($_COOKIE["discount_code"])):
$coupon = $couponService->getCoupon($_COOKIE["discount_code"], 'code');
endif;
if (isset($_COOKIE["reference_number"])):
$partner = $affilateProgramService->getPartner($_COOKIE["reference_number"], 'reference_number');
endif;
if($payment):
$values['payment_id'] = $payment->getId();
endif;
if($invoice):
$values['invoice_id'] = $invoice->getId();
endif;
$values['delivery_id'] = $delivery->getId();
$values['order_status_id'] = 1;
$order = $orderService->saveOrderFromArray($values);
$totalPrice = 0;
//$relatesProducts = array();
foreach($products as $product):
foreach($items as $id=>$item):
if($product->getId() == $id):
$arrayDiscounts = array($product['Discount'], $product['Producer']['Discount'], $userDiscount);
foreach($userGroupDiscounts as $userGroupDiscount):
$arrayDiscounts[] = $userGroupDiscount;
endforeach;
$flag = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$flag = $flag['flag'];
$valuesItem = array();
$valuesItem['order_id'] = $order->getId();
$valuesItem['product_id'] = $product->getId();
$valuesItem['number'] = $item[""]['count'];
if($flag || $product['promotion']):
if($product['promotion']):
if($flag):
$price = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$valuesItem['discount_id'] = $price['discount_id'];
$price = $price['price'];
$valuesItem['price'] = $price;
$totalPrice += $price*$item[""]['count'];
else:
$valuesItem['price'] = $product['promotion_price'];
$totalPrice += $product['promotion_price']*$item[""]['count'];
endif;
elseif($flag):
$price = MF_Discount::getPriceWithDiscount($product['price'], $arrayDiscounts);
$valuesItem['discount_id'] = $price['discount_id'];
$price = $price['price'];
$valuesItem['price'] = $price;
$totalPrice += $price*$item[""]['count'];
endif;
else:
$valuesItem['price'] = $product['price'];
$totalPrice += $product['price']*$item[""]['count'];
endif;
$product->setAvailability($product->getAvailability()-$item[""]['count']);
$productService->setSetItemsAvailability($product,$item[""]['count']);
$product->setOrderCounter($product->getOrderCounter()+1);
$product->save();
$orderService->saveItemFromArray($valuesItem);
//$relatesProducts[] = $product;
endif;
endforeach;
endforeach;
// save relates
$relatesIds = array();
foreach($items as $id=>$item):
$relatesIds[$id] = $id;
endforeach;
$productService->saveRelates($relatesIds);
// end saving relates
// check partner
if ($partner):
$totalPrice = $totalPrice-(($totalPrice*$partner->getDiscount())/100);
$affilateProgramService->saveOrderForPartner($order->getId(), $partner->getId());
endif;
// end check partner
// check coupon
if($coupon):
if (!$coupon->isUsed() && MF_Coupon::isValid($coupon)){
$valid = true;
}
endif;
if ($valid):
if ($coupon->getType() == "percent"):
$totalPrice = $totalPrice - ($coupon->getAmount()*$totalPrice/100);
endif;
if ($coupon->getType() == "amount"):
$totalPrice = $totalPrice - $coupon->getAmount();
endif;
$coupon->setOrderId($order->getId());
$coupon->setUsed(true);
if ($user):
$coupon->setUserId($user->getId());
endif;
$coupon->save();
setcookie("discount_code", null, time()-1000, '/');
endif;
// end check coupon
if ($totalPrice < 0):
$totalPrice = 0;
endif;
$deliveryType = $deliveryTypeService->getDeliveryType($values['delivery_type_id']);
if ($deliveryType):
if ($deliveryType->getPrice() != 0){
$deliveryPrice = $deliveryType->getPrice();
}
else{
if ($deliveryType['type'] == "przelew"):
$deliveryPrice = 0;
else:
$deliveryPrice = $deliveryType->getPrice();
endif;
}
endif;
$totalPrice = $totalPrice + $deliveryPrice;
// end calculate sum
$order->setTotalCost($totalPrice);
$order->save();
$cart->clean();
$mail = new Zend_Mail('UTF-8');
$mail->setSubject($translator->translate('Thank you for your order.'));
if ($user):
$mail->addTo($user->getEmail(), $user->getFirstName() . ' ' . $user->getLastName());
else:
$mail->addTo($values['contact_email'], $values['name']);
endif;
$mail->setReplyTo($contactEmail, 'System zamówień bodyempire.pl');
if($deliveryType->getId() == 11):
$orderService->sendConfirmationMailWithPaymentByTransferPayment($mail, $order, $this->view->language, $this->view);
endif;
if($payment && $deliveryType->getId() == 10):
$orderService->sendConfirmationMailWithPaymentByCourierCollection($mail, $order, $this->view->language, $this->view);
endif;
if($payment && $deliveryType->getId() == 1):
$orderService->sendConfirmationMailWithPaymentByTransferWithCollection($mail, $order, $this->view->language, $this->view);
endif;
if(!$payment):
$orderService->sendConfirmationMailWithPaymentByCash($mail, $order, $this->view->language, $this->view);
endif;
$mail2 = new Zend_Mail('UTF-8');
$mail2->setSubject('bodyempire.pl - Order - '.$order->getId());
$mail2->addTo($contactEmail);
$orderService->sendConfirmationWithOrderToUs($user, $order, $mail2, $this->view);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoRoute(array('payment' => $payment['id'], 'order' => $order->getId()), 'domain-i18n:order-complete');
} catch(Order_Model_ProductAvailabilityExistsException $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->view->messages()->add($e->getMessage(), "test");
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
else{
var_dump($orderForm->getMessage());exit;
}
}
else{
if($loginForm->isValid($this->getRequest()->getParams())) {
$user = $userService->getUser($loginForm->getValue('username'), 'email');
if ($user && !$user->isActive()):
$loginForm->addErrorMessage($this->view->translate('User is not active'));
$loginForm->getElement('username')->markAsError();
$loginForm->getElement('username')->setErrors(array($this->view->translate('User is not active')));
$user = NULL;
else:
$result = $auth->authenticate($loginForm->getValue('username'), $loginForm->getValue('password'));
switch($result->getCode()) {
case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
$loginForm->getElement('username')->markAsError();
$loginForm->getElement('username')->setErrors(array($this->view->translate('User not found!!!')));
$user = NULL;
break;
case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
$loginForm->getElement('password')->markAsError();
$loginForm->getElement('password')->setErrors(array($this->view->translate('Credential invalid!!!')));
$user = NULL;
break;
}
endif;
}
}
}
if ($user){
$orderForm->removeElement('contact_email');
$profile = $user->get('Profile');
}
$items = $cart->get('Product_Model_Doctrine_Product');
if ($items == NULL){
$this->_helper->redirector->gotoRoute(array(), 'domain-i18n:cart');
}
$orderForm->getElement('type')->setValue("order-form");
if(!$user || !$user->getFirstName() || !$user->getLastName() || !$profile->getProvince() ||
!$profile->getCity() || !$profile->getAddress() || !$profile->getPostalCode()){
$orderForm->removeElement('other_address');
if ($user){
if ($user->getFirstName() && $user->getLastName()){
$orderForm->getElement('name')->setValue($user->getFirstName()." ".$user->getLastName());
}
if ($profile->getProvince()){
$orderForm->getElement('province')->setValue($profile->getProvince());
}
if ($profile->getCountry()){
$orderForm->getElement('country')->setValue($profile->getCountry());
}
if ($profile->getCity()){
$orderForm->getElement('city')->setValue($profile->getCity());
}
if ($profile->getAddress()){
$orderForm->getElement('address')->setValue($profile->getAddress());
}
if ($profile->getPostalCode()){
$orderForm->getElement('postal_code')->setValue($profile->getPostalCode());
}
if ($profile->getPhone()){
$orderForm->getElement('contact_number')->setValue($profile->getPhone());
}
}
}
// invoice data
if ($user):
if ($profile->getCompanyName()){
$orderForm->getElement('invoice_company_name')->setValue($profile->getCompanyName());
}
if ($profile->getCity()){
$orderForm->getElement('invoice_city')->setValue($profile->getCity());
}
if ($profile->getAddress()){
$orderForm->getElement('invoice_address')->setValue($profile->getAddress());
}
if ($profile->getPostalCode()){
$orderForm->getElement('invoice_postal_code')->setValue($profile->getPostalCode());
}
if ($profile->getNip()){
$orderForm->getElement('invoice_nip')->setValue($profile->getNip());
}
endif;
// end invoice data
$productsIds = array();
foreach($items as $productId=>$item):
$productsIds[] = $productId;
endforeach;
if($productsIds):
$products = $productService->getPreSortedProductCart($productsIds);
endif;
$user = $this->_helper->user();
if($user):
$userDiscount = $user['Discount']->toArray();
$userGroups = $user->get("Groups");
endif;
$userGroupDiscounts = array();
foreach($userGroups as $userGroup):
$userGroupDiscounts[] = $userGroup['Discount']->toArray();
endforeach;
if (isset($_COOKIE["discount_code"])):
$coupon = $couponService->getCoupon($_COOKIE["discount_code"], 'code');
endif;
if (isset($_COOKIE["reference_number"])):
$partner = $affilateProgramService->getPartner($_COOKIE["reference_number"], 'reference_number');
endif;
$totalPrice = 0;
foreach($products as $product):
foreach($items as $id=>$item):
if($product->getId() == $id):
$arrayDiscounts = array($product['Discount'], $product['Producer']['Discount'], $userDiscount);
foreach($userGroupDiscounts as $userGroupDiscount):
$arrayDiscounts[] = $userGroupDiscount;
endforeach;
$flag = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$flag = $flag['flag'];
if($flag || $product['promotion']):
if($product['promotion']):
if($flag):
$price = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$price = $price['price'];
$totalPrice += $price*$item[""]['count'];
else:
$totalPrice += $product['promotion_price']*$item[""]['count'];
endif;
elseif($flag):
$price = MF_Discount::getPriceWithDiscount($product['price'], $arrayDiscounts);
$price = $price['price'];
$totalPrice += $price*$item[""]['count'];
endif;
else:
$totalPrice += $product['price']*$item[""]['count'];
endif;
endif;
endforeach;
endforeach;
$noCouponPrice = $totalPrice;
if ($partner):
$discountPartner = ($totalPrice*$partner->getDiscount())/100;
$totalPrice = $totalPrice-(($totalPrice*$partner->getDiscount())/100);
endif;
$valid = false;
if($coupon):
if (!$coupon->isUsed() && MF_Coupon::isValid($coupon)){
$valid = true;
}
endif;
if ($valid):
if ($coupon->getType() == "percent"):
$couponValue = $coupon->getAmount()." %";
$totalPrice = $totalPrice - ($totalPrice*$couponValue/100);
endif;
if ($coupon->getType() == "amount"):
$couponValue = $coupon->getAmount()." zł";
$totalPrice = $totalPrice - $couponValue;
endif;
endif;
if ($totalPrice < 0):
$totalPrice = 0;
endif;
$this->view->assign('userDiscount', $userDiscount);
$this->view->assign('userGroupDiscounts', $userGroupDiscounts);
$this->view->assign('items', $items);
$this->view->assign('products', $products);
$this->view->assign('totalPrice', $totalPrice);
$this->view->assign('couponValue', $couponValue);
$this->view->assign('noCouponPrice', $noCouponPrice);
$this->view->assign('coupon', $coupon);
$this->view->assign('orderForm', $orderForm);
$this->view->assign('loginForm', $loginForm);
$this->view->assign('user', $user);
$this->view->assign('profile', $profile);
$this->view->assign('partner', $partner);
$this->view->assign('discountPartner', $discountPartner);
$this->view->assign('hideSlider', true);
$this->_helper->actionStack('layout', 'index', 'default');
}
public function orderCompleteAction() {
$payUService = $this->_service->getService('Order_Service_Payment_PayU');
$orderService = $this->_service->getService('Order_Service_Order');
$orderId = (int) $this->getRequest()->getParam('order');
$order = $orderService->getOrder($orderId);
$paymentId = (int) $this->getRequest()->getParam('payment');
// if($paymentId):
// $payment = $payUService->getFullPayment($paymentId);
//
// if ($payment->getId() == $order->getPaymentId()):
// $options = $this->getInvokeArg('bootstrap')->getOptions();
// if(!array_key_exists('payu', $options)) {
// throw new Zend_Controller_Action_Exception('An error occured');
// }
//
// $payUForm = new Order_Form_Payu_Payment();
// $payUForm->setup(array(
// 'UrlPlatnosci_pl' => $options['payu']['UrlPlatnosci_pl'],
// 'PosId' => $this->view->cms()->setting('payuPosId'),
// 'PosAuthKey' => $this->view->cms()->setting('payuPosAuthKey')
// ));
//
// $payUForm->getElement('session_id')->setValue($payment->getId());
// $payUForm->getElement('amount')->setValue($payment['Order']['total_cost']*100); // wartość w groszach
// $desc = substr($payment['Order']['Items'][0]['Product']['Translation'][$this->view->language]['name'], 0, 50);
// $desc = $desc."...";
// $payUForm->getElement('desc')->setValue($desc);
// $payUForm->getElement('client_ip')->setValue($_SERVER['REMOTE_ADDR']);
// $date = new DateTime();
// if ($payment->getTs() == NULL):
// $ts = $date->getTimestamp();
// $payment->setTs($ts);
// $payment->save();
// endif;
// $payUForm->getElement('ts')->setValue($payment->getTs());
//
// if($payment['Order']['User']):
// $payUForm->getElement('first_name')->setValue($payment['Order']['User']['first_name']);
// $payUForm->getElement('last_name')->setValue($payment['Order']['User']['last_name']);
// $payUForm->getElement('email')->setValue($payment['Order']['User']['email']);
// $sig = md5( $this->view->cms()->setting('payuPosId') .
// "" .
// $payment->getId() .
// $this->view->cms()->setting('payuPosAuthKey') .
// $payment['Order']['total_cost']*100 .
// $desc .
// "" .
// "" .
// "" .
// $payment['Order']['User']['first_name'] .
// $payment['Order']['User']['last_name'] .
// "" .
// "" .
// "" .
// "" .
// "" .
// "" .
// $payment['Order']['User']['email'] .
// "" .
// "" .
// $_SERVER['REMOTE_ADDR'] .
// $payment->getTs() .
// $this->view->cms()->setting('key1')
// );
// $payUForm->getElement('sig')->setValue($sig);
// else:
// $name = explode(' ', $payment['Order']['Delivery']['DeliveryAddress']['name']);
// $first_name = $name[0];
// for($i=1;$i<count($name);$i++):
// $last_name .= $name[$i]." ";
// endfor;
// $payUForm->getElement('first_name')->setValue($first_name);
// $payUForm->getElement('last_name')->setValue($last_name);
// $payUForm->getElement('email')->setValue($payment['Order']['contact_email']);
// $sig = md5( $this->view->cms()->setting('payuPosId') .
// "" .
// $payment->getId() .
// $this->view->cms()->setting('payuPosAuthKey') .
// $payment['Order']['total_cost']*100 .
// $desc .
// "" .
// "" .
// "" .
// $first_name .
// $last_name .
// "" .
// "" .
// "" .
// "" .
// "" .
// "" .
// $payment['Order']['contact_email'] .
// "" .
// "" .
// $_SERVER['REMOTE_ADDR'] .
// $payment->getTs() .
// $this->view->cms()->setting('key1')
// );
// $payUForm->getElement('sig')->setValue($sig);
// endif;
// endif;
// endif;
$this->view->assign('payUForm', $payUForm);
$this->view->assign('payment', $payment);
$this->view->assign('hideSlider', true);
$this->_helper->actionStack('layout', 'index', 'default');
}
public function orderAbroadCompleteAction() {
$payUService = $this->_service->getService('Order_Service_Payment_PayU');
$orderService = $this->_service->getService('Order_Service_Order');
$orderId = (int) $this->getRequest()->getParam('order');
$order = $orderService->getOrder($orderId);
$paymentId = (int) $this->getRequest()->getParam('payment');
if($order['Payment']['id'] == $paymentId && $paymentId):
$payment = $payUService->getFullPayment($paymentId);
if ($payment->getId() == $order->getPaymentId()):
$options = $this->getInvokeArg('bootstrap')->getOptions();
if(!array_key_exists('payu', $options)) {
throw new Zend_Controller_Action_Exception('An error occured');
}
$payUForm = new Order_Form_Payu_Payment();
$payUForm->setup(array(
'UrlPlatnosci_pl' => $options['payu']['UrlPlatnosci_pl'],
'PosId' => $this->view->cms()->setting('payuPosId'),
'PosAuthKey' => $this->view->cms()->setting('payuPosAuthKey')
));
$payUForm->getElement('session_id')->setValue($payment->getId());
$payUForm->getElement('amount')->setValue($payment['Order']['total_cost']*100); // wartość w groszach
$desc = substr($payment['Order']['Items'][0]['Product']['Translation'][$this->view->language]['name'], 0, 50);
$desc = $desc."...";
$payUForm->getElement('desc')->setValue($desc);
$payUForm->getElement('client_ip')->setValue($_SERVER['REMOTE_ADDR']);
$date = new DateTime();
if ($payment->getTs() == NULL):
$ts = $date->getTimestamp();
$payment->setTs($ts);
$payment->save();
endif;
$payUForm->getElement('ts')->setValue($payment->getTs());
if($payment['Order']['User']):
$payUForm->getElement('first_name')->setValue($payment['Order']['User']['first_name']);
$payUForm->getElement('last_name')->setValue($payment['Order']['User']['last_name']);
$payUForm->getElement('email')->setValue($payment['Order']['User']['email']);
$sig = md5( $this->view->cms()->setting('payuPosId') .
"" .
$payment->getId() .
$this->view->cms()->setting('payuPosAuthKey') .
$payment['Order']['total_cost']*100 .
$desc .
"" .
"" .
"" .
$payment['Order']['User']['first_name'] .
$payment['Order']['User']['last_name'] .
"" .
"" .
"" .
"" .
"" .
"" .
$payment['Order']['User']['email'] .
"" .
"" .
$_SERVER['REMOTE_ADDR'] .
$payment->getTs() .
$this->view->cms()->setting('key1')
);
$payUForm->getElement('sig')->setValue($sig);
else:
$name = explode(' ', $payment['Order']['Delivery']['DeliveryAddress']['name']);
$first_name = $name[0];
for($i=1;$i<count($name);$i++):
$last_name .= $name[$i]." ";
endfor;
$payUForm->getElement('first_name')->setValue($first_name);
$payUForm->getElement('last_name')->setValue($last_name);
$payUForm->getElement('email')->setValue($payment['Order']['contact_email']);
$sig = md5( $this->view->cms()->setting('payuPosId') .
"" .
$payment->getId() .
$this->view->cms()->setting('payuPosAuthKey') .
$payment['Order']['total_cost']*100 .
$desc .
"" .
"" .
"" .
$first_name .
$last_name .
"" .
"" .
"" .
"" .
"" .
"" .
$payment['Order']['contact_email'] .
"" .
"" .
$_SERVER['REMOTE_ADDR'] .
$payment->getTs() .
$this->view->cms()->setting('key1')
);
$payUForm->getElement('sig')->setValue($sig);
endif;
endif;
endif;
$this->view->assign('payUForm', $payUForm);
$this->view->assign('payment', $payment);
$this->view->assign('order', $order);
$this->_helper->actionStack('layout-shop', 'index', 'default');
}
}
<file_sep>/application/modules/order/library/DataTables/PaymentType.php
<?php
/**
* Order_DataTables_PaymentType
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_PaymentType extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Order_DataTables_Adapter_PaymentType';
}
}
<file_sep>/application/modules/faq/services/Faq.php
<?php
/**
* Faq
*
* @author <NAME> <<EMAIL>>
*/
class Faq_Service_Faq extends MF_Service_ServiceAbstract {
protected $faqTable;
public static $articleItemCountPerPage = 5;
public static function getArticleItemCountPerPage(){
return self::$articleItemCountPerPage;
}
public function init() {
$this->faqTable = Doctrine_Core::getTable('Faq_Model_Doctrine_Faq');
}
public function getAllFaq($countOnly = false) {
if(true == $countOnly) {
return $this->faqTable->count();
} else {
return $this->faqTable->findAll();
}
}
public function getFaq($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->faqTable->findOneBy($field, $id, $hydrationMode);
}
public function getFullFaq($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->faqTable->getPublishFaqQuery();
$q = $this->faqTable->getPhotoQuery($q);
if(in_array($field, array('id'))) {
$q->andWhere('a.' . $field . ' = ?', array($id));
} elseif(in_array($field, array('slug'))) {
$q->andWhere('at.' . $field . ' = ?', array($id));
//$q->andWhere('at.lang = ?', 'pl');
}
return $q->fetchOne(array(), $hydrationMode);
}
public function getRecentFaq($limit, $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->faqTable->getPublishFaqQuery();
$q = $this->faqTable->getPhotoQuery($q);
$q = $this->faqTable->getLimitQuery($limit, $q);
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getNew($limit, $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->faqTable->getPublishFaqQuery();
$q = $this->faqTable->getPhotoQuery($q);
$q = $this->faqTable->getLimitQuery($limit, $q);
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getFaqPaginationQuery($language) {
$q = $this->faqTable->getPublishFaqQuery();
$q = $this->faqTable->getPhotoQuery($q);
$q->andWhere('at.lang = ?', $language);
$q->addOrderBy('a.sponsored DESC');
$q->addOrderBy('a.publish_date DESC');
return $q;
}
public function getFaqOnMainPage($limit, $language, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
$q = $this->faqTable->getPublishFaqQuery();
$q = $this->faqTable->getPhotoQuery($q);
$q->andWhere('at.lang = ?', $language);
$q->addOrderBy('a.sponsored DESC');
$q->addOrderBy('a.publish_date DESC');
$q->limit($limit);
return $q->execute(array(), $hydrationMode);
}
public function getFaqForm(Faq_Model_Doctrine_Faq $faq = null) {
$form = new Faq_Form_Faq();
$form->setDefault('publish', 1);
if(null != $faq) {
$form->populate($faq->toArray());
$i18nService = MF_Service_ServiceBroker::getInstance()->getService('Default_Service_I18n');
$languages = $i18nService->getLanguageList();
foreach($languages as $language) {
$i18nSubform = $form->translations->getSubForm($language);
if($i18nSubform) {
$i18nSubform->getElement('title')->setValue($faq->Translation[$language]->title);
$i18nSubform->getElement('content')->setValue($faq->Translation[$language]->content);
}
}
}
return $form;
}
public function saveFaqFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$faq = $this->faqTable->getProxy($values['id'])) {
$faq = $this->faqTable->getRecord();
}
$i18nService = MF_Service_ServiceBroker::getInstance()->getService('Default_Service_I18n');
$faq->fromArray($values);
$languages = $i18nService->getLanguageList();
foreach($languages as $language) {
if(is_array($values['translations'][$language]) && strlen($values['translations'][$language]['title'])) {
$faq->Translation[$language]->title = $values['translations'][$language]['title'];
$faq->Translation[$language]->slug = MF_Text::createUniqueTableSlug('Faq_Model_Doctrine_FaqTranslation', $values['translations'][$language]['title'], $faq->getId());
$faq->Translation[$language]->content = $values['translations'][$language]['content'];
}
}
$faq->save();
return $faq;
}
public function removeFaq(Faq_Model_Doctrine_Faq $faq) {
$faq->delete();
}
// public function searchFaq($phrase, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
// $q = $this->faqTable->getAllFaqQuery();
// $q->addSelect('TRIM(at.title) AS search_title, TRIM(at.content) as search_content, "faq" as search_type');
// $q->andWhere('at.title LIKE ? OR at.content LIKE ?', array("%$phrase%", "%$phrase%"));
// return $q->execute(array(), $hydrationMode);
// }
public function getAllSortedFaq($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->faqTable->getPublishFaqQuery();
$q = $this->faqTable->getPhotoQuery($q);
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getTargetFaqSelectOptions($prependEmptyValue = false, $language = null) {
$items = $this->getAllSortedFaq(Doctrine_Core::HYDRATE_RECORD);
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
foreach($items as $item) {
$result[$item->getId()] = $item->Translation[$language]->title;
}
return $result;
}
public function getPreSortedPredifiniedFaq($faqIds) {
$q = $this->faqTable->getAllFaqQuery();
$q->where('a.id IN ?', array($faqIds));
if(is_array($faqIds)):
$q->addOrderBy('FIELD(a.id, '.implode(', ', $faqIds).')');
endif;
return $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
}
public function refreshSponsoredFaq($faq){
if ($faq->isSponsored()):
$faq->setSponsored(0);
else:
$faq->setSponsored(1);
endif;
$faq->save();
}
public function searchFaq($phrase, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
$q = $this->faqTable->getPublishFaqQuery();
$q = $this->faqTable->getPhotoQuery($q);
$q->addSelect('TRIM(at.title) AS search_title, TRIM(at.content) as search_content, "faq" as search_type');
$q->andWhere('at.title LIKE ? OR at.content LIKE ?', array("%$phrase%", "%$phrase%"));
//$q->addOrderBy('RANDOM()');
return $q->execute(array(), $hydrationMode);
}
public function getAllFaqForSiteMap($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->faqTable->getPublishFaqQuery();
$q = $this->faqTable->getPhotoQuery($q);
return $q->execute(array(), $hydrationMode);
}
}
<file_sep>/application/modules/order/library/DataTables/Item.php
<?php
/**
* Order_DataTables_Item
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Item extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Order_DataTables_Adapter_Item';
}
}
<file_sep>/application/modules/tournament/models/Doctrine/Team.php
<?php
/**
* Tournament_Model_Doctrine_Team
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package Admi
* @subpackage Tournament
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Tournament_Model_Doctrine_Team extends Tournament_Model_Doctrine_BaseTeam
{
public function setUp()
{
parent::setUp();
$this->hasOne('Tournament_Model_Doctrine_Tournament as Tournament', array(
'local' => 'tournament_id',
'foreign' => 'id'));
$this->hasMany('Tournament_Model_Doctrine_Match as Matches1', array(
'local' => 'id',
'foreign' => 'team1'));
$this->hasMany('Tournament_Model_Doctrine_Match as Matches2', array(
'local' => 'id',
'foreign' => 'team2'));
$this->hasMany('Tournament_Model_Doctrine_Player as Players', array(
'local' => 'id',
'foreign' => 'team_id'));
}
}<file_sep>/application/modules/order/services/Payment.php
<?php
/**
* Order_Service_Payment
*
* @author <NAME> <<EMAIL>>
*/
abstract class Order_Service_Payment extends MF_Service_ServiceAbstract {
protected $paymentTable;
public function init() {
$this->paymentTable = Doctrine_Core::getTable('Order_Model_Doctrine_Payment');
parent::init();
}
public function getFullPayment($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->paymentTable->getFullPaymentQuery();
$q->andWhere('p.' . $field . ' = ?', $id);
return $q->fetchOne(array(), $hydrationMode);
}
public function getPayment($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->paymentTable->findOneBy($field, $id, $hydrationMode);
}
}
<file_sep>/application/modules/order/models/Doctrine/OrderStatusTable.php
<?php
/**
* Order_Model_Doctrine_OrderStatusTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Order_Model_Doctrine_OrderStatusTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Order_Model_Doctrine_OrderStatusTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Order_Model_Doctrine_OrderStatus');
}
public function getOrderStatusQuery() {
$q = $this->createQuery('os');
$q->addSelect('os.*');
return $q;
}
}<file_sep>/application/modules/order/library/DataTables/Payment.php
<?php
/**
* Order_DataTables_Payment
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Payment extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Order_DataTables_Adapter_Payment';
}
}
<file_sep>/application/modules/faq/services/Category.php
<?php
/**
* Category
*
* @author <NAME> <<EMAIL>>
*/
class Faq_Service_Category extends MF_Service_ServiceAbstract {
protected $categoryTable;
public static $articleItemCountPerPage = 5;
public static function getArticleItemCountPerPage(){
return self::$articleItemCountPerPage;
}
public function init() {
$this->categoryTable = Doctrine_Core::getTable('Faq_Model_Doctrine_Category');
}
public function getAllCategories($countOnly = false) {
if(true == $countOnly) {
return $this->categoryTable->count();
} else {
return $this->categoryTable->findAll();
}
}
public function getCategory($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->categoryTable->findOneBy($field, $id, $hydrationMode);
}
public function getFullCategory($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->categoryTable->getPublishCategoryQuery();
// $q = $this->categoryTable->getPhotoQuery($q);
if(in_array($field, array('id'))) {
$q->andWhere('a.' . $field . ' = ?', array($id));
} elseif(in_array($field, array('slug'))) {
$q->andWhere('at.' . $field . ' = ?', array($id));
//$q->andWhere('at.lang = ?', 'pl');
}
return $q->fetchOne(array(), $hydrationMode);
}
public function getRecentCategory($limit, $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->categoryTable->getPublishCategoryQuery();
$q = $this->categoryTable->getPhotoQuery($q);
$q = $this->categoryTable->getLimitQuery($limit, $q);
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getNew($limit, $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->categoryTable->getPublishCategoryQuery();
$q = $this->categoryTable->getPhotoQuery($q);
$q = $this->categoryTable->getLimitQuery($limit, $q);
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getCategoryPaginationQuery($language) {
$q = $this->categoryTable->getPublishCategoryQuery();
$q = $this->categoryTable->getPhotoQuery($q);
$q->andWhere('at.lang = ?', $language);
$q->addOrderBy('a.sponsored DESC');
$q->addOrderBy('a.publish_date DESC');
return $q;
}
public function getCategoryOnMainPage($limit, $language, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
$q = $this->categoryTable->getPublishCategoryQuery();
$q = $this->categoryTable->getPhotoQuery($q);
$q->andWhere('at.lang = ?', $language);
$q->addOrderBy('a.sponsored DESC');
$q->addOrderBy('a.publish_date DESC');
$q->limit($limit);
return $q->execute(array(), $hydrationMode);
}
public function getCategoryForm(Faq_Model_Doctrine_Category $faq = null) {
$form = new Faq_Form_Category();
if(null != $faq) {
$form->populate($faq->toArray());
$i18nService = MF_Service_ServiceBroker::getInstance()->getService('Default_Service_I18n');
$languages = $i18nService->getLanguageList();
foreach($languages as $language) {
$i18nSubform = $form->translations->getSubForm($language);
if($i18nSubform) {
$i18nSubform->getElement('title')->setValue($faq->Translation[$language]->title);
}
}
}
return $form;
}
public function saveCategoryFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$faq = $this->categoryTable->getProxy($values['id'])) {
$faq = $this->categoryTable->getRecord();
}
$i18nService = MF_Service_ServiceBroker::getInstance()->getService('Default_Service_I18n');
$faq->fromArray($values);
$languages = $i18nService->getLanguageList();
foreach($languages as $language) {
if(is_array($values['translations'][$language]) && strlen($values['translations'][$language]['title'])) {
$faq->Translation[$language]->title = $values['translations'][$language]['title'];
$faq->Translation[$language]->slug = MF_Text::createUniqueTableSlug('Faq_Model_Doctrine_CategoryTranslation', $values['translations'][$language]['title'], $faq->getId());
}
}
$faq->save();
return $faq;
}
public function removeCategory(Faq_Model_Doctrine_Category $faq) {
$faq->delete();
}
// public function searchCategory($phrase, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
// $q = $this->categoryTable->getAllCategoryQuery();
// $q->addSelect('TRIM(at.title) AS search_title, TRIM(at.content) as search_content, "faq" as search_type');
// $q->andWhere('at.title LIKE ? OR at.content LIKE ?', array("%$phrase%", "%$phrase%"));
// return $q->execute(array(), $hydrationMode);
// }
public function getAllSortedCategories($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->categoryTable->getPublishCategoryQuery();
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getTargetCategorySelectOptions($prependEmptyValue = false, $language = null) {
$items = $this->getAllSortedCategories(Doctrine_Core::HYDRATE_RECORD);
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
foreach($items as $item) {
$result[$item->getId()] = $item->Translation[$language]->title;
}
return $result;
}
public function getPreSortedPredifiniedCategory($faqIds) {
$q = $this->categoryTable->getAllCategoryQuery();
$q->where('a.id IN ?', array($faqIds));
if(is_array($faqIds)):
$q->addOrderBy('FIELD(a.id, '.implode(', ', $faqIds).')');
endif;
return $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
}
public function refreshSponsoredCategory($faq){
if ($faq->isSponsored()):
$faq->setSponsored(0);
else:
$faq->setSponsored(1);
endif;
$faq->save();
}
public function searchCategory($phrase, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
$q = $this->categoryTable->getPublishCategoryQuery();
$q = $this->categoryTable->getPhotoQuery($q);
$q->addSelect('TRIM(at.title) AS search_title, TRIM(at.content) as search_content, "faq" as search_type');
$q->andWhere('at.title LIKE ? OR at.content LIKE ?', array("%$phrase%", "%$phrase%"));
//$q->addOrderBy('RANDOM()');
return $q->execute(array(), $hydrationMode);
}
public function getAllCategoriesForSiteMap($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->categoryTable->getPublishCategoryQuery();
return $q->execute(array(), $hydrationMode);
}
}
<file_sep>/application/modules/affilateprogram/library/DataTables/Adapter/Partner.php
<?php
/**
* Partner
*
* @author <NAME> <<EMAIL>>
*/
class Affilateprogram_DataTables_Adapter_Partner extends Default_DataTables_Adapter_AdapterAbstract {
public function getBaseQuery() {
$q = $this->table->createQuery('p');
$q->select('p.*');
return $q;
}
}
<file_sep>/application/modules/order/library/DataTables/Adapter/PaymentType.php
<?php
/**
* Order_DataTables_Adapter_PaymentType
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Adapter_PaymentType extends Default_DataTables_Adapter_AdapterAbstract {
public function getBaseQuery() {
$q = $this->table->createQuery('pt');
$q->select('pt.*');
return $q;
}
}
<file_sep>/application/modules/faq/models/Doctrine/CategoryTranslationTable.php
<?php
/**
* Faq_Model_Doctrine_CategoryTranslationTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Faq_Model_Doctrine_CategoryTranslationTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Faq_Model_Doctrine_CategoryTranslationTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Faq_Model_Doctrine_CategoryTranslation');
}
}<file_sep>/application/modules/testimonial/controllers/IndexController.php
<?php
/**
* Testimonial_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class Testimonial_IndexController extends MF_Controller_Action {
public function testimonialsAction() {
$pageService = $this->_service->getService('Page_Service_Page');
$testimonialService = $this->_service->getService('Testimonial_Service_Testimonial');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$partnerItemCountPerPage = $partnerService->getPartnerItemCountPerPage();
if(!$page = $pageService->getI18nPage('partners', 'type', $this->view->language, Doctrine_Core::HYDRATE_RECORD)) {
throw new Zend_Controller_Action_Exception('Page not found');
}
$metatagService->setViewMetatags($page->get('Metatag'), $this->view);
$query = $partnerService->getPartnersPaginationQuery($this->view->language);
$adapter = new MF_Paginator_Adapter_Doctrine($query, Doctrine_Core::HYDRATE_ARRAY);
$paginator = new Zend_Paginator($adapter);
$paginator->setCurrentPageNumber($this->getRequest()->getParam('page', 1));
$paginator->setItemCountPerPage($partnerItemCountPerPage);
$this->view->assign('page', $page);
$this->view->assign('paginator', $paginator);
$this->_helper->actionStack('layout-ajurweda', 'index', 'default');
}
}
<file_sep>/application/modules/tournament/services/Tournament.php
<?php
/**
* Tournament_Service_Tournament
*
@author <NAME> <<EMAIL>>
*/
class Tournament_Service_Tournament extends MF_Service_ServiceAbstract {
protected $tournamentTable;
public function init() {
$this->tournamentTable = Doctrine_Core::getTable('Tournament_Model_Doctrine_Tournament');
parent::init();
}
public function getTournament($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->tournamentTable->findOneBy($field, $id, $hydrationMode);
}
public function getTournamentForm(Tournament_Model_Doctrine_Tournament $orderStatus = null) {
$form = new Tournament_Form_Tournament();
if(null != $orderStatus) {
$form->populate($orderStatus->toArray());
}
return $form;
}
public function saveTournamentFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$orderStatus = $this->getTournament((int) $values['id'])) {
$orderStatus = $this->tournamentTable->getRecord();
}
$orderStatus->fromArray($values);
$orderStatus->save();
return $orderStatus;
}
public function removeTournament(Tournament_Model_Doctrine_Tournament $orderStatus) {
$orderStatus->delete();
}
public function getAllTournament($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->tournamentTable->getTournamentQuery();
return $q->execute(array(), $hydrationMode);
}
public function getActiveTournaments($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->tournamentTable->createQuery('l');
$q->addWhere('l.active = 1');
$q->orderBy('l.id DESC');
return $q->execute(array(), $hydrationMode);
}
public function getTargetTournamentSelectOptions($prependEmptyValue = false) {
$items = $this->getAllTournament();
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
foreach($items as $item) {
$result[$item->getId()] = $item->name;
}
return $result;
}
}
?><file_sep>/application/modules/tournament/models/Doctrine/BaseMatch.php
<?php
/**
* Tournament_Model_Doctrine_BaseMatch
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property integer $id
* @property integer $team1
* @property integer $team2
* @property integer $goal1
* @property integer $goal2
* @property integer $tournament_id
* @property datetime $match_date
* @property boolean $played
* @property boolean $group_round
* @property Tournament_Model_Doctrine_Team $Team1
* @property Doctrine_Collection $Tournament
* @property Tournament_Model_Doctrine_Shooter $Shooters
*
* @package Admi
* @subpackage Tournament
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class Tournament_Model_Doctrine_BaseMatch extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('tournament_match');
$this->hasColumn('id', 'integer', 4, array(
'primary' => true,
'autoincrement' => true,
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('team1', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('team2', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('goal1', 'integer', 11, array(
'type' => 'integer',
'length' => '11',
));
$this->hasColumn('goal2', 'integer', 11, array(
'type' => 'integer',
'length' => '11',
));
$this->hasColumn('tournament_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('match_date', 'datetime', null, array(
'type' => 'datetime',
));
$this->hasColumn('played', 'boolean', null, array(
'type' => 'boolean',
'default' => 0,
));
$this->hasColumn('group_round', 'boolean', null, array(
'type' => 'boolean',
'default' => 1,
));
$this->option('type', 'MyISAM');
$this->option('collate', 'utf8_general_ci');
$this->option('charset', 'utf8');
}
public function setUp()
{
parent::setUp();
$this->hasOne('Tournament_Model_Doctrine_Team as Team1', array(
'local' => 'team1',
'foreign' => 'id'));
$this->hasMany('Tournament_Model_Doctrine_Tournament as Tournament', array(
'local' => 'tournament_id',
'foreign' => 'id'));
$this->hasOne('Tournament_Model_Doctrine_Shooter as Shooters', array(
'local' => 'id',
'foreign' => 'match_id'));
}
}<file_sep>/application/modules/order/services/Payment/PayU.php
<?php
/**
* Order_Service_Payment_PayU
*
* @author <NAME> <<EMAIL>>
*/
class Order_Service_Payment_PayU extends Order_Service_Payment {
// public function updatePayment(Order_Model_Doctrine_Payment $payment) {
// $options = $this->getOptions();
//
// $timestamp = MF_Text::timeFormat($payment['created_at'], 'U');
//
// $sig1 = md5( $options['PosId'] . $payment->getId() . $timestamp . $options['Key1'] );
//
// $client = new Zend_Http_Client($options['Payment_get']);
// $client->setMethod(Zend_Http_Client::POST);
// $client->setParameterPost(array(
// 'pos_id' => $options['PosId'],
// 'session_id' => $payment->getId(),
// 'ts' => $timestamp,
// 'sig' => $sig1
// ));
// $response = $client->request();
//
// $lines = explode(PHP_EOL, $response->getBody());
//
// $params = array();
// foreach($lines as $line) {
// $pairs = explode(':', $line);
// $key = isset($pairs[0]) ? $pairs[0] : '';
// $value = isset($pairs[1]) ? $pairs[1] : '';
// $params[$key] = $value;
// }
//
// if(array_key_exists('trans_session_id', $params)) {
// // zmiana statusu transakcji
// if($payment->getStatus() != $params['trans_status']) {
// $payment->setStatus((int) $params['trans_status']);
// $payment->setError(null);
// $payment->save();
// return true;
// }
// }
// }
}
<file_sep>/application/modules/testimonial/models/Doctrine/TestimonialTable.php
<?php
/**
* Testimonial_Model_Doctrine_TestimonialTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Testimonial_Model_Doctrine_TestimonialTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Testimonial_Model_Doctrine_TestimonialTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Testimonial_Model_Doctrine_Testimonial');
}
public function getTestimonialQuery() {
$q = $this->createQuery('t')
->addSelect('t.*')
->addSelect('tt.*')
->leftJoin('t.Translation tt');
return $q;
}
}<file_sep>/application/modules/location/models/Doctrine/LocationTable.php
<?php
/**
* Location_Model_Doctrine_LocationTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Location_Model_Doctrine_LocationTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Location_Model_Doctrine_LocationTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Location_Model_Doctrine_Location');
}
public function getPublishCategoryQuery() {
$q = $this->createQuery('a')
->addSelect('a.*')
->addSelect('at.*')
->leftJoin('a.Translation at');
return $q;
}
public function getPublishLocationQuery() {
$q = $this->createQuery('l')
->addSelect('l.*')
->addSelect('lt.*')
->leftJoin('l.Translation lt');
return $q;
}
}<file_sep>/application/modules/order/services/Order.php
<?php
/**
* Order_Service_Order
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_Order extends MF_Service_ServiceAbstract {
protected $orderTable;
protected $itemTable;
protected $deliveryTable;
protected $deliveryAddressTable;
protected $paymentTable;
protected $invoiceTable;
protected $cart;
public function init() {
$this->orderTable = Doctrine_Core::getTable('Order_Model_Doctrine_Order');
$this->itemTable = Doctrine_Core::getTable('Order_Model_Doctrine_Item');
$this->deliveryTable = Doctrine_Core::getTable('Order_Model_Doctrine_Delivery');
$this->deliveryAddressTable = Doctrine_Core::getTable('Order_Model_Doctrine_DeliveryAddress');
$this->paymentTable = Doctrine_Core::getTable('Order_Model_Doctrine_Payment');
$this->invoiceTable = Doctrine_Core::getTable('Order_Model_Doctrine_Invoice');
parent::init();
}
public function getItem($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->itemTable->findOneBy($field, $id, $hydrationMode);
}
public function getOrder($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->orderTable->findOneBy($field, $id, $hydrationMode);
}
public function getDelivery($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->deliveryTable->findOneBy($field, $id, $hydrationMode);
}
public function getPayment($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->paymentTable->findOneBy($field, $id, $hydrationMode);
}
public function getDeliveryAddress($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->deliveryAddressTable->findOneBy($field, $id, $hydrationMode);
}
public function getProductsWorth(Order_Model_Doctrine_Order $order)
{
$sum = 0;
foreach($order['Items'] as $item):
$sum += $item['price']*$item['number'];
endforeach;
return $sum;
}
public function getOrderForm(Order_Model_Doctrine_Order $order = null) {
$form = new Order_Form_Order();
if(null != $order) {
$form->populate($order->toArray());
}
return $form;
}
public function saveOrderFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$order = $this->getOrder((int) $values['id'])) {
$order = $this->orderTable->getRecord();
}
$order->fromArray($values);
$order->save();
return $order;
}
public function saveDeliveryFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$delivery = $this->getDelivery((int) $values['id'])) {
$delivery = $this->deliveryTable->getRecord();
}
$delivery->fromArray($values);
$delivery->save();
return $delivery;
}
public function saveDeliveryAddressFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$deliveryAddress = $this->getDeliveryAddress((int) $values['id'])) {
$deliveryAddress = $this->deliveryAddressTable->getRecord();
}
$deliveryAddress->fromArray($values);
$deliveryAddress->save();
return $deliveryAddress;
}
public function saveItemFromArray($values) {
$item = $this->itemTable->getRecord();
$item->fromArray($values);
$item->save();
return $item;
}
public function savePaymentFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$payment = $this->getPayment((int) $values['id'])) {
$payment = $this->paymentTable->getRecord();
}
$payment->fromArray($values);
$payment->save();
return $payment;
}
public function saveInvoiceFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$invoice = $this->getPayment((int) $values['id'])) {
$invoice = $this->invoiceTable->getRecord();
}
$invoice->fromArray($values);
$invoice->save();
return $invoice;
}
public function getFullOrder($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->orderTable->getFullOrderQuery();
$q->andWhere('o.' . $field . ' = ?', $id);
return $q->fetchOne(array(), $hydrationMode);
}
public function getNewOrders($date, $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->orderTable->getFullOrderQuery();
$q->andWhere('o.created_at > ?', $date);
return $q->execute(array(), $hydrationMode);
}
public function getAllOrders($countOnly = false) {
if(true == $countOnly) {
return $this->orderTable->count();
} else {
return $this->orderTable->findAll();
}
}
public function getOrderItemsIds($orderId, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
$q = $this->itemTable->getOrderItemsIdsQuery();
$q->andWhere('i.order_id = ?', $orderId);
return $q->execute(array(), $hydrationMode);
}
public function getCart() {
if(!$this->cart) {
$this->cart = new Order_Model_Cart();
}
return $this->cart;
}
public function getUserOrders($userId, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
$q = $this->orderTable->getFullOrderQuery();
$q->leftJoin('o.Payment p');
$q->leftJoin('p.Status ps');
$q->leftJoin('d.Status dels');
$q->addSelect('p.*,ps.*,dels.*');
$q->andWhere('u.id = ?', $userId);
$q->addOrderBy('o.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function sendConfirmationWithOrderToUs($user, Order_Model_Doctrine_Order $order, Zend_Mail $mail, Zend_View_Interface $view, $partial = 'email/confirmation-order-to-us.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'user' => $user))
);
$mail->send();
}
public function sendConfirmationMailWithPaymentByTransferPayment(Zend_Mail $mail, Order_Model_Doctrine_Order $order, $language, Zend_View_Interface $view, $partial = 'email/confirmation-order-payment-by-transfer.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'language' => $language))
);
$mail->send();
}
public function sendConfirmationMailWithPaymentByPayU(Zend_Mail $mail, Order_Model_Doctrine_Order $order, $language, Zend_View_Interface $view, $partial = 'email/confirmation-order-payment-by-payu.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'language' => $language))
);
$mail->send();
}
public function sendConfirmationMailWithPaymentByCash(Zend_Mail $mail, Order_Model_Doctrine_Order $order, $language, Zend_View_Interface $view, $partial = 'email/confirmation-order-payment-by-cash.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'language' => $language))
);
$mail->send();
}
public function sendConfirmationMailWithDeliveryAbroad(Zend_Mail $mail, Order_Model_Doctrine_Order $order, $language, Zend_View_Interface $view, $partial = 'email/confirmation-order-delivery-abroad.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'language' => $language))
);
$mail->send();
}
public function sendConfirmationMailChangeOrderStatusForRealized(Zend_Mail $mail, Zend_View_Interface $view, $partial = 'email/confirmation-change-order-status-for-realized.phtml') {
$mail->setBodyHtml(
$view->partial($partial)
);
$mail->send();
}
public function sendConfirmationMailChangeDeliveryStatusForSent(Zend_Mail $mail, Zend_View_Interface $view, $partial = 'email/confirmation-change-delivery-status-for-sent.phtml') {
$mail->setBodyHtml(
$view->partial($partial)
);
$mail->send();
}
public function sendConfirmationMailChangeDeliveryStatusForWaitWithCollection(Zend_Mail $mail, Zend_View_Interface $view, $partial = 'email/confirmation-change-delivery-status-for-wait-with-collection.phtml') {
$mail->setBodyHtml(
$view->partial($partial)
);
$mail->send();
}
public function sendConfirmationMailChangePaymentStatus(Zend_Mail $mail, Zend_View_Interface $view, $partial = 'email/confirmation-change-payment-status.phtml') {
$mail->setBodyHtml(
$view->partial($partial)
);
$mail->send();
}
public function sendConfirmationMailWithPaymentByTransferWithCollection(Zend_Mail $mail, Order_Model_Doctrine_Order $order, $language, Zend_View_Interface $view, $partial = 'email/confirmation-order-payment-by-transfer-with-collection.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'language' => $language))
);
$mail->send();
}
public function sendConfirmationMailWithPaymentByCourierCollection(Zend_Mail $mail, Order_Model_Doctrine_Order $order, $language, Zend_View_Interface $view, $partial = 'email/confirmation-order-payment-by-courier-with-collection.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'language' => $language))
);
$mail->send();
}
public function sendConfirmationMailDetermineDeliveryCostsPaymentTransfer(Order_Model_Doctrine_Order $order, $language, Zend_Mail $mail, Zend_View_Interface $view, $partial = 'email/confirmation-determine-delivery-costs-transfer.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'language' => $language))
);
$mail->send();
}
public function sendConfirmationMailDetermineDeliveryCostsPaymentPayU(Order_Model_Doctrine_Order $order, $language, Zend_Mail $mail, Zend_View_Interface $view, $partial = 'email/confirmation-determine-delivery-costs-payu.phtml') {
$mail->setBodyHtml(
$view->partial($partial, array('order' => $order, 'language' => $language))
);
$mail->send();
}
public function setVatItem($itemId, $vat){
$item = $this->getItem($itemId);
$item->setVat((double)$vat);
$item->save();
return $item;
}
}
?><file_sep>/application/modules/testimonial/library/DataTables/Adapter/Testimonial.php
<?php
/**
* Testimonial_DataTables_Adapter_Testimonial
*
* @author <NAME> <<EMAIL>>
*/
class Testimonial_DataTables_Adapter_Testimonial extends Default_DataTables_Adapter_AdapterAbstract {
public function getBaseQuery() {
$q = $this->table->createQuery('t');
$q->select('t.*');
$q->addSelect('tt.*');
$q->leftJoin('t.Translation tt');
$q->andWhere('t.level > ?', 0);
$q->addOrderBy('t.lft ASC');
return $q;
}
}
<file_sep>/application/modules/affilateprogram/library/DataTables/Partner.php
<?php
/**
* Partner
*
* @author <NAME> <<EMAIL>>
*/
class Affilateprogram_DataTables_Partner extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Affilateprogram_DataTables_Adapter_Partner';
}
}
<file_sep>/application/modules/location/library/DataTables/Location.php
<?php
/**
* Location
*
* @author <NAME> <<EMAIL>>
*/
class Location_DataTables_Location extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Location_DataTables_Adapter_Location';
}
}
<file_sep>/application/modules/order/forms/Payu.php
<?php
/**
* Order_Form_Payu
*
* @author <NAME> <<EMAIL>>
*/
class Order_Form_Payu extends Zend_Form {
public function init() {
$posId = $this->createElement('hidden', 'pos_id');
$posId->setDecorators(array('ViewHelper'));
$posAuthKey = $this->createElement('hidden', 'pos_auth_key');
$posAuthKey->setDecorators(array('ViewHelper'));
$sessionId = $this->createElement('hidden', 'session_id');
$sessionId->setDecorators(array('ViewHelper'));
$amount = $this->createElement('hidden', 'amount');
$amount->setDecorators(array('ViewHelper'));
$desc = $this->createElement('hidden', 'desc');
$desc->setDecorators(array('ViewHelper'));
$firstName = $this->createElement('hidden', 'first_name');
$firstName->setDecorators(array('ViewHelper'));
$lastName = $this->createElement('hidden', 'last_name');
$lastName->setDecorators(array('ViewHelper'));
$email = $this->createElement('hidden', 'email');
$email->setDecorators(array('ViewHelper'));
$clientIp = $this->createElement('hidden', 'client_ip');
$clientIp->setDecorators(array('ViewHelper'));
$ts = $this->createElement('hidden', 'ts');
$ts->setDecorators(array('ViewHelper'));
$sig = $this->createElement('hidden', 'sig');
$sig->setDecorators(array('ViewHelper'));
// $js = $this->createElement('hidden', 'js');
// $js->setDecorators(array('ViewHelper'));
// $js->setValue(0);
$submit = $this->createElement('submit', 'submit');
$submit->setLabel('Pay');
$submit->setDecorators(array('ViewHelper'));
$this->setDecorators(array(
'FormElements',
'Form'
));
$this->addElements(array(
$posId, $posAuthKey, $sessionId, $amount, $desc, $firstName, $lastName, $email, $clientIp, $ts, $sig, $submit
));
}
public function setup($config) {
if(array_key_exists('UrlPlatnosci_pl', $config)) {
$this->setAction($config['UrlPlatnosci_pl'] . '/UTF/NewPayment');
}
if(array_key_exists('PosId', $config)) {
$this->pos_id->setValue($config['PosId']);
}
if(array_key_exists('PosAuthKey', $config)) {
$this->pos_auth_key->setValue($config['PosAuthKey']);
}
$this->setName('payform');
$this->setMethod('post');
}
}
<file_sep>/application/modules/order/controllers/AjaxController.php
<?php
/**
* Order_AjaxController
*
* @author <NAME> <<EMAIL>>
*/
class Order_AjaxController extends MF_Controller_Action {
public function init() {
$this->_helper->ajaxContext()
->addActionContext('remove-product-from-cart', 'json')
->addActionContext('add-to-cart', 'json')
->addActionContext('check-coupon', 'json')
->addActionContext('check-delivery-type', 'json')
->addActionContext('change-number-of-product', 'json')
->initContext();
parent::init();
}
public function addToCartAction() {
$productService = $this->_service->getService('Product_Service_Product');
$orderService = $this->_service->getService('Order_Service_Order');
$cartService = $this->_service->getService('Order_Service_Cart');
$i18nService = $this->_service->getService('Default_Service_I18n');
$this->view->clearVars();
$language = $i18nService->getDefaultLanguage();
$translator = $this->_service->get('translate');
$cart = $cartService->getCart();
$counter = (int) $this->getRequest()->getParam('counter');
if($product = $productService->getFullProduct((int) $this->getRequest()->getParam('product-id'))) {
/* price calculate */
$user = $this->_helper->user();
if($user):
$userDiscount = $user['Discount']->toArray();
$userGroups = $user->get("Groups");
endif;
$userGroupDiscounts = array();
foreach($userGroups as $userGroup):
$userGroupDiscounts[] = $userGroup['Discount']->toArray();
endforeach;
$arrayDiscounts = array($product['Discount'], $product['Producer']['Discount'], $userDiscount);
foreach($userGroupDiscounts as $userGroupDiscount):
$arrayDiscounts[] = $userGroupDiscount;
endforeach;
$flag = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$flag = $flag['flag'];
if($flag || $product['promotion']):
if($product['promotion']):
if($flag):
$price = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$price = $price['price'];
$productPrice = $price;
else:
$productPrice = $product['promotion_price'];
endif;
else:
$price = MF_Discount::getPriceWithDiscount($product['price'], $arrayDiscounts);
$price = $price['price'];
$productPrice = $price;
endif;
else:
$productPrice = $product['price'];
endif;
$item = $cart->get('Product_Model_Doctrine_Product', $product->getId());
if ($product->getAvailability() > $item[""]['count']):
$cart->remove('Product_Model_Doctrine_Product', $product->getId());
if ($counter && $counter > 0):
$cart->add('Product_Model_Doctrine_Product', $product->getId(),
$product->Translation[$language->getId()]->name, $productPrice, $item[""]['count']+$counter, null, true,
array('photoOffset' => $product['PhotoRoot']['offset'],
'photoFilename' => $product['PhotoRoot']['filename'],
'categoryName' => $product['Categories'][0]['Translation'][$language->getId()]['name'],
'categorySlug' => $product['Categories'][0]['Translation'][$language->getId()]['slug'],
'productSlug' => $product['Translation'][$language->getId()]['slug'],
));
else:
$cart->add('Product_Model_Doctrine_Product', $product->getId(),
$product->Translation[$language->getId()]->name,
$productPrice, $item[""]['count']+1, null, true,
array('photoOffset' => $product['PhotoRoot']['offset'],
'photoFilename' => $product['PhotoRoot']['filename'],
'categoryName' => $product['Categories'][0]['Translation'][$language->getId()]['name'],
'categorySlug' => $product['Categories'][0]['Translation'][$language->getId()]['slug'],
'productSlug' => $product['Translation'][$language->getId()]['slug'],
)
);
endif;
endif;
}
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
$cart = $cartService->getCart();
$cartItems = $cart->get('Product_Model_Doctrine_Product');
$this->view->assign('cartItems', $cartItems);
$this->view->assign('cart', $cart);
$cartItemsView = $this->view->partial('cart/mini-cart.phtml', 'order', array('cartItems' => $cartItems,'cart' => $cart));
$this->view->assign('status', "success");
$this->view->assign('miniCartView', $cartItemsView);
}
public function removeProductFromCartAction() {
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
$productService = $this->_service->getService('Product_Service_Product');
$cartService = $this->_service->getService('Order_Service_Cart');
$cart = $cartService->getCart();
$productId = $this->getRequest()->getParam('product-id');
$cart->remove('Product_Model_Doctrine_Product', $productId);
$counterCart = $cart->count();
$items = $cart->get('Product_Model_Doctrine_Product');
$language = $this->view->language;
$productsIds = array();
foreach($items as $productId=>$item):
$productsIds[] = $productId;
endforeach;
if($productsIds):
$products = $productService->getPreSortedProductCart($productsIds);
endif;
$user = $this->_helper->user();
if($user):
$userDiscount = $user['Discount']->toArray();
$userGroups = $user->get("Groups");
endif;
$userGroupDiscounts = array();
foreach($userGroups as $userGroup):
$userGroupDiscounts[] = $userGroup['Discount']->toArray();
endforeach;
$totalPrice = 0;
foreach($products as $product):
foreach($items as $id=>$item):
if($product->getId() == $id):
$arrayDiscounts = array($product['Discount'], $product['Producer']['Discount'], $userDiscount);
foreach($userGroupDiscounts as $userGroupDiscount):
$arrayDiscounts[] = $userGroupDiscount;
endforeach;
$flag = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$flag = $flag['flag'];
if($flag || $product['promotion']):
if($product['promotion']):
if($flag):
$price = MF_Discount::getPriceWithDiscount($product['promotion_price'], $arrayDiscounts);
$price = $price['price'];
$totalPrice += $price*$item[""]['count'];
else:
$totalPrice += $product['promotion_price']*$item[""]['count'];
endif;
elseif($flag):
$price = MF_Discount::getPriceWithDiscount($product['price'], $arrayDiscounts);
$price = $price['price'];
$totalPrice += $price*$item[""]['count'];
endif;
else:
$totalPrice += $product['price']*$item[""]['count'];
endif;
endif;
endforeach;
endforeach;
if (isset($_COOKIE["reference_number"])):
$partner = $affilateProgramService->getPartner($_COOKIE["reference_number"], 'reference_number');
if ($partner):
$discountPartner = ($totalPrice*$partner->getDiscount())/100;
$discountPartner = $this->view->currency($discountPartner);
endif;
endif;
$this->view->assign('totalPrice', $totalPrice);
$this->view->assign('userDiscount', $userDiscount);
$this->view->assign('userGroupDiscounts', $userGroupDiscounts);
$this->view->assign('items', $items);
$this->view->assign('products', $products);
$miniCartView = $this->view->partial('cart/mini-cart.phtml', 'order', array('cartItems' => $items,'cart' => $cart));
$this->view->assign('body', $cartView);
$this->_helper->json(array(
'status' => 'success',
'body' => $cartView,
'miniCartView' => $miniCartView,
'counterCart' => $counterCart,
'totalPrice' => $this->view->currency($totalPrice),
'discountPartner' => $discountPartner
));
$this->_helper->layout->disableLayout();
}
public function checkCouponAction() {
$couponService = $this->_service->getService('Order_Service_Coupon');
$this->view->clearVars();
$cartService = $this->_service->getService('Order_Service_Cart');
$cart = $cartService->getCart();
$totalPrice = $cart->getSum();
$translator = $this->_service->get('translate');
if ($this->getRequest()->getParam('code')){
$coupon = $couponService->getCoupon($this->getRequest()->getParam('code'), 'code');
}
$valid = false;
if($coupon):
if (!$coupon->isUsed() && MF_Coupon::isValid($coupon)){
$valid = true;
}
endif;
$noCouponPrice = $totalPrice;
if ($valid):
if ($coupon->getType() == "percent"):
$totalPrice = $totalPrice - ($coupon->getAmount()*$totalPrice/100);
$couponAmount = $coupon->getAmount()."%";
endif;
if ($coupon->getType() == "amount"):
$totalPrice = $totalPrice - $coupon->getAmount();
$couponAmount = $coupon->getAmount()." zł";
endif;
endif;
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
$this->view->assign('noCouponPrice', $noCouponPrice." zł");
$this->view->assign('couponAmount', $couponAmount);
$this->view->assign('valid', $valid);
$this->view->assign('totalSum', $totalPrice." zł");
$this->view->assign('status', "success");
}
public function checkDeliveryTypeAction() {
$deliveryTypeService = $this->_service->getService('Order_Service_DeliveryType');
$this->view->clearVars();
$translator = $this->_service->get('translate');
if ($this->getRequest()->getParam('deliveryTypeId')){
$deliveryType = $deliveryTypeService->getDeliveryType($this->getRequest()->getParam('deliveryTypeId'), 'id');
}
$totalPrice = $this->getRequest()->getParam('totalPrice');
if ($deliveryType):
if ($deliveryType->getPrice() != 0){
$deliveryPrice = $deliveryType->getPrice();
}
else{
if ($deliveryType['type'] == "przelew"):
$deliveryPrice = 0;
else:
$deliveryPrice = $deliveryType->getPrice();
endif;
}
endif;
if ($deliveryType->getType() == "przelew"){
$showPayment = true;
}
else{
$showPayment = false;
}
$priceWithDelivery = $totalPrice + $deliveryPrice;
$priceWithDelivery = $this->view->currency($priceWithDelivery);
$deliveryPrice = $this->view->currency($deliveryPrice);
if ($deliveryType->getId() == 9){
$deliveryPrice = "wyceniamy indywidualnie";
$priceWithDelivery .= " <span style='font-size: 10px;'> + koszt dostawy</span>";
}
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
$this->view->assign('deliveryPrice', $deliveryPrice);
$this->view->assign('totalPrice', $totalPrice);
$this->view->assign('showPayment', $showPayment);
$this->view->assign('priceWithDelivery', $priceWithDelivery);
$this->view->assign('status', "success");
}
public function changeNumberOfProductAction() {
$productService = $this->_service->getService('Product_Service_Product');
$cartService = $this->_service->getService('Order_Service_Cart');
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
$i18nService = $this->_service->getService('Default_Service_I18n');
$couponService = $this->_service->getService('Order_Service_Coupon');
$this->view->clearVars();
$language = $i18nService->getDefaultLanguage();
$translator = $this->_service->get('translate');
$cart = $cartService->getCart();
$counter = (int) $this->getRequest()->getParam('counter');
$flagAvailability = false;
if($product = $productService->getFullProduct((int) $this->getRequest()->getParam('id'))) {
$item = $cart->get('Product_Model_Doctrine_Product', $product->getId());
$oldCounterProduct = $item[""]['count'];
$oldOptions = $item[""]['options'];
$oldPrice = $item[""]['price'];
$totalPrice = $oldCounterProduct * $item[""]['price'];
if ($product->getAvailability() >= $counter):
$cart->remove('Product_Model_Doctrine_Product', $product->getId());
$cart->add('Product_Model_Doctrine_Product', $product->getId(), $product->Translation[$language->getId()]->name,$oldPrice, $counter, null, TRUE, $oldOptions);
$flagAvailability = true;
$totalPrice = $counter * $item[""]['price'];
endif;
}
$items = $cart->get('Product_Model_Doctrine_Product');
$productsIds = array();
foreach($items as $productId=>$item):
$productsIds[] = $productId;
endforeach;
if($productsIds):
$products = $productService->getPreSortedProductCart($productsIds);
endif;
$user = $this->_helper->user();
if($user):
$userDiscount = $user['Discount']->toArray();
$userGroups = $user->get("Groups");
endif;
$userGroupDiscounts = array();
foreach($userGroups as $userGroup):
$userGroupDiscounts[] = $userGroup['Discount']->toArray();
endforeach;
$productOldId = $product->getId();
$totalItems = 0;
$cart = $cartService->getCart();
if (isset($_COOKIE["reference_number"])):
$partner = $affilateProgramService->getPartner($_COOKIE["reference_number"], 'reference_number');
if ($partner):
$discountPartner = ($totalPrice*$partner->getDiscount())/100;
$discountPartner = $this->view->currency($discountPartner);
endif;
endif;
$totalSum = $cart->getSum();
$noCouponPrice = $totalSum;
if (isset($_COOKIE["discount_code"])):
$coupon = $couponService->getCoupon($_COOKIE["discount_code"], 'code');
if ($coupon->getType() == "percent"):
$totalSum = $totalSum - ($coupon->getAmount()*$totalSum/100);
$couponAmount = $coupon->getAmount()."%";
elseif ($coupon->getType() == "amount"):
$totalSum = $totalSum - $coupon->getAmount();
$couponAmount = $coupon->getAmount()." zł";
endif;
endif;
$basketItemCount = $cart->count();
// $cartItemsView = $this->view->partial('cart/mini-cart.phtml', 'order', array('cartItems' => $items));
$this->view->assign('noCouponPrice', $noCouponPrice." zł");
$this->view->assign('totalPrice', $totalPrice." zł");
$this->view->assign('totalSum', $totalSum." zł");
$this->view->assign('productId', $productOldId);
$this->view->assign('basketItemCount', $basketItemCount);
$this->view->assign('discountPartner', $discountPartner);
$this->view->assign('flagAvailability', $flagAvailability);
$this->view->assign('oldCounterProduct', $oldCounterProduct);
$this->view->assign('status', "success");
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
}
}
<file_sep>/application/modules/tournament/models/Doctrine/TeamTable.php
<?php
/**
* Tournament_Model_Doctrine_TeamTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Tournament_Model_Doctrine_TeamTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Tournament_Model_Doctrine_TeamTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Tournament_Model_Doctrine_Team');
}
}<file_sep>/application/modules/order/services/OrderStatus.php
<?php
/**
* Order_Service_OrderStatus
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_OrderStatus extends MF_Service_ServiceAbstract {
protected $orderStatusTable;
public function init() {
$this->orderStatusTable = Doctrine_Core::getTable('Order_Model_Doctrine_OrderStatus');
parent::init();
}
public function getOrderStatus($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->orderStatusTable->findOneBy($field, $id, $hydrationMode);
}
public function getOrderStatusForm(Order_Model_Doctrine_OrderStatus $orderStatus = null) {
$form = new Order_Form_OrderStatus();
if(null != $orderStatus) {
$form->populate($orderStatus->toArray());
}
return $form;
}
public function saveOrderStatusFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$orderStatus = $this->getOrderStatus((int) $values['id'])) {
$orderStatus = $this->orderStatusTable->getRecord();
}
$orderStatus->fromArray($values);
$orderStatus->save();
return $orderStatus;
}
public function removeOrderStatus(Order_Model_Doctrine_OrderStatus $orderStatus) {
$orderStatus->delete();
}
public function getAllOrderStatus($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->orderStatusTable->getOrderStatusQuery();
return $q->execute(array(), $hydrationMode);
}
public function getTargetOrderStatusSelectOptions($prependEmptyValue = false, $type = null) {
$items = $this->getAllOrderStatus();
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
foreach($items as $item) {
if ($type == $item->type):
$result[$item->getId()] = $item->name;
endif;
}
return $result;
}
public function getTargetTypeOrderStatusSelectOptions($prependEmptyValue = false) {
$items = $this->getAllOrderStatus();
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
$result= array("status zamówienia" => "status zamówienia",
"status przesyłki" => "status przesyłki",
"status płatności" => "status płatności"
);
return $result;
}
}
?><file_sep>/application/modules/order/library/DataTables/OrderStatus.php
<?php
/**
* Order_DataTables_OrderStatus
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_OrderStatus extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Order_DataTables_Adapter_OrderStatus';
}
}
<file_sep>/application/modules/order/models/Doctrine/BaseCoupon.php
<?php
/**
* Order_Model_Doctrine_BaseCoupon
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property integer $id
* @property string $code
* @property string $type
* @property boolean $used
* @property timestamp $start_validity_date
* @property timestamp $finish_validity_date
* @property integer $amount_coupon
* @property boolean $sent
* @property integer $order_id
* @property integer $user_id
* @property Order_Model_Doctrine_Order $Order
*
* @package Admi
* @subpackage Order
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class Order_Model_Doctrine_BaseCoupon extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('order_coupon');
$this->hasColumn('id', 'integer', 4, array(
'primary' => true,
'autoincrement' => true,
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('code', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('type', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('used', 'boolean', null, array(
'type' => 'boolean',
'default' => 0,
));
$this->hasColumn('start_validity_date', 'timestamp', null, array(
'type' => 'timestamp',
));
$this->hasColumn('finish_validity_date', 'timestamp', null, array(
'type' => 'timestamp',
));
$this->hasColumn('amount_coupon', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('sent', 'boolean', null, array(
'type' => 'boolean',
'default' => 0,
));
$this->hasColumn('order_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('user_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('share_product_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('share_product_email', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->option('type', 'MyISAM');
$this->option('collate', 'utf8_general_ci');
$this->option('charset', 'utf8');
}
public function setUp()
{
parent::setUp();
$this->hasOne('Order_Model_Doctrine_Order as Order', array(
'local' => 'order_id',
'foreign' => 'id'));
$softdelete0 = new Doctrine_Template_SoftDelete();
$this->actAs($softdelete0);
}
}<file_sep>/application/modules/affilateprogram/models/Doctrine/Partner.php
<?php
/**
* Affilateprogram_Model_Doctrine_Partner
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package Admi
* @subpackage Affilateprogram
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Affilateprogram_Model_Doctrine_Partner extends Affilateprogram_Model_Doctrine_BasePartner
{
public function getId() {
return $this->_get('id');
}
public function getReferenceNumber() {
return $this->_get('reference_number');
}
public function getDiscount() {
return $this->_get('discount');
}
public function getCommission() {
return $this->_get('comission');
}
}<file_sep>/application/modules/affilateprogram/services/Affilateprogram.php
<?php
/**
* Affilateprogram_Service_Affilateprogram
*
@author <NAME> <<EMAIL>>
*/
class Affilateprogram_Service_Affilateprogram extends MF_Service_ServiceAbstract {
protected $partnerTable;
protected $partnerOrdersTable;
public function init() {
$this->partnerTable = Doctrine_Core::getTable('Affilateprogram_Model_Doctrine_Partner');
$this->partnerOrdersTable = Doctrine_Core::getTable('Affilateprogram_Model_Doctrine_PartnerOrders');
parent::init();
}
public function getPartner($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->partnerTable->findOneBy($field, $id, $hydrationMode);
}
public function getPartnerForm(Affilateprogram_Model_Doctrine_Partner $partner = null) {
$form = new Affilateprogram_Form_Partner();
if(null != $partner) {
$form->populate($partner->toArray());
}
return $form;
}
public function getCheckCommissionForm() {
$form = new Affilateprogram_Form_Commission();
return $form;
}
public function savePartnerWithNewNumberFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
$partner = $this->partnerTable->getRecord();
$partner->reference_number = MF_Text::createUniqueTableReferenceNumber('Affilateprogram_Model_Doctrine_Partner', $this->generateReferenceNumber(), $partner->getId());
$partner->fromArray($values);
$partner->save();
}
public function generateReferenceNumber($length = 12) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$ret = '';
for($i = 0; $i < $length; ++$i) {
$random = str_shuffle($chars);
$ret .= $random[0];
}
return $ret;
}
public function savePartnerFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$partner = $this->getPartner((int) $values['id'])) {
$partner = $this->partnerTable->getRecord();
}
$partner->fromArray($values);
$partner->save();
return $partner;
}
public function saveOrderForPartner($orderId, $partnerId){
$partnerOrder = $this->partnerOrdersTable->getRecord();
$partnerOrder->setOrderId($orderId);
$partnerOrder->setPartnerId($partnerId);
$partnerOrder->save();
}
public function removePartner(Affilateprogram_Model_Doctrine_Partner $partner) {
$partner->delete();
}
public function getOrdersForPartner($partnerId, $values, $hydrationMode = Doctrine_Core::HYDRATE_ARRAY) {
if(strlen($values['start_date'])) {
$date = new Zend_Date($values['start_date'], 'dd/MM/yyyy HH:mm');
$values['start_date'] = $date->toString('yyyy-MM-dd HH:mm:00');
}
if(strlen($values['end_date'])) {
$date = new Zend_Date($values['end_date'], 'dd/MM/yyyy HH:mm');
$values['end_date'] = $date->toString('yyyy-MM-dd HH:mm:00');
}
$q = $this->partnerTable->getOrdersForPartnerQuery($partnerId, $values);
return $q->execute(array(), $hydrationMode);
}
}
?><file_sep>/application/modules/tournament/library/DataTables/Booking.php
<?php
/**
* Gallery
*
* @author <NAME> <<EMAIL>>
*/
class Tournament_DataTables_Booking extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Tournament_DataTables_Adapter_Booking';
}
}
<file_sep>/application/modules/order/models/Doctrine/BaseInvoice.php
<?php
/**
* Order_Model_Doctrine_BaseInvoice
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property integer $id
* @property string $invoice_company_name
* @property string $invoice_city
* @property string $invoice_address
* @property string $invoice_postal_code
* @property string $invoice_nip
* @property Order_Model_Doctrine_Order $Order
*
* @package Admi
* @subpackage Order
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class Order_Model_Doctrine_BaseInvoice extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('order_invoice');
$this->hasColumn('id', 'integer', 4, array(
'primary' => true,
'autoincrement' => true,
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('invoice_company_name', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('invoice_city', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('invoice_address', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('invoice_postal_code', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->hasColumn('invoice_nip', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
$this->option('type', 'MyISAM');
$this->option('collate', 'utf8_general_ci');
$this->option('charset', 'utf8');
}
public function setUp()
{
parent::setUp();
$this->hasOne('Order_Model_Doctrine_Order as Order', array(
'local' => 'id',
'foreign' => 'invoice_id'));
$timestampable0 = new Doctrine_Template_Timestampable();
$softdelete0 = new Doctrine_Template_SoftDelete();
$this->actAs($timestampable0);
$this->actAs($softdelete0);
}
}<file_sep>/application/modules/affilateprogram/models/Doctrine/PartnerOrders.php
<?php
/**
* Affilateprogram_Model_Doctrine_PartnerOrders
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package Admi
* @subpackage Affilateprogram
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Affilateprogram_Model_Doctrine_PartnerOrders extends Affilateprogram_Model_Doctrine_BasePartnerOrders
{
public function setPartnerId($partnerId) {
$this->_set('partner_id', $partnerId);
}
public function setOrderId($orderId) {
$this->_set('order_id', $orderId);
}
public function setUp() {
$this->hasOne('Order_Model_Doctrine_Order as Order', array(
'local' => 'order_id',
'foreign' => 'id'
));
parent::setUp();
}
}<file_sep>/application/modules/testimonial/library/DataTables/Testimonial.php
<?php
/**
* Testimonial_DataTables_Testimonial
*
* @author <NAME> <<EMAIL>>
*/
class Testimonial_DataTables_Testimonial extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Testimonial_DataTables_Adapter_Testimonial';
}
}
<file_sep>/application/modules/order/forms/Order.php
<?php
/**
* Order_Form_Order
*
* @author <NAME> <<EMAIL>>
*/
class Order_Form_Order extends Admin_Form {
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$type = $this->createElement('hidden', 'type');
$type->setDecorators(array('ViewHelper'));
$deliveryStatusId = $this->createElement('select', 'delivery_status_id');
$deliveryStatusId->setLabel('Delivery status');
$deliveryStatusId->setDecorators(self::$selectDecorators);
$paymentStatusId = $this->createElement('select', 'payment_status_id');
$paymentStatusId->setLabel('Payment status');
$paymentStatusId->setDecorators(self::$selectDecorators);
$orderStatusId = $this->createElement('select', 'order_status_id');
$orderStatusId->setLabel('Order status');
$orderStatusId->setDecorators(self::$selectDecorators);
$deliveryCost = $this->createElement('text', 'delivery_cost');
$deliveryCost->setLabel('Delivery cost');
$deliveryCost->setDecorators(self::$textDecorators);
$deliveryCost->setAttrib('class', 'span8');
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Save');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$id,
$orderStatusId,
$deliveryStatusId,
$paymentStatusId,
$deliveryCost,
$type,
$submit
));
}
}
<file_sep>/application/modules/location/services/Location.php
<?php
/**
* Location
*
* @author <NAME> <<EMAIL>>
*/
class Location_Service_Location extends MF_Service_ServiceAbstract {
protected $locationTable;
public static $articleItemCountPerPage = 5;
public static function getArticleItemCountPerPage(){
return self::$articleItemCountPerPage;
}
public function init() {
$this->locationTable = Doctrine_Core::getTable('Location_Model_Doctrine_Location');
}
public function getAllLocation($countOnly = false) {
if(true == $countOnly) {
return $this->locationTable->count();
} else {
return $this->locationTable->findAll();
}
}
public function getLocation($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->locationTable->findOneBy($field, $id, $hydrationMode);
}
public function getFullLocation($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->locationTable->getPublishLocationQuery();
// $q = $this->locationTable->getPhotoQuery($q);
if(in_array($field, array('id'))) {
$q->andWhere('l.' . $field . ' = ?', array($id));
} elseif(in_array($field, array('slug'))) {
$q->andWhere('lt.' . $field . ' = ?', array($id));
//$q->andWhere('at.lang = ?', 'pl');
}
return $q->fetchOne(array(), $hydrationMode);
}
public function getRecentLocation($limit, $categoryIds, $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->locationTable->getPublishLocationQuery();
$q = $this->locationTable->getPhotoQuery($q);
$q = $this->locationTable->getLimitQuery($limit, $q);
$q = $this->locationTable->getCategoryIdQuery($categoryIds, $q);
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getLocationsForJson($language = 'en', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->locationTable->createQuery('l');
$q->leftJoin('l.Translation lt');
$q->addSelect('lt.city,lt.id,l.lat,l.lng');
$q->addWhere('lt.lang = ?',$language);
return $q->execute(array(), $hydrationMode);
}
public function getAlli18nLocations($order = 'lt.title DESC',$language = 'en', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->locationTable->getPublishLocationQuery();
$q->addWhere('lt.lang = ?',$language);
$q->orderBy($order);
return $q->execute(array(), $hydrationMode);
}
public function getNew($limit, $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->locationTable->getPublishLocationQuery();
$q = $this->locationTable->getPhotoQuery($q);
$q = $this->locationTable->getLimitQuery($limit, $q);
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getLocationPaginationQuery($language) {
$q = $this->locationTable->getPublishLocationQuery();
$q = $this->locationTable->getPhotoQuery($q);
$q->andWhere('at.lang = ?', $language);
$q->addOrderBy('a.sponsored DESC');
$q->addOrderBy('a.publish_date DESC');
return $q;
}
public function getLocationOnMainPage($limit, $language, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
$q = $this->locationTable->getPublishLocationQuery();
$q = $this->locationTable->getPhotoQuery($q);
$q->andWhere('at.lang = ?', $language);
$q->addOrderBy('a.sponsored DESC');
$q->addOrderBy('a.publish_date DESC');
$q->limit($limit);
return $q->execute(array(), $hydrationMode);
}
public function getLocationForm(Location_Model_Doctrine_Location $location = null) {
$form = new Location_Form_Location();
$form->setDefault('publish', 1);
if(null != $location) {
$form->populate($location->toArray());
$i18nService = MF_Service_ServiceBroker::getInstance()->getService('Default_Service_I18n');
$languages = $i18nService->getLanguageList();
foreach($languages as $language) {
$i18nSubform = $form->translations->getSubForm($language);
if($i18nSubform) {
$i18nSubform->getElement('title')->setValue($location->Translation[$language]->title);
$i18nSubform->getElement('content')->setValue($location->Translation[$language]->content);
$i18nSubform->getElement('city')->setValue($location->Translation[$language]->city);
}
}
}
return $form;
}
public function saveLocationFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$location = $this->locationTable->getProxy($values['id'])) {
$location = $this->locationTable->getRecord();
}
$i18nService = MF_Service_ServiceBroker::getInstance()->getService('Default_Service_I18n');
$location->fromArray($values);
$languages = $i18nService->getLanguageList();
foreach($languages as $language) {
if(is_array($values['translations'][$language]) && strlen($values['translations'][$language]['title'])) {
$location->Translation[$language]->title = $values['translations'][$language]['title'];
$location->Translation[$language]->slug = MF_Text::createUniqueTableSlug('Location_Model_Doctrine_LocationTranslation', $values['translations'][$language]['title'], $location->getId());
$location->Translation[$language]->content = $values['translations'][$language]['content'];
$location->Translation[$language]->city = $values['translations'][$language]['city'];
}
}
$location->save();
return $location;
}
public function removeLocation(Location_Model_Doctrine_Location $location) {
$location->delete();
}
// public function searchLocation($phrase, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
// $q = $this->locationTable->getAllLocationQuery();
// $q->addSelect('TRIM(at.title) AS search_title, TRIM(at.content) as search_content, "location" as search_type');
// $q->andWhere('at.title LIKE ? OR at.content LIKE ?', array("%$phrase%", "%$phrase%"));
// return $q->execute(array(), $hydrationMode);
// }
public function getAllSortedLocation($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->locationTable->getPublishLocationQuery();
$q = $this->locationTable->getPhotoQuery($q);
$q->orderBy('a.created_at DESC');
return $q->execute(array(), $hydrationMode);
}
public function getTargetLocationSelectOptions($prependEmptyValue = false, $language = null) {
$items = $this->getAllSortedLocation(Doctrine_Core::HYDRATE_RECORD);
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
foreach($items as $item) {
$result[$item->getId()] = $item->Translation[$language]->title;
}
return $result;
}
public function getPreSortedPredifiniedLocation($locationIds) {
$q = $this->locationTable->getAllLocationQuery();
$q->where('a.id IN ?', array($locationIds));
if(is_array($locationIds)):
$q->addOrderBy('FIELD(a.id, '.implode(', ', $locationIds).')');
endif;
return $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
}
public function refreshSponsoredLocation($location){
if ($location->isSponsored()):
$location->setSponsored(0);
else:
$location->setSponsored(1);
endif;
$location->save();
}
public function searchLocation($phrase, $hydrationMode = Doctrine_Core::HYDRATE_RECORD){
$q = $this->locationTable->getPublishLocationQuery();
$q = $this->locationTable->getPhotoQuery($q);
$q->addSelect('TRIM(at.title) AS search_title, TRIM(at.content) as search_content, "location" as search_type');
$q->andWhere('at.title LIKE ? OR at.content LIKE ?', array("%$phrase%", "%$phrase%"));
//$q->addOrderBy('RANDOM()');
return $q->execute(array(), $hydrationMode);
}
public function getAllLocationsForSiteMap($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->locationTable->getPublishLocationQuery();
return $q->execute(array(), $hydrationMode);
}
}
<file_sep>/application/modules/affilateprogram/controllers/AdminController.php
<?php
/**
* Affilateprogram_AdminController
*
* @author <NAME> <<EMAIL>>
*/
class Affilateprogram_AdminController extends MF_Controller_Action {
public static $itemCountPerPage = 15;
public function listPartnerAction() {
}
public function listPartnerDataAction() {
$table = Doctrine_Core::getTable('Affilateprogram_Model_Doctrine_Partner');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Affilateprogram_DataTables_Partner',
'columns' => array('p.name'),
'searchFields' => array('p.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result->name;
$row[] = $result->reference_number;
$options = '<a href="' . $this->view->adminUrl('check-commission', 'affilateprogram', array('id' => $result->id)) . '" title="' . $this->view->translate('Edit') . '"><span class="icon24 icomoon-icon-history"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('edit-partner', 'affilateprogram', array('id' => $result->id)) . '" title="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-partner', 'affilateprogram', array('id' => $result->id)) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addPartnerAction() {
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
$translator = $this->_service->get('translate');
$form = $affilateProgramService->getPartnerForm();
$form->setAction($this->view->adminUrl('add-partner', 'affilateprogram'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$affilateProgramService->savePartnerWithNewNumberFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-partner', 'affilateprogram'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
}
public function editPartnerAction() {
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
$translator = $this->_service->get('translate');
if(!$partner = $affilateProgramService->getPartner((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Partner not found');
}
$form = $affilateProgramService->getPartnerForm($partner);
$form->setAction($this->view->adminUrl('edit-partner', 'affilateprogram'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$affilateProgramService->savePartnerFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-partner', 'affilateprogram'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('partner', $partner);
}
public function removePartnerAction() {
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
if($partner = $affilateProgramService->getPartner($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$affilateProgramService->removePartner($partner);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-partner', 'affilateprogram'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-partner', 'affilateprogram'));
}
public function checkCommissionAction() {
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
$translator = $this->_service->get('translate');
if(!$partner = $affilateProgramService->getPartner((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Partner not found');
}
$form = $affilateProgramService->getCheckCommissionForm();
$commission = 0;
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$partnerOrders = $affilateProgramService->getOrdersForPartner($partner->getId(), $values);
foreach($partnerOrders[0]['PartnerOrders'] as $order):
$commission = $commission + $order['Order']['total_cost']*$partner->getCommission()/100;
endforeach;
$this->_service->get('doctrine')->getCurrentConnection()->commit();
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('commission', $commission);
$this->view->assign('form', $form);
$this->view->assign('partner', $partner);
}
}
<file_sep>/application/modules/order/forms/Payu/Payment.php
<?php
/**
* Order_Form_Payu_Payment
*
* @author <NAME> <<EMAIL>>
*/
class Order_Form_Payu_Payment extends Order_Form_Payu {
public function init() {
parent::init();
$this->getElement('submit')->setLabel('Zapłać teraz');
}
public function setup($config) {
parent::setup($config);
if(array_key_exists('UrlPlatnosci_pl', $config)) {
$this->setAction($config['UrlPlatnosci_pl'] . '/UTF/NewPayment');
}
}
}
<file_sep>/application/modules/order/forms/CouponSend.php
<?php
/**
* Order_Form_CouponSend
*
* @author <NAME> <<EMAIL>>
*/
class Order_Form_CouponSend extends Admin_Form {
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$email = $this->createElement('text', 'email');
$email->setLabel('Email');
$email->setRequired(false);
$email->setDecorators(self::$textDecorators);
$email->setAttrib('class', 'span8');
$userId = $this->createElement('select', 'user_id');
$userId->setLabel('User');
$userId->setRequired(false);
$userId->setDecorators(self::$selectDecorators);
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Send');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$id,
$email,
$userId,
$submit
));
}
}
<file_sep>/application/modules/tournament/forms/Timetable.php
<?php
class Tournament_Form_Timetable extends Admin_Form
{
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$date = $this->createElement('text', 'date');
$date->setDecorators(self::$textDecorators);
$date->setAttrib('class', 'span8 mask_date2');
for($j=1;$j<=20;$j++):
${'time'.$j} = $this->createElement('text', 'time'.$j);
${'time'.$j}->setDecorators(self::$textDecorators);
${'time'.$j}->setAttrib('class', 'span8 mask_time2');
$this->addElement(${'time'.$j});
${'group_round'.$j} = $this->createElement('checkbox', 'group_round'.$j);
${'group_round'.$j}->setDecorators(self::$textDecorators);
${'group_round'.$j}->setAttrib('class', 'span8');
${'group_round'.$j}->setValue(1);
$this->addElement(${'group_round'.$j});
endfor;
for($i=1;$i<=40;$i++):
${'team'.$i} = $this->createElement('select', 'team'.$i);
${'team'.$i}->setDecorators(User_BootstrapForm::$bootstrapElementDecorators);
${'team'.$i}->setAttrib('class', 'span2');
${'team'.$i}->addMultiOption('', '');
$this->addElement(${'team'.$i});
endfor;
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Save');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->addElement($date);
$this->addElement($submit);
}
}<file_sep>/application/modules/order/forms/DiscountCode.php
<?php
/**
* Order_Form_DiscountCode
*
* @author <NAME> <<EMAIL>>
*/
class Order_Form_DiscountCode extends Admin_Form {
public function init() {
$code = $this->createElement('text', 'discount_code');
$code->setRequired(true);
$code->setDecorators(User_BootstrapForm::$bootstrapElementDecorators);
$code->setAttrib('class', 'form-control');
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Apply coupon');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-default', 'type' => 'submit'));
$this->setElements(array(
$id,
$code,
$submit
));
}
}
<file_sep>/application/modules/attachment/models/Doctrine/Attachment.php
<?php
/**
* Attachment_Model_Doctrine_Attachment
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package Admi
* @subpackage Attachment
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Attachment_Model_Doctrine_Attachment extends Attachment_Model_Doctrine_BaseAttachment
{
public static $attachmentPhotoDimensions = array(
'126x126' => 'Photo in admin panel', // admin
'400x200' => 'Main photo'
);
public static function getAttachmentPhotoDimensions() {
return self::$attachmentPhotoDimensions;
}
public function setId($id) {
$this->_set('id', $id);
}
public function getId() {
return $this->_get('id');
}
public function setFilename($filename) {
$this->_set('filename', $filename);
}
public function getFilename() {
return $this->_get('filename');
}
public function setTitle($title) {
$this->_set('title', $title);
}
public function getTitle(){
return $this->_get('title');
}
public function setExtension($extension) {
$this->_set('extension', $extension);
}
public function setUp() {
$this->hasOne('Media_Model_Doctrine_Photo as PhotoRoot', array(
'local' => 'photo_root_id',
'foreign' => 'id'
));
parent::setUp();
}
}<file_sep>/application/modules/order/library/DataTables/Adapter/Item.php
<?php
/**
* Order_DataTables_Adapter_Item
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Adapter_Item extends Default_DataTables_Adapter_AdapterAbstract {
public function getBaseQuery() {
$q = $this->table->createQuery('it');
$q->select('it.*');
$q->addSelect('pro.*');
$q->leftJoin('it.Product pro');
$q->andWhere('it.order_id = ?', array($this->request->getParam('id')));
return $q;
}
}
<file_sep>/application/modules/tournament/controllers/AdminController.php
<?php
/**
* Order_AdminController
*
* @author <NAME> <<EMAIL>>
*/
class Tournament_AdminController extends MF_Controller_Action {
public function listGroupAction() {
$groupService = $this->_service->getService('Tournament_Service_Team');
$tournament_id = $this->getRequest()->getParam('tournament_id');
$groups = $groupService->getGroupTeams();
$this->view->assign('groups', $groups);
$this->view->assign('tournament_id', $tournament_id);
}
public function addTeamAction() {
$teamService = $this->_service->getService('Tournament_Service_Team');
// if(!$booking = $bookingService->getSingleBooking((int) $this->getRequest()->getParam('id'))) {
// throw new Zend_Controller_Action_Exception('Booking not found');
// }
$tournament_id = $this->getRequest()->getParam('tournament_id');
$form = $teamService->getGroupTeamForm();
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$values['tournament_id'] = $tournament_id;
$team = $teamService->saveTeamFromArray($values);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-group', 'tournament',array('tournament_id' => $tournament_id)));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('tournament_id', $tournament_id);
$this->view->assign('form', $form);
}
public function editGroupAction() {
$bookingService = $this->_service->getService('Tournament_Service_Booking');
$playerService = $this->_service->getService('Tournament_Service_Player');
if(!$booking = $bookingService->getSingleBooking((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Booking not found');
}
$tournament_id = $this->getRequest()->getParam('tournament_id');
$form = $bookingService->getBookingForm($booking);
$form->getElement('player_id')->setMultiOptions($playerService->prependPlayerOptions($tournament_id));
$form->getElement('player_id')->setValue($booking['player_id']);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$booking = $bookingService->saveBookingFromArray($values);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-booking', 'tournament',array('tournament_id' => $tournament_id)));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('tournament_id', $tournament_id);
$this->view->assign('form', $form);
}
public function setGroupActiveAction() {
$bookingService = $this->_service->getService('Tournament_Service_Booking');
if(!$booking = $bookingService->getSingleBooking((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Booking not found');
}
if($booking->get('active'))
$booking->set('active',false);
else
$booking->set('active',true);
$booking->save();
$this->_helper->redirector->gotoUrl($_SERVER['HTTP_REFERER']);
}
public function removeGroupAction() {
$bookingService = $this->_service->getService('Tournament_Service_Booking');
if(!$booking = $bookingService->getSingleBooking((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Booking not found');
}
$booking->delete();
$this->_helper->redirector->gotoUrl($_SERVER['HTTP_REFERER']);
}
public function listTournamentAction() {
}
public function listTournamentDataAction() {
$table = Doctrine_Core::getTable('Tournament_Model_Doctrine_Tournament');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Tournament_DataTables_Tournament',
'columns' => array('l.id','l.name'),
'searchFields' => array('l.id','l.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['id'];
$row[] = $result['name'];
$options = '<a href="' . $this->view->adminUrl('edit-order', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
/* tournament - finish */
/* match - start */
public function listMatchAction() {
$tournament_id = $this->getRequest()->getParam('tournament_id');
$this->view->assign('tournament_id',$tournament_id);
}
public function listMatchDataAction() {
$table = Doctrine_Core::getTable('Tournament_Model_Doctrine_Match');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Tournament_DataTables_Match',
'columns' => array('m.id','t1.name','t2.name','m.match_date'),
'searchFields' => array('m.id','t1.name','t2.name','m.match_date')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['id'];
$row[] = $result['Team1']['name'];
$row[] = $result['Team2']['name'];
$goal = "Edit <input type = 'checkbox' rel = '".$result['id']."' /><br /><br />";
$goal .= "<input type = 'text' size='4' style='width:20px' disabled parent = '".$result['id']."' inp_id = '".$result['id']."_1' value='".$result['goal1']."' /> ";
$goal .= "<input type = 'text' size = '4' style='width:20px' disabled parent = '".$result['id']."' inp_id = '".$result['id']."_2' value='".$result['goal2']."' /><br />";
$goal .= "<input type = 'submit' sub_id = '".$result['id']."' disabled parent = '".$result['id']."' name='submit' value='submit' />";
$row[] = $goal;
$row[] = $result['match_date'];
$options = '<a href="' . $this->view->adminUrl('edit-match', 'tournament', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-match', 'tournament', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon16 icon-remove"></span></a> ';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function saveMatchAction() {
$matchService = $this->_service->getService('Tournament_Service_Match');
if(!$match = $matchService->getMatch((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Match not found');
}
$match->setGoal1($this->getRequest()->getParam('goal1'));
$match->setGoal2($this->getRequest()->getParam('goal2'));
$match->setPlayed();
$match->save();
$response = array(
"success" => "success"
);
$this->_helper->json($response);
}
public function editMatchAction() {
$matchService = $this->_service->getService('Tournament_Service_Match');
$teamService = $this->_service->getService('Tournament_Service_Team');
$shooterService = $this->_service->getService('Tournament_Service_Shooter');
if(!$match = $matchService->getMatch((int) $this->getRequest()->getParam('id'),'id')) {
throw new Zend_Controller_Action_Exception('Match not found');
}
$players1 = $teamService->getTeamPlayers($match['team1'],'id');
$players2 = $teamService->getTeamPlayers($match['team2'],'id');
$shooters = $shooterService->getMatchShooters($match['id']);
// Zend_Debug::dump($shooters);exit;
if(isset($_POST['submit'])){
$values = $_POST;
$matchService->saveShootersFromArray($values,$match);
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-match', 'tournament',array('tournament_id' => $match->tournament_id)));
}
$this->view->assign('match',$match);
$this->view->assign('players1',$players1);
$this->view->assign('players2',$players2);
$this->view->assign('shooters',$shooters);
}
/* match - finish */
public function timetableAction() {
$matchService = $this->_service->getService('Tournament_Service_Match');
$teamService = $this->_service->getService('Tournament_Service_Team');
$tournamentService = $this->_service->getService('Tournament_Service_Tournament');
$form = new Tournament_Form_Timetable();
if(!$tournament = $tournamentService->getTournament((int) $this->getRequest()->getParam('tournament_id'))) {
throw new Zend_Controller_Action_Exception('Tournament not found');
}
$teams = $teamService->getTournamentTeams($tournament->id,'id');
$teamsTimetable = $teamService->getTeamsTimetable($tournament->id);
for($i=1;$i<41;$i++):
$t = $form->getElement('team'.$i);
foreach($teams as $team):
$t->addMultiOption($team->id,$team->name);
endforeach;
endfor;
$this->view->assign('teamsTimetable',$teamsTimetable);
$this->view->assign('tournament',$tournament);
$this->view->assign('form',$form);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$values['tournament_id'] = $tournament->id;
$matchService->saveTimetableFromArray($values);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('timetable', 'tournament',array('tournament_id' => $tournament->id)));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
}
public function listBookingAction() {
$tournament_id = $this->getRequest()->getParam('tournament_id');
$this->view->assign('tournament_id', $tournament_id);
}
public function listBookingDataAction() {
$table = Doctrine_Core::getTable('Tournament_Model_Doctrine_Booking');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Tournament_DataTables_Booking',
'columns' => array('b.id','p.last_name', 't.name','p.weight'),
'searchFields' => array('b.id','p.last_name', 't.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['id'];
$row[] = $result['Player']['last_name']." ".$result['Player']['first_name'];
$row[] = $result['Player']['Team']['name'];
if($result['weight']==2)
$row[] = "Czerwona";
else
$row[] = "Żółta";
$row[] = $result['quantity'];
if($result['active']==1)
$row[] = '<a href="' . $this->view->adminUrl('set-booking-active', 'tournament', array('id' => $result['id'])) . '" title="' . $this->view->translate('Aktywna') . '"><span class="icon16 icomoon-icon-checkbox"></span></a>';
else
$row[] = '<a href="' . $this->view->adminUrl('set-booking-active', 'tournament', array('id' => $result['id'])) . '" title="' . $this->view->translate('Nieaktywna') . '"><span class="icon16 icomoon-icon-checkbox-unchecked"></span></a>';
$options = '<a href="' . $this->view->adminUrl('edit-booking', 'tournament', array('id' => $result['id'])) .'/tournament_id/'.$result['Player']['Team']['tournament_id']. '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-booking', 'tournament', array('id' => $result['id'])) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icomoon-icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addBookingAction() {
$bookingService = $this->_service->getService('Tournament_Service_Booking');
$playerService = $this->_service->getService('Tournament_Service_Player');
// if(!$booking = $bookingService->getSingleBooking((int) $this->getRequest()->getParam('id'))) {
// throw new Zend_Controller_Action_Exception('Booking not found');
// }
$tournament_id = $this->getRequest()->getParam('tournament_id');
$form = $bookingService->getBookingForm();
$form->getElement('player_id')->setMultiOptions($playerService->prependPlayerOptions($tournament_id));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$booking = $bookingService->saveBookingFromArray($values);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-booking', 'tournament',array('tournament_id' => $tournament_id)));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('tournament_id', $tournament_id);
$this->view->assign('form', $form);
}
public function editBookingAction() {
$bookingService = $this->_service->getService('Tournament_Service_Booking');
$playerService = $this->_service->getService('Tournament_Service_Player');
if(!$booking = $bookingService->getSingleBooking((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Booking not found');
}
$tournament_id = $this->getRequest()->getParam('tournament_id');
$form = $bookingService->getBookingForm($booking);
$form->getElement('player_id')->setMultiOptions($playerService->prependPlayerOptions($tournament_id));
$form->getElement('player_id')->setValue($booking['player_id']);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$booking = $bookingService->saveBookingFromArray($values);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-booking', 'tournament',array('tournament_id' => $tournament_id)));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('tournament_id', $tournament_id);
$this->view->assign('form', $form);
}
public function setBookingActiveAction() {
$bookingService = $this->_service->getService('Tournament_Service_Booking');
if(!$booking = $bookingService->getSingleBooking((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Booking not found');
}
if($booking->get('active'))
$booking->set('active',false);
else
$booking->set('active',true);
$booking->save();
$this->_helper->redirector->gotoUrl($_SERVER['HTTP_REFERER']);
}
public function removeBookingAction() {
$bookingService = $this->_service->getService('Tournament_Service_Booking');
if(!$booking = $bookingService->getSingleBooking((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Booking not found');
}
$booking->delete();
$this->_helper->redirector->gotoUrl($_SERVER['HTTP_REFERER']);
}
public function removeDeliveryTypeAction() {
$deliveryTypeService = $this->_service->getService('Order_Service_DeliveryType');
if($deliveryType = $deliveryTypeService->getDeliveryType($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$deliveryTypeService->removeDeliveryType($deliveryType);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-delivery-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-delivery-type', 'order'));
}
public function listPaymentTypeAction() {
}
public function listPaymentTypeDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_PaymentType');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_PaymentType',
'columns' => array('pt.name'),
'searchFields' => array('pt.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['name'];
$options = '<a href="' . $this->view->adminUrl('edit-payment-type', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-payment-type', 'order', array('id' => $result['id'])) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function listDiscountCodeDataAction()
{
$table = Doctrine_Core::getTable('Order_Model_Doctrine_DiscountCode');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_DiscountCode',
'columns' => array('dc.code','dc.active','dc.id'),
'searchFields' => array('dc.active')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['code'];
if($result['active'])
$row[] = "tak";
else
$row[] = "nie";
$row[] = ($result['discount']*100)."%";
$options = '<a href="' . $this->view->adminUrl('edit-discount-code', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Change status') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$row[] = $options;
$rows[] = $row;
}
// Zend_Debug::dump($rows);
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function editDiscountCodeAction() {
$discountCodeService = $this->_service->getService('Order_Service_DiscountCode');
$translator = $this->_service->get('translate');
// $discountCode = $discountCodeService->getDiscountCode(2);
// echo $discountCode;
// exit;
if(!$discountCode = $discountCodeService->getDiscountCodeById((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Discount Code not found');
}
try {
if($discountCode['active'])
$status = 0;
else
$status = 1;
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$discountCodeService->changeActiveStatus((int) $this->getRequest()->getParam('id'),$status);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('order-discount', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
// $this->view->assign('form', $form);
// $this->view->assign('orderStatus', $orderStatus);
}
public function addDiscountCodeAction() {
$discountCodeService = $this->_service->getService('Order_Service_DiscountCode');
$translator = $this->_service->get('translate');
$form = $discountCodeService->getDiscountCodeForm();
$form->setAction($this->view->adminUrl('add-discount-code', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$discountCodeService = $discountCodeService->saveDiscountCodeFromArray($values);
$this->view->messages()->add($translator->translate('Discount code has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('order-discount', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
}
public function addPaymentTypeAction() {
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
$translator = $this->_service->get('translate');
$form = $paymentTypeService->getPaymentTypeForm();
$form->setAction($this->view->adminUrl('add-payment-type', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$paymentType = $paymentTypeService->savePaymentTypeFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-payment-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
}
public function editPaymentTypeAction() {
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
$translator = $this->_service->get('translate');
if(!$paymentType = $paymentTypeService->getPaymentType((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Payment type not found');
}
$form = $paymentTypeService->getPaymentTypeForm($paymentType);
$form->setAction($this->view->adminUrl('edit-payment-type', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$paymentTypeService->savePaymentTypeFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-payment-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('paymentType', $paymentType);
}
public function removePaymentTypeAction() {
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
if($paymentType = $paymentTypeService->getPaymentType($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$paymentTypeService->removePaymentType($paymentType);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-payment-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-payment-type', 'order'));
}
public function listOrderStatusAction() {
}
public function listOrderStatusDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_OrderStatus');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_OrderStatus',
'columns' => array('os.name'),
'searchFields' => array('os.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['name'];
$options = '<a href="' . $this->view->adminUrl('edit-order-status', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-order-status', 'order', array('id' => $result['id'])) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
// Zend_Debug::dump($rows);
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addOrderStatusAction() {
$orderStatusService = $this->_service->getService('Order_Service_OrderStatus');
$translator = $this->_service->get('translate');
$form = $orderStatusService->getOrderStatusForm();
$form->setAction($this->view->adminUrl('add-order-status', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$orderStatus = $orderStatusService->saveOrderStatusFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-order-status', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
}
public function editOrderStatusAction() {
$orderStatusService = $this->_service->getService('Order_Service_OrderStatus');
$translator = $this->_service->get('translate');
if(!$orderStatus = $orderStatusService->getOrderStatus((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Order status not found');
}
$form = $orderStatusService->getOrderStatusForm($orderStatus);
$form->setAction($this->view->adminUrl('edit-order-status', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$orderStatusService->saveOrderStatusFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-order-status', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('orderStatus', $orderStatus);
}
public function removeOrderStatusAction() {
$orderStatusService = $this->_service->getService('Order_Service_OrderStatus');
if($orderStatus = $orderStatusService->getOrderStatus($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$orderStatusService->removeOrderStatus($orderStatus);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-order-status', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-order-status', 'order'));
}
public function pdfInvoiceAction() {
require_once('tcpdf/tcpdf.php');
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$orderService = $this->_service->getService('Order_Service_Order');
if(!$order = $orderService->getFullOrder((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Order not found');
}
$code = 'F-'.MF_Text::timeFormat($order['created_at'], 'Ymd').'-'.$order['id'];
$saleDate = MF_Text::timeFormat($order['created_at'], 'd.m.Y');
$invoiceDate = date('d.m.Y');
$this->view->assign('sale_date', $saleDate);
$this->view->assign('invoice_date', $invoiceDate);
$this->view->assign('code', $code);
$this->view->assign('order', $order);
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetAutoPageBreak(1, 30);
$pdf->SetFont('freesans');
$htmlcontent = $this->view->render('admin/pdf-invoice.phtml');
//$pdf->SetPrintHeader(false);
// $pdf->SetPrintFooter(false);
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->addPage();
$pdf->writeHTML($htmlcontent, true, 0, true, 0);
$pdf->lastPage();
$pdf->Output();
$pdf->Output($code . '.pdf', 'D');
}
}
<file_sep>/application/modules/league/controllers/IndexController.php
<?php
/**
* Order_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class League_IndexController extends MF_Controller_Action {
public function indexAction() {
$orderService = $this->_service->getService('Order_Service_Order');
$modelCart = $orderService->getCart();
}
public function timetableAction()
{
$matchService = $this->_service->getService('League_Service_Match');
$leagueService = $this->_service->getService('League_Service_League');
if(!$league = $leagueService->getLeague($this->getRequest()->getParam('league'),'slug')){
throw new Zend_Exception('League not found');
}
$data = $matchService->getTimetableDate($league->id);
$timetable = $matchService->getTimetable($league->id);
$this->view->assign('data',$data->toArray());
$this->view->assign('timetable',$timetable);
$this->view->assign('league',$league);
$this->_helper->actionStack('layout','index','default');
}
public function showResultAction()
{
$leagueService = $this->_service->getService('League_Service_League');
$matchService = $this->_service->getService('League_Service_Match');
$shooterService = $this->_service->getService('League_Service_Shooter');
if(!$league = $leagueService->getLeague($this->getRequest()->getParam('league'),'slug')){
throw new Zend_Exception('League not found');
}
$results = $matchService->getResults($league->id);
$this->view->assign('results',$results);
$this->view->assign('league',$league);
$this->view->assign('shooterService',$shooterService);
$this->_helper->actionStack('layout','index','default');
}
public function showTableAction()
{
$leagueService = $this->_service->getService('League_Service_League');
$matchService = $this->_service->getService('League_Service_Match');
if(!$league = $leagueService->getLeague($this->getRequest()->getParam('league'),'slug')){
throw new Zend_Exception('League not found');
}
$results = $matchService->getTable($league->id);
$this->view->assign('tabela',$results);
$this->view->assign('league',$league);
$this->_helper->actionStack('layout','index','default');
}
public function showShootersAction()
{
$leagueService = $this->_service->getService('League_Service_League');
$shooterService = $this->_service->getService('League_Service_Shooter');
if(!$league = $leagueService->getLeague($this->getRequest()->getParam('league'),'slug')){
throw new Zend_Exception('League not found');
}
$results = $shooterService->getShooters($league->id);
$this->view->assign('strzelcy',$results);
$this->view->assign('league',$league);
$this->_helper->actionStack('layout','index','default');
}
public function showBookingAction()
{
$leagueService = $this->_service->getService('League_Service_League');
$bookingService = $this->_service->getService('League_Service_Booking');
if(!$league = $leagueService->getLeague($this->getRequest()->getParam('league'),'slug')){
throw new Zend_Exception('League not found');
}
$yellowCards = $bookingService->getBooking($league->id,1);
$redCards = $bookingService->getBooking($league->id,2);
$this->view->assign('redCards',$redCards);
$this->view->assign('yellowCards',$yellowCards);
$this->view->assign('league',$league);
$this->_helper->actionStack('layout','index','default');
}
public function showSquadAction()
{
$leagueService = $this->_service->getService('League_Service_League');
$teamService = $this->_service->getService('League_Service_Team');
if(!$league = $leagueService->getLeague($this->getRequest()->getParam('league'),'slug')){
throw new Zend_Exception('League not found');
}
$team = $teamService->getTeam($this->getRequest()->getParam('team'),'slug');
$this->view->assign('team',$team);
$this->_helper->actionStack('layout','index','default');
}
public function showCupAction() {
$photoDimensionService = $this->_service->getService('Default_Service_PhotoDimension');
$cupService = $this->_service->getService('League_Service_Cup');
$metatagService = $this->_service->getService('Default_Service_Metatag');
if(!$cup = $cupService->getCup($this->getRequest()->getParam('slug'), 'slug', Doctrine_Core::HYDRATE_RECORD)) {
throw new Zend_Controller_Action_Exception('Cup not found');
}
$photoDimension = $photoDimensionService->getElementDimension('page');
$metatagService->setViewMetatags($cup['metatag_id'], $this->view);
$this->_helper->actionStack('layout', 'index', 'default');
$this->view->assign('cup', $cup);
$this->view->assign('photoDimension', $photoDimension);
}
public function basketAction() {
$this->_helper->layout->setLayout('login');
$orderService = $this->_service->getService('Order_Service_Order');
$modelCart = $orderService->getCart();
$items = $modelCart->getItems();
// liczenie wartości przedmiotów w koszyku i zapisywanie do sesji
$itemsValue = $modelCart->countItemsValue($items);
$modelCart->updatePrice('total_price',$itemsValue);
$form = new Order_Form_DeliveryPayment();
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$modelCart->updatePrice('delivery_type_id',$values['delivery_type_id']);
$modelCart->updatePrice('payment_type_id',$values['payment_type_id']);
$this->_helper->redirector->gotoUrl($this->view->url(array('action' => 'first-step'),'domain-order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}}
// jeżeli nie jest wprowadzony kod rabatowy to cena po rabacie jest ceną produktów
else{
$modelCart->updatePrice('total_price_after_discount',$modelCart->getPrice('total_price'));
}
$prices = $modelCart->getPrices();
$this->view->assign('prices',$prices);
$this->view->assign('form',$form);
$this->view->assign('items',$items);
$this->_helper->actionStack('layout', 'index', 'default');
// $modelCart->clean();
}
public function displayDimensionAction()
{
}
public function removeItemAction()
{
$id = $this->getRequest()->getParam('id');
$orderService = $this->_service->getService('Order_Service_Order');
$modelCart = $orderService->getCart();
$modelCart->remove('Product_Model_Doctrine_Product',$id);
$this->_helper->viewRenderer->setNoRender();
return $this->redirect($this->view->url(array('action' => 'basket'),'domain-order'));
}
public function firstStepAction()
{
$this->_helper->layout->setLayout('login');
$orderService = $this->_service->getService('Order_Service_Order');
$userService = $this->_service->getService('User_Service_User');
$ud = $userService->getFullUser(Zend_Auth::getInstance()->getIdentity(),'email');
if($ud)
{
$user_id = $ud->getId();
$userData = $userService->getProfile($user_id);
}
else
{
$userData = null;
}
$modelCart = $orderService->getCart();
$form = new Order_Form_PersonalData();
$clientType = $form->getElement('client_type');
$form->removeElement('client_type');
$form->removeElement('difAddress');
// Zend_Debug::dump($modelCart->getItems());
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$modelCart->storeValues($values);
$this->_helper->redirector->gotoUrl($this->view->url(array('action' => 'second-step'),'domain-order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
//
}}
if($dataValues = $modelCart->getValues())
$this->view->assign('dataValues',$dataValues);
$this->_helper->actionStack('layout', 'index', 'default');
$this->view->assign('form',$form);
$this->view->assign('clientType',$clientType);
$this->view->assign('userData',$userData);
}
public function secondStepAction()
{
$this->_helper->layout->setLayout('login');
$orderService = $this->_service->getService('Order_Service_Order');
$deliveryTypeService = $this->_service->getService('Order_Service_DeliveryType');
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
$discountCodeService = $this->_service->getService('Order_Service_DiscountCode');
$modelCart = $orderService->getCart();
$items = $modelCart->getItems();
// Zend_Debug::dump($items);
// liczenie wartości przedmiotów w koszyku i zapisywanie do sesji
$itemsValue = $modelCart->countItemsValue($items);
$modelCart->updatePrice('total_price',$itemsValue);
$deliveryType = $deliveryTypeService->getDeliveryType((int)$modelCart->getPrice('delivery_type_id'));
$paymentType = $paymentTypeService->getPaymentType((int)$modelCart->getPrice('payment_type_id'));
$dataValues = $modelCart->getValues();
$form = new Order_Form_DeliveryPayment();
if($modelCart->getPrice('discount')!=null)
{
$form->getElement('code')->setAttrib('disabled','disabled');
$form->getElement('submit')->setAttrib('disabled','disabled');
}
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
if(trim($values['code'])!="Wprowdź kod rabatowy")
{
$discountValue = $discountCodeService->getDiscountCode($values['code'])->getDiscount();
$discountValue *= 100;
$modelCart->updatePrice('discount',$discountValue);
$itemsValueAfterDiscount = $modelCart->countDiscountedPrice($itemsValue,$discountValue);
$modelCart->updatePrice('total_price_after_discount',$itemsValueAfterDiscount);
}
else
{
echo "Podany kod jest nieaktywny";
}
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}}
// jeżeli nie jest wprowadzony kod rabatowy to cena po rabacie jest ceną produktów
else{
$modelCart->updatePrice('total_price_after_discount',$modelCart->getPrice('total_price'));
}
$prices = $modelCart->getPrices();
$this->view->assign('prices',$prices);
$this->view->assign('dataValues',$dataValues);
$this->view->assign('deliveryType',$deliveryType);
$this->view->assign('paymentType',$paymentType);
$this->view->assign('form',$form);
$this->view->assign('items',$items);
$this->_helper->actionStack('layout', 'index', 'default');
}
public function thirdStepAction()
{
$this->_helper->layout->setLayout('login');
$userService = $this->_service->getService('User_Service_User');
$orderService = $this->_service->getService('Order_Service_Order');
$deliveryAddressService = $this->_service->getService('Order_Service_DeliveryAddress');
$deliveryService = $this->_service->getService('Order_Service_Delivery');
$paymentService = $this->_service->getService('Order_Service_Payment');
$itemService = $this->_service->getService('Order_Service_Item');
$modelCart = $orderService->getCart();
$dataValues = $modelCart->getValues();
$deliveryAddress = $deliveryAddressService->checkDeliveryAddress($dataValues);
// zapisywanie uzytkownika
$newDataValues = array_merge($dataValues,$deliveryAddress);
$us = $userService->saveClientFromArray($newDataValues);
// zapisywanie sposobu dostawy
$das = $deliveryAddressService->saveDeliveryAddressFromArray($deliveryAddress);
$deliveryData = array('delivery_type_id' => $modelCart->getPrice('delivery_type_id'),'delivery_address_id' => $das->getId());
//laczenie adresu i sposobu dostawy
$ds = $deliveryService->saveDeliveryFromArray($deliveryData);
$ps = $paymentService->savePaymentFromArray(array('payment_type_id'=>$modelCart->getPrice('payment_type_id')));
$orderData = array(
'total_cost'=>$modelCart->countItemsValue(),
'user_id'=>$us->getId(),
'order_status_id'=>8,
'delivery_id'=>$ds->getId(),
'payment_id'=>$ps->getId());
// zapisywanie zamowienia
$os = $orderService->saveOrderFromArray($orderData);
// zapisywanie przedmiotów
$itemService->saveItemsFromArray($modelCart->getItems(),$os->getId());
// $this->_service->get('doctrine')->getCurrentConnection()->commit();
$modelCart->clean();
$this->_helper->actionStack('layout', 'index', 'default');
}
public function shippingAction() {
$deliveryTypeService = $this->_service->getService('Order_Service_DeliveryType');
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
$deliveryAddressService = $this->_service->getService('Order_Service_DeliveryAddress');
$paymentService = $this->_service->getService('Order_Service_Payment');
$orderService = $this->_service->getService('Order_Service_Order');
$deliveryService = $this->_service->getService('Order_Service_Delivery');
$itemService = $this->_service->getService('Order_Service_Item');
// $produktService = $this->_service->getService('Product_Service_Product');
$modelCart = $orderService->getCart();
// var_dump($modelCart->getPrices());
$form = new User_Form_Order();
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
// laczymy podane nazwisko i imie przed wrzuceniem do bazy
$values['name'] = $values['last_name']." ".$values['first_name'];
// ustawianie statusu zamówienia jako nowe
$values['order_status_id'] = 8;
// zapisywanie adresu dostawy
$das = $deliveryAddressService->saveDeliveryAddressFromArray($values);
// zapisywanie sposobu platnosci
$ps = $paymentService->savePaymentFromArray($values);
$values['payment_id'] = $ps->getId();
$values['delivery_address_id'] = $das->getId();
//laczenie adresu i sposobu dostawy
$ds = $deliveryService->saveDeliveryFromArray($values);
$values['delivery_id'] = $ds->getId();
$deliveryType = $deliveryTypeService->getDeliveryType($values['delivery_type_id']);
// pobranie nazwy płatności, nazwie dostawcy i koszcie dostawy
$values['payment_name'] = $paymentTypeService->getPaymentType($values['payment_type_id'])->getName();
$values['delivery_name'] = $deliveryType->getName();
$values['delivery_price'] = $deliveryType->getPrice();
// suma kosztu wszystkich przedmiotów
$values['total_price'] = number_format($modelCart->getPrice('total_price_after_discount'),2);
// do zapłaty (koszt przedmiotów + koszt dostawy)
$values['total_cost'] = number_format($values['total_price'] + $values['delivery_price'],2);
// zapisywanie zamowienia
$os = $orderService->saveOrderFromArray($values);
// zapisywanie przedmiotów
$itemService->saveItemsFromArray($modelCart->getItems(),$os->getId());
$this->_service->get('doctrine')->getCurrentConnection()->commit();
// Tworzenie sesji aby przekazać dane do podsumowania zamówienia
$summarySession = new Zend_Session_Namespace('summary');
$summarySession->summary = $values;
$this->_helper->redirector->gotoUrl('/order/index/summary');
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
else{
$form->populate($_POST);
}
}
$this->view->assign('form',$form);
}
public function summaryAction()
{
$orderService = $this->_service->getService('Order_Service_Order');
$modelCart = $orderService->getCart();
$itemsCart = $modelCart->getItems();
$summarySession = new Zend_Session_Namespace('summary');
$values = $summarySession->summary;
$prices = $modelCart->getPrices();
//Zend_Debug::dump($values);
$this->view->assign('values',$values);
$this->view->assign('cart',$itemsCart);
$this->view->assign('prices',$prices);
$summarySession->unsetAll();
$modelCart->clean();
}
public function clearBasketAction()
{
$orderService = $this->_service->getService('Order_Service_Order');
$modelCart = $orderService->getCart();
$modelCart->clean();
$this->_helper->redirector->gotoUrl('/');
}
}
<file_sep>/application/modules/location/models/Doctrine/CategoryTranslationTable.php
<?php
/**
* Location_Model_Doctrine_CategoryTranslationTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Location_Model_Doctrine_CategoryTranslationTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Location_Model_Doctrine_CategoryTranslationTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Location_Model_Doctrine_CategoryTranslation');
}
}<file_sep>/application/modules/order/controllers/PayuController.php
<?php
/**
* Order_PayuController
*
* @author <NAME> <<EMAIL>>
*/
class Order_PayuController extends MF_Controller_Action {
// public function init() {
// $this->view->assign('langParams', array());
// }
//
public function successAction() {
$payUService = $this->_service->getService('Order_Service_Payment_PayU');
$options = $this->getInvokeArg('bootstrap')->getOptions();
$config = $options['payu'];
$config['PosId'] = $this->view->cms()->setting('payuPosId');
$config['PostAuthKey'] = $this->view->cms()->setting('payuPosAuthKey');
if($payment = $payUService->getPayment($this->getRequest()->getParam('session_id'))) {
$this->view->assign('payment', $payment);
}
$this->_helper->actionStack('layout-shop', 'index', 'default');
}
public function errorAction() {
$payUService = $this->_service->getService('Order_Service_Payment_PayU');
if($payment = $payUService->getPayment($this->getRequest()->getParam('session_id'))) {
$this->view->assign('error', $this->getRequest()->getParam('error'));
}
$this->_helper->actionStack('layout-shop', 'index', 'default');
}
public function statusAction() {
$payUService = $this->_service->getService('Order_Service_Payment_PayU');
if($this->getRequest()->isPost()) {
if($payment = $payUService->getPayment($this->getRequest()->getParam('session_id'))) {
$options = $this->getInvokeArg('bootstrap')->getOptions();
$config = $options['payu'];
// sig in
$sig2 = md5( $this->view->cms()->setting('payuPosId') . $payment->getId() . $this->getRequest()->getParam('ts') . $this->view->cms()->setting('key2') );
// sig out
$sig1 = md5( $this->view->cms()->setting('payuPosId') . $payment->getId() . $payment->getTs() . $this->view->cms()->setting('key1') );
/* walidacja sig */
if($sig2 == $this->getRequest()->getParam('sig')) {
/* odczytanie statusu transakcji */
$client = new Zend_Http_Client($config['Payment_get']);
$client->setMethod(Zend_Http_Client::POST);
$client->setParameterPost(array(
'pos_id' => $this->view->cms()->setting('payuPosId'),
'session_id' => $payment->getId(),
'ts' => $payment->getTs(),
'sig' => $sig1
));
$response = $client->request();
$data = simplexml_load_string($response->getBody());
$sig3 = md5 ( $this->view->cms()->setting('payuPosId') .
(int)$data->trans->session_id .
"" .
(int)$data->trans->status .
(int)$data->trans->amount .
(string)$data->trans->desc .
(string)$data->trans->ts .
$this->view->cms()->setting('key2')
);
if ($sig3 == ((string)$data->trans->sig)):
if((int)$data->trans->session_id && $payment = $payUService->getPayment((int)$data->trans->session_id)) {
// zmiana statusu transakcji
if($payment->getStatus() != ((int)$data->trans->status)) {
$payment->setStatus((int)$data->trans->status);
$payment->setErrorStatus(null);
$payment->save();
if ($payment->getStatus() == 99):
$payment->setStatusId(5);
$payment->save();
endif;
}
if($payment->getTransId() == NULL):
$payment->setTransId((int)$data->trans->id);
$payment->save();
endif;
if ($payment->getDesc() == NULL):
$payment->setDesc((string)$data->trans->desc);
$payment->save();
endif;
}
endif;
echo 'OK';
}
}
}
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
}
/**
* Debug
* wysyłanie żądania do systemu Platnosci.pl w celu uzyskania statusu transakcji
*/
public function test2Action()
{
// $payUService = $this->_service->getService('Order_Service_Payment_PayU');
//
// $this->_helper->viewRenderer->setNoRender();
// $this->_helper->layout->disableLayout();
//
// $options = $this->getInvokeArg('bootstrap')->getOptions();
// $config = $options['payu'];
//
// $payment = $payUService->getPayment(14);
//
// $sig1 = md5( $this->view->cms()->setting('payuPosId') . $payment->getId() . $payment->getTs() . $this->view->cms()->setting('key1') );
//
// $client = new Zend_Http_Client($config['Payment_get']);
// $client->setMethod(Zend_Http_Client::POST);
// $client->setParameterPost(array(
// 'pos_id' => $this->view->cms()->setting('payuPosId'),
// 'session_id' => $payment->getId(),
// 'ts' => $payment->getTs(),
// 'sig' => $sig1
// ));
// $response = $client->request();
// $data = simplexml_load_string($response->getBody());
//
// $sig2 = md5 ( $this->view->cms()->setting('payuPosId') .
// (int)$data->trans->session_id .
// "" .
// (int)$data->trans->status .
// (int)$data->trans->amount .
// (string)$data->trans->desc .
// (string)$data->trans->ts .
// $this->view->cms()->setting('key2') );
//
// if ($sig2 == ((string)$data->trans->sig)):
// if((int)$data->trans->session_id && $payment = $payUService->getPayment((int)$data->trans->session_id)) {
// // zmiana statusu transakcji
// if($payment->getStatus() != ((int)$data->trans->status)) {
// $payment->setStatus((int)$data->trans->status);
// $payment->setErrorStatus(null);
// $payment->save();
// if ($payment->getStatus() == 99):
// $payment->setStatusId(5);
// $payment->save();
// endif;
// }
// if($payment->getTransId() == NULL):
// $payment->setTransId((int)$data->trans->id);
// $payment->save();
// endif;
// if ($payment->getDesc() == NULL):
// $payment->setDesc((string)$data->trans->desc);
// $payment->save();
// endif;
// }
// endif;
//
// echo 'OK';
}
}
<file_sep>/application/modules/order/library/DataTables/Adapter/Delivery.php
<?php
/**
* Order_DataTables_Adapter_Delivery
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Adapter_Delivery extends Default_DataTables_Adapter_AdapterAbstract {
public function getBaseQuery() {
$q = $this->table->createQuery('d');
$q->select('d.*');
$q->addSelect('dt.*');
$q->addSelect('da.*');
$q->leftJoin('d.DeliveryType dt');
$q->leftJoin('d.DeliveryAddress da');
$q->andWhere('d.id = ?', array($this->request->getParam('id')));
return $q;
}
}
<file_sep>/application/modules/order/library/DataTables/Adapter/Order.php
<?php
/**
* Order_DataTables_Adapter_Order
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Adapter_Order extends Default_DataTables_Adapter_AdapterAbstract {
public function getBaseQuery() {
$q = $this->table->createQuery('or');
$q->select('or.*');
$q->addSelect('u.*');
$q->addSelect('c.*');
$q->addSelect('p.*');
$q->addSelect('ct.*');
$q->addSelect('pt.*');
$q->addSelect('pr.*');
$q->addSelect('da.*');
$q->leftJoin('or.User u');
$q->leftJoin('u.Profile pr');
$q->leftJoin('or.Delivery c');
$q->leftJoin('c.DeliveryType dt');
$q->leftJoin('c.DeliveryAddress da');
$q->leftJoin('or.Payment p');
$q->leftJoin('p.PaymentType pt');
return $q;
}
}
<file_sep>/application/modules/order/services/DeliveryType.php
<?php
/**
* Order_Service_DeliveryType
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_DeliveryType extends MF_Service_ServiceAbstract {
protected $deliveryTypeTable;
public function init() {
$this->deliveryTypeTable = Doctrine_Core::getTable('Order_Model_Doctrine_DeliveryType');
parent::init();
}
public function getDeliveryType($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->deliveryTypeTable->findOneBy($field, $id, $hydrationMode);
}
public function getDeliveryTypeForm(Order_Model_Doctrine_DeliveryType $deliveryType = null) {
$form = new Order_Form_DeliveryType();
if(null != $deliveryType) {
$form->populate($deliveryType->toArray());
}
return $form;
}
public function saveDeliveryTypeFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$deliveryType = $this->getDeliveryType((int) $values['id'])) {
$deliveryType = $this->deliveryTypeTable->getRecord();
}
$deliveryType->fromArray($values);
$deliveryType->save();
return $deliveryType;
}
public function removeDeliveryType(Order_Model_Doctrine_DeliveryType $deliveryType) {
$deliveryType->delete();
}
public function getAllDeliveryType($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->deliveryTypeTable->getDeliveryTypeQuery();
return $q->execute(array(), $hydrationMode);
}
public function getAllDeliveryTypeSorted($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->deliveryTypeTable->getDeliveryTypeQuery();
$q->addOrderBy('dt.created_at ASC');
return $q->execute(array(), $hydrationMode);
}
public function getTargetDeliveryTypeSelectOptionsSorted($prependEmptyValue = false) {
$items = $this->getAllDeliveryTypeSorted();
$result = array();
if($prependEmptyValue) {
$result[''] = '';
}
foreach($items as $item) {
if($item->getId() != 9){
$result[$item->getId()] = $item->name." - ".$item->price." zł ";
}
else{
$result[$item->getId()] = $item->name;
}
}
return $result;
}
public function getTargetDeliveryTypeSelectOptions($prependEmptyValue = false) {
$items = $this->getAllDeliveryType();
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
foreach($items as $item) {
$result[$item->getId()] = $item->name." - ".$item->price." zł";
}
return $result;
}
public function getTargetTypeSelectOptions($prependEmptyValue = false) {
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
$result['pobranie'] = "pobranie";
$result['przelew'] = "przelew";
$result['brak'] = "brak";
return $result;
}
public function getMinimalPriceForDelivery() {
$items = $this->getAllDeliveryType();
$min = $items[0]->getPrice();
foreach($items as $item):
if ($item->getPrice() > 0):
if ($min > $item->getPrice()):
$min = $item->getPrice();
endif;
endif;
endforeach;
return $min;
}
}
?>
<file_sep>/application/modules/league/services/DeliveryAddress.php
<?php
/**
* Order_Service_PaymentType
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_DeliveryAddress extends MF_Service_ServiceAbstract {
protected $deliveryAddressTable;
public function init() {
$this->deliveryAddressTable = Doctrine_Core::getTable('Order_Model_Doctrine_DeliveryAddress');
parent::init();
}
public function getDeliveryAddress($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->deliveryAddressTable->findOneBy($field, $id, $hydrationMode);
}
public function getPaymentTypes() {
return $this->deliveryAddressTable->findAll();
}
public function getDeliveryAddressForm(Order_Model_Doctrine_PaymentType $paymentType = null) {
$form = new Order_Form_PaymentType();
if(null != $paymentType) {
$form->populate($paymentType->toArray());
}
return $form;
}
public function saveDeliveryAddressFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$paymentType = $this->getDeliveryAddress((int) $values['id'])) {
$paymentType = $this->deliveryAddressTable->getRecord();
}
$paymentType->fromArray($values);
$paymentType->save();
return $paymentType;
}
public function removePaymentType(Order_Model_Doctrine_PaymentType $paymentType) {
$paymentType->delete();
}
public function checkDeliveryAddress($values) {
$delAddress['name'] = $values['last_name']." ".$values['first_name'];
if($values['difAddress']==1)
{
$delAddress['address'] = $values['difstreet']." ".$values['difhouseNr'];
if(!empty($values['difflatNr'])) $delAddress['address'] .= "/".$values['difflatNr'];
$delAddress['postal_code'] = $values['difpostal_code'];
$delAddress['city'] = $values['difcity'];
}
else{
$delAddress['address'] = $values['street']." ".$values['houseNr'];
if(!empty($values['flatNr'])) $delAddress['address'] .= "/".$values['flatNr'];
$delAddress['postal_code'] = $values['postal_code'];
$delAddress['city'] = $values['city'];
}
return $delAddress;
}
}
?><file_sep>/application/modules/order/models/ProductAvailabilityExistsException.php
<?php
class Order_Model_ProductAvailabilityExistsException extends Exception
{
}<file_sep>/application/modules/order/controllers/AdminController.php
<?php
/**
* Order_AdminController
*
* @author <NAME> <<EMAIL>>
*/
class Order_AdminController extends MF_Controller_Action {
public function init() {
$this->_helper->ajaxContext()
->addActionContext('change-item-vat', 'json')
->initContext();
parent::init();
}
public function listOrderAction() {
if($dashboardTime = $this->_helper->user->get('dashboard_time')) {
if(isset($dashboardTime['new_orders'])) {
$dashboardTime['new_orders'] = time();
$this->_helper->user->set('dashboard_time', $dashboardTime);
}
}
}
public function listOrderDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_Order');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_Order',
'columns' => array('or.id', 'CONCAT_WS(" ", u.first_name, u.last_name)', 'or.total_cost', 'or.created_at'),
'searchFields' => array('or.id', 'CONCAT_WS(" ", u.first_name, u.last_name)', 'dt.name', 'pt.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
if ($result['OrderStatus']['name'] == 'nowe'):
$row['DT_RowClass'] = 'info';
endif;
$row[] = $result['id'];
$row[] = $result['User']['first_name'].' '.$result['User']['last_name'];
$row[] = $result['total_cost'];
$row[] = $result['created_at'];
$row[] = $result['Delivery']['DeliveryType']['name'];
$row[] = $result['Payment']['PaymentType']['name'];
$row[] = $result['OrderStatus']['name'];
if ($result['invoice_id']):
$row[] = '<span class="icon16 icomoon-icon-checkbox-2"></span>';
else:
$row[] = '<span class="icon16 icomoon-icon-checkbox-unchecked-2"></span>';
endif;
$options = '<a href="' . $this->view->adminUrl('edit-order', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function editOrderAction() {
$orderService = $this->_service->getService('Order_Service_Order');
$orderStatusService = $this->_service->getService('Order_Service_OrderStatus');
$translator = $this->_service->get('translate');
if(!$order = $orderService->getFullOrder((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Order not found');
}
$form = $orderService->getOrderForm($order);
$form->setAction($this->view->adminUrl('edit-order', 'order'));
$form->getElement('order_status_id')->setMultiOptions($orderStatusService->getTargetOrderStatusSelectOptions(false, "status zamówienia"));
$form->getElement('delivery_status_id')->setMultiOptions($orderStatusService->getTargetOrderStatusSelectOptions(false, "status przesyłki"));
$form->getElement('delivery_status_id')->setValue($order->get('Delivery')->getStatusId());
$form->getElement('payment_status_id')->setMultiOptions($orderStatusService->getTargetOrderStatusSelectOptions(false, "status płatności"));
$form->getElement('payment_status_id')->setValue($order->get('Payment')->getStatusId());
$form->getElement('delivery_cost')->setValue($order->get('Delivery')->getDeliveryCost());
if ($order['Delivery']['delivery_type_id'] != 9){
$form->removeElement('delivery_cost');
}
$productsWorth = $orderService->getProductsWorth($order);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$mail = new Zend_Mail('UTF-8');
if($order['user_id'] != NULL):
$mail->addTo($order['User']['email'], $order['User']['first_name'].' '.$order['User']['last_name']);
else:
$mail->addTo($order['contact_email'], $order['Delivery']['DeliveryAddress']['name']);
endif;
$mail->setReplyTo("<EMAIL>", 'System zamówień slimtea.pl');
$oldOrderStatus = $order['order_status_id'];
if ($values['type'] == "order"){
$orderService->saveOrderFromArray($values);
if ($oldOrderStatus != $values['order_status_id']):
$mail->setSubject($translator->translate('Zmiana statusu wysyłki.'));
if($values['order_status_id'] == 7 && $order->get('Delivery')->getDeliveryTypeId() != 8):
$orderService->sendConfirmationMailChangeOrderStatusForRealized($mail, $this->view);
endif;
endif;
}
$oldDeliveryStatus = $order['Delivery']['status_id'];
if ($values['type'] == "delivery"){
$valuesDelivery['id'] = $order['Delivery']->getId();
$valuesDelivery['status_id'] = $values['delivery_status_id'];
$orderService->saveDeliveryFromArray($valuesDelivery);
if ($oldDeliveryStatus != $values['delivery_status_id']):
$mail->setSubject($translator->translate('Zmiana statusu wysyłki.'));
if($values['delivery_status_id'] == 6):
$orderService->sendConfirmationMailChangeDeliveryStatusForWaitWithCollection($mail, $this->view);
endif;
if($values['delivery_status_id'] == 9):
$orderService->sendConfirmationMailChangeDeliveryStatusForSent($mail, $this->view);
endif;
endif;
}
$oldPaymentStatus = $order['Payment']['status_id'];
if ($values['type'] == "payment"){
$valuesPayment['id'] = $order['Payment']->getId();
$valuesPayment['status_id'] = $values['payment_status_id'];
$orderService->savePaymentFromArray($valuesPayment);
if ($oldPaymentStatus != $values['payment_status_id']):
$mail->setSubject($translator->translate('Zmiana statusu płatności.'));
if($values['payment_status_id'] == 5):
$orderService->sendConfirmationMailChangePaymentStatus($mail, $this->view);
endif;
endif;
}
if ($values['type'] == "delivery_cost" && $order['Delivery']['delivery_cost'] == NULL){
$valuesDeliveryCost['id'] = $order['Delivery']->getId();
$values['delivery_cost'] = str_replace(",",".", $values['delivery_cost']);
$valuesDeliveryCost['delivery_cost'] = $values['delivery_cost'];
$orderService->saveDeliveryFromArray($valuesDeliveryCost);
$order->setTotalCost($order->getTotalCost()+(double)$values['delivery_cost']);
$order->save();
$valuesPayment['id'] = $order['Payment']->getId();
$valuesPayment['status_id'] = 3;
$orderService->savePaymentFromArray($valuesPayment);
$mail->setSubject('Delivery cost has been set.');
if($order['Payment']['payment_type_id'] == 1):
$orderService->sendConfirmationMailDetermineDeliveryCostsPaymentTransfer($order, $this->view->language, $mail, $this->view);
elseif($order['Payment']['payment_type_id'] == 2):
$orderService->sendConfirmationMailDetermineDeliveryCostsPaymentPayU($order, $this->view->language, $mail, $this->view);
endif;
}
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('edit-order', 'order', array('id' => $order->getId())));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('productsWorth', $productsWorth);
$this->view->assign('order', $order);
}
public function listOrderItemDataAction() {
$i18nService = $this->_service->getService('Default_Service_I18n');
$table = Doctrine_Core::getTable('Order_Model_Doctrine_Item');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_Item',
'columns' => array('pro.name'),
'searchFields' => array('pro.name')
));
$results = $dataTables->getResult();
$language = $i18nService->getAdminLanguage();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['Product']->Translation[$language->getId()]->name;
$row[] = $result['price'];
$row[] = $result['number'];
$row[] = $result['Discount']['amount_discount'];
$row[] = $result['Product']['vat'];
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $results->count(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function paymentOrderDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_Payment');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_Payment',
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['PaymentType']['name'];
$row[] = $result['Status']['name'];
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $results->count(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function deliveryOrderDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_Delivery');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_Delivery',
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['DeliveryType']['name'];
$row[] = $result['Status']['name'];
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $results->count(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function listDeliveryTypeAction() {
}
public function listDeliveryTypeDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_DeliveryType');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_DeliveryType',
'columns' => array('dt.name'),
'searchFields' => array('dt.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['name'];
$row[] = $result['type'];
$row[] = $result['price'];
$options = '<a href="' . $this->view->adminUrl('edit-delivery-type', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
// $options .= '<a href="' . $this->view->adminUrl('remove-delivery-type', 'order', array('id' => $result['id'])) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addDeliveryTypeAction() {
$deliveryTypeService = $this->_service->getService('Order_Service_DeliveryType');
$translator = $this->_service->get('translate');
$form = $deliveryTypeService->getDeliveryTypeForm();
$form->getElement('type')->setMultiOptions($deliveryTypeService->getTargetTypeSelectOptions(true));
$form->setAction($this->view->adminUrl('add-delivery-type', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$deliveryType = $deliveryTypeService->saveDeliveryTypeFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-delivery-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
}
public function editDeliveryTypeAction() {
$deliveryTypeService = $this->_service->getService('Order_Service_DeliveryType');
$translator = $this->_service->get('translate');
if(!$deliveryType = $deliveryTypeService->getDeliveryType((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Delivery type not found');
}
$form = $deliveryTypeService->getDeliveryTypeForm($deliveryType);
$form->getElement('type')->setMultiOptions($deliveryTypeService->getTargetTypeSelectOptions(true));
$form->setAction($this->view->adminUrl('edit-delivery-type', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$deliveryTypeService->saveDeliveryTypeFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-delivery-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('deliveryType', $deliveryType);
}
public function removeDeliveryTypeAction() {
$deliveryTypeService = $this->_service->getService('Order_Service_DeliveryType');
if($deliveryType = $deliveryTypeService->getDeliveryType($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$deliveryTypeService->removeDeliveryType($deliveryType);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-delivery-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-delivery-type', 'order'));
}
public function listPaymentTypeAction() {
}
public function listPaymentTypeDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_PaymentType');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_PaymentType',
'columns' => array('pt.name'),
'searchFields' => array('pt.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['name'];
$options = '<a href="' . $this->view->adminUrl('edit-payment-type', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-payment-type', 'order', array('id' => $result['id'])) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addPaymentTypeAction() {
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
$translator = $this->_service->get('translate');
$form = $paymentTypeService->getPaymentTypeForm();
$form->setAction($this->view->adminUrl('add-payment-type', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$paymentType = $paymentTypeService->savePaymentTypeFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-payment-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
}
public function editPaymentTypeAction() {
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
$translator = $this->_service->get('translate');
if(!$paymentType = $paymentTypeService->getPaymentType((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Payment type not found');
}
$form = $paymentTypeService->getPaymentTypeForm($paymentType);
$form->setAction($this->view->adminUrl('edit-payment-type', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$paymentTypeService->savePaymentTypeFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-payment-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('paymentType', $paymentType);
}
public function removePaymentTypeAction() {
$paymentTypeService = $this->_service->getService('Order_Service_PaymentType');
if($paymentType = $paymentTypeService->getPaymentType($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$paymentTypeService->removePaymentType($paymentType);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-payment-type', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-payment-type', 'order'));
}
public function listOrderStatusAction() {
}
public function listOrderStatusDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_OrderStatus');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_OrderStatus',
'columns' => array('os.name'),
'searchFields' => array('os.name')
));
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['name'];
$row[] = $result['type'];
$options = '<a href="' . $this->view->adminUrl('edit-order-status', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
//$options .= '<a href="' . $this->view->adminUrl('remove-order-status', 'order', array('id' => $result['id'])) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addOrderStatusAction() {
$orderStatusService = $this->_service->getService('Order_Service_OrderStatus');
$translator = $this->_service->get('translate');
$form = $orderStatusService->getOrderStatusForm();
$form->setAction($this->view->adminUrl('add-order-status', 'order'));
$form->getElement('type')->setMultiOptions($orderStatusService->getTargetTypeOrderStatusSelectOptions(true));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$orderStatus = $orderStatusService->saveOrderStatusFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-order-status', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
}
public function editOrderStatusAction() {
$orderStatusService = $this->_service->getService('Order_Service_OrderStatus');
$translator = $this->_service->get('translate');
if(!$orderStatus = $orderStatusService->getOrderStatus((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Order status not found');
}
$form = $orderStatusService->getOrderStatusForm($orderStatus);
$form->getElement('type')->setMultiOptions($orderStatusService->getTargetTypeOrderStatusSelectOptions(true));
$form->setAction($this->view->adminUrl('edit-order-status', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$orderStatusService->saveOrderStatusFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-order-status', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('orderStatus', $orderStatus);
}
public function removeOrderStatusAction() {
$orderStatusService = $this->_service->getService('Order_Service_OrderStatus');
if($orderStatus = $orderStatusService->getOrderStatus($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$orderStatusService->removeOrderStatus($orderStatus);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-order-status', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-order-status', 'order'));
}
public function pdfInvoiceAction() {
require_once('tcpdf/tcpdf.php');
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$orderService = $this->_service->getService('Order_Service_Order');
if(!$order = $orderService->getFullOrder((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Order not found');
}
// $code = 'F-'.MF_Text::timeFormat($order['created_at'], 'Ymd').'-'.$order['id'];
$code = 'F/'.$order['id'];
$saleDate = MF_Text::timeFormat($order['created_at'], 'd.m.Y');
$invoiceDate = date('d.m.Y');
$this->view->assign('sale_date', $saleDate);
$this->view->assign('invoice_date', $invoiceDate);
$this->view->assign('code', $code);
$this->view->assign('order', $order);
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetAutoPageBreak(1, 30);
$pdf->SetFont('freesans');
$htmlcontent = $this->view->render('admin/pdf-invoice.phtml');
//$pdf->SetPrintHeader(false);
// $pdf->SetPrintFooter(false);
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->addPage();
$pdf->writeHTML($htmlcontent, true, 0, true, 0);
$pdf->lastPage();
$pdf->Output();
$pdf->Output($code . '.pdf', 'D');
}
public function listCouponAction() {
}
public function listCouponDataAction() {
$table = Doctrine_Core::getTable('Order_Model_Doctrine_Coupon');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Order_DataTables_Coupon',
'columns' => array('c.type, c.amount, c.valid'),
'searchFields' => array('c.type, c.amount, c.valid')
));
$translator = $this->_service->get('translate');
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result['code'];
$row[] = $translator->translate($result['type']);
$row[] = $result['amount_coupon'];
if (MF_Coupon::isValid($result)){
$row[] = $translator->translate('yes');
}
else{
$row[] = $translator->translate('no');
}
if ($result['used'] == 1){
$row[] = $translator->translate('yes');
}
else{
$row[] = $translator->translate('no');
}
if ($result['sent'] == 1){
$row[] = $translator->translate('yes');
}
else{
$row[] = $translator->translate('no');
}
$options = "";
if ($result['sent'] == 0){
$options .= '<a href="' . $this->view->adminUrl('send-coupon', 'order', array('id' => $result['id'])) . '" title="' . $this->view->translate('Send') . '"><span class="icon24 icon-arrow-up"></span></a> ';
}
$options .= '<a href="' . $this->view->adminUrl('edit-coupon', 'order', array('id' => $result['id'])) . '" title ="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-coupon', 'order', array('id' => $result['id'])) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addCouponAction() {
$couponService = $this->_service->getService('Order_Service_Coupon');
$translator = $this->_service->get('translate');
$form = $couponService->getCouponForm();
$form->getElement('type')->setMultiOptions($couponService->getTargetCouponTypeSelectOptions(true, $translator));
$form->setAction($this->view->adminUrl('add-coupon', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$couponService->saveCouponsFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-coupon', 'order'));
} catch(Exception $e) {
var_dump($e->getMessage()); exit;
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
}
public function editCouponAction() {
$couponService = $this->_service->getService('Order_Service_Coupon');
$translator = $this->_service->get('translate');
if(!$coupon = $couponService->getCoupon((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Coupon not found');
}
$form = $couponService->getCouponForm($coupon);
$form->getElement('type')->setMultiOptions($couponService->getTargetCouponTypeSelectOptions(true, $translator));
$form->removeElement('number_of_coupon');
$form->setAction($this->view->adminUrl('edit-coupon', 'order'));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$couponService->saveCouponFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-coupon', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('coupon', $coupon);
}
public function removeCouponAction() {
$couponService = $this->_service->getService('Order_Service_Coupon');
if($coupon = $couponService->getCoupon($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$couponService->removeCoupon($coupon);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-coupon', 'order'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-coupon', 'order'));
}
public function sendCouponAction() {
$couponService = $this->_service->getService('Order_Service_Coupon');
$userService = $this->_service->getService('User_Service_User');
$translator = $this->_service->get('translate');
if(!$coupon = $couponService->getCoupon((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Coupon not found');
}
$form = new Order_Form_CouponSend();
$form->getElement('user_id')->setMultiOptions($userService->getTargetClientSelectOptions(true));
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$mail = new Zend_Mail('UTF-8');
$mail->setSubject("Slimtea - kupon rabatowy");
if ($values['user_id']){
if(!$user = $userService->getFullUser($values['user_id'], 'id', Doctrine_Core::HYDRATE_ARRAY_SHALLOW)) {
throw new Zend_Controller_Action_Exception('User not found');
}
$mail->addTo($user['email']);
}
else{
$mail->addTo($values['email']);
}
$mail->setBodyHtml($this->view->partial('coupon.phtml', array('coupon' => $coupon)));
$mail->send();
$coupon->setSent(1);
$coupon->save();
$this->view->messages()->add($translator->translate('Coupon has been sent'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-coupon', 'order'));
} catch(Exception $e) {
var_dump($e->getMessage()); exit;
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('coupon', $coupon);
}
public function changeItemVatAction() {
$itemService = $this->_service->getService('Order_Service_Order');
$itemId = $this->getRequest()->getParam('itemId');
$vat = $this->getRequest()->getParam('vat');
$item = $itemService->setVatItem($itemId, $vat);
$newVat = $item->getVat();
$this->view->assign('newVat', $newVat);
$this->view->assign('status', "success");
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
}
}
<file_sep>/application/modules/order/services/Coupon.php
<?php
/**
* Order_Service_Coupon
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_Coupon extends MF_Service_ServiceAbstract {
protected $couponTable;
public function init() {
$this->couponTable = Doctrine_Core::getTable('Order_Model_Doctrine_Coupon');
parent::init();
}
public function getCoupon($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->couponTable->findOneBy($field, $id, $hydrationMode);
}
public function checkProductShared($email,$product_id){
$q = $this->couponTable->createQuery('c');
$q->andWhere('c.share_product_id = ?', $product_id);
$q->andWhere('c.share_product_email like ?', $email);
$q->andWhere('c.sent = 1');
$result = $q->fetchOne(array(),Doctrine_Core::HYDRATE_RECORD);
if($result)
return true;
else
return false;
}
public function getCouponForm(Order_Model_Doctrine_Coupon $coupon = null) {
$form = new Order_Form_Coupon();
if(null != $coupon) {
$form->populate($coupon->toArray());
}
return $form;
}
public function saveCouponsFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(strlen($values['start_validity_date'])) {
$date = new Zend_Date($values['start_validity_date'], 'dd/MM/yyyy HH:mm');
$values['start_validity_date'] = $date->toString('yyyy-MM-dd HH:mm:00');
}
if(strlen($values['finish_validity_date'])) {
$date = new Zend_Date($values['finish_validity_date'], 'dd/MM/yyyy HH:mm');
$values['finish_validity_date'] = $date->toString('yyyy-MM-dd HH:mm:00');
}
$counter = (integer)$values['number_of_coupon'];
for ($i = 1; $i <= $counter; $i++) {
$coupon = $this->couponTable->getRecord();
$coupon->code = MF_Text::createUniqueTableCode('Order_Model_Doctrine_Coupon', $this->generateCouponCode(), $coupon->getId());
$coupon->fromArray($values);
$coupon->save();
}
}
public function saveCouponFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(strlen($values['start_validity_date'])) {
$date = new Zend_Date($values['start_validity_date'], 'dd/MM/yyyy HH:mm');
$values['start_validity_date'] = $date->toString('yyyy-MM-dd HH:mm:00');
}
if(strlen($values['finish_validity_date'])) {
$date = new Zend_Date($values['finish_validity_date'], 'dd/MM/yyyy HH:mm');
$values['finish_validity_date'] = $date->toString('yyyy-MM-dd HH:mm:00');
}
if(!$coupon = $this->getCoupon((int) $values['id'])) {
$coupon = $this->couponTable->getRecord();
}
$coupon->fromArray($values);
$coupon->save();
return $coupon;
}
public function saveShareCouponFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$coupon = $this->getCoupon((int) $values['id'])) {
$coupon = $this->couponTable->getRecord();
}
$coupon->fromArray($values);
$coupon->save();
return $coupon;
}
public function generateCouponCode($length = 12) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$ret = '';
for($i = 0; $i < $length; ++$i) {
$random = str_shuffle($chars);
$ret .= $random[0];
}
return $ret;
}
public function removeCoupon(Order_Model_Doctrine_Coupon $coupon) {
$coupon->delete();
}
public function getTargetCouponTypeSelectOptions($prependEmptyValue = false, $translator){
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
$result['percent'] = $translator->translate('percent');
$result['amount'] = $translator->translate('amount');;
return $result;
}
}
?><file_sep>/application/modules/order/library/DataTables/Adapter/Payment.php
<?php
/**
* Order_DataTables_Adapter_Payment
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Adapter_Payment extends Default_DataTables_Adapter_AdapterAbstract {
public function getBaseQuery() {
$q = $this->table->createQuery('p');
$q->select('p.*');
$q->addSelect('pt.*');
$q->addSelect('s.*');
$q->leftJoin('p.PaymentType pt');
$q->leftJoin('p.Status s');
$q->andWhere('p.id = ?', array($this->request->getParam('id')));
return $q;
}
}
<file_sep>/application/modules/order/models/Doctrine/PaymentTable.php
<?php
/**
* Order_Model_Doctrine_PaymentTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Order_Model_Doctrine_PaymentTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Order_Model_Doctrine_PaymentTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Order_Model_Doctrine_Payment');
}
public function getFullPaymentQuery() {
$q = $this->createQuery('p')
->addSelect('p.*')
->addSelect('o.*')
->addSelect('u.*')
->addSelect('d.*')
->addSelect('da.*')
->leftJoin('p.Order o')
->leftJoin('o.User u')
->leftJoin('o.Delivery d')
->leftJoin('d.DeliveryAddress da')
;
return $q;
}
}<file_sep>/application/modules/faq/models/Doctrine/CategoryTable.php
<?php
/**
* Category_Model_Doctrine_CategoryTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Faq_Model_Doctrine_CategoryTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Category_Model_Doctrine_CategoryTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Faq_Model_Doctrine_Category');
}
public function getPublishCategoryQuery() {
$q = $this->createQuery('a')
->addSelect('a.*')
->addSelect('at.*')
->leftJoin('a.Translation at');
return $q;
}
public function getPhotoQuery(Doctrine_Query $q = null) {
if(null == $q) {
$q = $this->createQuery('a');
$q->addSelect('a.*');
}
$q->addSelect('pr.*');
$q->addSelect('p.*');
$q->leftJoin('a.PhotoRoot pr');
$q->leftJoin('a.Photos p');
return $q;
}
public function getLimitQuery($limit, Doctrine_Query $q = null) {
if(null == $q) {
$q = $this->createQuery('a');
$q->addSelect('a.*');
}
$q->limit($limit);
return $q;
}
public function getCategoryIdQuery($categoryId = null, Doctrine_Query $q = null) {
if(null == $q) {
$q = $this->createQuery('ac');
}
$q->addSelect('ac.*');
$q->leftJoin('a.Category ac');
if(is_integer($categoryId)) {
$q->andWhere('ac.id');
} elseif(is_array($categoryId && !empty($categoryId))) {
$q->andWhere('ac.id IN ?', array($categoryId));
}
return $q;
}
public function getAllCategoryQuery() {
$q = $this->createQuery('a')
->addSelect('a.*')
->addSelect('at.*')
->addSelect('pr.*')
->leftJoin('a.PhotoRoot pr')
->leftJoin('a.Translation at');
return $q;
}
public function getCategoryForSiteMapQuery() {
$q = $this->createQuery('cat');
$q->addSelect('cat.*');
$q->addSelect('pro.*');
$q->addSelect('tr.*');
$q->leftJoin('cat.Translation tr');
$q->leftJoin('cat.Products pro');
$q->andWhere('pro.status = ?', 1);
$q->andWhere('pro.availability > ?', 0);
$q->andWhere('pro.reduced_price = ?', 0);
return $q;
}
}<file_sep>/application/modules/league/forms/DeliveryPayment.php
<?php
class Order_Form_DeliveryPayment extends Admin_Form
{
public function init() {
$deliveryTypeService = MF_Service_ServiceBroker::getInstance()->getService('Order_Service_DeliveryType');
$deliveryTypes = $deliveryTypeService->getDeliveryTypes();
$paymentTypeService = MF_Service_ServiceBroker::getInstance()->getService('Order_Service_PaymentType');
$paymentTypes = $paymentTypeService->getPaymentTypes();
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$delivery = $this->createElement('radio', 'delivery_type_id');
$delivery->setLabel('Sposób dostawy');
// $delivery->setRequired(true);
$delivery->setDecorators(self::$textDecorators);
$delivery->setAttrib('class', 'span8');
$delivery->setRequired();
foreach($deliveryTypes as $type):
$delivery->addMultiOption($type['id'],$type['name']." - ".$type['price']." zł");
endforeach;
$payment = $this->createElement('radio', 'payment_type_id');
$payment->setLabel('Sposób płatności');
// $payment->setRequired(true);
$payment->setDecorators(self::$textDecorators);
$payment->setAttrib('class', 'span8');
$payment->setRequired();
foreach($paymentTypes as $type):
$payment->addMultiOption($type['id'],$type['name']);
endforeach;
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Make order');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$id,
$delivery,
$payment,
$submit
));
}
}<file_sep>/application/modules/order/models/Doctrine/Coupon.php
<?php
/**
* Order_Model_Doctrine_Coupon
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package Admi
* @subpackage Order
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Order_Model_Doctrine_Coupon extends Order_Model_Doctrine_BaseCoupon
{
public function getId() {
return $this->_get('id');
}
public function getCode() {
return $this->_get('code');
}
public function setSent($sent = true) {
$this->_set('sent', $sent);
}
public function isUsed() {
return $this->_get('used');
}
public function getAmount() {
return $this->_get('amount_coupon');
}
public function getType() {
return $this->_get('type');
}
public function setOrderId($orderId) {
$this->_set('order_id', $orderId);
}
public function setUsed($used = true) {
$this->_set('used', $used);
}
public function setUserId($userId) {
$this->_set('user_id', $userId);
}
public function setUp() {
$this->hasOne('User_Model_Doctrine_User as User', array(
'local' => 'user_id',
'foreign' => 'id'
));
parent::setUp();
}
}<file_sep>/application/modules/testimonial/controllers/AdminController.php
<?php
/**
* Testimonial_AdminController
*
* @author <NAME> <<EMAIL>>
*/
class Testimonial_AdminController extends MF_Controller_Action {
public function init() {
$this->_helper->ajaxContext()
->addActionContext('move-testimonial', 'json')
->initContext();
parent::init();
}
public function listTestimonialAction() {
$testimonialService = $this->_service->getService('Testimonial_Service_Testimonial');
if(!$testimonialRoot = $testimonialService->getTestimonialRoot()) {
$testimonialService->createTestimonialRoot();
}
}
public function listTestimonialDataAction() {
$i18nService = $this->_service->getService('Default_Service_I18n');
$table = Doctrine_Core::getTable('Testimonial_Model_Doctrine_Testimonial');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Testimonial_DataTables_Testimonial',
'columns' => array('pt.name', 'p.created_at'),
'searchFields' => array('pt.name')
));
$language = $i18nService->getAdminLanguage();
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result->author_name;
$row[] = $result['created_at'];
if ($result['status'] == 1)
$row[] = '<a href="' . $this->view->adminUrl('refresh-status-testimonial', 'testimonial', array('testimonial-id' => $result->id)) . '" title=""><span class="icon16 icomoon-icon-lamp-2"></span></a>';
else
$row[] = '<a href="' . $this->view->adminUrl('refresh-status-testimonial', 'testimonial', array('testimonial-id' => $result->id)) . '" title=""><span class="icon16 icomoon-icon-lamp-3"></span></a>';
$moving = '<a href="' . $this->view->adminUrl('move-testimonial', 'testimonial', array('id' => $result->id, 'move' => 'up')) . '" class="move" title ="' . $this->view->translate('Move up') . '"><span class="icomoon-icon-arrow-up"></span></a>';
$moving .= '<a href="' . $this->view->adminUrl('move-testimonial', 'testimonial', array('id' => $result->id, 'move' => 'down')) . '" class="move" title ="' . $this->view->translate('Move down') . '"><span class="icomoon-icon-arrow-down"></span></a>';
$row[] = $moving;
$options = '<a href="' . $this->view->adminUrl('edit-testimonial', 'testimonial', array('id' => $result->id)) . '" title="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-testimonial', 'testimonial', array('id' => $result->id)) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $dataTables->getTotal(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addTestimonialAction() {
$testimonialService = $this->_service->getService('Testimonial_Service_Testimonial');
$i18nService = $this->_service->getService('Default_Service_I18n');
$translator = $this->_service->get('translate');
$adminLanguage = $i18nService->getAdminLanguage();
$form = $testimonialService->getTestimonialForm();
if(!$parent = $testimonialService->getTestimonial($this->getRequest()->getParam('id', 0))) {
$parent = $testimonialService->getTestimonialRoot();
}
$form->getElement('parent_id')->setValue($parent->getId());
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$testimonial = $testimonialService->saveTestimonialFromArray($values);
$this->view->messages()->add($translator->translate('Item has been added'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-testimonial', 'testimonial'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$languages = $i18nService->getLanguageList();
$this->view->assign('adminLanguage', $adminLanguage);
$this->view->assign('languages', $languages);
$this->view->assign('form', $form);
}
public function editTestimonialAction() {
$testimonialService = $this->_service->getService('Testimonial_Service_Testimonial');
$i18nService = $this->_service->getService('Default_Service_I18n');
$translator = $this->_service->get('translate');
if(!$testimonial = $testimonialService->getTestimonial($this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Testimonial not found');
}
$adminLanguage = $i18nService->getAdminLanguage();
$form = $testimonialService->getTestimonialForm($testimonial);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$testimonial = $testimonialService->saveTestimonialFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-testimonial', 'testimonial'));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$languages = $i18nService->getLanguageList();
$this->view->assign('adminLanguage', $adminLanguage);
$this->view->assign('languages', $languages);
$this->view->assign('testimonial', $testimonial);
$this->view->assign('form', $form);
}
public function removeTestimonialAction() {
$testimonialService = $this->_service->getService('Testimonial_Service_Testimonial');
if($testimonial = $testimonialService->getTestimonial($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$testimonialService->removeTestimonial($testimonial);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-testimonial', 'testimonial'));
} catch(Exception $e) {
$this->_service->get('Logger')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-testimonial', 'testimonial'));
}
public function refreshStatusTestimonialAction() {
$testimonialService = $this->_service->getService('Testimonial_Service_Testimonial');
if(!$testimonial = $testimonialService->getTestimonial((int) $this->getRequest()->getParam('testimonial-id'))) {
throw new Zend_Controller_Action_Exception('Book not found');
}
$testimonialService->refreshStatusTestimonial($testimonial);
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-testimonial', 'testimonial'));
$this->_helper->viewRenderer->setNoRender();
}
public function moveTestimonialAction() {
$testimonialService = $this->_service->getService('Testimonial_Service_Testimonial');
$this->view->clearVars();
$testimonial = $testimonialService->getTestimonial((int) $this->getRequest()->getParam('id'));
$status = 'success';
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$testimonialService->moveTestimonial($testimonial, $this->getRequest()->getParam('move', 'down'));
$this->_service->get('doctrine')->getCurrentConnection()->commit();
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage());
$status= 'error';
}
$this->_helper->viewRenderer->setNoRender();
$this->view->assign('status', $status);
}
}
<file_sep>/application/modules/faq/library/DataTables/Faq.php
<?php
/**
* Faq
*
* @author <NAME> <<EMAIL>>
*/
class Faq_DataTables_Faq extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Faq_DataTables_Adapter_Faq';
}
}
<file_sep>/application/modules/tournament/services/Booking.php
<?php
/**
* Tournament_Service_Tournament
*
@author <NAME> <<EMAIL>>
*/
class Tournament_Service_Booking extends MF_Service_ServiceAbstract {
protected $bookingTable;
public function init() {
$this->bookingTable = Doctrine_Core::getTable('Tournament_Model_Doctrine_Booking');
parent::init();
}
public function getBooking($tournament_id,$weight,$hydrationMode = Doctrine_Core::HYDRATE_RECORD)
{
$q = $this->bookingTable->createQuery('b');
$q->leftJoin('b.Player p');
$q->leftJoin('p.Team t');
$q->addSelect('*, sum(quantity) as kar');
$q->addWhere('t.tournament_id = ?',$tournament_id)
->addWhere('b.weight = ?',$weight)
->addOrderBy('kar DESC')
->addOrderBy('p.last_name DESC')
->addOrderBy('p.first_name DESC')
->addGroupBy('p.last_name')
->addGroupBy('p.first_name')
->addGroupBy('b.weight');
$q->addWhere('b.active = 1');
return $q->execute(array(), $hydrationMode);
}
public function getSingleBooking($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->bookingTable->findOneBy($field, $id, $hydrationMode);
}
public function getBookingForm(Tournament_Model_Doctrine_Booking $booking = null) {
$form = new Tournament_Form_Booking();
if(null != $booking) {
$form->populate($booking->toArray());
}
return $form;
}
public function saveBookingFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$booking = $this->getSingleBooking((int) $values['id'])) {
$booking = $this->bookingTable->getRecord();
}
$booking->fromArray($values);
$booking->save();
return $booking;
}
public function removeTournament(Tournament_Model_Doctrine_Tournament $orderStatus) {
$orderStatus->delete();
}
public function getAllTournament($hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
$q = $this->bookingTable->getTournamentQuery();
return $q->execute(array(), $hydrationMode);
}
public function getTargetTournamentSelectOptions($prependEmptyValue = false) {
$items = $this->getAllTournament();
$result = array();
if($prependEmptyValue) {
$result[''] = ' ';
}
foreach($items as $item) {
$result[$item->getId()] = $item->name;
}
return $result;
}
}
?><file_sep>/application/modules/default/controllers/IndexController.php
<?php
class Default_IndexController extends MF_Controller_Action
{
public function indexAction()
{
$metatagService = $this->_service->getService('Default_Service_Metatag');
$pageService = $this->_service->getService('Page_Service_Page');
$newsService = $this->_service->getService('News_Service_News');
$leagueService = $this->_service->getService('League_Service_League');
$matchService = $this->_service->getService('League_Service_Match');
$photoService = $this->_service->getService('Media_Service_Photo');
$photoDimensionService = $this->_service->getService('Default_Service_PhotoDimension');
$photoDimension = $photoDimensionService->getElementDimension('news');
$query = $newsService->getNewsPaginationQuery();
$adapter = new MF_Paginator_Adapter_Doctrine($query, Doctrine_Core::HYDRATE_RECORD);
$paginator = new Zend_Paginator($adapter);
$paginator->setItemCountPerPage(10);
$page = $this->_request->getParam('strona', 1);
$paginator->setCurrentPageNumber($page);
$leagues = $leagueService->getActiveLeaguesWithTable();
$leagueIds = $leagueService->getActiveLeagueIds();
$nextMatches = $matchService->getNextMatches($leagueIds);
$prevMatches = $matchService->getPrevMatches($leagueIds);
$eventService = $this->_service->getService('District_Service_Event');
$nextEvents = $eventService->getNextEvents();
$this->view->assign('nextEvents',$nextEvents);
if(!$homepage = $pageService->getI18nPage('homepage', 'type', $this->view->language, Doctrine_Core::HYDRATE_RECORD)) {
throw new Zend_Controller_Action_Exception('Homepage not found');
}
if($homepage != NULL):
$metatagService->setViewMetatags($homepage->get('Metatag'), $this->view);
endif;
$this->view->assign('homepage', $homepage);
$this->view->assign('prevMatches', $prevMatches);
$this->view->assign('nextMatches', $nextMatches);
$this->view->assign('leagues', $leagues);
$this->view->paginator = $paginator;
$this->view->modelPhoto = $photoService;
$this->_helper->actionStack('layout');
}
public function layoutAction()
{
$teamService = $this->_service->getService('League_Service_Team');
$this->view->assign('teamService',$teamService);
$galleryService = $this->_service->getService('Gallery_Service_Gallery');
$galleryList = $galleryService->getAllGallerys();
$this->view->assign('galleryList',$galleryList);
$cupService = $this->_service->getService('League_Service_Cup');
$cupsList = $cupService->getAllCups();
$this->view->assign('cupsList',$cupsList);
// $bannerService = $this->_service->getService('Banner_Service_Banner');
// $bannerLeft = $bannerService->getCategoryBanners(1);
// $bannerRight = $bannerService->getCategoryBanners(2);
//
// $this->view->assign('bannerLeft',$bannerLeft);
// $this->view->assign('bannerRight',$bannerRight);
$photoDimensionService = $this->_service->getService('Default_Service_PhotoDimension');
$sponsorPhotoDimension = $photoDimensionService->getElementDimension('sponsor');
$this->view->assign('sponsorPhotoDimension', $sponsorPhotoDimension);
$this->_helper->actionStack('sidebar');
$this->_helper->actionStack('slider');
$this->_helper->actionStack('menu');
$this->_helper->viewRenderer->setNoRender(true);
}
public function leftSidebarAction()
{
$modelNews = new Application_Model_News();
$news = $modelNews->getAllNewsNoPagination(6);
$this->view->assign('news',$news);
$this->_helper->viewRenderer->setResponseSegment('leftSidebar');
}
public function sidebarAction()
{
$resultService = $this->_service->getService('League_Service_Match');
$results = $resultService->getLastResults();
$this->view->assign('lastResults',$results);
$this->_helper->viewRenderer->setResponseSegment('sidebar');
}
public function footerAction()
{
$this->_helper->viewRenderer->setResponseSegment('footer');
}
public function showNewsAction()
{
$modelNews = new Application_Model_News();
$modelPhoto = new Application_Model_Photo();
// $allNews = $modelNews->getAllNewsNoPagination(1500);
//
// foreach($allNews as $n):
// // echo "ok";
// $slug = Application_Model_News::createUniqueTableSlug('aktualnosci', $n['tytul']);
// $modelNews->addSlug($n['id_news'],$slug);
// endforeach;
// exit;
if(!$news = $modelNews->getNews($this->getRequest()->getParam('slug'))){
throw new Zend_Exception('News not found');
}
$this->view->assign('news',$news);
$this->view->modelPhoto = $modelPhoto;
$this->_helper->actionStack('layout');
}
public function showResultAction()
{
echo $this->getRequest()->getParam('slug');
}
public function sponsorsAction()
{
$this->_helper->actionStack('layout');
}
public function zarzadAction()
{
$this->_helper->actionStack('layout');
}
public function archiwumAction()
{
// action body
}
public function sliderAction() {
$sliderService = $this->_service->getService('Slider_Service_Slider');
$slideLayerService = $this->_service->getService('Slider_Service_SlideLayer');
$mainSliderSlides = $sliderService->getAllForSlider("main");
$mainSlides = array();
foreach($mainSliderSlides[0]['Slides'] as $slide):
$layers = $slideLayerService->getLayersForSlide($slide['id']);
$slide['Layers'] = $layers;
$mainSlides[] = $slide;
endforeach;
$this->view->assign('mainSlides',$mainSlides);
$this->_helper->viewRenderer->setResponseSegment('slider');
$videoService = $this->_service->getService('Gallery_Service_Video');
$promotedVideo = $videoService->getPromotedVideo();
$this->view->assign('promotedVideo', $promotedVideo);
}
public function menuAction(){
$i18nService = $this->_service->getService('Default_Service_I18n');
$menuService = $this->_service->getService('Menu_Service_Menu');
if(!$menu = $menuService->getMenu(1)) {
throw new Zend_Controller_Action_Exception('Menu not found');
}
$treeRoot = $menuService->getMenuItemTree($menu, $this->view->language);
$tree = $treeRoot[0]->getNode()->getChildren();
$activeLanguages = $i18nService->getLanguageList();
$this->view->assign('activeLanguages', $activeLanguages);
$this->view->assign('menu', $menu);
$this->view->assign('tree', $tree);
$this->_helper->viewRenderer->setNoRender();
}
}
<file_sep>/application/modules/order/forms/Coupon.php
<?php
/**
* Order_Form_Coupon
*
* @author <NAME> <<EMAIL>>
*/
class Order_Form_Coupon extends Admin_Form {
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$numberofCoupon = $this->createElement('text', 'number_of_coupon');
$numberofCoupon->setLabel('Number of coupon');
$numberofCoupon->setRequired(true);
$numberofCoupon->setDecorators(self::$textDecorators);
$numberofCoupon->setAttrib('class', 'span8');
$type = $this->createElement('select', 'type');
$type->setLabel('Type');
$type->setRequired();
$type->setDecorators(self::$selectDecorators);
$amountCoupon = $this->createElement('text', 'amount_coupon');
$amountCoupon->setLabel('Amount');
$amountCoupon->setRequired(true);
$amountCoupon->setDecorators(self::$textDecorators);
$amountCoupon->setAttrib('class', 'span8');
$startValidityDate = $this->createElement('text', 'start_validity_date');
$startValidityDate->setLabel('Start date');
$startValidityDate->setRequired(true);
$startValidityDate->setDecorators(self::$datepickerDecorators);
$startValidityDate->setAttrib('class', 'span8');
$finishValidityDate = $this->createElement('text', 'finish_validity_date');
$finishValidityDate->setLabel('Finish date');
$finishValidityDate->setRequired(true);
$finishValidityDate->setDecorators(self::$datepickerDecorators);
$finishValidityDate->setAttrib('class', 'span8');
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Save');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$id,
$numberofCoupon,
$type,
$amountCoupon,
$startValidityDate,
$finishValidityDate,
$submit
));
}
}
<file_sep>/application/modules/order/services/Cart.php
<?php
/**
* Order_Service_Cart
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_Cart extends MF_Service_ServiceAbstract {
protected $orderTable;
protected $cart;
public function init() {
$this->orderTable = Doctrine_Core::getTable('Order_Model_Doctrine_Order');
parent::init();
}
public function getCart() {
if(!$this->cart) {
$this->cart = new Order_Model_Cart();
}
return $this->cart;
}
public function getDiscountCodeForm() {
$form = new Order_Form_DiscountCode();
return $form;
}
}
?><file_sep>/application/modules/attachment/library/DataTables/Attachment.php
<?php
/**
* Attachment_DataTables_Attachment
*
* @author <NAME> <<EMAIL>>
*/
class Attachment_DataTables_Attachment extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Attachment_DataTables_Adapter_Attachment';
}
}
<file_sep>/application/modules/league/forms/Discount.php
<?php
class Order_Form_Discount extends Admin_Form
{
public function init() {
$code = $this->createElement('text', 'code');
$code->setLabel('Kod rabatowy');
$code->setRequired()
-> removeDecorator('HtmlTag')
-> removeDecorator('Label');
$code->addValidators(array(
array('alnum', false, array('allowWhiteSpace' => true))
));
$code->addFilters(array(
array('alnum', array('allowWhiteSpace' => true))
));
$code->setValue('Wprowdź kod rabatowy');
$code->setAttrib('onfocus','this.value = ""');
// $code->setAttrib('onblur','this.value = "Wprowdź kod rabatowy"');
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Add bonus code')
-> removeDecorator('DtDdWrapper');
$submit->setAttrib('type', 'submit');
$this->setElements(array(
$code,
$submit
));
}
}<file_sep>/application/modules/attachment/controllers/AdminController.php
<?php
/**
* Attachment_AdminController
*
* @author <NAME> <<EMAIL>>
*/
class Attachment_AdminController extends MF_Controller_Action {
public function listAttachmentAction() {
}
public function listAttachmentDataAction() {
$i18nService = $this->_service->getService('Default_Service_I18n');
$table = Doctrine_Core::getTable('Attachment_Model_Doctrine_Attachment');
$dataTables = Default_DataTables_Factory::factory(array(
'request' => $this->getRequest(),
'table' => $table,
'class' => 'Attachment_DataTables_Attachment',
'columns' => array('a.title'),
'searchFields' => array('a.title')
));
$language = $i18nService->getAdminLanguage();
$results = $dataTables->getResult();
$rows = array();
foreach($results as $result) {
$row = array();
$row[] = $result->Translation[$language->getId()]->title;
$row[] = "/media/attachments/". $result['filename'];
$row[] = $result['extension'];
$options = '<a href="' . $this->view->adminUrl('edit-attachment', 'attachment', array('id' => $result->id)) . '" title="' . $this->view->translate('Edit') . '"><span class="icon24 entypo-icon-settings"></span></a> ';
$options .= '<a href="' . $this->view->adminUrl('remove-attachment', 'attachment', array('id' => $result->id)) . '" class="remove" title="' . $this->view->translate('Remove') . '"><span class="icon16 icon-remove"></span></a>';
$row[] = $options;
$rows[] = $row;
}
$response = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $dataTables->getDisplayTotal(),
"iTotalDisplayRecords" => $results->count(),
"aaData" => $rows
);
$this->_helper->json($response);
}
public function addAttachmentAction() {
$i18nService = $this->_service->getService('Default_Service_I18n');
$attachmentService = $this->_service->getService('Attachment_Service_Attachment');
$fileForm = new Attachment_Form_UploadAttachment();
$fileForm->setDecorators(array('FormElements'));
$fileForm->removeElement('submit');
$fileForm->getElement('file')->setValueDisabled(true);
$adminLanguage = $i18nService->getAdminLanguage();
if($this->getRequest()->isPost()) {
if($fileForm->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$attachment = $attachmentService->createAttachmentFromUpload($fileForm->getElement('file')->getName(), $fileForm->getValue('file'), null, $adminLanguage->getId());
$this->_service->get('doctrine')->getCurrentConnection()->commit();
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
var_dump($e->getMessage()); exit;
}
}
}
$this->_helper->viewRenderer->setNoRender();
}
public function editAttachmentAction() {
$i18nService = $this->_service->getService('Default_Service_I18n');
$attachmentService = $this->_service->getService('Attachment_Service_Attachment');
$translator = $this->_service->get('translate');
$adminLanguage = $i18nService->getAdminLanguage();
if(!$attachment = $attachmentService->getAttachment((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Attachment not found');
}
$form = $attachmentService->getAttachmentForm($attachment);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$attachmentService->saveAttachmentFromArray($values);
$this->view->messages()->add($translator->translate('Item has been updated'), 'success');
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-attachment', 'attachment'));
} catch(Exception $e) {
var_dump($e->getMessage()); exit;
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$languages = $i18nService->getLanguageList();
$this->view->assign('adminLanguage', $adminLanguage);
$this->view->assign('languages', $languages);
$this->view->assign('form', $form);
$this->view->assign('attachment', $attachment);
}
public function removeAttachmentAction() {
$attachmentService = $this->_service->getService('Attachment_Service_Attachment');
$photoService = $this->_service->getService('Media_Service_Photo');
if($attachment = $attachmentService->getAttachment($this->getRequest()->getParam('id'))) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$attachmentService->removeAttachment($attachment);
$photoRoot = $attachment->get('PhotoRoot');
$photoService->removePhoto($photoRoot);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-attachment', 'attachment'));
} catch(Exception $e) {
var_dump($e->getMessage()); exit;
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
$this->_helper->redirector->gotoUrl($this->view->adminUrl('list-attachment', 'attachment'));
}
public function addAttachmentPhotoAction() {
$attachmentService = $this->_service->getService('Attachment_Service_Attachment');
$photoService = $this->_service->getService('Media_Service_Photo');
if(!$attachment = $attachmentService->getAttachment((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Attachment not found');
}
$options = $this->getInvokeArg('bootstrap')->getOptions();
if(!array_key_exists('domain', $options)) {
throw new Zend_Controller_Action_Exception('Domain string not set');
}
$href = $this->getRequest()->getParam('hrefs');
if(is_string($href) && strlen($href)) {
$path = str_replace("http://" . $options['domain'], "", urldecode($href));
$filePath = urldecode($options['publicDir'] . $path);
if(file_exists($filePath)) {
$pathinfo = pathinfo($filePath);
$slug = MF_Text::createSlug($pathinfo['basename']);
$name = MF_Text::createUniqueFilename($slug, $photoService->photosDir);
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$root = $attachment->get('PhotoRoot');
if(!$root || $root->isInProxyState()) {
$photo = $photoService->createPhoto($filePath, $name, $pathinfo['filename'], array_keys(Attachment_Model_Doctrine_Attachment::getAttachmentPhotoDimensions()), false, false);
} else {
$photo = $photoService->clearPhoto($root);
$photo = $photoService->updatePhoto($root, $filePath, null, $name, $pathinfo['filename'], array_keys(Attachment_Model_Doctrine_Attachment::getAttachmentPhotoDimensions()), false);
}
$attachment->set('PhotoRoot', $photo);
$attachment->save();
$this->_service->get('doctrine')->getCurrentConnection()->commit();
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
}
}
$list = '';
$attachmentPhotos = new Doctrine_Collection('Media_Model_Doctrine_Photo');
$root = $attachment->get('PhotoRoot');
if($root && !$root->isInProxyState()) {
$attachmentPhotos->add($root);
$list = $this->view->partial('admin/attachment-main-photo.phtml', 'attachment', array('photos' => $attachmentPhotos, 'attachment' => $attachment));
}
$this->_helper->json(array(
'status' => 'success',
'body' => $list,
'id' => $attachment->getId()
));
}
public function editAttachmentPhotoAction() {
$attachmentService = $this->_service->getService('Attachment_Service_Attachment');
$photoService = $this->_service->getService('Media_Service_Photo');
$i18nService = $this->_service->getService('Default_Service_I18n');
$translator = $this->_service->get('translate');
$adminLanguage = $i18nService->getAdminLanguage();
if(!$attachment = $attachmentService->getAttachment((int) $this->getRequest()->getParam('attachment-id'))) {
throw new Zend_Controller_Action_Exception('Attachment not found');
}
if(!$photo = $photoService->getPhoto((int) $this->getRequest()->getParam('id'))) {
$this->view->messages()->add($translator->translate('First you have to choose picture'), 'error');
$this->_helper->redirector->gotoUrl($this->view->adminUrl('edit-attachment', 'attachment', array('id' => $attachment->getId())));
}
$form = $photoService->getPhotoForm($photo);
$form->setAction($this->view->adminUrl('edit-attachment-photo', 'attachment', array('attachment-id' => $attachment->getId(), 'id' => $photo->getId())));
$photosDir = $photoService->photosDir;
$offsetDir = realpath($photosDir . DIRECTORY_SEPARATOR . $photo->getOffset());
if(strlen($photo->getFilename()) > 0 && file_exists($offsetDir . DIRECTORY_SEPARATOR . $photo->getFilename())) {
list($width, $height) = getimagesize($offsetDir . DIRECTORY_SEPARATOR . $photo->getFilename());
$this->view->assign('imgDimensions', array('width' => $width, 'height' => $height));
}
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
$values = $form->getValues();
$photo = $photoService->saveFromArray($values);
$this->_service->get('doctrine')->getCurrentConnection()->commit();
if($this->getRequest()->getParam('saveOnly') == '1')
$this->_helper->redirector->gotoUrl($this->view->adminUrl('edit-attachment-photo', 'attachment', array('id' => $attachment->getId(), 'photo' => $photo->getId())));
$this->_helper->redirector->gotoUrl($this->view->adminUrl('edit-attachment', 'attachment', array('id' => $attachment->getId())));
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('Logger')->log($e->getMessage(), 4);
}
}
}
$this->view->admincontainer->findOneBy('id', 'edit-attachment')->setLabel($attachment->Translation[$adminLanguage->getId()]->title);
$this->view->admincontainer->findOneBy('id', 'edit-attachment')->setParam('id', $attachment->getId());
$this->view->adminTitle = $this->view->translate($this->view->admincontainer->findOneBy('id', 'cropattachmentphoto')->getLabel());
$this->view->assign('attachment', $attachment);
$this->view->assign('photo', $photo);
$this->view->assign('dimensions', Attachment_Model_Doctrine_Attachment::getAttachmentPhotoDimensions());
$this->view->assign('form', $form);
}
public function removeAttachmentPhotoAction() {
$attachmentService = $this->_service->getService('Attachment_Service_Attachment');
$photoService = $this->_service->getService('Media_Service_Photo');
if(!$attachment = $attachmentService->getAttachment((int) $this->getRequest()->getParam('id'))) {
throw new Zend_Controller_Action_Exception('Attachment not found');
}
try {
$this->_service->get('doctrine')->getCurrentConnection()->beginTransaction();
if($root = $attachment->get('PhotoRoot')) {
if($root && !$root->isInProxyState()) {
$photo = $photoService->updatePhoto($root);
$photo->setOffset(null);
$photo->setFilename(null);
$photo->setTitle(null);
$photo->save();
}
}
$this->_service->get('doctrine')->getCurrentConnection()->commit();
} catch(Exception $e) {
$this->_service->get('doctrine')->getCurrentConnection()->rollback();
$this->_service->get('log')->log($e->getMessage(), 4);
}
$list = '';
$attachmentPhotos = new Doctrine_Collection('Media_Model_Doctrine_Photo');
$root = $attachment->get('PhotoRoot');
if($root && !$root->isInProxyState()) {
$attachmentPhotos->add($root);
$list = $this->view->partial('admin/attachment-main-photo.phtml', 'attachment', array('photos' => $attachmentPhotos, 'attachment' => $attachment));
}
$this->_helper->json(array(
'status' => 'success',
'body' => $list,
'id' => $attachment->getId()
));
}
}<file_sep>/application/modules/order/models/Doctrine/ItemTable.php
<?php
/**
* Order_Model_Doctrine_ItemTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Order_Model_Doctrine_ItemTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Order_Model_Doctrine_ItemTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Order_Model_Doctrine_Item');
}
public function getOrderItemsIdsQuery(){
$q = $this->createQuery('i')
->addSelect('i.id')
;
return $q;
}
}<file_sep>/application/modules/attachment/controllers/IndexController.php
<?php
/**
* Attachment_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class Attachment_IndexController extends MF_Controller_Action {
public function attachmentsSerwis5Action(){
$attachmentService = $this->_service->getService('Attachment_Service_AttachmentSerwis5');
$attachments = $attachmentService->getAllAttachments($this->view->language, Doctrine_Core::HYDRATE_ARRAY);
$hideSlider = true;
$this->view->assign('hideSlider', $hideSlider);
$this->view->assign('attachments', $attachments);
$this->_helper->actionStack('layout-serwis5', 'index', 'default');
}
public function showPdfAttachmentSerwis5Action() {
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
$attachmentService = $this->_service->getService('Attachment_Service_AttachmentSerwis5');
if(!$attachment = $attachmentService->getFullAttachment($this->getRequest()->getParam('attachment'), 'slug')) {
throw new Zend_Controller_Action_Exception('Attachment not found', 404);
}
header ('Content-Type:', 'application/pdf');
header ('Content-Disposition:', 'inline;');
$fileName = "media/attachments/".$attachment->getFileName();
$pdf = new Zend_Pdf($fileName, null, true);
echo $pdf->render();
}
}
<file_sep>/application/modules/faq/models/Doctrine/FaqTable.php
<?php
/**
* Faq_Model_Doctrine_FaqTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Faq_Model_Doctrine_FaqTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Faq_Model_Doctrine_FaqTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Faq_Model_Doctrine_Faq');
}
public function getPublishFaqQuery($id, $field = 'id') {
$q = $this->createQuery('a')
->addSelect('a.*')
->addSelect('at.*')
->addSelect('m.*')
->addSelect('mt.*')
->leftJoin('a.Translation at')
->leftJoin('a.Metatags m')
->leftJoin('m.Translation mt')
;
if(is_integer($id)) {
$q->andWhere('a.' . $field . ' = ?', array($id));
} elseif(is_array($id) && !empty($id)) {
$q->andWhere('a.' . $field . ' IN ?', array($id));
}
return $q;
}
public function getPhotoQuery(Doctrine_Query $q = null) {
if(null == $q) {
$q = $this->createQuery('a');
$q->addSelect('a.*');
}
$q->addSelect('pr.*');
$q->addSelect('p.*');
$q->leftJoin('a.PhotoRoot pr');
$q->leftJoin('a.Photos p');
return $q;
}
public function getLimitQuery($limit, Doctrine_Query $q = null) {
if(null == $q) {
$q = $this->createQuery('a');
$q->addSelect('a.*');
}
$q->limit($limit);
return $q;
}
public function getCategoryIdQuery($categoryId = null, Doctrine_Query $q = null) {
if(null == $q) {
$q = $this->createQuery('ac');
}
$q->addSelect('ac.*');
$q->leftJoin('a.Category ac');
if(is_integer($categoryId)) {
$q->andWhere('ac.id');
} elseif(is_array($categoryId && !empty($categoryId))) {
$q->andWhere('ac.id IN ?', array($categoryId));
}
return $q;
}
public function getAllFaqQuery() {
$q = $this->createQuery('a')
->addSelect('a.*')
->addSelect('at.*')
->addSelect('pr.*')
->leftJoin('a.PhotoRoot pr')
->leftJoin('a.Translation at');
return $q;
}
public function getFaqForSiteMapQuery() {
$q = $this->createQuery('cat');
$q->addSelect('cat.*');
$q->addSelect('pro.*');
$q->addSelect('tr.*');
$q->leftJoin('cat.Translation tr');
$q->leftJoin('cat.Products pro');
$q->andWhere('pro.status = ?', 1);
$q->andWhere('pro.availability > ?', 0);
$q->andWhere('pro.reduced_price = ?', 0);
return $q;
}
}<file_sep>/application/modules/tournament/forms/GroupTeam.php
<?php
/**
* Order_Form_OrderStatus
*
* @author <NAME> <<EMAIL>>
*/
class Tournament_Form_GroupTeam extends Admin_Form {
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$name = $this->createElement('text', 'name');
$name->setLabel('Name');
$name->setRequired(true);
$name->setDecorators(self::$textDecorators);
$name->setAttrib('class', 'span8');
$group_id = $this->createElement('select', 'group_id');
$group_id->setLabel('Grupa');
$group_id->setRequired(false);
$group_id->setDecorators(self::$selectDecorators);
$group_id->setAttrib('class', 'span8');
for($i=1;$i<10;$i++):
$group_id->addMultiOption($i,'Groupa '.$i);
endfor;
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Save');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$id,
$name,
$group_id,
$submit
));
}
}
<file_sep>/application/modules/order/library/DataTables/Order.php
<?php
/**
* Order_DataTables_Order
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Order extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Order_DataTables_Adapter_Order';
}
}
<file_sep>/application/modules/order/models/Doctrine/Order.php
<?php
/**
* Order_Model_Doctrine_Order
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package Admi
* @subpackage Order
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Order_Model_Doctrine_Order extends Order_Model_Doctrine_BaseOrder
{
public function getId() {
return $this->_get('id');
}
public function getDeliveryId() {
return $this->_get('delivery_id');
}
public function getPaymentId() {
return $this->_get('payment_id');
}
public function getUserId() {
return $this->_get('user_id');
}
public function getCreatedAt() {
return $this->_get('created_at');
}
public function getContactMail() {
return $this->_get('contact_email');
}
public function getTotalCost() {
return $this->_get('total_cost');
}
public function setTotalCost($totalCost) {
$this->_set('total_cost', $totalCost);
}
public function setUp() {
$this->hasOne('User_Model_Doctrine_User as User', array(
'local' => 'user_id',
'foreign' => 'id'
));
parent::setUp();
}
}<file_sep>/application/modules/league/forms/DiscountCode.php
<?php
/**
* Order_Form_PaymentType
*
*/
class Order_Form_DiscountCode extends Admin_Form {
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$code = $this->createElement('text', 'code');
$code->setLabel('Code');
$code->setRequired(true);
$code->setDecorators(self::$textDecorators);
$code->setAttrib('class', 'span8');
$discount = $this->createElement('text', 'discount');
$discount->setLabel('Discount (%)');
$discount->setDecorators(self::$textareaDecorators);
$discount->setAttrib('class', 'span8');
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Save');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$id,
$code,
$discount,
$submit
));
}
}
<file_sep>/application/modules/league/services/DeliveryType.php
<?php
/**
* Order_Service_DeliveryType
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_DeliveryType extends MF_Service_ServiceAbstract {
protected $deliveryTypeTable;
public function init() {
$this->deliveryTypeTable = Doctrine_Core::getTable('Order_Model_Doctrine_DeliveryType');
parent::init();
}
public function getDeliveryType($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->deliveryTypeTable->findOneBy($field, $id, $hydrationMode);
}
public function getDeliveryTypes() {
return $this->deliveryTypeTable->findAll();
}
public function getDeliveryTypeForm(Order_Model_Doctrine_DeliveryType $deliveryType = null) {
$form = new Order_Form_DeliveryType();
if(null != $deliveryType) {
$form->populate($deliveryType->toArray());
}
return $form;
}
public function saveDeliveryTypeFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$deliveryType = $this->getDeliveryType((int) $values['id'])) {
$deliveryType = $this->deliveryTypeTable->getRecord();
}
$deliveryType->fromArray($values);
$deliveryType->save();
return $deliveryType;
}
public function removeDeliveryType(Order_Model_Doctrine_DeliveryType $deliveryType) {
$deliveryType->delete();
}
}
?><file_sep>/application/modules/affilateprogram/models/Doctrine/PartnerTable.php
<?php
/**
* Affilateprogram_Model_Doctrine_PartnerTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Affilateprogram_Model_Doctrine_PartnerTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Affilateprogram_Model_Doctrine_PartnerTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Affilateprogram_Model_Doctrine_Partner');
}
public function getOrdersForPartnerQuery($partnerId, $values) {
$q = $this->createQuery('p');
$q->addSelect('p.*');
$q->addSelect('po.*');
$q->addSelect('o.*');
$q->leftJoin('p.PartnerOrders po');
$q->leftJoin('po.Order o');
$q->where('p.id = ?', $partnerId);
$q->andWhere('(po.created_at >= ? AND po.created_at <= ?)', array($values['start_date'], $values['end_date']));
return $q;
}
}<file_sep>/application/modules/league/services/Delivery.php
<?php
/**
* Order_Service_DeliveryType
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_Delivery extends MF_Service_ServiceAbstract {
protected $deliveryTypeTable;
public function init() {
$this->deliveryTable = Doctrine_Core::getTable('Order_Model_Doctrine_Delivery');
parent::init();
}
public function getDelivery($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->deliveryTable->findOneBy($field, $id, $hydrationMode);
}
public function getDeliverys() {
return $this->deliveryTable->findAll();
}
public function getDeliveryForm(Order_Model_Doctrine_Delivery $delivery = null) {
$form = new Order_Form_Delivery();
if(null != $delivery) {
$form->populate($delivery->toArray());
}
return $form;
}
public function saveDeliveryFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$delivery = $this->getDelivery((int) $values['id'])) {
$delivery = $this->deliveryTable->getRecord();
}
$delivery->fromArray($values);
$delivery->save();
return $delivery;
}
public function removeDelivery(Order_Model_Doctrine_Delivery $delivery) {
$delivery->delete();
}
}
?><file_sep>/application/modules/xml/controllers/IndexController.php
<?php
/**
* Xml_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class Xml_IndexController extends MF_Controller_Action {
}
<file_sep>/application/modules/location/library/DataTables/Category.php
<?php
/**
* Location_DataTables_Category
*
* @author <NAME> <<EMAIL>>
*/
class Location_DataTables_Category extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Location_DataTables_Adapter_Category';
}
}
<file_sep>/application/modules/order/models/Doctrine/DeliveryTypeTable.php
<?php
/**
* Order_Model_Doctrine_DeliveryTypeTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Order_Model_Doctrine_DeliveryTypeTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Order_Model_Doctrine_DeliveryTypeTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Order_Model_Doctrine_DeliveryType');
}
public function getDeliveryTypeQuery() {
$q = $this->createQuery('dt');
$q->addSelect('dt.*');
return $q;
}
}<file_sep>/application/modules/tournament/library/DataTables/League.php
<?php
/**
* Gallery
*
* @author <NAME> <<EMAIL>>
*/
class Tournament_DataTables_Tournament extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Tournament_DataTables_Adapter_Tournament';
}
}
<file_sep>/application/modules/order/forms/Payu/Sms.php
<?php
/**
* Order_Form_Payu_Sms
*
* @author <NAME> <<EMAIL>>
*/
class Order_Form_Payu_Sms extends Order_Form_Payu {
public function init() {
parent::init();
$this->getElement('amount')->setName('amount_netto');
$this->getElement('submit')->setLabel('SMS');
}
public function setup($config) {
parent::setup($config);
if(array_key_exists('UrlPlatnosci_pl', $config)) {
$this->setAction($config['UrlPlatnosci_pl'] . '/UTF/NewSMS');
}
}
}
<file_sep>/application/modules/affilateprogram/models/Doctrine/PartnerOrdersTable.php
<?php
/**
* Affilateprogram_Model_Doctrine_PartnerOrdersTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Affilateprogram_Model_Doctrine_PartnerOrdersTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Affilateprogram_Model_Doctrine_PartnerOrdersTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Affilateprogram_Model_Doctrine_PartnerOrders');
}
}<file_sep>/application/modules/xml/controllers/AdminController.php
<?php
/**
* XML_AdminController
*
* @author <NAME> <<EMAIL>>
*/
class Xml_AdminController extends MF_Controller_Action {
public function generateSitemapAction() {
$categoryService = $this->_service->getService('Product_Service_Category');
$productService = $this->_service->getService('Product_Service_Product');
$i18nService = $this->_service->getService('Default_Service_I18n');
$newsService = $this->_service->getService('News_Service_News');
$locationService = $this->_service->getService('Location_Service_Location');
$languageList = $i18nService->getLanguageListForSiteMap();
$categories = $categoryService->getAllCategoriesForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$products = $productService->getAllProductForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$news = $newsService->getAllNewsForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$locations = $locationService->getAllLocationsForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$numberOfProductsPerPageCategory = $categoryService->getProductCountPerPage();
$numberOfNewsPerPage = $newsService->getArticleItemCountPerPage();
$file = fopen(APPLICATION_PATH."/../public/sitemap/sitemap.xml", 'w+');
$time = date("Y-m-d")."T".date("H:i:s+00:00");
$domain = "http://bodyempire.pl/";
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
';
foreach($languageList as $lang):
if ($lang == "en"):
$xml .= '<url>
<loc>'.$domain.$lang.'/page/about-us</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/page/prof-andrzej-frydrychowski-md-ph-d</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/contact</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/login</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/register</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/cart</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
foreach($categories as $category):
if(count($category['Products'])%$numberOfProductsPerPageCategory != 0):
$categoryPage = (int)(count($category['Products'])/$numberOfProductsPerPageCategory) + 1;
else:
$categoryPage = count($category['Products'])/$numberOfProductsPerPageCategory;
endif;
for($i=1;$i<=$categoryPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$category['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$category['Translation'][$lang]['slug'].'/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
endforeach;
foreach($products as $product):
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$product['Categories'][0]['Translation'][$lang]['slug'].'/'.$product['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
if(count($news)%$numberOfNewsPerPage != 0):
$newsPage = (int)(count($news)/$numberOfNewsPerPage) + 1;
else:
$newsPage = count($news)/$numberOfNewsPerPage;
endif;
if ($lang == "en"):
for($i=1;$i<=$newsPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/news</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/news/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($news as $newsItem):
$xml .= '<url>
<loc>'.$domain.$lang.'/news/'.$newsItem['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
endif;
if ($lang == "en"):
$xml .= '<url>
<loc>'.$domain.$lang.'/faq</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/faq/psoriasis</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/faq/rosacea</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/faq/collagen</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
if ($lang == "en"):
$xml .= '<url>
<loc>'.$domain.$lang.'/location</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
foreach($locations as $location):
$xml .= '<url>
<loc>'.$domain.$lang.'/location/'.$location['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
endif;
endforeach;
$xml .='</urlset>';
fwrite($file, $xml);
fclose($file);
}
public function generateSitemapAjurwedaAction() {
$menuService = $this->_service->getService('Menu_Service_Menu');
$articleService = $this->_service->getService('Article_Service_Article');
$newsService = $this->_service->getService('News_Service_News');
$eventService = $this->_service->getService('Event_Service_Event');
$eventPromotedService = $this->_service->getService('Event_Service_EventPromoted');
$basicActivityService = $this->_service->getService('Company_Service_BasicActivity');
$companyService = $this->_service->getService('Company_Service_Company');
$bookService = $this->_service->getService('Book_Service_Book');
$workshopService = $this->_service->getService('Workshop_Service_Workshop');
$reviewService = $this->_service->getService('Review_Service_Review');
$partnerService = $this->_service->getService('Partner_Service_Partner');
$categoriesCookingService = $this->_service->getService('Cooking_Service_Category');
$recipeService = $this->_service->getService('Cooking_Service_Recipe');
$trainerService = $this->_service->getService('Trainer_Service_Trainer');
$trainerPromotedService = $this->_service->getService('Trainer_Service_TrainerPromoted');
$i18nService = $this->_service->getService('Default_Service_I18n');
$languageList = $i18nService->getLanguageListForSiteMap();
$menu = $menuService->getMenu(1);
if($menu):
$menuTree = $menuService->getMenuItemTreeForSiteMap($menu);
endif;
$news = $newsService->getAllNewsForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$eventsNormal = $eventService->getAllEventsForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$eventsPromoted = $eventPromotedService->getAllEventsPromotedForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$events = array_merge($eventsPromoted, $eventsNormal);
$basicActivities = $basicActivityService->getAllBasicActivitiesForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$companies = $companyService->getAllCompaniesForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$books = $bookService->getAllBooksForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$workshops = $workshopService->getAllWorkshopsForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$reviews = $reviewService->getAllReviewsForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$partners = $partnerService->getAllPartnersForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$categoriesCooking = $categoriesCookingService->getAllCategoriesForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$recipes = $recipeService->getAllRecipesForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$trainersNormal = $trainerService->getAllTrainersForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$trainersPromoted = $trainerPromotedService->getAllTrainersPromotedForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
$trainers = array_merge($trainersPromoted, $trainersNormal);
// $numberOfNewestProduct = $productService->getNumberOfNewestProductForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
// $numberOfNewestProduct = $numberOfNewestProduct[0]['number_of_products'];
// $numberOfPromotionProduct = $productService->getNumberOfPromotionProductForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
// $numberOfPromotionProduct = $numberOfPromotionProduct[0]['number_of_products'];
// $numberOfReducedPriceProduct = $productService->getNumberOfReducedPriceProductForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
// $numberOfReducedPriceProduct = $numberOfReducedPriceProduct[0]['number_of_products'];
// $numberOfAyurvedaProduct = $productService->getNumberOfAyurvedaProductForSiteMap(Doctrine_Core::HYDRATE_ARRAY);
// $numberOfAyurvedaProduct = $numberOfAyurvedaProduct[0]['number_of_products'];
$numberOfArticleItemPerPage = $articleService->getArticleItemCountPerPage();
$numberOfNewsPerPage = $newsService->getArticleItemCountPerPage();
$numberOfEventsPerPage = $eventService->getArticleItemCountPerPage();
$numberOfCompaniesCategoryPerPage = $companyService->getCompaniesCategoryCountPerPage();
$numberOfCompaniesPerPage = $companyService->getCompaniesCountPerPage();
$numberOfBooksPerPage = $bookService->getBookItemCountPerPage();
$numberOfWorkshopsPerPage = $workshopService->getWorkshopItemCountPerPage();
$numberOfReviewsPerPage = $reviewService->getReviewItemCountPerPage();
$numberOfPartnersPerPage = $partnerService->getPartnerItemCountPerPage();
$numberOfRecipesPerPage = $recipeService->getRecipesCountPerPage();
$numberOfTrainersPerPage = $trainerService->getTrainersCountPerPage();
$file = fopen(APPLICATION_PATH."/../public/sitemaps/sitemap-ajurweda.xml", 'w+');
$time = date("Y-m-d")."T".date("H:i:s+00:00");
$domain = "http://a-ajurweda.pl/";
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
';
foreach($languageList as $lang):
$xml .= '<url>
<loc>'.$domain.$lang.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/strona/visit-us</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/program-partnerski-ajurweda</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/newsletter/register</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/register</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/login</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/profil/firma</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/profil/wydarzenia</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/profil/ustawienia</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/pomoc</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/strona/condition</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/strona/privacy-policy</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/kontakt</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/results-searching</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
foreach($menuTree as $item):
if($item['level'] == 1 && $item->Translation[$lang]->title):
if(count($item['Articles'])%$numberOfArticleItemPerPage != 0):
$articlePage = (int)(count($item['Articles'])/$numberOfArticleItemPerPage) + 1;
else:
$articlePage = count($item['Articles'])/$numberOfArticleItemPerPage;
endif;
if($item['target_type'] && count($item['Articles']) > 0):
if(count($item['Articles']) < 2 && $item->Translation[$lang]->slug):
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$item['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
for($i=1;$i<=$articlePage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/kategoria/'.$item['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/kategoria/'.$item['Translation'][$lang]['slug'].'/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
endif;
endif;
if($item->getNode()->getChildren()):
$subtree = $item->getNode()->getChildren();
foreach($subtree as $item):
if($item->Translation[$lang]->title):
if(count($item['Articles'])%$numberOfArticleItemPerPage != 0):
$articlePage = (int)(count($item['Articles'])/$numberOfArticleItemPerPage) + 1;
else:
$articlePage = count($item['Articles'])/$numberOfArticleItemPerPage;
endif;
if($item['target_type'] && count($item['Articles']) > 0):
if(count($item['Articles']) < 2 && $item->Translation[$lang]->slug):
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$item['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
for($i=1;$i<=$articlePage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/kategoria/'.$item['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/kategoria/'.$item['Translation'][$lang]['slug'].'/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
endif;
endif;
endif;
endforeach;
endif;
endif;
endforeach;
if(count($news)%$numberOfNewsPerPage != 0):
$newsPage = (int)(count($news)/$numberOfNewsPerPage) + 1;
else:
$newsPage = count($news)/$numberOfNewsPerPage;
endif;
for($i=1;$i<=$newsPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/aktualnosci</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/aktualnosci/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($news as $newsItem):
$xml .= '<url>
<loc>'.$domain.$lang.'/aktualnosci/'.$newsItem['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
if(count($events)%$numberOfEventsPerPage != 0):
$eventPage = (int)(count($events)/$numberOfEventsPerPage) + 1;
else:
$eventPage = count($events)/$numberOfEventsPerPage;
endif;
for($i=1;$i<=$eventPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/wydarzenia</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/wydarzenia/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($events as $event):
if($event['type'] == "promoted"):
$xml .= '<url>
<loc>'.$domain.$lang.'/wydarzenia/'.$event['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endforeach;
if(count($trainers)%$numberOfTrainersPerPage != 0):
$trainerPage = (int)(count($trainers)/$numberOfTrainersPerPage) + 1;
else:
$trainerPage = count($trainers)/$numberOfTrainersPerPage;
endif;
for($i=1;$i<=$trainerPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/sylwetki</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/sylwetki/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($trainers as $trainer):
if($trainer['type'] == "promoted"):
$xml .= '<url>
<loc>'.$domain.$lang.'/sylwetka/promowana/'.$trainer['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
elseif($trainer['type'] == "normal"):
$xml .= '<url>
<loc>'.$domain.$lang.'/sylwetka/zwykla/'.$trainer['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endforeach;
foreach($basicActivities as $basicActivity):
if($basicActivity['companies_count']%$numberOfCompaniesCategoryPerPage != 0):
$basicActivityPage = (int)($basicActivity['companies_count']/$numberOfCompaniesCategoryPerPage) + 1;
else:
$basicActivityPage = $basicActivity['companies_count']/$numberOfCompaniesCategoryPerPage;
endif;
for($i=1;$i<=$basicActivityPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$basicActivity['Translation'][$lang]['slug'].'/firmy</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$basicActivity['Translation'][$lang]['slug'].'/firmy/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
endforeach;
if(count($companies)%$numberOfCompaniesPerPage != 0):
$companyPage = (int)(count($companies)/$numberOfCompaniesPerPage) + 1;
else:
$companyPage = count($companies)/$numberOfCompaniesPerPage;
endif;
for($i=1;$i<=$companyPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/katalog-firm</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/katalog-firm/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($companies as $company):
if($company['BusinessCard']['type'] == 'premium'):
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$company['BasicActivity']['Translation'][$lang]['slug'].'/firma/'.$company['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endforeach;
$xml .= '<url>
<loc>'.$domain.$lang.'/katalog-firm-mapa</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/profil/add-company</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/profil/edit-company</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
$xml .= '<url>
<loc>'.$domain.$lang.'/company-searching</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
if(count($books)%$numberOfBooksPerPage != 0):
$bookPage = (int)(count($books)/$numberOfBooksPerPage) + 1;
else:
$bookPage = count($books)/$numberOfBooksPerPage;
endif;
for($i=1;$i<=$bookPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/ksiazki</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/ksiazki/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($books as $book):
$xml .= '<url>
<loc>'.$domain.$lang.'/ksiazki/'.$book['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
if(count($workshops)%$numberOfWorkshopsPerPage != 0):
$workshopPage = (int)(count($workshops)/$numberOfWorkshopsPerPage) + 1;
else:
$workshopPage = count($workshops)/$numberOfWorkshopsPerPage;
endif;
for($i=1;$i<=$workshopPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/warsztaty</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/warsztaty/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($workshops as $workshop):
$xml .= '<url>
<loc>'.$domain.$lang.'/warsztaty/'.$workshop['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
if(count($reviews)%$numberOfReviewsPerPage != 0):
$reviewPage = (int)(count($reviews)/$numberOfReviewsPerPage) + 1;
else:
$reviewPage = count($reviews)/$numberOfReviewsPerPage;
endif;
for($i=1;$i<=$reviewPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/w-mediach</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/w-mediach/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($reviews as $review):
$xml .= '<url>
<loc>'.$domain.$lang.'/w-mediach/'.$review['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
if(count($partners)%$numberOfPartnersPerPage != 0):
$partnerPage = (int)(count($partners)/$numberOfPartnersPerPage) + 1;
else:
$partnerPage = count($partners)/$numberOfPartnersPerPage;
endif;
for($i=1;$i<=$partnerPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/partnerzy</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/partnerzy/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($categoriesCooking as $categoryCook):
if(count($categoryCook['Recipes'])%$numberOfRecipesPerPage != 0):
$categoryCookingPage = (int)(count($categoryCook['Recipes'])/$numberOfRecipesPerPage) + 1;
else:
$categoryCookingPage = count($categoryCook['Recipes'])/$numberOfRecipesPerPage;
endif;
for($i=1;$i<=$categoryCookingPage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$categoryCook['Translation'][$lang]['slug'].'/przepisy</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$categoryCook['Translation'][$lang]['slug'].'/przepisy/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
endforeach;
if(count($recipes)%$numberOfRecipesPerPage != 0):
$recipePage = (int)(count($recipes)/$numberOfRecipesPerPage) + 1;
else:
$recipePage = count($recipes)/$numberOfRecipesPerPage;
endif;
for($i=1;$i<=$recipePage;$i++):
if($i==1):
$xml .= '<url>
<loc>'.$domain.$lang.'/przepisy</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
else:
$xml .= '<url>
<loc>'.$domain.$lang.'/przepisy/'.$i.'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endif;
endfor;
foreach($recipes as $recipe):
$xml .= '<url>
<loc>'.$domain.$lang.'/'.$recipe['Categories'][0]['Translation'][$lang]['name'].'/przepis/'.$recipe['Translation'][$lang]['slug'].'</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
$xml .= '<url>
<loc>'.$domain.$lang.'/recipe-searching</loc>
<lastmod>'.$time.'</lastmod>
</url>
';
endforeach;
$xml .='</urlset>';
fwrite($file, $xml);
fclose($file);
}
}
?><file_sep>/application/modules/affilateprogram/forms/Commission.php
<?php
/**
* Affilateprogram_Form_Commission
*
* @author <NAME> <<EMAIL>>
*/
class Affilateprogram_Form_Commission extends Admin_Form {
public function init() {
$id = $this->createElement('hidden', 'id');
$id->setDecorators(array('ViewHelper'));
$startDate = $this->createElement('text', 'start_date');
$startDate->setLabel('From');
$startDate->setRequired(true);
$startDate->setDecorators(self::$datepickerDecorators);
$startDate->setAttrib('class', 'span8');
$endDate = $this->createElement('text', 'end_date');
$endDate->setLabel('To');
$endDate->setRequired(true);
$endDate->setDecorators(self::$datepickerDecorators);
$endDate->setAttrib('class', 'span8');
$submit = $this->createElement('button', 'submit');
$submit->setLabel('Check');
$submit->setDecorators(array('ViewHelper'));
$submit->setAttrib('type', 'submit');
$submit->setAttribs(array('class' => 'btn btn-info', 'type' => 'submit'));
$this->setElements(array(
$id,
$startDate,
$endDate,
$submit
));
}
}
<file_sep>/application/modules/league/services/Payment.php
<?php
/**
* Order_Service_PaymentType
*
*/
class Order_Service_Payment extends MF_Service_ServiceAbstract {
protected $paymentTable;
public function init() {
$this->paymentTable = Doctrine_Core::getTable('Order_Model_Doctrine_Payment');
parent::init();
}
public function getPaymentType($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->paymentTable->findOneBy($field, $id, $hydrationMode);
}
public function getPaymentTypes() {
return $this->paymentTable->findAll();
}
public function getPaymentTypeForm(Order_Model_Doctrine_PaymentType $payment = null) {
$form = new Order_Form_PaymentType();
if(null != $payment) {
$form->populate($payment->toArray());
}
return $form;
}
public function savePaymentFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$payment = $this->getPaymentType((int) $values['id'])) {
$payment = $this->paymentTable->getRecord();
}
$payment->fromArray($values);
$payment->save();
return $payment;
}
public function removePaymentType(Order_Model_Doctrine_PaymentType $payment) {
$payment->delete();
}
}
?><file_sep>/application/modules/faq/library/DataTables/Category.php
<?php
/**
* Faq_DataTables_Category
*
* @author <NAME> <<EMAIL>>
*/
class Faq_DataTables_Category extends Default_DataTables_DataTablesAbstract {
public function getAdapterClass() {
return 'Faq_DataTables_Adapter_Category';
}
}
<file_sep>/application/modules/faq/controllers/IndexController.php
<?php
/**
* Faq_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class Faq_IndexController extends MF_Controller_Action {
public function indexAction() {
$faqService = $this->_service->getService('Faq_Service_Faq');
$categoryService = $this->_service->getService('Faq_Service_Category');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$categoryList = $categoryService->getAllCategories();
if(strlen($this->getRequest()->getParam('category'))){
if(!$category = $categoryService->getFullCategory($this->getRequest()->getParam('category'),'slug')) {
$category = $categoryList[0];
}
}
else{
$category = $categoryList[0];
}
$this->view->assign('category', $category);
$this->view->assign('categoryList', $categoryList);
$this->_helper->actionStack('layout', 'index', 'default');
}
public function newsItemAction() {
$newsService = $this->_service->getService('Faq_Service_Faq');
$metatagService = $this->_service->getService('Default_Service_Metatag');
if(!$news = $newsService->getFullFaq($this->getRequest()->getParam('slug'), 'slug')) {
throw new Zend_Controller_Action_Exception('Faq not found', 404);
}
$metatagService->setViewMetatags($news->get('Metatags'), $this->view);
$this->view->assign('news', $news);
$this->_helper->actionStack('layout-ajurweda', 'index', 'default');
}
}
<file_sep>/application/modules/league/services/PaymentType.php
<?php
/**
* Order_Service_PaymentType
*
@author <NAME> <<EMAIL>>
*/
class Order_Service_PaymentType extends MF_Service_ServiceAbstract {
protected $paymentTypeTable;
public function init() {
$this->paymentTypeTable = Doctrine_Core::getTable('Order_Model_Doctrine_PaymentType');
parent::init();
}
public function getPaymentType($id, $field = 'id', $hydrationMode = Doctrine_Core::HYDRATE_RECORD) {
return $this->paymentTypeTable->findOneBy($field, $id, $hydrationMode);
}
public function getPaymentTypes() {
return $this->paymentTypeTable->findAll();
}
public function getPaymentTypeForm(Order_Model_Doctrine_PaymentType $paymentType = null) {
$form = new Order_Form_PaymentType();
if(null != $paymentType) {
$form->populate($paymentType->toArray());
}
return $form;
}
public function savePaymentTypeFromArray($values) {
foreach($values as $key => $value) {
if(!is_array($value) && strlen($value) == 0) {
$values[$key] = NULL;
}
}
if(!$paymentType = $this->getPaymentType((int) $values['id'])) {
$paymentType = $this->paymentTypeTable->getRecord();
}
$paymentType->fromArray($values);
$paymentType->save();
return $paymentType;
}
public function removePaymentType(Order_Model_Doctrine_PaymentType $paymentType) {
$paymentType->delete();
}
}
?><file_sep>/application/modules/affilateprogram/models/Doctrine/BasePartnerOrders.php
<?php
/**
* Affilateprogram_Model_Doctrine_BasePartnerOrders
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property integer $partner_id
* @property integer $order_id
* @property Affilateprogram_Model_Doctrine_Partner $Partner
*
* @package Admi
* @subpackage Affilateprogram
* @author <NAME> <<EMAIL>>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class Affilateprogram_Model_Doctrine_BasePartnerOrders extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('affilateprogram_partner_orders');
$this->hasColumn('partner_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('order_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->option('type', 'MyISAM');
$this->option('collate', 'utf8_general_ci');
$this->option('charset', 'utf8');
}
public function setUp()
{
parent::setUp();
$this->hasOne('Affilateprogram_Model_Doctrine_Partner as Partner', array(
'local' => 'partner_id',
'foreign' => 'id'));
$timestampable0 = new Doctrine_Template_Timestampable();
$this->actAs($timestampable0);
}
}<file_sep>/application/modules/location/controllers/IndexController.php
<?php
/**
* Location_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class Location_IndexController extends MF_Controller_Action {
public function indexAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$locations = $locationService->getAlli18nLocations('lt.title',$this->view->language,DOCTRINE_CORE::HYDRATE_ARRAY);
$locationsJson = $locationService->getLocationsForJson($this->view->language,DOCTRINE_CORE::HYDRATE_SCALAR);
$this->view->assign('locations', $locations);
$this->view->assign('locationsJson', $locationsJson);
$this->_helper->actionStack('layout', 'index', 'default');
}
public function jsonAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$locationsJson = $locationService->getLocationsForJson($this->view->language,DOCTRINE_CORE::HYDRATE_SCALAR);
$this->view->assign('locationsJson', $locationsJson);
$response = array(
"locationsJson" => $locationsJson,
);
$this->_helper->json($response);
}
public function savejsonAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$values = array(
'id' => $this->getRequest()->getParam('id'),
'lat' => $this->getRequest()->getParam('lat'),
'lng' => $this->getRequest()->getParam('lng'),
);
$locationService->saveLocationFromArray($values);
$this->_helper->layout->disableLayout();
}
public function locationAction() {
$locationService = $this->_service->getService('Location_Service_Location');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$translator = $this->_service->get('translate');
if(!$location = $locationService->getFullLocation($this->getRequest()->getParam('location'),'slug')){
throw new Zend_Controller_Action_Exception('Location not found');
}
$metatagService->setViewMetatags($location['metatag_id'],$this->view);
$form = new Default_Form_Contact();
$form->getElement('name')->setAttrib('placeholder', $translator->translate('Name'));
$form->getElement('email')->setAttrib('placeholder', $translator->translate('Email'));
$form->getElement('phone')->setAttrib('placeholder', $translator->translate('Phone'));
$form->getElement('subject')->setAttrib('placeholder', $translator->translate('Subject'));
$form->getElement('message')->setAttrib('placeholder', $translator->translate('Your Message ...'));
$captchaDir = $this->getFrontController()->getParam('bootstrap')->getOption('captchaDir');
$form->addElement('captcha', 'captcha',
array(
'label' => 'Rewrite the chars',
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 4,
'timeout' => 300,
'font' => APPLICATION_PATH . '/../data/arial.ttf',
'imgDir' => $captchaDir,
'imgUrl' => $this->view->serverUrl() . '/captcha/',
'width' => 150,
'fontSize' => 25
)
));
$form->getElement('captcha')->setAttrib('class', 'form-control');
$session = new Zend_Session_Namespace('CONTACT_CSRF');
$form->getElement('csrf')->setSession($session)->initCsrfValidator();
$options = $this->getFrontController()->getParam('bootstrap')->getOptions();
$contactEmail = $options['reply_email'];
$mail = new Zend_Mail('UTF-8');
$mail->addTo($contactEmail);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$contentMessage = $form->getValue('name')."\n";
$contentMessage .= $form->getValue('phone')."\n";
$contentMessage .= $form->getValue('message')."\n";
$mail->setReplyTo($form->getValue('email'));
$mail->setSubject($form->getValue('subject'));
$mail->setBodyText($contentMessage);
$mail->send();
$form->reset();
$this->view->messages()->add($this->view->translate('Message sent!'));
$this->_helper->redirector->gotoRoute(array('location' => $location['Translation'][$this->view->language]['title']), 'domain-location');
} catch(Exception $e) {
$this->_service->get('Logger')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('location', $location);
$this->view->assign('form', $form);
$this->_helper->actionStack('layout', 'index', 'default');
}
}
<file_sep>/application/modules/order/library/DataTables/Adapter/Coupon.php
<?php
/**
* Order_DataTables_Adapter_Coupon
*
* @author <NAME> <<EMAIL>>
*/
class Order_DataTables_Adapter_Coupon extends Default_DataTables_Adapter_AdapterAbstract {
public function getBaseQuery() {
$q = $this->table->createQuery('c');
$q->select('c.*');
return $q;
}
}
<file_sep>/application/modules/order/models/Doctrine/CouponTable.php
<?php
/**
* Order_Model_Doctrine_CouponTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Order_Model_Doctrine_CouponTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object Order_Model_Doctrine_CouponTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('Order_Model_Doctrine_Coupon');
}
}<file_sep>/application/modules/affilateprogram/controllers/IndexController.php
<?php
/**
* Affilateprogram_IndexController
*
* @author <NAME> <<EMAIL>>
*/
class Affilateprogram_IndexController extends MF_Controller_Action {
public function indexAction() {
$pageService = $this->_service->getService('Page_Service_PageShop');
$metatagService = $this->_service->getService('Default_Service_Metatag');
$affilateProgramService = $this->_service->getService('Affilateprogram_Service_Affilateprogram');
if(!$page = $pageService->getI18nPage('partner-program', 'type', $this->view->language, Doctrine_Core::HYDRATE_RECORD)) {
throw new Zend_Controller_Action_Exception('Page not found');
}
$metatagService->setViewMetatags($page->get('Metatag'), $this->view);
$referenceNumber = $this->getRequest()->getParam('reference_number');
if ($referenceNumber):
$partner = $affilateProgramService->getPartner($referenceNumber, 'reference_number');
elseif(isset($_COOKIE["reference_number"])):
$partner = $affilateProgramService->getPartner($_COOKIE["reference_number"], 'reference_number');
endif;
if($partner):
$expire=time()+60*60*24*90;
setcookie("reference_number", $partner->getReferenceNumber(), $expire, '/');
endif;
$form = new Default_Form_Contact();
$captchaDir = $this->getFrontController()->getParam('bootstrap')->getOption('captchaDir');
$form->addElement('captcha', 'captcha',
array(
'label' => 'Rewrite the chars',
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 4,
'timeout' => 300,
'font' => APPLICATION_PATH . '/../data/arial.ttf',
'imgDir' => $captchaDir,
'imgUrl' => $this->view->serverUrl() . '/captcha/',
'width' => 150,
'fontSize' => 25
)
));
$session = new Zend_Session_Namespace('CONTACT_CSRF');
$form->getElement('csrf')->setSession($session)->initCsrfValidator();
$contactEmail = "<EMAIL>";
$mail = new Zend_Mail('UTF-8');
$mail->addTo($contactEmail);
if($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getParams())) {
try {
$mail->setReplyTo($form->getValue('email'));
$mail->setSubject($form->getValue('subject'));
$mail->setBodyText($form->getValue('message'));
$mail->send();
$form->reset();
$this->view->messages()->add($this->view->translate('Message sent!'));
$this->_helper->redirector->gotoRoute(array(), 'domain-i18n:affilate-program');
} catch(Exception $e) {
$this->_service->get('Logger')->log($e->getMessage(), 4);
}
}
}
$this->view->assign('form', $form);
$this->view->assign('page', $page);
$this->view->assign('partner', $partner);
$this->_helper->actionStack('layout-shop', 'index', 'default');
}
}
|
1ae17ea0c0dff7d281aadd145a22b6fbb51bed84
|
[
"PHP"
] | 109 |
PHP
|
kardi31/ap
|
d7d1cf2d2a85a8f2e80b7016e4f4e89cfa6ca26a
|
54700fe28c16e04d328d0a69bec5e67e629a04f1
|
refs/heads/main
|
<file_sep>import React from 'react';
import { useSelector } from 'react-redux';
import Todo from '../todo/todo';
import './todoList.sass'
const TodoList = () => {
const todos = useSelector((state) => state.todos);
const active = useSelector(state => state.todos.active);
if (active === 'all') {
return (
<div className="todoList">
{
todos.allTodos.map(todo => {
return (
<Todo
title = {todo.todo}
id = {todo.id}
completed = {todo.completed}
key = {todo.id}
/>
)
})
}
</div>
)
} else if (active === 'completed') {
return (
<div className="todoList">
{
todos.completedTodos.map(todo => {
return (
<Todo
title = {todo.todo}
id = {todo.id}
completed = {todo.completed}
key = {todo.id}
/>
)
})
}
</div>
)
} else if (active === 'active') {
return (
<div className="todoList">
{
todos.activeTodos.map(todo => {
return (
<Todo
title = {todo.todo}
id = {todo.id}
completed = {todo.completed}
key = {todo.id}
/>
)
})
}
</div>
)
}
}
export default TodoList
<file_sep>import {React, useState} from 'react';
import { useDispatch } from 'react-redux';
import './form.sass'
import { addTodo } from '../../features/todosSlice';
const Form = () => {
const [value, setValue] = useState('');
const dispatch = useDispatch();
const handleAddTodo = () => {
dispatch(addTodo({title: value}));
}
return (
<div className="form">
<input
className="form__input"
type="text"
value={value}
onChange={(event) => {setValue(event.target.value)}}
/>
<button
type="button"
className="form__button"
onClick={handleAddTodo}
>
Add
</button>
</div>
)
}
export default Form
<file_sep>import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { filterAllTodos, filterCompletedTodos, filterActiveTodos } from '../../features/todosSlice';
import './filterButtons.sass';
const FilterButtons = () => {
const dispatch = useDispatch();
const active = useSelector(state => state.todos.active);
const handleFilterAllTodos = () => {
dispatch(filterAllTodos());
}
const handleFilterCompletedTodos = () => {
dispatch(filterCompletedTodos());
}
const handleFilterActiveTodos = () => {
dispatch(filterActiveTodos());
}
return (
<div className="filterButtons">
<button
className={active === 'all' ? "filterButtons__button active" : "filterButtons__button"}
type="button"
onClick={handleFilterAllTodos}
>
All
</button>
<button
className={active === 'completed' ? "filterButtons__button active" : "filterButtons__button"}
type="button"
onClick={handleFilterCompletedTodos}
>
Completed
</button>
<button
className={active === 'active' ? "filterButtons__button active" : "filterButtons__button"}
type="button"
onClick={handleFilterActiveTodos}
>
Active
</button>
</div>
)
}
export default FilterButtons
|
c0b557bbbce3b953144313dbc1681724dd90e636
|
[
"JavaScript"
] | 3 |
JavaScript
|
lizakrasn/redux-todolist
|
6e08a0d715da09dfb897cfb51ac937b8f55624f5
|
7e1cdd885214d2b9d9ea99e8f6f54e15ce3de52b
|
refs/heads/master
|
<repo_name>Rekhakode/VJIM-Intro-to-BA-Project<file_sep>/SQL PROJECT-VJIM/schema sql-vjim.sql
drop schema vjim;
create schema vjim;
drop table if exists studentdata;
CREATE TABLE studentdata (
rollnumber int NOT NULL,
firstname VARCHAR(255) NOT NULL,lastname VARCHAR(255) NOT NULL,
dateofbirth date ,gender CHAR(255) NOT NULL,
gpa Int,attendance int,
PRIMARY KEY (rollnumber)
);
load data local infile 'C:/Users/3XP/Desktop/SQL 2/studentdata.csv' into table studentdata fields terminated by ','
enclosed by '"'
lines terminated by '\n' IGNORE 1 Rows
(rollnumber,firstname,lastname,dateofbirth,gender,gpa,attendance) ;
Select * from studentdata;
DROP TABLE IF EXISTS `vjim`.`parentdetails` ;
CREATE TABLE IF NOT EXISTS `vjim`.`parentdetails` (
`fathername` VARCHAR(45) NULL,
`mobilenumber` VARCHAR(45) NULL,
`address` VARCHAR(45) NULL,
`location` VARCHAR(45) NULL,`rollnumber` INT NOT NULL);
load data local infile 'C:/Users/3XP/Desktop/SQL 2/parentdetails.csv' into table parentdetails fields terminated by ','
enclosed by '"'
lines terminated by '\n' IGNORE 1 Rows
(fathername,mobilenumber,address,location,rollnumber)
;
select * from parentdetails;
DROP TABLE IF EXISTS `vjim`.`studenteducationdata` ;
CREATE TABLE IF NOT EXISTS `vjim`.`studenteducationdata` (
`sscmarks` VARCHAR(45) NULL,
`intermarks` VARCHAR(45) NULL,
`workeperience` DECIMAL(10,0) NULL,
`rollnumber` INT NOT NULL,
`graduation` VARCHAR(45) NULL,
`graduationpercentage` VARCHAR(45) NULL,
`specialization` VARCHAR(45) NULL,`specialization2` VARCHAR(45) NULL,
PRIMARY KEY (`rollnumber`));
load data local infile 'C:/Users/3XP/Desktop/SQL 2/studenteducationdata.csv' into table studenteducationdata fields terminated by ','
enclosed by '"'
lines terminated by '\n' IGNORE 1 Rows
(sscmarks,intermarks,
workeperience,rollnumber,graduation,graduationpercentage,specialization,specialization2)
;
select * from studenteducationdata;
DROP TABLE IF EXISTS `vjim`.`entranceresults` ;
CREATE TABLE IF NOT EXISTS `vjim`.`entranceresults` (
`entrancetest` TEXT NULL,
`entrancescore` VARCHAR(45) NULL,
`entrancepercentile` VARCHAR(45) NULL,
`rollnumber` INT NOT NULL,PRIMARY KEY (`rollnumber`));
load data local infile 'C:/Users/3XP/Desktop/SQL 2/entrance results.csv' into table entranceresults fields terminated by ','
enclosed by '"'
lines terminated by '\n' IGNORE 1 Rows
(entrancetest,
entrancescore,
entrancepercentile,
rollnumber)
;
<file_sep>/SQL PROJECT-VJIM/vjim queries.sql
# Querying all data in a table
select * from studentdata;
select * from parentdetails;
select * from studenteducationdata;
select * from entranceresults;
# Querying the structure of the table
describe studentdata;
describe parentdetails;
describe studenteducationdata;
describe entranceresults;
#gpa greater than 3.6
select rollnumber,firstname,gpa
from studentdata
where gpa < 3.6;
#complete details of entrance
select *
from studentdata,entranceresults
where studentdata.rollnumber = entranceresults.rollnumber;
# Simple Joinsapply
# What colleges and majors did each of the student apply to?
select firstname,entrancetest,entrancepercentile
from studentdata,entranceresults
where studentdata.rollnumber = entranceresults.rollnumber;
# Using aliases for tables
select firstname,fathername,location
from studentdata s, parentdetails p
where s.rollnumber = p.rollnumber;
select firstname, specialization,attendance
from studentdata s,studenteducationdata se
where s.rollnumber = se.rollnumber;
# Distinct values
select distinct firstname, specialization
from studentdata s,studenteducationdata se
where s.rollnumber = se.rollnumber;
#students names starting with c
select rollnumber,firstname,gpa
from studentdata
where firstname like "C%";
select firstname,entrancescore from studentdata,entranceresults where entrancescore >=500;
#specialization
Select rollnumber, firstname
from studentdata
where rollnumber in
( select rollnumber from studenteducationdata where specialization = "HR");
#students with 5 gpa
Select gpa ,firstname,rollnumber
from studentdata where gpa=5 and rollnumber in (select rollnumber from studenteducationdata where specialization like "F%");
select firstname, gpa
from studentdata
where gpa >= ALL (select gpa
from studentdata);
#To find students number in various specializations
select count(specialization) from studenteducationdata where specialization like "M%" AND graduation ="B.Tech";
select count(specialization) from studenteducationdata where specialization like "A%" and graduation="B.Com";
select count(specialization) from studenteducationdata where specialization like "O%";
select count(specialization) from studenteducationdata where specialization like "H%";
select count(specialization) from studenteducationdata where specialization like "F%";
select count(gpa) from studentdata where gpa>4;
#students with 100% attendence
select attendance ,firstname, gpa from studentdata where attendance = 100 and gpa <5;
#students with b.com,marketing
select rollnumber, firstname
from studentdata
where rollnumber in (select rollnumber
from studenteducationdata
where graduation = "B.Com")
AND
rollnumber not in (select rollnumber
from studenteducationdata
where specialization = 'MARKETING');
#students from telegana
select count(rollnumber),location
from parentdetails p1
where exists (select *
from parentdetails p2
where p1.location='TELANGANA');
#students from rest of telegana
select studentdata.rollnumber,firstname,location
from parentdetails p1,studentdata
where NOT exists (select *
from parentdetails p2
where p1.location='TELANGANA');
|
4c58243a63285645887eaf1f40d3adbcd3410088
|
[
"SQL"
] | 2 |
SQL
|
Rekhakode/VJIM-Intro-to-BA-Project
|
098873c3fbd04971f12a5b56129163b53e110f7d
|
97d19ecd2e928777ea2d35bcc42ec369d59fc00c
|
refs/heads/master
|
<repo_name>tied/chef-single-cookbooks<file_sep>/Berksfile
# frozen_string_literal: true
source 'https://supermarket.chef.io'
cookbook 'mc', path: '../../mc'
cookbook 'git', path: '../../git'
cookbook 'cowsay', path: '../../cowsay'
metadata
|
9bf44c1f12c8fcc1bcf742c7c3f10b6862324805
|
[
"Ruby"
] | 1 |
Ruby
|
tied/chef-single-cookbooks
|
a9d71368a9fd8c0c5348cd805867635c1b95d80d
|
260f912375850539bcf11d672c1b074dceb5d0d1
|
refs/heads/master
|
<repo_name>grzanka/fairtaskassigner<file_sep>/app.py
'''
Flask App for serving three pages web server based on templates
and storage connector.
'''
from fairtask_db_tools import fairtaskDB
import fairtask_badges as badges
import fairtask_utils
from flask import Flask, render_template, request, json, redirect, url_for, session, flash
from flask_oauth import OAuth
import os
DEBUG = os.environ.get("FN_DEBUG", default=False)
HOST_PORT = os.environ.get("FN_HOST_PORT", default='8040')
LISTEN_HOST_IP = os.environ.get("FN_LISTEN_HOST_IP", default='127.0.0.1')
ADMIN_EMAIL = os.environ.get("FN_ADMIN_EMAIL", default=False)
# You must configure these 3 first values from Google APIs console
# https://code.google.com/apis/console
# here they are read from the ENV that is setup on server startup
GOOGLE_CLIENT_ID = os.environ.get("FN_GOOGLE_CLIENT_ID", default=False)
GOOGLE_CLIENT_SECRET = os.environ.get("FN_GOOGLE_CLIENT_SECRET", default=False)
# one of the Redirect URIs from Google APIs console
REDIRECT_URI = os.environ.get("FN_REDIRECT_URI", default=False)
BASE_URL = 'https://www.google.com/accounts/'
AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/auth'
SCOPE_URL = 'https://www.googleapis.com/auth/userinfo.email'
ACCESS_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token'
USER_INFO_URL = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='
HOUR_IN_SECONDS = 3600
NON_EXISTING_ID = -666
NON_SELECTED_VALUE = -1
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = 'development key'
storage = fairtaskDB(allowCommit=True)
oauth = OAuth()
google = oauth.remote_app('google',
base_url=BASE_URL,
authorize_url=AUTHORIZE_URL,
request_token_url=None,
request_token_params={'scope': SCOPE_URL,
'response_type': 'code'},
access_token_url=ACCESS_TOKEN_URL,
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET)
@app.route(REDIRECT_URI)
@google.authorized_handler
def authorized(resp):
access_token = resp['access_token']
session['access_token'] = access_token, ''
return redirect(url_for('main'))
@google.tokengetter
def getAccessToken():
return session.get('access_token')
def getUserInfo(access_token):
import urllib3
import json
http = urllib3.PoolManager()
res = http.request('GET', USER_INFO_URL+access_token)
userData = json.loads(res.data.decode('utf-8'))
return userData
def getLoggedUsernameEmailPicture():
access_token = getAccessToken()[0]
userData = getUserInfo(access_token)
email, picture = (userData['email'], userData['picture'])
localUserData = storage.get_username_and_email(email=email)
if len(localUserData):
id, username, emailLocal = localUserData[0]
if emailLocal == email:
favProduct = storage.get_favorite_product(id)
return {'id': id, 'email': email,
'username': username,
'picture': picture,
'idProduct':favProduct[0],
'productName': favProduct[1].upper()}
else:
return {'id': NON_EXISTING_ID, 'email': email,
'username': '', 'picture': picture,
'idProduct':NON_SELECTED_VALUE,
'productName': 'NONE'}
def isLoginValid():
access_token = getAccessToken()
if access_token is not None:
userDetails = getUserInfo(access_token[0])
try:
userDetails['error'] # 99% cases when some cookie/session problem
return False
except KeyError:
# TODO Handle some error cases here
return True
return False
def isAnAdmin():
localId = getLoggedUsernameEmailPicture()
adminsList = storage.get_admins()
if localId['id'] in adminsList['admin'].keys() \
or localId['id'] in adminsList['badgeadmin'].keys():
return True
return True
@app.route('/login')
def login():
if not isLoginValid():
callback = url_for('authorized', _external=True)
return google.authorize(callback=callback)
else:
return redirect(url_for('main'))
@app.route('/logout')
def logout():
session['access_token'] = 'LOGOUT', ''
return redirect(url_for('main'))
@app.route("/")
@app.route('/main')
def main():
googleSession = False
loggedUsernameEmail = ()
getLoggedUserBadges = ()
inBucket = False
if isLoginValid():
googleSession = True
loggedUsernameEmail = getLoggedUsernameEmailPicture()
inBucket = storage.check_if_in_bucket(loggedUsernameEmail['id'])
getLoggedUserBadges = storage.get_users_badges(userId=loggedUsernameEmail['id'])
lastDate = storage.get_last_transaction(n=1)[0]
top3 = storage.get_top_buyers()
candidates = storage.get_top_candidates()
getAssignedBadges = storage.get_users_badges()
return render_template('index.html',
top3=top3,
lastDate=lastDate,
candidates=candidates,
googleSession=googleSession,
loggedUsernameEmail=loggedUsernameEmail,
inBucket=inBucket,
assignedBadges=getAssignedBadges,
loggedUserBadges=getLoggedUserBadges)
@app.route('/addJobs')
def addJobs():
if not isLoginValid():
return redirect(url_for('login'))
loggedUsernameEmail = getLoggedUsernameEmailPicture()
if loggedUsernameEmail['id'] == NON_EXISTING_ID:
return redirect(url_for('showSignUp'))
inBucket = storage.check_if_in_bucket(loggedUsernameEmail['id'])
googleSession = True
users = storage.get_users()
products = storage.get_products()
allJobs = storage.get_jobs_summary()
badgesTimeline = storage.get_badge_grant_history()
eventsTimeLine = fairtask_utils.combineEvents(allJobs, badgesTimeline)
summaryToday = storage.get_bucket()
getLoggedUserBadges = storage.get_users_badges(userId=loggedUsernameEmail['id'])
return render_template('addjobs.html',
todaysJobs=summaryToday,
eventsTimeLine=eventsTimeLine,
loggedUserBadges=getLoggedUserBadges,
users=users,
products=products,
googleSession=googleSession,
inBucket=inBucket,
loggedUsernameEmail=loggedUsernameEmail)
@app.route('/stats')
def stats():
if not isLoginValid():
return redirect(url_for('login'))
loggedUsernameEmail = getLoggedUsernameEmailPicture()
users = storage.get_users()
products = storage.get_products()
notValidatedUsers = storage.get_users(onlyNotValidated=True)
adminsList = storage.get_admins()
getUsersStats = storage.get_users_stats()
getAllBadges = storage.get_all_badges()
getAssignedBadges = storage.get_users_badges()
grantedBadges = storage.get_badge_grant_history()
getLoggedUserBadges = storage.get_users_badges(userId=loggedUsernameEmail['id'])
return render_template('stats.html',
users=users,
notValidatedUsers=notValidatedUsers,
products=products,
allBadges=getAllBadges,
adminsList=adminsList,
usersStats=getUsersStats,
assignedBadges=getAssignedBadges,
loggedUserBadges=getLoggedUserBadges,
grantedBadges=grantedBadges,
loggedUsernameEmail=loggedUsernameEmail,
invalidId=NON_EXISTING_ID,
nonSelectedId=NON_SELECTED_VALUE)
@app.route('/showSignUp')
def showSignUp():
if not isLoginValid():
return redirect(url_for('login'))
loggedUsernameEmail = getLoggedUsernameEmailPicture()
users = storage.get_users()
notValidatedUsers = storage.get_users(onlyNotValidated=True)
getLoggedUserBadges = storage.get_users_badges(userId=loggedUsernameEmail['id'])
adminsList = storage.get_admins()
badgesToGrant = storage.get_all_badges(badgeUniqe=True)
return render_template('signup.html',
users=users,
notValidatedUsers=notValidatedUsers,
loggedUserBadges=getLoggedUserBadges,
loggedUsernameEmail=loggedUsernameEmail,
adminsList=adminsList,
badgesToGrant=badgesToGrant,
invalidId=NON_EXISTING_ID,
nonSelectedId=NON_SELECTED_VALUE)
@app.route('/signUp', methods=['POST'])
def signUp():
if not isLoginValid():
return redirect(url_for('login'))
_name = request.form['inputName']
_email = request.form['inputEmail']
try:
_assignedNameId = int(request.form['assignedNameId'])
except KeyError:
_assignedNameId = NON_SELECTED_VALUE
validated = 0
loggedUsernameEmail = getLoggedUsernameEmailPicture()
if _email and (_name or _assignedNameId != NON_SELECTED_VALUE):
if loggedUsernameEmail['id'] == NON_EXISTING_ID:
validated = 1
if _assignedNameId == NON_SELECTED_VALUE:
storage.add_user(_name, _email,
loggedUsernameEmail['id'],
validated=validated)
else:
storage.update_user(_assignedNameId, _email,
loggedUsernameEmail['id'],
validated=validated)
flash('User %s/%s successfuly added!' % (_name, _email))
return redirect(url_for('showSignUp'))
else:
return json.dumps({'html': '<span>Enter the required fields</span>'})
@app.route('/registerJob', methods=['POST'])
def registerJob():
if not isLoginValid():
return redirect(url_for('login'))
loggedUsernameEmail = getLoggedUsernameEmailPicture()
if loggedUsernameEmail['id'] == NON_EXISTING_ID:
return redirect(url_for('showSignUp'))
_name = request.form['inputName']
_product = request.form['inputProduct']
if _name and _product:
storage.add_to_bucket(_name, _product)
return redirect(url_for('addJobs'))
@app.route('/emptyBucket', methods=['POST'])
def emptyBucket():
if not isLoginValid():
return redirect(url_for('login'))
loggedUsernameEmail = getLoggedUsernameEmailPicture()
if loggedUsernameEmail['id'] == NON_EXISTING_ID:
return redirect(url_for('showSignUp'))
storage.clean_bucket()
flash('Wishlist cleared!')
return redirect(url_for('addJobs'))
@app.route('/finalizeJob', methods=['POST'])
def finalizeJob():
if not isLoginValid():
return redirect(url_for('login'))
loggedUsernameEmail = getLoggedUsernameEmailPicture()
if loggedUsernameEmail['id'] == NON_EXISTING_ID:
return redirect(url_for('showSignUp'))
_name = request.form['finalzeName']
if int(_name) < 0:
return redirect(url_for('addJobs'))
bucketContent = storage.get_bucket_raw()
if len(bucketContent) < 2:
flash('Cannot proceed with less then three orders!')
return redirect(url_for('addJobs'))
for whomWhat in bucketContent:
storage.add_transaction(_name, whomWhat[0], whomWhat[1],
loggedUsernameEmail['id'])
storage.clean_bucket()
dates = storage.get_last_transaction(n=1)
for date in dates:
actualbadges = badges.get_current_badges(date[0], storage=storage)
for oneBadge in actualbadges:
storage.insert_user_badges(*oneBadge)
if len(actualbadges):
flash('New badges awarded!')
storage.calculate_actal_scoring(commit=True)
flash('Order registered!')
return redirect(url_for('main'))
@app.route('/grantBadge', methods=['POST'])
def grantBadge():
if not isLoginValid():
return redirect(url_for('login'))
if not isAnAdmin():
flash('You Need to be AN ADMIN for this action!', 'error')
return redirect(url_for('main'))
try:
_name = int(request.form['nameIdToGrant'])
_badge = int(request.form['badgeId'])
except ValueError:
redirect(url_for('showSignUp'))
if _name > 0 and _badge > 0:
storage.insert_user_badges(_name, _badge, None)
storage.calculate_actal_scoring(commit=True)
return redirect(url_for('showSignUp'))
@app.route('/removeBucketItem', methods=['GET'])
def removeBucketItem():
if not isLoginValid():
return redirect(url_for('login'))
try:
what = int(request.args.get('what', -1))
towhom = int(request.args.get('towhom', -1))
except ValueError:
redirect(url_for('main'))
if what > 0 and towhom > 0:
storage.remove_item_in_bucket(towhom, what)
return redirect(url_for('addJobs'))
@app.route('/removeBadge', methods=['GET'])
def removeBadge():
if not isLoginValid():
return redirect(url_for('login'))
if not isAnAdmin():
flash('You Need to be AN ADMIN for this action!', 'error')
return redirect(url_for('main'))
try:
badgeId = int(request.args.get('grantId', -1))
except ValueError:
redirect(url_for('main'))
if badgeId > 0:
storage.remove_user_bagde(badgeId)
return redirect(url_for('stats'))
@app.route('/addProduct', methods=['POST'])
def addProduct():
if not isLoginValid():
return redirect(url_for('login'))
if not isAnAdmin():
flash('You Need to be AN ADMIN for this action!', 'error')
return redirect(url_for('main'))
_name = request.form['productName']
try:
_price = float(request.form['productPrice'])
except ValueError:
return redirect(url_for('showSignUp'))
storage.add_product(_name, _price)
return redirect(url_for('stats'))
@app.route('/calculateScoring', methods=['POST'])
def calculateScoring():
if not isLoginValid():
return redirect(url_for('login'))
if not isAnAdmin():
flash('You Need to be AN ADMIN for this action!', 'error')
return redirect(url_for('main'))
storage.calculate_actal_scoring(commit=True)
flash('Scoring recalculated!')
return redirect(url_for('stats'))
if __name__ == "__main__":
import logging
logging.basicConfig(filename='error.log', level=logging.DEBUG)
app.run(host=LISTEN_HOST_IP, port=HOST_PORT)
<file_sep>/fairtask_badges.py
import inspect
from fairtask_db_tools import fairtaskDB
import fairtask_badge_factory
EMPTY_RESULT = {}
def get_current_badges(date, storage=None):
storageReadOnly = storage
if storage is None:
storageReadOnly = fairtaskDB(allowCommit=False)
badgesAlredyInTheSystem = {}
for one in storageReadOnly.get_granted_badges(date):
try:
badgesAlredyInTheSystem[one[2]].append((one[1], one[3]))
except KeyError:
badgesAlredyInTheSystem[one[2]] = [(one[1], one[3])]
userIds = storageReadOnly.execute_get_sql('select id from user')
allTimeBadges = {}
for name, obj in inspect.getmembers(fairtask_badge_factory):
if inspect.isclass(obj) and name.startswith('badge'):
oneBadge = obj(storageReadOnly)
print(oneBadge.getBadgeId(), name)
allTimeBadges[oneBadge.getBadgeId()] = {}
for userId in userIds:
tmpBadges = badgesAlredyInTheSystem.get(oneBadge.getBadgeId(),[])
earlierDate = None
for one in tmpBadges:
if one[0] == userId[0]:
earlierDate = one[1]
result = oneBadge.find(date, userId[0], earlierDate=earlierDate)
if len(result.keys()):
allTimeBadges[oneBadge.getBadgeId()] = result
toReturn = []
for oneBadgeId in allTimeBadges.keys():
for oneUserId in allTimeBadges[oneBadgeId].keys():
toReturn.append((oneUserId, oneBadgeId, date))
return toReturn
<file_sep>/db/db_scheme.sql
CREATE TABLE sqlite_sequence(name,seq)
CREATE TABLE "user_badges" ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`userId` INTEGER NOT NULL, `badgeId` INTEGER NOT NULL, `date` TEXT NOT NULL, `valid` INTEGER )
CREATE TABLE "badges" ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`name` TEXT NOT NULL, `img` TEXT, `desc` TEXT NOT NULL, `effect` INTEGER NOT NULL, `adminawarded` INTEGER NOT NULL )
CREATE TABLE "user" ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`email` TEXT NOT NULL, `username` TEXT NOT NULL, `rating` INTEGER NOT NULL,
`creator` INTEGER NOT NULL, `validated` INTEGER NOT NULL )
CREATE TABLE "product" ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, `name` TEXT NOT NULL, `price` REAL )
CREATE TABLE "contract_temp" ( `to_whom` INTEGER NOT NULL, `product` INTEGER NOT NULL )
CREATE TABLE "contract" ( `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, `buyer`
INTEGER NOT NULL, `to_whom` INTEGER NOT NULL, `product` INTEGER NOT NULL, `date` INTEGER NOT NULL, `creator` INTEGER NOT NULL )
CREATE VIEW all_list as select date, buyer, to_whom, name product, price, buyer_rating from
(select date, buyer,buyer_rating, username to_whom, product from
(select date, username buyer, to_whom, product, rating buyer_rating from
contract join user on contract.buyer=user.id) buyer join user on buyer.to_whom = user.id) transactions
join product on transactions.product = product.id
CREATE VIEW badges_granted_timeline AS
select grantId, user.id, username, date, img, badgeName, badgeId from
(select grantId, userId, badgeId, date, img, badges.name badgeName from
(select user_badges.id grantId, user.id userId, date, badgeId from user join user_badges on user.id=user_badges.userId where user_badges.valid=1) a
join badges on badges.id=a.badgeId) join user on user.id=userId order by date desc
<file_sep>/fairtask_utils.py
def combineEvents(allJobs, badgesTimeline):
toReturn = []
for oneJob in allJobs:
toReturn.append(oneJob)
for oneBadge in badgesTimeline:
toReturn.append( (oneBadge[4], 'system', oneBadge[1], "<img src=\'%s\'/ width=\"25\", height=\"25\"> %s "%(oneBadge[3], oneBadge[2]) ) )
sortedToReturn = sorted(toReturn, key=lambda x: x[0], reverse=True)
return sortedToReturn
<file_sep>/fairtask_db_tools.py
import sqlite3
from datetime import datetime, timedelta
from fairtask_scoring import fairtask_scoring
import os
# use db/dbScheme.sql to create an sqlite db
DATABASE_NAME = os.environ.get("FN_DB_TO_USE", default=False)
NON_SELECTED_VALUE = -1
'''
utility class for SQLite connection
'''
class fairtaskDB:
ALLOW_COMMIT = False
def __init__(self, allowCommit=False):
self.load_db()
self.ALLOW_COMMIT = allowCommit
def load_db(self):
self.con = sqlite3.connect(DATABASE_NAME, check_same_thread=False)
self.c = self.con.cursor()
def execute_sql(self, sql, commit=False):
try:
errors = [] # TODO add SQL injection check on sql
if len(errors) > 0:
return False
self.c.execute(sql)
if commit and self.ALLOW_COMMIT:
self.con.commit()
return True
except sqlite3.IntegrityError:
return False
def execute_get_sql(self, sql):
self.c.execute(sql)
data = self.c.fetchall()
return data
# ####################
# Customized calls
def add_user(self, name, email, creator, validated=0):
sql = 'insert into user (email, username, rating, creator, validated) values (\'%s\', \'%s\', 0.0, %s, %s)' % (email, name, creator, validated)
self.execute_sql(sql, commit=True)
def update_user(self, existingId, email, creator, validated=0):
sql = 'update user set email=\'%s\', creator=%s, validated=%s where id=%s'%(email, creator, validated, existingId)
self.execute_sql(sql, commit=True)
def add_product(self, name, price):
sql = 'insert into user vales (%s, %s) ' % (name, price)
self.execute_sql(sql, commit=True)
def add_transaction(self, who, whom, what, creator, commit=False):
if who == NON_SELECTED_VALUE or whom == NON_SELECTED_VALUE or what == NON_SELECTED_VALUE:
raise ValueError('Cannot save transaction for an unspecified person or goods!')
else:
sql = 'insert into contract (buyer, to_whom, product, date, creator) values (%s, %s, %s, CURRENT_TIMESTAMP, %s)' % (who, whom, what,creator)
self.execute_sql(sql, commit=commit)
self.calculate_actal_scoring(commit=commit)
return True
def add_to_bucket(self, whom, what):
if int(whom) > 0 and int(what) > 0:
sql = 'insert into contract_temp (to_whom, product) values (%s, %s)' % (whom, what)
self.execute_sql(sql)
self.calculate_actal_scoring(commit=True)
def check_if_in_bucket(self, userId):
result = self.execute_get_sql('select * from contract_temp where to_whom=%d' % userId)
if len(result):
return True
return False
def get_favorite_product(self, userId):
sql = 'SELECT product, COUNT(product) AS vo FROM contract where to_whom=%d GROUP BY product ORDER BY vo DESC LIMIT 1'%userId
result = self.execute_get_sql(sql)
if len(result) > 0:
return self.get_product_details(result[0][0])
else:
return (NON_SELECTED_VALUE, 'NOT FOUND')
def get_scoring_from_badges(self):
scoringFromBadgesData = self.execute_get_sql('select userId, sum(effect) from user_badges join badges on user_badges.badgeId = badges.id group by userId')
scoringFromBadges = {}
for one in scoringFromBadgesData:
scoringFromBadges[one[0]] = one[1]
return scoringFromBadges
def calculate_actal_scoring(self, commit=False, presentContractors=[]):
data = self.execute_get_sql('select buyer, to_whom, product from contract')
scoring = fairtask_scoring()
scoring.setScoringFromBadges(self.get_scoring_from_badges())
result = scoring.recalculate_scoring(data, presentContractors=presentContractors)
for one in result.keys():
self.c.execute('update user set rating=%f where id=%s' % (result[one], one))
if commit and self.ALLOW_COMMIT:
try:
self.con.commit()
return True
except sqlite3.IntegrityError:
return False
def clean_bucket(self):
self.execute_sql('delete from contract_temp', commit=True)
def get_bucket_raw(self):
return self.execute_get_sql('select * from contract_temp')
def remove_item_in_bucket(self, towhom, what):
sql = 'delete from contract_temp where product=%d and to_whom=%d' % \
(what, towhom)
self.execute_sql(sql, commit=True)
def get_bucket(self):
dataBucket = self.execute_get_sql('select username, what, rating, user.id, whatId from (select to_whom whom, name what, product.id whatId from contract_temp join product on product.id = product) join user on user.id=whom')
# (whom, what, rating) with origanl scorings
if len(dataBucket):
dataBucketSimple = self.execute_get_sql('select to_whom from contract_temp')
data = self.execute_get_sql('select buyer, to_whom, product from contract')
scoring = fairtask_scoring()
scoring.setScoringFromBadges(self.get_scoring_from_badges())
presentContractors = []
for one in dataBucketSimple:
presentContractors.append(one[0])
resultForOrdering = scoring.recalculate_scoring(data,
presentContractors=presentContractors)
toReturn = []
for data in dataBucket:
toReturn.append((data[0],
data[1],
resultForOrdering.get(data[3], 0),
data[3],
data[4], ))
return toReturn
return dataBucket
def get_granted_badges(self, date=None):
sqlAdd = ""
if date is not None:
sqlAdd = " where date <=\'%s\'" % date
sql = "select * from user_badges %s" % sqlAdd
return self.execute_get_sql(sql)
def get_all_badges(self, badgeUniqe=None):
whereBadge = ''
if badgeUniqe is not None:
whereBadge = ' where adminawarded=1 '
sql = 'select * from badges %s order by effect, name' % whereBadge
return self.execute_get_sql(sql)
def get_badge_grant_history(self):
sql = 'select grantId, username, badgeName, img, date from badges_granted_timeline'
return self.execute_get_sql(sql)
def get_users_badges_timeline(self):
sql = 'select * from badges_granted_timeline'
return self.execute_get_sql(sql)
def get_users_badges(self, userId=None):
where = ' where user_badges.valid=1 '
if userId is not None:
where = ' where user_badges.valid=1 and user.id=%d ' % userId
sql = 'select * from (select user.id userId, date, badgeId from user join user_badges on user.id=user_badges.userId %s ) a join badges on badges.id=a.badgeId' % (where)
# TODO return as dict
return self.execute_get_sql(sql)
def insert_user_badges(self, badgeId, userId, date):
if date is None:
date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sql='insert into user_badges (userId, badgeId, date, valid) values (\'%d\', \'%d\',\'%s\', 1)' % (badgeId, userId, date)
self.execute_sql(sql, commit=True)
def remove_user_bagde(self, badgeGrantId):
sql='update user_badges set valid=0 where id=%d' % badgeGrantId
self.execute_sql(sql, commit=True)
def get_products(self):
return self.execute_get_sql('select * from product order by price, name')
def get_product_details(self, productId):
data = self.execute_get_sql('select * from product where id=%s'%str(productId))
if len(data)>0:
return data[0]
else:
raise ValueError('No Product with that ID ', id)
def get_users(self, onlyNotValidated=False):
sql = 'select * from user order by username'
if onlyNotValidated:
sql = 'select * from user where validated=0 order by username'
return self.execute_get_sql(sql)
def get_users_stats(self):
toReturn = {}
sql = 'select buyer, count(buyer) from all_list where buyer!=to_whom group by buyer'
for one in self.execute_get_sql(sql):
toReturn[one[0]] = {'consumed': 0, 'served': 0, 'offered': one[1]}
sql = 'select to_whom, count(to_whom) from all_list where buyer!=to_whom group by to_whom'
#sql = 'select to_whom, count(to_whom) from all_list group by to_whom'
for one in self.execute_get_sql(sql):
try:
toReturn[one[0]]['consumed'] = one[1]
except KeyError:
toReturn[one[0]] = {'consumed': one[1], 'served': 0, 'offered': 0}
sql = 'select buyer, count(buyer) from (select buyer from all_list where buyer!=to_whom group by date) group by buyer'
for one in self.execute_get_sql(sql):
try:
toReturn[one[0]]['served'] = one[1]
except KeyError:
toReturn[one[0]] = {'served': one[1], 'consumed': 0, 'offered': 0}
return toReturn
def get_last_transaction(self, n=None):
extra = ''
if n is not None:
extra = ' desc limit %d' % n
sql = 'select date from contract group by date order by date %s' % extra
return self.execute_get_sql(sql)
def get_admins(self):
#badges 7(admin) and 8(badgeadmin)
sql = 'select userId, email, username, badgeId from user_badges join user on user_badges.userId=user.id where user_badges.badgeId=7 or user_badges.badgeId=8'
toReturn = {'admin': {},
'badgeadmin': {}}
for one in self.execute_get_sql(sql):
if one[3] == 7:
toReturn['admin'] = {one[1]: (one[0], one[2])}
if one[3] == 8:
toReturn['badgeadmin'] = {one[1]: (one[0], one[2])}
return toReturn
def get_username_and_email(self, id=None, email=None):
if id is None and email is None:
raise ValueError('Need at least one parameter!')
if id is None:
sql = 'select id,username,email from user where email=\'%s\'' % email
if email is None:
sql = 'select id,username,email from user where id=\'%s\'' % id
return self.execute_get_sql(sql)
def get_jobs_summary(self, today=False, buffer_seconds=3*3600):
if today:
now = datetime.now() - timedelta(seconds=buffer_seconds)
sql = 'select * from all_list where date > \'%s\' order by date desc' % now.strftime("%Y-%m-%d %H:%M:%S")
else:
sql = 'select * from all_list order by date desc'
return self.execute_get_sql(sql)
def get_summary_per_user(self, user):
return self.execute_get_sql('select * from all_list where buyer like \'\% %s \%\' '%user)
def get_top_buyers(self):
return self.execute_get_sql('select buyer, count(buyer) count, sum(price) total_spent, max(buyer_rating) from all_list group by buyer order by count desc limit 5')
def get_top_candidates(self):
return self.execute_get_sql('select id, username, rating from user order by rating limit 5')
def close_db(self):
self.con.close()
<file_sep>/README.md
# FairTaskAssigner
IT is a simple web server application that allows to track the activities (e.g. coffee servings) within the group of friends.
It works based on google authentication token (uses only login and identity picture!).
*1.2*
- job can be saved only when at least three orders are in the bucket
- remove an item in the wish list
- fix the bug for the stats view when not an admin nor the badge admin
*1.1*
- admins can grant remove badges
*1.0*
- new tab - statistics
- new badge and achievements system triggered at every ordering event
- prepared for role based modifications (admin, badge admins, users)
- prepared for a events timeline
*0.3*
- The temporary rating is calculated within the preselected bucket only among the current waiting list users.
- For a logged user a predefined order button (adding to the current wish list) is available for the most often ordered product. No button is visible when never made an order.
- Moved the order history to the 'AddTask' tab accessible only for the logged users
- Disabled 'Register Job' and 'who is buying' for an empty Wish list.
*0.2*
- Preselected bucket is validated at later step
*0.1*
- Not logged user can see actual servings, top three candidates and top three servants
- Logged user can add new users
- Logged user can add serving (as him)
- New user can login and add himself to the system
## Installation
Install all modules:
```bash
pip install -r requirements.txt
```
Use `db/db_scheme.sql` to create [SQLite]() DB.
Finally, create `run.sh` with the credentials created using [Google API Console](https://console.cloud.google.com/apis/credentials):
```bash
export FN_GOOGLE_CLIENT_ID='YOUR_CLIENT_ID'
export FN_GOOGLE_CLIENT_SECRET='YOUR_CLIENT_SECRET'
export FN_FLASK_SECRET_KEY='whatever_key'
export FN_REDIRECT_URI='REDIRECT_URL_YOU_SPECIFY_IN_GOOGLE'
export FN_DB_TO_USE='db/YOUR_SQLite_PATH'
export FN_DEBUG=True # if not set default False
export FN_LISTEN_HOST_IP='any ip' # if not set default 127.0.0.1
python app.py
```
To start server `sh run.sh`, it will start server listening at `FN_LISTEN_HOST_IP:8040`.
|
45ad7c351c0a1b18c4bcf8074ca1248ba81d9498
|
[
"Markdown",
"SQL",
"Python"
] | 6 |
Python
|
grzanka/fairtaskassigner
|
2483f93e79a4d0aef5086931ec6cc8605166f842
|
ae4283da371df22c7b7f76ad886bcc770c559894
|
refs/heads/master
|
<repo_name>Firestitch/ngx-select-button<file_sep>/src/app/enums/color.enum.ts
export enum Color {
Primary = 'primary',
Basic = 'basic',
Accent = 'accent',
Warn = 'warn',
}
<file_sep>/playground/app/components/example/example.component.ts
import { Component } from '@angular/core';
import { Color } from '@firestitch/select-button';
@Component({
selector: 'example',
templateUrl: 'example.component.html',
})
export class ExampleComponent {
public basic = null;
public values = [
{value: 'steak', name: 'Steak'},
{value: 'pizza', name: 'Pizza'},
{value: 'tacos', name: 'Tacos'},
{value: 'sour', name: 'Low Fat Sour Cream'}
];
public Color = Color;
constructor() { }
}
<file_sep>/src/app/enums/index.ts
export { ColorType } from './color-type.enum';
export { Color } from './color.enum';
<file_sep>/playground/app/components/configure/configure.component.ts
import { Component, Inject } from '@angular/core';
import { DrawerRef, DRAWER_DATA, DrawerDataProxy } from '@firestitch/drawer';
@Component({
templateUrl: './configure.component.html',
styleUrls: ['./configure.component.scss']
})
export class ConfigureComponent {
public config;
public defaultConfig;
public galleryService;
constructor(public drawer: DrawerRef<ConfigureComponent>,
@Inject(DRAWER_DATA) public data: DrawerDataProxy<any>) {
this.config = data.config;
}
}
<file_sep>/src/app/enums/color-type.enum.ts
export const enum ColorType {
Klass = 'klass',
Style = 'style',
}
<file_sep>/src/app/directives/select-button/select-button.directive.ts
import {
Directive,
Input,
ElementRef,
Renderer2,
OnInit,
HostBinding,
OnChanges,
SimpleChanges,
} from '@angular/core';
import { ColorType, Color } from '../../enums';
@Directive({
selector: '[fsSelectButton]'
})
export class FsSelectButtonDirective implements OnInit, OnChanges {
@Input()
set color(value: Color | string) {
if (!value) {
return;
}
this._clearColor();
this._color = value;
if (value.match(/^#/)) {
this.renderer.setStyle(this.hostElement.nativeElement, 'background-color', value);
this._colorType = ColorType.Style;
} else {
this.renderer.addClass(this.hostElement.nativeElement, 'mat-' + value);
this._colorType = ColorType.Klass;
}
}
@Input('width')
set setWidth(width) {
this.width = width;
};
@Input() public buttonType: 'raised' | 'basic' | 'flat' = 'raised';
@HostBinding('style.max-width')
public width = '';
private _color: Color | string = Color.Basic;
private _colorType: ColorType = null;
constructor(private renderer: Renderer2, private hostElement: ElementRef) { }
public ngOnInit() {
const buttonType = this.buttonType === 'basic' ? 'mat-button' : `mat-${this.buttonType}-button`;
this.renderer.addClass(this.hostElement.nativeElement, buttonType);
this.renderer.addClass(this.hostElement.nativeElement, 'fs-select-button');
this._textColorUpdate();
}
public ngOnChanges(changes: SimpleChanges) {
if (changes.color && changes.color.currentValue !== changes.color.previousValue) {
this._textColorUpdate();
}
}
private _clearColor() {
if (this._colorType === ColorType.Klass) {
this.renderer.removeClass(this.hostElement.nativeElement, 'mat-' + this._color);
} else if (this._colorType === ColorType.Style) {
this.renderer.removeStyle(this.hostElement.nativeElement, 'background-color');
}
this._color = null;
this._colorType = null;
}
private _textColorUpdate() {
const value = this.hostElement.nativeElement.querySelector('.mat-select-trigger .mat-select-value');
const arrow = this.hostElement.nativeElement.querySelector('.mat-select-arrow-wrapper .mat-select-arrow');
let textColor = null;
switch (this._color) {
case Color.Basic:
textColor = 'initial';
break;
default:
textColor = '#fff';
}
this.renderer.setStyle(value, 'color', textColor);
this.renderer.setStyle(arrow, 'color', textColor);
}
}
<file_sep>/src/public_api.ts
/*
* Public API Surface of fs-menu
*/
// Modules
export { FsSelectButtonModule } from './app/fs-select-button.module';
export { FsSelectButtonDirective } from './app/directives/select-button/select-button.directive';
export { Color } from './app/enums/color.enum';
<file_sep>/src/app/fs-select-button.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatSelectModule } from '@angular/material/select';
import { FormsModule } from '@angular/forms';
import { FsSelectButtonDirective } from './directives/select-button/select-button.directive';
@NgModule({
imports: [
CommonModule,
MatSelectModule,
FormsModule
],
exports: [
FsSelectButtonDirective
],
entryComponents: [
],
declarations: [
FsSelectButtonDirective
]
})
export class FsSelectButtonModule {
// static forRoot(): ModuleWithProviders {
// return {
// ngModule: FsSelectButtonModule
// };
// }
}
|
2a50d77e135430cc9eda8130f1b270182e26d261
|
[
"TypeScript"
] | 8 |
TypeScript
|
Firestitch/ngx-select-button
|
8d862b98468977ff06f50457859feddccd3be896
|
e2ce9f29cf188c36e8bd01a9ee531ff21ee44e36
|
refs/heads/master
|
<repo_name>aliceinnets/java-finance-api<file_sep>/src/aliceinnets/finance/api/GoogleFinanceGetprices.java
package aliceinnets.finance.api;
import java.io.IOException;
import org.jsoup.Jsoup;
/**
* This class provides historical data (close, high, low, open and volume) on the requested stocks
* by retrieving quotes from Google Finance API, {@linkplain http://www.google.com/finanace/getprices}.
*
* <p>FIXME beginning and end of summer time introduce extra time zone offset config, which break the system
* e.g. TIME_ZONE_OFFSET = -240 (from -300) inbetween data</p>
*
* @author alice <aliceinnets[at]gmail.com>
*
*/
public class GoogleFinanceGetprices {
public final static String BASE_URL = "http://www.google.com/finance/getprices";
String symbol;
double intervalInput;
String period;
String exchangeInput;
String columns;
String url;
String bodyText;
String exchange;
double marketOpenMinute;
double marketCloseMinute;
double interval;
String[] dataColumns;
String dataLog;
double timezoneOffset;
double[][] data;
public GoogleFinanceGetprices(String symbol) {
this(symbol, 86400.0, null, null);
}
public GoogleFinanceGetprices(String symbol, double interval) {
this(symbol, interval, null, null);
}
public GoogleFinanceGetprices(String symbol, String period) {
this(symbol, 86400.0, period, null);
}
public GoogleFinanceGetprices(String symbol, double interval, String period) {
this(symbol, interval, period, null);
}
/**
* Getting historical data on the requested stocks by retrieving quotes from Google Finance API.
*
* @param symbol stock symbol
* @param interval time interval in seconds, default value is 86400 seconds (1 day)
* @param period period which data covers up to now, e.g. "1y" (1 year), "15d" (15 days), default value is "30d" (30 days)
* @param exchange stock exchange symbol, e.g. NASD
*/
public GoogleFinanceGetprices(String symbol, double interval, String period, String exchange) {
this.symbol = symbol;
this.intervalInput = interval;
this.period = period;
this.exchangeInput = exchange;
update();
}
public static String generateUrl(String symbol, double interval, String period, String exchange, String columns) {
String url = BASE_URL+"?q="+symbol;
if(interval > 0.0) url += "&i="+interval;
if(period != null) url += "&p="+period;
if(exchange != null) url += "&x="+exchange;
if(columns != null) url += "&f="+columns;
return url;
}
public void update() {
try {
url = generateUrl(symbol, intervalInput, period, exchangeInput, columns);
bodyText = Jsoup.connect(url).get().text();
String[] bodyTextLines = bodyText.split(" ");
exchange = bodyTextLines[0].replace("EXCHANGE", "");
marketOpenMinute = Double.parseDouble(bodyTextLines[1].replace("MARKET_OPEN_MINUTE=", ""));
marketCloseMinute = Double.parseDouble(bodyTextLines[2].replace("MARKET_CLOSE_MINUTE=", ""));
interval = Double.parseDouble(bodyTextLines[3].replace("INTERVAL=", ""));
dataColumns = bodyTextLines[4].replace("COLUMNS=", "").split(",");
dataLog = bodyTextLines[5].replace("DATA", "");
timezoneOffset = Double.parseDouble(bodyTextLines[6].replace("TIMEZONE_OFFSET=", ""));
data = new double[dataColumns.length][bodyTextLines.length-7];
String[] dataStringHeader = bodyTextLines[7].split(",");
double firstTimeStamp = Double.parseDouble(dataStringHeader[0].replace("a", ""));
data[0][0] = firstTimeStamp;
for(int i=1;i<dataStringHeader.length;++i) {
data[i][0] = Double.parseDouble(dataStringHeader[i]);
}
// FIXME: it can have TIMEZONE_OFFET between the data due to summer time
for(int j=1;j<data[0].length;++j) {
String[] dataString = bodyTextLines[j+7].split(",");
if(dataString[0].contains("a")) {
firstTimeStamp = Double.parseDouble(dataString[0].replace("a", ""));
data[0][j] = firstTimeStamp;
} else {
data[0][j] = firstTimeStamp + interval * Double.parseDouble(dataString[0]);
}
for(int i=1;i<data.length;++i) {
data[i][j] = Double.parseDouble(dataString[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String getUrl() {
return url;
}
public String getBodyText() {
return bodyText;
}
public String getExchange() {
return exchange;
}
public double getMarketOpenMinute() {
return marketOpenMinute;
}
public double getMarketCloseMinute() {
return marketCloseMinute;
}
public double getTimeInterval() {
return interval;
}
public String[] getDataColumns() {
return dataColumns;
}
public String getDataLog() {
return dataLog;
}
public double getTimezoneOffset() {
return timezoneOffset;
}
public double[][] getData() {
return data;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
update();
}
public String getPeriod() {
return period;
}
public void setPeriod(String period) {
this.period = period;
update();
}
public void setInterval(double intervalInput) {
this.intervalInput = intervalInput;
update();
}
public void setExchange(String exchangeInput) {
this.exchangeInput = exchangeInput;
update();
}
}
<file_sep>/README.md
# finance-java
Contents
1. Google Finance Java API<br/>
This class provides historical data (close, high, low, open and volume) on the requested stocks by retrieving quotes from Google Finance API, http://www.google.com/finanace/getprices.<br/>

<file_sep>/test/aliceinnets/finance/api/TestGoogleFinanceGetpricesApi.java
package aliceinnets.finance.api;
import junit.framework.TestCase;
public class TestGoogleFinanceGetpricesApi extends TestCase {
public void testGoogleFinanceGetprices() {
GoogleFinanceGetprices api = new GoogleFinanceGetprices("GOOG", 120.0, "1d");
api.getData();
api = new GoogleFinanceGetprices("GOOG", 120.0, "5d");
double[][] data1 = api.getData();
api.setPeriod("1d");
double[][] data2 = api.getData();
}
}
|
0cd6b15f8016c706d9c9af52a5f0fcd864daf201
|
[
"Markdown",
"Java"
] | 3 |
Java
|
aliceinnets/java-finance-api
|
ea89626ff9e59ec41031cb56c235f3468ce3b5f6
|
34bd620cbb0d0254ae97576b993c438c5619a8cc
|
refs/heads/main
|
<file_sep>export default function (value, page) {
const TOKEN = '<KEY>'
return fetch(`https://pixabay.com/api/?image_type=photo&orientation=horizontal&q=${value}&page=${page}&per_page=12&key=${TOKEN}`)
.then((data) => data.json())
};
|
8725eda206076fcc63c35f581e3ad06642aa1c50
|
[
"JavaScript"
] | 1 |
JavaScript
|
Twinkeeyj/goit-js-hw-13-image-finder
|
4e48f50eb5224bf0467c8f1de609714280682b89
|
b95fa89749dd53f427b8abefc5c14b20c3f99efb
|
refs/heads/master
|
<repo_name>GabrielArsenio/CopyPlaylist<file_sep>/src/view/PrincipalGUI.java
package view;
import util.FuncaoCopia;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* @author <NAME>
* @since 26/05/2015
* @version 1.0
*/
public class PrincipalGUI extends javax.swing.JFrame {
public PrincipalGUI() {
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PrincipalGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
System.out.println("antes");
initComponents();
System.out.println("depois");
this.setLocationRelativeTo(null);
}
private void abrirSeletorLista() {
int acao;
String caminho = System.getProperty("user.home").concat("\\Music\\Listas de Reprodução");
seletor.setCurrentDirectory(new File(caminho));
seletor.setFileSelectionMode(JFileChooser.FILES_ONLY);
acao = seletor.showOpenDialog(this);
if (acao == JFileChooser.APPROVE_OPTION) {
caminho = seletor.getSelectedFile().getPath();
if (caminho.endsWith(".wpl")) {
txLista.setText(caminho);
} else {
JOptionPane.showMessageDialog(null, "Selecione apenas arquivos de lista de reprodução (.wpl)");
txLista.setText("");
}
}
}
private void abrirSeletorDestino() {
int acao;
String caminho = System.getProperty("user.home").concat("\\Desktop");
seletor.setCurrentDirectory(new File(caminho));
seletor.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
acao = seletor.showOpenDialog(this);
if (acao == JFileChooser.APPROVE_OPTION) {
caminho = seletor.getSelectedFile().getPath();
txDestino.setText(caminho);
} else {
txDestino.setText("");
}
}
private void iniciarCopia() {
if (txLista.getText().equals("") || txLista.getText() == null) {
JOptionPane.showMessageDialog(null, "Informe o caminho da lista de reprodução.");
throw new IllegalArgumentException("Lista de reprodução não informada.");
}
if (txDestino.getText().equals("") || txDestino.getText() == null) {
JOptionPane.showMessageDialog(null, "Informe o caminho da pasta destino.");
throw new IllegalArgumentException("Pasta destino não informada.");
}
new Thread() {
@Override
public void run() {
new FuncaoCopia().iniciarCopia(
new File(txLista.getText()), txDestino.getText(), barraProgresso, lbStatus);
}
}.start();
txLista.setEnabled(false);
txDestino.setEnabled(false);
btProcuraLista.setEnabled(false);
btProcuraDestino.setEnabled(false);
txDestino.setEnabled(false);
btCopiar.setEnabled(false);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
seletor = new javax.swing.JFileChooser();
painelFundo = new javax.swing.JPanel();
lbTitulo = new javax.swing.JLabel();
lbLista = new javax.swing.JLabel();
txLista = new javax.swing.JTextField();
lbDestino = new javax.swing.JLabel();
txDestino = new javax.swing.JTextField();
btProcuraLista = new javax.swing.JButton();
btProcuraDestino = new javax.swing.JButton();
btCopiar = new javax.swing.JButton();
barraProgresso = new javax.swing.JProgressBar();
sp1 = new javax.swing.JSeparator();
lbStatus = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("CopyPlaylist by <NAME>");
setResizable(false);
lbTitulo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
lbTitulo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbTitulo.setText("Copiar Lista de Reprodução");
lbLista.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
lbLista.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
lbLista.setText("Lista de Reprodução:");
txLista.setNextFocusableComponent(btProcuraLista);
lbDestino.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
lbDestino.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
lbDestino.setText("Pasta Destino:");
txDestino.setNextFocusableComponent(btProcuraDestino);
btProcuraLista.setText("Procurar...");
btProcuraLista.setNextFocusableComponent(txDestino);
btProcuraLista.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btProcuraListaActionPerformed(evt);
}
});
btProcuraDestino.setText("Procurar...");
btProcuraDestino.setNextFocusableComponent(btCopiar);
btProcuraDestino.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btProcuraDestinoActionPerformed(evt);
}
});
btCopiar.setText("Copiar");
btCopiar.setNextFocusableComponent(txLista);
btCopiar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btCopiarActionPerformed(evt);
}
});
barraProgresso.setName(""); // NOI18N
barraProgresso.setStringPainted(true);
lbStatus.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
javax.swing.GroupLayout painelFundoLayout = new javax.swing.GroupLayout(painelFundo);
painelFundo.setLayout(painelFundoLayout);
painelFundoLayout.setHorizontalGroup(
painelFundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelFundoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(painelFundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(barraProgresso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbTitulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(painelFundoLayout.createSequentialGroup()
.addComponent(lbLista, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txLista)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btProcuraLista))
.addGroup(painelFundoLayout.createSequentialGroup()
.addComponent(lbDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txDestino)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btProcuraDestino))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelFundoLayout.createSequentialGroup()
.addComponent(lbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 506, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btCopiar))
.addComponent(sp1))
.addContainerGap())
);
painelFundoLayout.setVerticalGroup(
painelFundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelFundoLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lbTitulo)
.addGap(18, 18, 18)
.addGroup(painelFundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbLista)
.addComponent(txLista, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btProcuraLista))
.addGap(18, 18, 18)
.addGroup(painelFundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbDestino)
.addComponent(txDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btProcuraDestino))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(barraProgresso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sp1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(painelFundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelFundoLayout.createSequentialGroup()
.addComponent(btCopiar)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(painelFundoLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(lbStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(painelFundo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(painelFundo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btProcuraListaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btProcuraListaActionPerformed
abrirSeletorLista();
}//GEN-LAST:event_btProcuraListaActionPerformed
private void btProcuraDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btProcuraDestinoActionPerformed
abrirSeletorDestino();
}//GEN-LAST:event_btProcuraDestinoActionPerformed
private void btCopiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCopiarActionPerformed
iniciarCopia();
}//GEN-LAST:event_btCopiarActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JProgressBar barraProgresso;
private javax.swing.JButton btCopiar;
private javax.swing.JButton btProcuraDestino;
private javax.swing.JButton btProcuraLista;
private javax.swing.JLabel lbDestino;
private javax.swing.JLabel lbLista;
private javax.swing.JLabel lbStatus;
private javax.swing.JLabel lbTitulo;
private javax.swing.JPanel painelFundo;
private javax.swing.JFileChooser seletor;
private javax.swing.JSeparator sp1;
private javax.swing.JTextField txDestino;
private javax.swing.JTextField txLista;
// End of variables declaration//GEN-END:variables
}
|
89765ddceefff14a9f9ffe039eb123fa49c63349
|
[
"Java"
] | 1 |
Java
|
GabrielArsenio/CopyPlaylist
|
2b84cdfe44f3ebbd44af907ee6971d4533ebbdb5
|
735e6ee852499433a5e97c654f02745bd03567ff
|
refs/heads/master
|
<repo_name>Adys23/CodersCamp---Project-2<file_sep>/time_tracking_tool/src/WorkPeriodSelector.js
import React from "react";
import Dropdown from 'react-bootstrap/Dropdown'
import DropdownButton from 'react-bootstrap/DropdownButton'
import { Container, Row, Col } from "react-bootstrap";
class WorkPeriodSelector extends React.Component {
state = {
buttonTextYear: "Select year",
buttonTextMonth: "Select month"
};
yearButtonClicker = (yearProvided) => {
this.setState({
buttonTextYear: yearProvided
});
let yearSelected = yearProvided;
console.log(yearSelected);
};
monthButtonClicker = (monthProvided) => {
this.setState({
buttonTextMonth: monthProvided
});
let monthSelected;
switch (monthProvided) {
case "January":
monthSelected = 0;
break;
case "February":
monthSelected = 1;
break;
case "March":
monthSelected = 2;
break;
case "April":
monthSelected = 3;
break;
case "May":
monthSelected = 4;
break;
case "June":
monthSelected = 5;
break;
case "July":
monthSelected = 6;
break;
case "August":
monthSelected = 7;
break;
case "September":
monthSelected = 8;
break;
case "October":
monthSelected = 9;
break;
case "November":
monthSelected = 10;
break;
case "December":
monthSelected = 11;
break;
default:
monthSelected = "None of the months was selected"
}
console.log(monthSelected);
};
render() {
return (
<div>
<Container>
<Row>
<Col>
<DropdownButton id="dropdown-basic-button" title={this.state.buttonTextYear}>
<Dropdown.Item href="#" value='2019' onClick={() => this.yearButtonClicker(2019)}>2019</Dropdown.Item>
<Dropdown.Item href="#" value='2020' onClick={() => this.yearButtonClicker(2020)}>2020</Dropdown.Item>
<Dropdown.Item href="#" value='2021' onClick={() => this.yearButtonClicker(2021)}>2021</Dropdown.Item>
</DropdownButton>
</Col>
<Col>
<DropdownButton id="dropdown-basic-button" title={this.state.buttonTextMonth}>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("January")}>January</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("February")}>February</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("March")}>March</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("April")}>April</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("May")}>May</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("June")}>June</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("July")}>July</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("August")}>August</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("September")}>September</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("October")}>October</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("November")}>November</Dropdown.Item>
<Dropdown.Item href="#" onClick={() => this.monthButtonClicker("December")}>December</Dropdown.Item>
</DropdownButton>
</Col>
</Row>
</Container>
</div>
)
}
}
export default WorkPeriodSelector<file_sep>/time_tracking_tool/src/CalendarCreator.js
import React from "react";
import WorkPeriodSelector from "./WorkPeriodSelector";
const CalendarCreator = () => {
function daysInMonth(m, y){
return(m===2?y&3||!(y%25)&&y&15?28:29:30+(5546>>m&1));
}
let monthEnd = daysInMonth(currentMonth, currentYear);
let monthArray = [];
for (var i = 1; i <= monthEnd; i++) {
monthArray.push(i);
}
return (
<tr key={monthArray}>
<td>{monthArray}</td>
</tr>
)
}
export default CalendarCreator<file_sep>/time_tracking_tool/src/App.js
import React from 'react';
import TopNavbar from './TopNavbar';
import TabSelector from './TabSelector';
const App = (props) => {
return (
<div className="App">
<TopNavbar />
<TabSelector />
</div>
)
}
export default App;
<file_sep>/time_tracking_tool/src/AddNewEmployee.js
import React from 'react';
import Form from 'react-bootstrap/Form';
import {Col, Row, Button, Container} from 'react-bootstrap';
import Jumbotron from 'react-bootstrap/Jumbotron';
class NewEmployeeForm extends React.Component {
render() {
return (
<div>
<Jumbotron fluid>
<Container>
<h2>Provide employee's details</h2>
</Container>
</Jumbotron>
<Form>
<Form.Group as={Row} controlId="formHorizontalName">
<Form.Label column sm={2}>
Name
</Form.Label>
<Col sm={10}>
<Form.Control type="text" placeholder="Name" />
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formHorizontalSurname">
<Form.Label column sm={2}>
Surname
</Form.Label>
<Col sm={10}>
<Form.Control type="text" placeholder="Surname" />
</Col>
</Form.Group>
<fieldset>
<Form.Group as={Row}>
<Form.Label as="FormHorizontalRadio" column sm={2}>
Type of contract
</Form.Label>
<Col sm={10}>
<Form.Check
type="radio"
label="Full-time"
name="formHorizontalRadios"
id="fullTimeEmployee"
/>
<Form.Check
type="radio"
label="Part-time"
name="formHorizontalRadios"
id="partTimeEmployee"
/>
</Col>
</Form.Group>
</fieldset>
<Form.Group as={Row}>
<Col sm={{ span: 10, offset: 2 }}>
<Button type="submit">Save</Button>
</Col>
</Form.Group>
</Form>
</div>
)
}
}
export default NewEmployeeForm<file_sep>/time_tracking_tool/src/EmployeeOverview.js
import React from "react";
import WorkPeriodSelector from './WorkPeriodSelector';
class EmployeeOverview extends React.Component {
render() {
return (
<div>
<WorkPeriodSelector />
</div>
)
}
}
export default EmployeeOverview<file_sep>/time_tracking_tool/src/TopNavbar.js
import React from 'react';
import {Navbar, Nav} from 'react-bootstrap';
class TopNavbar extends React.Component {
render() {
return (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">Time Tracking Tool</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-sm-2">
<Nav.Link href="#">Log in</Nav.Link>
<Nav.Link href="#">Settings</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
}
export default TopNavbar<file_sep>/time_tracking_tool/src/RecordHolidays.js
import React from 'react';
import Form from 'react-bootstrap/Form';
import {Container, Col, Row, Button} from 'react-bootstrap';
import Jumbotron from 'react-bootstrap/Jumbotron';
import DatePicker1 from './DatePicker';
class RecordHolidays extends React.Component {
render() {
return (
<div>
<Jumbotron fluid>
<Container>
<h2>Enter holidays period</h2>
</Container>
</Jumbotron>
<Form>
<Form.Group as={Row} controlId="formHorizontalHolidayBeginning">
<Form.Label column sm={2}>
Start Date
</Form.Label>
<Col>
<DatePicker1 />
</Col>
</Form.Group>
<Form.Group as={Row} controlId="formHorizontalHolidayEnd">
<Form.Label column sm={2}>
End Date
</Form.Label>
<Col>
<DatePicker1 />
</Col>
</Form.Group>
<Form.Group as={Row}>
<Col sm={{ span: 10, offset: 2 }}>
<Button type="submit">Save</Button>
</Col>
</Form.Group>
</Form>
</div>
)
}
}
export default RecordHolidays
|
cc215c706f29698aa34616926ffb92965e05bf93
|
[
"JavaScript"
] | 7 |
JavaScript
|
Adys23/CodersCamp---Project-2
|
17e4ce6a151d0f36a1b9ff59fc8766b7790bf5c1
|
42ce1cd71570b4cbff4053b0c7e1b5b1d79cdee9
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using static GoogleHashCode2020.GlovalVar;
namespace GoogleHashCode2020
{
class Program
{
static void Main(string[] args)
{
string projectPath = System.IO.Directory.GetCurrentDirectory().Substring(0, System.IO.Directory.GetCurrentDirectory().Length - 24);
string inputPath = projectPath + "\\inputData";
string outputPath = projectPath + "\\outputData";
string[] inputFileNames = new string[] { "a_example.txt", "b_read_on.txt", "c_incunabula.txt", "d_tough_choices.txt", "e_so_many_books.txt", "f_libraries_of_the_world.txt" };
// INTERPRET INPUT DATA, DON'T CHANGE IT
string line;
int lineCount = 0;
System.IO.StreamReader file = new System.IO.StreamReader(inputPath + "\\" + inputFileNames[3]); // CHANGE TTHIS TO CHANGE FILE
line = file.ReadLine();
while (line != null)
{
string[] raw = line.Split(' ');
if(lineCount == 0)
{
nBooks = Int32.Parse(raw[0]);
books = new Book[nBooks];
nLibraries = Int32.Parse(raw[1]);
libraries = new Library[nLibraries];
nDays = Int32.Parse(raw[2]);
}
else if(lineCount == 1)
{
for (int i = 0; i < raw.Length; i++)
{
books[i] = new Book(i, Int32.Parse(raw[i]));
}
}
else{
if(lineCount % 2 == 0)
{
if ((lineCount - 2) / 2 >= nLibraries) break;
libraries[(lineCount - 2) / 2] = new Library((lineCount - 2) / 2, Int32.Parse(raw[0]), Int32.Parse(raw[1]), Int32.Parse(raw[2]));
libraries[(lineCount - 2) / 2].SetOfBooks = new Book[libraries[(lineCount - 2) / 2].nBooks];
}
else
{
Library lib = libraries[(lineCount - 2) / 2];
for (int i = 0; i < lib.nBooks; i++)
{
lib.SetOfBooks[i] = books[Int32.Parse(raw[i])];
}
// SORT? comment this if you dont want them to have books sorted from the start
lib.SortBooks();
}
// //Console.WriteLine(lineCount + " " + line + " " + (lineCount - 2) / 2);
// Console.WriteLine((lineCount - 2) / 2 + " " + libraries.Length);
//if (libraries[(lineCount - 2) / 2] == null)
//{
// Console.WriteLine("Library " + (lineCount - 2) / 2 + " is null");
//}
}
lineCount++;
line = file.ReadLine();
}
Simple.main();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace GoogleHashCode2020
{
public static class GlovalVar
{
/////////////////////// GLOBAL VARIABLES /////////////////////
public static int nBooks; // number of books
public static int nLibraries; // number of libraries
public static int nDays; // days we have to scan
public static Book[] books = null;
public static Library[] libraries = null;
/////////////////////////////////////////////////////////////////
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace GoogleHashCode2020
{
public class Book
{
public int id;
public int score;
public Book(int id, int sc)
{
this.id = id;
this.score = sc;
}
public Book(int sc)
{
score = sc;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using static GoogleHashCode2020.GlovalVar;
namespace GoogleHashCode2020
{
static class BruteFQ
{
public static void main()
{
bool[] usedBooks = new bool[nBooks];
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using static GoogleHashCode2020.GlovalVar;
namespace GoogleHashCode2020
{
public class Library
{
/////////////////////////////////////////////
// FROM PROBLEM
public int id;
public Book[] setOfBooks; // id of the books
public int nBooks;
public int days;
public int booksPerDay;
/////////////////////////////////////////////
public int estimatePunctuation;
public Book[] SetOfBooks { get => setOfBooks; set => setOfBooks = value; }
public Library(int id, Book[] setOfBooks, int days, int booksPerDay)
{
this.id = id;
this.setOfBooks = setOfBooks;
this.days = days;
this.booksPerDay = days;
}
public Library(int id, int nBooks, int days, int booksPerDay )
{
this.id = id;
this.days = days;
this.booksPerDay = days;
this.nBooks = nBooks;
}
public void SortBooks()
{
Array.Sort(setOfBooks, delegate (Book a, Book b)
{
return b.score - a.score;
});
}
public void LibraryPunctuation()
{
LibraryPunctuation(0);
}
public void LibraryPunctuation(int threshold)
{
int howMany = (nDays - days) * booksPerDay + threshold;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using static GoogleHashCode2020.GlovalVar;
namespace GoogleHashCode2020
{
class Simple
{
public static string projectPath = System.IO.Directory.GetCurrentDirectory().Substring(0, System.IO.Directory.GetCurrentDirectory().Length - 24);
public static void main() {
int days = nDays;
List<Int32> scanned = new List<Int32>();
string res="";
string outText = "";
string libs = "";
int dayNow = 0;
int dayLib = 0;
int i = libraries.Length - 1;
int j = 0;
int l = 0;
int b = 0;
int bpd = 0;
while (dayNow < days && i > -1) {
if (libraries[i].days + dayNow < days - 1)
{
dayNow += libraries[i].days;
l++;
res += libraries[i].id + " ";
j = libraries[i].setOfBooks.Length - 1;
dayLib = dayNow;
bpd = libraries[i].booksPerDay;
libs = "";
b = 0;
while (dayLib < days && j > -1)
{
Book book = libraries[i].setOfBooks[j];
if (!scanned.Contains(book.id))
{
libs += book.id + " ";
scanned.Add(book.id);
b++;
dayLib += 1 / bpd;
}
j--;
}
res += b + "\n";
res += libs + "\n";
}
i--;
}
outText = l + "\n";
outText += res;
Console.WriteLine(outText);
System.IO.File.WriteAllText(projectPath+"\\"+ "d_tough_choices.out.txt", outText);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace GoogleHashCode2020
{
class Random
{
public static void main(Library[] libraries, Book[] books, int days)
{
List<Int32> scanned = new List<Int32>();
string res = "";
string outText = "";
string libs = "";
int dayNow = 0;
int dayLib = 0;
int i = libraries.Length - 1;
int j = 0;
int l = 0;
int b = 0;
int bpd = 0;
while (dayNow < days && i > -1)
{
if (libraries[i].days + dayNow < days - 1)
{
dayNow += libraries[i].days;
l++;
res += libraries[i].id + "\n";
j = libraries[i].setOfBooks.Length - 1;
dayLib = dayNow;
bpd = libraries[i].booksPerDay;
while (dayLib < days && j > -1)
{
Book book = libraries[i].setOfBooks[j];
if (!scanned.Contains(book.id))
{
libs += book.id;
scanned.Add(book.id);
b++;
dayLib += 1 / bpd;
}
}
res += b + "\n";
res += libs;
}
}
outText = l + "\n";
outText += res;
}
}
}
|
2bc921c90c4a8035a2cfa7fbce4063e654afa45e
|
[
"C#"
] | 7 |
C#
|
qiqetes/HashCode2020
|
42c1fc1b236f4875d704e0d158af63d7c0d32add
|
b580e54b573c289cb13d1e79352e7b02f24ec7c2
|
refs/heads/master
|
<repo_name>abhinv01/covidTracker<file_sep>/src/App.js
import StateWise from "./components/StateWise/StateWise.js";
function App() {
return (
<>
<StateWise/>
</>
);
}
export default App;
<file_sep>/src/components/StateWise/StateWise.js
import React, {useEffect, useState} from "react";
import "../../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./StateWise.css"
const StateWise = () => {
const [data, setData] = useState([])
const getCovidData = async () => {
const res = await fetch('https://api.covid19india.org/data.json')
const actualData = await res.json();
console.log(actualData.statewise);
setData(actualData.statewise);
}
useEffect(() => {
getCovidData();
}, []);
return (
<>
< div className = "table_head" >
<h1>
<span>😷India's</span> Statewise Covid-19 Count</h1>
</div>
<table className="table table-hover">
<thead className="tableH text-center">
<tr>
<th>State Number</th>
<th>
State</th>
<th>Confirmed</th>
<th>
Recovered</th>
<th>
deaths</th>
<th>
active</th>
<th>updated ON</th>
</tr>
</thead>
<tbody className="text-center table_body">
{
data.map((currElement, index) => {
return (
<tr key = {index}>
<td>{index}</td>
<td>{currElement.state}</td>
<td>{currElement.confirmed}</td>
<td>{currElement.recovered}</td>
<td>{currElement.deaths}</td>
<td>{currElement.active}</td>
<td>{currElement.lastupdatedtime}</td>
</tr>
)
})
}
</tbody>
</table>
</>
)
}
export default StateWise;
|
fd354ce41164d754d38cd962f78913138d6f3c81
|
[
"JavaScript"
] | 2 |
JavaScript
|
abhinv01/covidTracker
|
8a7e7199f063557d587dc2620196ce8773687394
|
498fef87216d04cdad60909a6b09fe58e4f538c6
|
refs/heads/master
|
<file_sep>import celery
import workers
from settings import (REDIS_HOST, REDIS_PORT, REDIS_DB)
CELERY_REDIS_URL = 'redis://{}:{}/{}'.format(REDIS_HOST, REDIS_PORT, REDIS_DB)
app = celery.Celery('tasks', broker=CELERY_REDIS_URL, backend=CELERY_REDIS_URL)
_workers = { }
@app.task
def download(msg):
if not _workers.get('download'):
_workers['download'] = workers.DownloadWorker()
return _workers['download'].run(msg)
@app.task
def scrape(req):
if not _workers.get('scrape'):
_workers['scrape'] = workers.ScrapeWorker()
return _workers['scrape'].run(msg)
@app.task
def index(req):
if not _workers.get('index'):
_workers['index'] = workers.IndexWorker()
return _workers['index'].run(msg)
<file_sep>'''
settings.py should begin with:
from defaults import *
followed by overrides of specific settings
'''
# Redis
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
# AWS
AWS_KEY = None
AWS_SECRET = None
# Timeouts
DEFAULT_SITE_WAIT_TIME = 10
DEFAULT_URL_WAIT_TIME = 86400
<file_sep>#boto
celery[redis]
#elasticsearch
redis
requests
<file_sep>import json
import redis
import requests
from settings import (REDIS_HOST, REDIS_PORT, REDIS_DB, AWS_KEY, AWS_SECRET)
class BaseWorker():
TYPE = None
def __init__(self):
if self.TYPE is None:
raise NotImplementedError()
self.redis = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
def run(self, req):
response = {}
try:
response['request'] = json.loads(req)
except ValueError:
return {'error':'could not parse request'}
request = response['request']
# validate request
# get site config
# check wait times
url = request['url']
rr = requests.get(url)
response = self.process(rr)
return json.dumps(response)
def process(self, rr):
raise NotImplementedError()
class IndexWorker(BaseWorker):
TYPE = 'index'
def process(self, rr):
return rr.status_code
class ScrapeWorker(BaseWorker):
TYPE = 'scrape'
def process(self, rr):
return rr.status_code
class DownloadWorker(BaseWorker):
TYPE = 'download'
def process(self, rr):
return rr.status_code
<file_sep># forest
Distributed Web Crawler
|
a19ee5e3e111aba4bed0a6078962385610c6f26d
|
[
"Markdown",
"Python",
"Text"
] | 5 |
Python
|
martinezah/forest
|
7ed86608f1f18224c4bfaab2522425d6c95130aa
|
43e3f46318ba44e89a499a27611a49161a181890
|
refs/heads/master
|
<repo_name>iandesj/dotfiles<file_sep>/README.md
# dotfiles
My dotfiles
Do this
```bash
$ chmod +x setup.sh
$ ./setup.sh
$ vim # then :PluginInstall
```
<file_sep>/setup.sh
#!/usr/bin/env bash
# create backup dir
echo '====== Creating Backup Directory... ======'
mkdir $PWD/backups
# back it all up bro
echo '====== Copying Files to Backup Directory... ======'
cp $HOME/.vimrc $PWD/backups/.vimrc.bak 2>/dev/null
cp $HOME/.tmux.conf $PWD/backups/.tmux.conf.bak 2>/dev/null
cp $HOME/.tmux.conf.local $PWD/backups/.tmux.conf.local.bak 2>/dev/null
# make it so bro
echo '====== Linking Dotfiles to Proper Paths in $HOME ======'
ln -s -f "$PWD/vimrc" ~/.vimrc
ln -s -f "$PWD/tmux.conf" ~/.tmux.conf
ln -s -f "$PWD/tmux.conf.local" ~/.tmux.conf.local
echo '====== Setting up Vundle ======'
git clone https://github.com/VundleVim/Vundle.vim.git $HOME/.vim/bundle/Vundle.vim
echo "* Run the following command in Vim to install all plugins: *"
echo " :PluginInstall"
|
70ac019be9e55bd222d69400454e29b52052a846
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
iandesj/dotfiles
|
c8cc43e9e01ce554a92a8149d257cb748ab330db
|
912ab965dc9ae107e12c95c2f8b3b1c27424db53
|
refs/heads/main
|
<file_sep>const {
PORT,
NODE_ENV,
GRAPHQL_DEPTH_LIMIT
} = process.env;
export const constants = {
PORT,
NODE_ENV,
GRAPHQL_DEPTH_LIMIT: parseInt(GRAPHQL_DEPTH_LIMIT || '4'),
ENVIRONMENTS: {
DEV: 'development',
PROD: 'production',
TEST: 'test'
},
SUBSCRIPTION_TOPICS: {
USER_ADDED: 'USER_ADDED'
},
LOG_LEVELS: {
INFO: 'info',
ERROR: 'error',
DEBUG: 'debug',
WARN: 'warn',
},
ERRORS: {
BAD_REQUEST: {
TYPE: 'BAD_REQUEST',
CODE: 400
},
NOT_FOUND: {
TYPE: 'NOT_FOUND',
CODE: 404
},
INTERNAL_SERVER_ERROR: {
TYPE: 'INTERNAL_SERVER_ERROR',
CODE: 500
},
UNAUTHORIZED: {
TYPE: 'UNAUTHORIZED',
CODE: 403
},
UNAUTHENTICATED: {
TYPE: 'UNAUTHENTICATED',
CODE: 402
}
}
};
<file_sep>export const BootStrapers = {
Apollo: Symbol.for('Apollo'),
App: Symbol.for('App'),
Server: Symbol.for('Server')
};
<file_sep>import DIContainer from '@/config/di-container';
import { IServer } from '@/bin/server';
import { BootStrapers } from '@/config/boot-strapers';
const server = DIContainer.get<IServer>(
BootStrapers.Server
);
server.init().catch((error) => {
console.error(error);
});
<file_sep>import 'reflect-metadata';
import { Container } from 'inversify';
import { UserResolvers } from '@/modules/user/user-resolver';
import { ILoggerService, LoggerService } from '@/services/logger.service';
import { ErrorService, IErrorService } from '@/services/error.service';
import { Services } from './services';
import { BootStrapers } from './boot-strapers';
import { App, IApp } from '@/bin/app';
import { Apollo, IApollo } from '@/bin/apollo';
import { IServer, Server } from '@/bin/server';
const bindResolvers = (c: Container) => {
c.bind<UserResolvers>(UserResolvers).toSelf().inSingletonScope();
}
// Binds service signatures to their implementations
const bindServices = (c: Container) => {
c.bind<ILoggerService>(Services.LoggerService).to(LoggerService).inSingletonScope();
c.bind<IErrorService>(Services.ErrorService).to(ErrorService).inSingletonScope();
}
// Binds service signatures to their implementations
const bindBootstrapers = (c: Container) => {
c.bind<IApollo>(BootStrapers.Apollo).to(Apollo).inSingletonScope();
c.bind<IApp>(BootStrapers.App).to(App).inSingletonScope();
c.bind<IServer>(BootStrapers.Server).to(Server).inSingletonScope();
}
const DIContainer = new Container();
bindResolvers(DIContainer);
bindServices(DIContainer);
bindBootstrapers(DIContainer);
export default DIContainer;<file_sep>import { NonEmptyArray } from 'type-graphql';
import { UserResolvers } from '@/modules/user/user-resolver';
export const Resolvers: NonEmptyArray<Function> = [
UserResolvers
];
<file_sep>import { ApolloServer } from 'apollo-server-express';
import { constants } from '@/config/constants';
import depthLimit from 'graphql-depth-limit';
import { inject, injectable } from 'inversify';
import { GraphQLSchema } from 'graphql';
import { Resolvers } from '@/modules/';
import DIContainer from '@/config/di-container';
import { buildSchema } from 'type-graphql';
import { Services } from '@/config/services';
import { ILoggerService } from '@/services/logger.service';
const {NODE_ENV, ENVIRONMENTS, GRAPHQL_DEPTH_LIMIT, LOG_LEVELS, ERRORS } = constants;
@injectable()
export class Apollo {
constructor(
@inject(Services.LoggerService)
private readonly logger: ILoggerService,
) {}
private async createSchema (): Promise<GraphQLSchema> {
return buildSchema({
resolvers: Resolvers,
dateScalarMode: 'timestamp',
container: DIContainer,
validate: false
});
}
private formatError(error: Error) {
// Format errors here
console.error(error, 'error');
return error;
}
async init(): Promise<ApolloServer> {
const schema = await this.createSchema();
const isProduction = NODE_ENV === ENVIRONMENTS.PROD;
return new ApolloServer({
schema,
debug: !constants,
introspection: !isProduction,
playground: !isProduction,
tracing: !isProduction,
formatError: this.formatError,
validationRules: [depthLimit(GRAPHQL_DEPTH_LIMIT)]
});
}
}
export interface IApollo {
init: () => Promise<ApolloServer>;
}<file_sep># inversify-graphql-example
Node js sample app with `inversify` and `graphql(using apollo graphql)`.
It includes `winston` for logging and `stoppable` for graceful shutdowns.
Can be used with or without docker. Instructions are written below.
## How to use
* Clone the repo and `cd` into it.
### Using without docker
* Run `npm i`
* create `.env` file to the root of this folder and copy contents from `example.env` into it.
* Run `npm run dev` to run server with nodemon.
> To run compiled code, run `npm run build`, provide environment variables(.env file will not be read with compiled code) and then `npm start`
### Using with docker
a. For building dev stage
* create `.env` file to the root of this folder and copy contents from `example.env` into it.
* Run `docker-compose build`
* Run `docker-compose up`
b. For building prod stage
* For environment variables, create `.env` file to the root of this folder and copy contents from `example.env` into it. OR use some other way of providing environment variables to the compose file.
> Note: the above method is only used for this example.
> More secure way must be used for passing environment variables to the docker container.
> See the comment in `dockerfile` in `prod` stage section
* Run `docker-compose -f docker-compose.yml build`
* Run `docker-compose -f docker-compose.yml up`
`You are ready to build exciting things upon this sample app.`
<file_sep>import { injectable } from 'inversify';
import { createLogger, format, transports } from 'winston';
import { constants } from '@/config/constants';
const { LOG_LEVELS } = constants;
@injectable()
export class LoggerService {
private readonly logger;
constructor() {
this.logger = this.createLoggerInstance();
}
private createLoggerInstance() {
return createLogger({
level: LOG_LEVELS.DEBUG,
format: format.json(),
transports: [
new transports.Console({
format: format.simple(),
level: LOG_LEVELS.INFO
})
]
});
}
log(logLevel: string, message: string, extraInfo: any): void {
this.logger.log(logLevel, message, extraInfo);
}
}
export interface ILoggerService {
log(logLevel: string, message: string, extraInfo: any): void;
}<file_sep>import Express from 'express';
import { injectable } from 'inversify';
@injectable()
export class App {
init(): Express.Express {
const app = Express();
// Returns middleware that only parses json
// and only looks at requests where the Content-Type header matches the type option.
app.use(Express.json());
app.get('/ping', function (_, res) {
res.status(200).end();
});
return app;
}
}
export interface IApp {
init: () => Express.Express;
}
<file_sep>import { Services } from '@/config/services';
import { inject, injectable } from 'inversify';
import { constants } from '@/config/constants';
import { ILoggerService } from './logger.service';
const { LOG_LEVELS, ERRORS } = constants;
class AppError extends Error {
type: string;
message: string;
code: number;
level: string;
stackTrace: string;
isOperational: boolean;
time: Date;
constructor(level: string, type: string, message: string, code: number, isOperational: boolean) {
super(message);
this.type = type;
this.message = message;
// status code to throw(if any).
this.code = code;
this.level = level;
// true, when our app throws an error intentionally, e.g.: Missing some input
this.isOperational = isOperational;
this.time = new Date();
this.stackTrace = this.stack || '';
}
}
@injectable()
export class ErrorService {
constructor(
@inject(Services.LoggerService)
private readonly logger: ILoggerService,
) {}
throwUnAuthenticatedError(message: string, isOperational = true): AppError {
this.logger.log(LOG_LEVELS.ERROR, message, {
type: ERRORS.UNAUTHENTICATED.TYPE,
code: ERRORS.UNAUTHENTICATED.CODE,
time: new Date(),
isOperational
});
throw new AppError(LOG_LEVELS.ERROR, ERRORS.UNAUTHENTICATED.TYPE, message, ERRORS.UNAUTHENTICATED.CODE, isOperational);
};
throwBadRequestError(message: string, isOperational = true): AppError {
this.logger.log(LOG_LEVELS.ERROR, message, {
type: ERRORS.BAD_REQUEST.TYPE,
code: ERRORS.BAD_REQUEST.CODE,
time: new Date(),
isOperational
});
throw new AppError(LOG_LEVELS.ERROR, ERRORS.BAD_REQUEST.TYPE, message, ERRORS.BAD_REQUEST.CODE, isOperational);
};
throwNotFoundError(message: string, isOperational = true): AppError {
this.logger.log(LOG_LEVELS.ERROR, message, {
type: ERRORS.NOT_FOUND.TYPE,
code: ERRORS.NOT_FOUND.CODE,
time: new Date(),
isOperational
});
throw new AppError(LOG_LEVELS.ERROR, ERRORS.NOT_FOUND.TYPE, message, ERRORS.NOT_FOUND.CODE, isOperational);
};
throwUnAuthorizedError(message: string, isOperational = true): AppError {
this.logger.log(LOG_LEVELS.ERROR, message, {
type: ERRORS.UNAUTHORIZED.TYPE,
code: ERRORS.UNAUTHORIZED.CODE,
time: new Date(),
isOperational
});
throw new AppError(LOG_LEVELS.ERROR, ERRORS.UNAUTHORIZED.TYPE, message, ERRORS.UNAUTHORIZED.CODE, isOperational);
};
throwInternalServerError(message: string, isOperational = true): AppError {
this.logger.log(LOG_LEVELS.ERROR, message, {
type: ERRORS.INTERNAL_SERVER_ERROR.TYPE,
code: ERRORS.INTERNAL_SERVER_ERROR.CODE,
time: new Date(),
isOperational
});
throw new AppError(LOG_LEVELS.ERROR, ERRORS.INTERNAL_SERVER_ERROR.TYPE, message, ERRORS.INTERNAL_SERVER_ERROR.CODE, isOperational);
};
}
export interface IErrorService {
throwUnAuthenticatedError(message: string, isOperational?: boolean): AppError;
throwBadRequestError(message: string, isOperational?: boolean): AppError;
throwNotFoundError(message: string, isOperational?: boolean): AppError;
throwUnAuthorizedError(message: string, isOperational?: boolean): AppError;
throwInternalServerError(message: string, isOperational?: boolean): AppError;
}<file_sep>import { User } from '@/model/user';
import { Arg, PubSub, PubSubEngine, Query, Resolver, Root, Subscription, Mutation } from 'type-graphql';
import { inject, injectable } from 'inversify';
import { Services } from '@/config/services';
import { constants } from '@/config/constants';
import { IErrorService } from '@/services/error.service';
const { SUBSCRIPTION_TOPICS } = constants;
(global as any).id = 1;
@injectable()
@Resolver(User)
export class UserResolvers {
constructor(
@inject(Services.ErrorService) private readonly errorService: IErrorService
) {}
@Query((_returns: void) => User)
user(
@Arg('age') age: number
): User {
if (age < 18) {
this.errorService.throwBadRequestError('Age must be greater than 18');
}
return {
id: (global as any).id,
name: 'example',
email: '<EMAIL>',
age,
};
}
@Mutation((_returns: void) => User)
addUser(
@PubSub() pubSub: PubSubEngine,
@Arg('age') age: number,
@Arg('name') name: string,
@Arg('email') email: string
): User {
if (age < 18) {
this.errorService.throwBadRequestError('Age must be greater than 18');
}
const user = {
name,
email,
age,
id: (global as any).id,
};
(global as any).id++;
pubSub.publish(SUBSCRIPTION_TOPICS.USER_ADDED, user);
return user;
}
@Subscription((_returns: void) => User, {topics: SUBSCRIPTION_TOPICS.USER_ADDED})
userAdded(
@Root() res: User,
): User {
return res;
}
}<file_sep>import { Field, Int, ObjectType } from 'type-graphql';
@ObjectType()
export class User {
@Field((_type) => Int)
public id!: number;
@Field({ nullable: false })
public name!: string;
@Field({ nullable: false })
public email!: string;
@Field((_type) => Int)
public age?: number;
}<file_sep>const http = require('http');
const options = {
host: 'localhost',
protocol: 'http:',
port: '80',
timeout: 2000,
path: '/ping'
};
const request = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
if (res.statusCode === 200) {
process.exit(0);
}
process.exit(1);
}).on('error', function(err) {
console.log('ERROR', err);
process.exit(1);
});
process.on('exit', function(code) {
console.log(`EXIT CODE: ${code}`);
});
request.end();<file_sep>export const Services = {
LoggerService: Symbol.for('LoggerService'),
ErrorService: Symbol.for('ErrorService'),
};
<file_sep>import { createServer } from 'http';
import stoppable from 'stoppable';
import { inject, injectable } from 'inversify';
import { constants } from '@/config/constants';
import { BootStrapers } from '@/config/boot-strapers';
import { IApollo } from './apollo';
import { IApp } from './app';
const { PORT } = constants;
@injectable()
export class Server {
private readonly expressApp;
private readonly server;
constructor(
@inject(BootStrapers.Apollo)
private readonly apollo: IApollo,
@inject(BootStrapers.App)
private readonly app: IApp
) {
if (!PORT) {
console.error();
process.exit(1);
}
this.expressApp = this.app.init();
this.server = stoppable(createServer(this.expressApp));
}
private shutdown(): void {
// handle some special things here
// Like closing the connections
this.server.stop((err) => {
if (err) {
console.log(err, 'err');
process.exit(1);
}
process.exit();
});
}
private addProcessEvents(): void {
process.on('uncaughtException', (error) => {
console.log(error, 'error - uncaughtException');
this.shutdown();
});
process.on('unhandledRejection', (error) => {
console.log(error, 'error - unhandledRejection');
this.shutdown();
});
process.on('SIGTERM', () => {
console.log('SIGTERM');
this.shutdown();
});
process.on('SIGINT', () => {
console.log('SIGINT');
this.shutdown();
});
process.on('exit', (code) => {
console.log(`Exiting with code: ${code}`);
});
}
async init(): Promise<void> {
const apolloServer = await this.apollo.init();
apolloServer.applyMiddleware({ app: this.expressApp, path: '/graphql' });
apolloServer.installSubscriptionHandlers(this.server);
this.addProcessEvents();
this.server.listen(PORT, async () => {
console.log(`App listening on port ${PORT}`);
});
}
}
export interface IServer {
init: () => Promise<void>;
}
|
2d39f66743e25c1b81cc7fbf31767c12a073fcc9
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 15 |
TypeScript
|
sankalpkataria/inversify-graphql-example
|
252aed8367c4b12a74f571e563b2f574483ce3f4
|
c5a5f4bec3472b4d39ead119b1e8e39fe7442f76
|
refs/heads/master
|
<repo_name>Mohammed-A-Hassan/NoteKeeper<file_sep>/app/src/main/java/com/example/myapplication/DataManager.kt
package com.example.myapplication
class DataManager {
//this will server as a central point of managing instances for the courseinfo and noteinfo classes created
//DataManager class won't need a primary constructor but it will need some properties
//you need a property to hold a collection of courses and a property to hold a collection of notes
//Kotlin has a variety of collection classes and we will use some here
//for courses we will use a collection that makes it easy for us to lookup courses by the CourseID therefoe use Hashmap!
//hashmap is a generic type (same in other languages) which allows us to specify the specific type we want to use within the type
val courses = HashMap<String,CourseInfo>()
//the first type parameter in hashmap will be used for lookups - since we are using courseid for lookups then that is a string
// the second type of parameter is the one to be stored - in our case it is the course info which is of type courseInfo
//this will take care of creating new instances of our Hashmap, the hashmap maps string values to instances of our courseinfo class and a reference of that hashmap is assigned to our courses property
val notes = ArrayList<NoteInfo>()
//no lookups are needed for the notes here and we will use the Arraylist collection
init{
initialiseCourses()
//anytime an instance of our datamanager class is created, the code within the init bock will automatically run and populates our collection of courses for us
//init blocks accept no parameters because there's no way to call them explicitly. they run automatically as part of instance creation
//inti block can access the parameters of our primary constructor as well as properties within the class
//in Kotlin type initialisation occurs through a combination of the type's primary constructor which provides the initialisation values along with the code that runs inside of our initialiser blocks
//initialiser block provides initialisation code and primary constructor provides the initialisation values
}
private fun initialiseCourses(){
//by default in Kotlin all members are visible unless we state otherwise
// for this function we don't anything from outside this class to call it so we label it as 2private"
var course = CourseInfo("android_intents","Android Programming with intents" )
courses.set(course.courseID, course)
course = CourseInfo(courseID = "android_async", title = "Android Async Programming and Services")
courses.set(course.courseId, course)
course = CourseInfo("Java fundamentals: The Java Language", "Java_Lang")
courses.set(course.courseId, course)
course = CourseInfo("Java_Core", "Java Fundamentals: The Core Platform")
courses.set(course.courseId, course)
//we need to add a code that runs this function whenever an instance of DataManager class is created and we can do that with an initializer block
}
}<file_sep>/app/src/main/java/com/example/myapplication/NoteKeeperData.kt
package com.example.myapplication
// We will add the classes related to our data model to this file
// The first class we need to add is the class related to our module
class CourseInfo (val courseID: String, val title: String) {
override fun toString(): String {
return title
}
}
// courseid and titleid won't change from our app point of view - they are assigned once "val" properties!
//by addind val in between the brackets at the header of the class will mean we don't have to mention the properties again in the body of the class
// because the class now does not have any body so we don't need the curly braces anymore and the class is declared entirely in a single line
class NoteInfo(var course: CourseInfo, var title: String, var text: String)
// we add the var keyword to make "course" a property
//we choose var because we might want to change the name of a course the ntoe is associated with
//courseInfo is inherited from the class above https://www.callicoder.com/kotlin-inheritance/
//the class that inherits is called child, derived or subclass
//while parent class could be called base, parent or super class
//THE ABOVE TWO CLASSES ARE USED TO REPRESENT DATA WITHIN OUR APP
|
428ad7fb94c39c70fae61c56c0c6e773d30c2255
|
[
"Kotlin"
] | 2 |
Kotlin
|
Mohammed-A-Hassan/NoteKeeper
|
1a5790ba55fe9b5953f4e2da2972652be23cfcdc
|
df8bbe0f5ef91683ab664c96ca70c206faeebdc4
|
refs/heads/master
|
<file_sep>var words = [
"Black",
"White",
"Blue",
"Red",
"Yellow",
"Green",
"Pink",
"Orange",
"Grey"
];
var wins = 0;
var losses = 0;
var guesses = 10;
var letterGuessed = "";
var randomWord;
var lettersInWord = [];
var numberOfletters;
var dashAndLetterHandler = [];
function reset() {
wins = 0;
losses = 0;
guesses = 10;
letterGuessed = "";
randomWord = "";
lettersInWord = [];
numberOfletters = 0;
dashAndLetterHandler = [];
}
|
78c897ffd2d9efe0b77b647c6ae0b9c5017880d8
|
[
"JavaScript"
] | 1 |
JavaScript
|
priyanshkumar/WordGuess
|
c4b06076c7c83e8d7d44449b1a2f045ce260e180
|
36bcaca090d52bea78d934494c64d25e73c5c713
|
refs/heads/master
|
<repo_name>jueyaye/SortOfScrabble<file_sep>/src/App.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { search } from './functions/search';
import { score } from './functions/score';
import { findOptimalSolution } from './functions/solution';
it('finds all solutions', () => {
const result = search('TAR');
console.log(result.includes('AR')
&& result.includes('AR')
&& result.includes('ART')
&& result.includes('AT')
&& result.includes('RAT')
&& result.includes('TA')
&& result.includes('TAR'));
});
it('scores correctly', () => {
const result = score('QUEEN', 7)
console.log(result == 70);
})
it('finds the optimal solution', () => {
const result = findOptimalSolution('INERTIA');
console.log(result.bestChildPath === '/INERTIA' && result.bestChildScore == 99);
});
it('finds the optimal solution in combinations', () => {
const result = findOptimalSolution('QUEENBEE');
console.log(result.bestChildPath === '/QUEEN//BEE' && result.bestChildScore == 85);
});
it('correctly finds no solutions', () => {
const result = findOptimalSolution('');
console.log(result === undefined);
});
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
<file_sep>/src/components/board.js
import React, { useState, useEffect } from "react";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Tile from "./tile.js";
import { score } from "../functions/score";
import { search } from "../functions/search";
const useStyles = makeStyles(theme => ({
scoreBoard: {
width: "100%",
position: "relative",
padding: "10px",
border: "3px solid black"
},
board: {
height: "500px",
width: "100%",
position: "relative",
border: "3px solid black"
},
gameOptions: {
height: "180px",
width: "100%",
position: "relative",
padding: "10px",
border: "3px solid black"
},
button: {
display: "block",
margin: "10px 0",
padding: "10px",
width: "100%",
height: "100%"
}
}));
const Board = props => {
const classes = useStyles();
let indexId = -1;
const [state, setState] = useState({
letters: props.hand.map(a => {
return {
id: (indexId += 1),
value: a.toUpperCase(),
pos: { x: 0, y: 44 * indexId }
};
}),
score: 0,
observedWords: [],
observedWordsString: [],
validWords: search(props.hand.join("").toUpperCase()),
taregtLength: props.handSize
});
useEffect(() => {
indexId = -1;
setState({
letters: props.hand.map(a => {
return {
id: (indexId += 1),
value: a.toUpperCase(),
pos: state.letters[indexId].pos
};
}),
score: 0,
observedWords: [],
observedWordsString: [],
validWords: search(props.hand.join("").toUpperCase()),
taregtLength: props.handSize
});
}, [props]);
const checkRemoveWords = (tile, observedWords) => {
const scrubbedWords = observedWords;
for (let i = 0; i < observedWords.length; i += 1) {
const word = observedWords[i];
for (let j = 0; j < word.length; j += 1) {
const observedTile = word[j];
if (observedTile.id == tile.id) {
scrubbedWords.splice(i, 1);
}
}
}
return scrubbedWords;
};
const checkAddWords = (letters, newWords) => {
const { validWords } = state;
let updatedWordsJSON = [];
for (let i = 0; i < letters.length; i += 1) {
const inLineWith = [letters[i]];
for (let j = 0; j < letters.length; j += 1) {
if (
Math.abs(letters[i].pos.y - letters[j].pos.y) < 20 &&
letters[i].id != letters[j].id
) {
updatedWordsJSON = checkRemoveWords(letters[i], newWords);
inLineWith.push(letters[j]);
}
}
inLineWith.sort((a, b) => {
return a.pos.x - b.pos.x;
});
const createdWord = inLineWith.map(a => a.value).join("");
if (inLineWith.length > 1 && validWords.includes(createdWord)) {
updatedWordsJSON.push(inLineWith);
}
}
return updatedWordsJSON;
};
const handleTileChange = tile => {
const { letters, observedWords, validWords, taregtLength } = state;
const newLetters = letters.map(a => {
if (a.id == tile.id) return tile;
return a;
});
let updatedWordsJSON = [];
const updatedWordsString = [];
let roundScore = 0;
// check to see if tile was part of observed words
updatedWordsJSON = checkRemoveWords(tile, observedWords);
// check to see if tile forms new words
updatedWordsJSON = checkAddWords(newLetters, updatedWordsJSON);
// create string array for scoring
for (let i = 0; i < updatedWordsJSON.length; i += 1) {
const wordString = updatedWordsJSON[i].map(a => a.value).join("");
updatedWordsString.push(wordString);
// score current play
roundScore += score(wordString, taregtLength);
}
// update state
setState({
letters: newLetters,
score: roundScore,
observedWords: updatedWordsJSON,
observedWordsString: updatedWordsString,
validWords,
taregtLength: state.taregtLength
});
};
return (
<>
<div className={classes.scoreBoard}>
<Grid container spacing={2}>
<Grid item xs={12} sm container>
<Grid item xs container direction="column" spacing={2}>
<Grid item xs>
<Typography gutterBottom variant="h3">
Word Game
</Typography>
<Typography variant="h6" gutterBottom>
Words played: {props.wordsPlayed.join(", ")}
</Typography>
<Typography variant="h6" gutterBottom>
Words to play: {state.observedWordsString.join(", ")}
</Typography>
</Grid>
</Grid>
<Grid item>
<Typography variant="h5">
Game score:
{props.score}
</Typography>
<Typography variant="h6">
Hand score:
{state.score}
</Typography>
<Button
variant="contained"
color="primary"
onClick={props.handleViewBag}
>
View bag
</Button>
</Grid>
</Grid>
</Grid>
</div>
<div className={classes.board}>
{state.letters.map(letter => (
<Tile {...letter} onChange={handleTileChange} key={letter.id} />
))}
</div>
<div className={classes.gameOptions}>
<Grid container spacing={2}>
<Grid item xs={6}>
<Button
variant="contained"
color="primary"
className={classes.button}
onClick={props.handlePlayRound}
value={JSON.stringify(state)}
>
Play round
</Button>
</Grid>
<Grid item xs={6}>
<Button
variant="contained"
color="secondary"
className={classes.button}
onClick={props.handleEndGame}
>
End game
</Button>
</Grid>
</Grid>
<Grid container spacing={2}>
<Grid item xs={6}>
<Button
variant="contained"
className={classes.button}
onClick={props.handleViewSolution}
>
View solution
</Button>
</Grid>
<Grid item xs={6}>
<Button
variant="contained"
className={classes.button}
onClick={props.handleSaveGame}
>
Save game
</Button>
</Grid>
</Grid>
</div>
</>
);
};
export default Board;
<file_sep>/README.md
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.
The project will be available by default from http://localhost:3000.
### `npm test`
Launches the test runner in the interactive watch mode.
The current available test check for: "solution finding" and "optimal solution building".
### `npm run build`
Builds the app for production to the `build` folder.
A deployed/production copy of the app is available from https://sort-of-scrabble.herokuapp.com/
## Requirement Fulfillment
### 1.1 As a player, I need to be able to know the hand when a new game starts.
A user begins at the menu screen where they will be presented with the option to play a "new game" or to launch a game from history.

When entering a "new game" the user will have the option to launch the game with a typical scrabble bag or customise the bag, this is particularly useful for games where only one "hand" is meant to be played.


Once in the game the user will be presented with their current "hand" which they can the use to start forming words. Note that this initial starting hand is what will be recorded for "replaying" games.

### 1.2 As a player, I need to be able to end the game.
When entering the game the player will also have access to a lower tab containing "game options" which will allow them to perform various game actions including "playing round/hand", "viewing solution", "ending the game" and "saving the game". The user is free to exit the game at any time by clicking the "End game" option, which will then present them with the "end game" modal which presents them with the total score and the words played throughout the game. The modal also offers the option to return back to the menu screen as well as the option to save the game to "history".

### 1.3 As a player, I need to be able to know the total number of points I have earned when the game ends.
Same as 1.2.
### 2.1 As a player, I need to be able to see my hand throughout the game.
The player's hand is presented as tiles (like in scabble/words with friends) on a "free" board which allows the players to drag and drop tiles freely in order to create words. When a user "plays" a hand the tiles/letters used in the words played will be removed and replaced with new tiles/letters (the players hand is "shuffled" when this occurs) from the "bag" this process continues until there are no letters left in the bag or the game detects that there are no longer any words which can be played.

### 2.2 As a player, I need to be able to see how many points I earn when I submit a word.
When forming words, the game actively tracks what words are being formed by the player and will stage valid words detected to be played in "round". The score of these staged words are calculated and presented in the top right hand corner of the game screen in the "game options" tab.
### 2.3 As a player, I need to be able to see how many points I have earned throughout the game.
As an extension of 2.2 when a round is "played" the score of the valid words is added to the running game score as well as a record of the words played.

### 2.4 As a player, I need to be able to replay a game with the same initial hand as a new game if I desire.
Throughout the game and in in the end game modal there is the option to "save the game" which makes a record of the gameId, Date and starting hand in the browsers localstorage. To replay a "saved" game the user can navigate through the history screen which has a record of the current saved games on the browser. The option to "play" a saved game will launch a new game keeping the starting hand and updates the "bag" to match.

### 2.5 As a player, I need to be informed when I run out of letters in my hand.
The user is free to rearrange the letters in the hand to make words for the current hand and can use the "view bag" option to view the remaining letters left in the bag that are still to be played. When the user has exhausted the bag or has reached a state which the game identifies is no longer playable (has a hand of "QQQQQQQ") the game will automatically transition the player onto the end game modal.

### 3.1 As a player, at the end of a game, I need to be able to know what the optimal outcome of the game\* is if I desire.
The "View solution" option is available to users who wish to see the current optimal solution for their current hand. Using a filter stratergy the game will devise an optimal solution which returns the highest score. The type of solution can include a single word or combination of words depending on the hand. Whilst there maybe multiple combinations which deliver the highest score (tar/rat return the same score), the game simply returns the one it sees first (i.e. only on will be presented).

<file_sep>/src/components/history.js
import React from "react";
import moment from "moment";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
const useStyles = makeStyles(theme => ({
"@global": {
body: {
backgroundColor: theme.palette.common.white
}
},
paper: {
marginTop: theme.spacing(30),
display: "flex",
flexDirection: "column",
alignItems: "center"
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(6)
},
submit: {
margin: theme.spacing(3, 0, 2)
}
}));
const History = props => {
const classes = useStyles();
const values = [];
const keys = Object.keys(localStorage);
for (let i = 0; i < keys.length; i += 1) {
if (keys[i].split("-")[0] === "WG") {
const fromStorgae = JSON.parse(localStorage.getItem(keys[i]));
values.push(fromStorgae);
}
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h3">
History
</Typography>
<form className={classes.form} noValidate>
<Grid container spacing={2}>
<Grid item xs={3}>
<h4>Date:</h4>
</Grid>
<Grid item xs={3}>
<h4>ID:</h4>
</Grid>
<Grid item xs={3}>
<h4>Hand:</h4>
</Grid>
<Grid item xs={3} />
</Grid>
{values.map(element => (
<Grid container spacing={2} key={element.id}>
<Grid item xs={3}>
{`${element.id.substring(0, 5)}...`}
</Grid>
<Grid item xs={3}>
{moment(element.date).format("DD-MM-YYYY")}
</Grid>
<Grid item xs={3}>
{element.startingHand.join("").toUpperCase()}
</Grid>
<Grid item xs={3}>
<Button
fullWidth
variant="contained"
color="secondary"
name="game"
value={element.startingHand}
onClick={props.handleEvent}
>
Play
</Button>
</Grid>
</Grid>
))}
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
name="menu"
onClick={props.handleEvent}
>
Back to menu
</Button>
</form>
</div>
</Container>
);
};
export default History;
|
5c08d5c6ef90f405c4052677af45428d7aea4bd8
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
jueyaye/SortOfScrabble
|
3cb62e5c32c1fb2309e1ffbb289cfd5ea708c018
|
d1073f36e33c5fbf503e0d1481657766e9a0aea0
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <conio.h>
#include <random>
#include <time.h>
void main()
{
int a[10];
int d;
srand(time(NULL));
for(int i=0;i<10;++i)
{
a[i]=rand()%200;
}
bool fl;
fl=true;
while(fl)
{
fl=false;
for(int i=0;i<9;++i)
{
if(a[i]<a[i+1])
{
fl=true;
d=a[i];
a[i]=a[i+1];
a[i+1]=d;
}
}
}
for(int i=0;i<10;++i)
{
printf("%d ",a[i]);
}
getch();
}
|
de87917e08f86cba88a0dc7b661ff028b9e74d6c
|
[
"C++"
] | 1 |
C++
|
usern999/sortf
|
43674e5decece389f73c07ce2a4fdb424b9127f0
|
3030844e9022a12e878b433ad758cf0cb3d7da55
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Graduation Projects Space | <?php if (isset($page_title)) echo $page_title; ?><</title>
<link rel="shortcut icon" href="img/favicon.ico">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="./css/style.css" type="text/css" />
<script type="text/javascript" src="./js/javascript.js"></script>
</head>
<body>
<div class="container">
<section class="menu">
<div class="menu-content">
<div class="logo">
<a href="#"><img src="img/logos/logo-dark.png"/></a>
</div>
<ul class="user_menu">
<?php if (isset($user_name) && $user_name == 'Admin') { ?>
<li><a href="admin_page.php">ADMIN</a></li>
<li><a href="add_project.php">ADD PROJECT</a></li>
<li><a href="index.php">LOGOUT</a></li>
<?php } else { ?>
<li><a href="login.php">LOGIN</a></li>
<?php } ?>
</ul>
<ul id="menu">
<li><a href="index.php">HOME</a></li>
<li><a href="departments.php">DEPARTMENTS</a></li>
<li><a href="about.php">ABOUT</a></li>
<li><a href="contact.php">CONTACT</a></li>
</ul>
</div>
</section><file_sep><?php $page_title = "Departments"; ?>
<?php include "include/header.php" ?>
<?php include_once('include/db_conn.php'); ?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>Departments</span></h1>
</div>
</div>
</section>
<section class="departments" id="departments">
<h2 class="title">College of Computers and Information Technology</h2>
<hr/>
<div class="column-one" onclick="window.location.href='projects.php?d=1'">
<div class="circle-one"></div>
<h2>IT</h2>
<p>Information Technology</p>
</div>
<div class="column-two" onclick="window.location.href='projects.php?d=2'">
<div class="circle-two"></div>
<h2>CS</h2>
<p>Computer Science</p>
</div>
<div class="column-three" onclick="window.location.href='projects.php?d=3'">
<div class="circle-three"></div>
<h2>CE</h2>
<p>Computer Engineering</p>
</div>
</section>
<?php include "include/footer.php" ?>
<file_sep><?php $page_title = "Contact"; ?>
<?php include "include/header.php" ?>
<?php include_once('include/db_conn.php'); ?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>Contact Us</span></h1>
</div>
</div>
</section>
<section class="form_content" id="contact">
<img src="img/background/contact.jpg"/>
<div class="content">
<h1>Contact</h1>
<hr/>
<div class="form">
<form action="#" method="post" enctype="text/plain">
<input name="your-name" id="your-name" placeholder="YOUR NAME" />
<input name="your-email" id="your-email" placeholder="YOUR E-MAIL" />
<textarea id="message" name="message" placeholder="MESSAGE"></textarea>
<a href="#">
<div class="button">
<span>SEND</span>
</div>
</a>
</form>
</div>
</div>
</section>
<?php include "include/footer.php" ?>
<file_sep><?php
include_once 'dbsettings.php';
$conn=false;
$message = "";
function conndb() {
global $conn, $dbserver, $dbname, $dbpassword, $dbusername;
global $message;
$conn = mysqli_connect($dbserver, $dbusername, $dbpassword);
if (!$conn)
$message = "Cannot connect to server";
else if (!@mysqli_select_db($conn, $dbname))
$message = "Cannot select database";
if ($message)
die($message);
}
function executeQuery($query) {
global $conn;
if(!$conn)
conndb();
$result = mysqli_query($conn, $query);
closedb();
if(!$result)
$message = "Error while executing query.<br/>Mysql Error: " . mysqli_error($conn);
else
return $result;
}
function closedb() {
global $conn;
if(!$conn)
mysqli_close($conn);
}
?>
<file_sep><?php $page_title = "Edit Project"; ?>
<?php $user_name = "Admin"; ?>
<?php include "include/header.php"; ?>
<?php include_once('include/db_conn.php'); ?>
<?php
$message = "";
function uplouadImage($target_dir, $file) {
global $message ;
$target_file = strtolower ($target_dir . basename($file["name"]));
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($file["tmp_name"]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$message .= "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$message .= "Sorry, file already exists.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$message .= "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$message .= "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($file["tmp_name"], $target_file)) {
//echo "The file ". basename( $file["name"]). " has been uploaded.";
return $target_file;
} else {
$message .= "Sorry, there was an error uploading your file.";
}
}
}
function uplouadFile($target_dir, $file) {
global $message;
$target_file = strtolower ($target_dir . basename($file["name"]));
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
$message .= "Sorry, file already exists.";
$uploadOk = 0;
}
// Allow certain file formats
if($fileType != "pdf") {
$message .= "Sorry, only PDF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$message .= "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($file["tmp_name"], $target_file)) {
//echo "The file ". basename( $file["name"]). " has been uploaded.";
return $target_file;
} else {
$message .= "Sorry, there was an error uploading your file.";
}
}
}
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
global $message ;
if (isset($_POST['id']) && isset($_POST['name']) && isset($_POST['supervisor'])) {
conndb();
$id = mysqli_real_escape_string($conn, $_POST['id']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$supervisor = mysqli_real_escape_string($conn, $_POST['supervisor']);
$description = "";
$book_cover = "";
if (isset($_POST['description']))
$description = $_POST['description'];
$query = "update project set name = '$name', supervisor = '$supervisor', description = '$description' where id = '$id';";
$result = executeQuery($query);
if(!$result)
$message .= "Error while executing query.<br/>Mysql Error: " . mysqli_error($conn);
else {
$message .= "The project has been updated.";
}
closedb();
} else {
$message .= "Please fill all required fileds.";
}
}
?>
<?php
if (!isset($_REQUEST['id'])) {
header('Location:admin_page.php');
}
$id = $_REQUEST['id'];
$result = executeQuery("select * from project where id = $id;");
if (!$result)
header('Location:admin_page.php');
$project = mysqli_fetch_array($result)
?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>Edit Project</span></h1>
</div>
</div>
</section>
<section class="form_content" id="login" style="padding: 20px 0;">
<div class="content">
<h1>Edit Project</h1>
<hr/>
<div class="form">
<form id="edit_project" action="edit_project.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id" name="id" value="<?php echo $project['id']; ?>">
<input name="name" id="name" value="<?php echo $project['name']; ?>" />
<input name="supervisor" id="supervisor" value="<?php echo $project['supervisor']; ?>" />
<textarea id="description" name="description" value="<?php echo $project['description']; ?>"></textarea>
<?php
if(!empty($message)) {
echo "<div class=\"message\">" . $message . "</div>";
}
?>
<a href="#" onclick="document.getElementById('edit_project').submit()">
<div class="button">
<span>Edit</span>
</div>
</a>
</form>
</div>
</div>
</section>
<?php include "include/footer.php" ?><file_sep><?php $page_title = "Projects"; ?>
<?php include "include/header.php" ?>
<?php include_once('include/db_conn.php'); ?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>projects</span></h1>
</div>
</div>
</section>
<?php
if (isset($_REQUEST['id'])) {
$id = $_REQUEST['id'];
$result = executeQuery("select * from project where id = $id;");
if ($result) {
$r = mysqli_fetch_array($result);
?>
<section class="page-content" id="page-content">
<h2 class="title"><?php echo $r['name']; ?></h2><hr>
<img src="<?php echo $r['image']; ?>" alt="<?php echo $r['name']; ?>" />
<h3 class="title">Supervisor</h3>
<p>
<?php echo $r['supervisor']; ?>
</p>
<h3 class="title">Description</h3>
<p>
<?php echo $r['description']; ?>
</p>
<h3 class="title">Download</h3>
<p>
<a href="<?php echo $r['file']; ?>"> Project Document </a>
</p>
</section>
<?php
}
}
?>
<?php include "include/footer.php" ?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 25, 2020 at 02:46 AM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.2.28
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `graduation_projects_space`
--
-- --------------------------------------------------------
--
-- Table structure for table `department`
--
CREATE TABLE `department` (
`id` int(11) NOT NULL,
`code` varchar(10) NOT NULL,
`name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `department`
--
INSERT INTO `department` (`id`, `code`, `name`) VALUES
(1, 'IT', 'Information Technolog'),
(2, 'CS', 'Computer Science\r\n'),
(3, 'CE', 'Computer Engineering\r\n\r\n');
-- --------------------------------------------------------
--
-- Table structure for table `project`
--
CREATE TABLE `project` (
`id` int(11) NOT NULL,
`department_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`supervisor` varchar(100) NOT NULL,
`description` varchar(1000) DEFAULT NULL,
`image` varchar(255) DEFAULT NULL,
`file` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `project`
--
INSERT INTO `project` (`id`, `department_id`, `name`, `supervisor`, `description`, `image`, `file`) VALUES
(1, 1, 'Project 1', 'Supervisor 1', 'Project 1', 'img/projects/01.jpg', 'files/projects/01.pdf'),
(2, 1, 'Project 2', 'Supervisor 1', 'Project 2', 'img/projects/02.jpg', 'files/projects/02.pdf'),
(3, 1, 'Project 3', 'Supervisor 1', 'Project 3', 'img/projects/03.jpg', 'files/projects/03.pdf'),
(4, 2, 'Project 4', 'Supervisor 2', 'Project 4', 'img/projects/04.jpg', 'files/projects/04.pdf'),
(5, 2, 'Project 5', 'Supervisor 2', 'Project 5', 'img/projects/05.jpg', 'files/projects/05.pdf'),
(6, 2, 'Project 6', 'Supervisor 2', 'Project 6', 'img/projects/06.jpg', 'files/projects/06.pdf'),
(7, 3, 'Project 7', 'Supervisor 3', 'Project 7', 'img/projects/07.jpg', 'files/projects/07.pdf'),
(8, 3, 'Project 8', 'Supervisor 3', 'Project 8', 'img/projects/08.jpg', 'files/projects/08.pdf'),
(9, 3, 'Project 9', 'Supervisor 3', 'Project 9', 'img/projects/09.jpg', 'files/projects/09.pdf');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id`, `username`, `password`, `name`, `email`) VALUES
(1, 'admin', '<PASSWORD>', '', '<EMAIL>');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `department`
--
ALTER TABLE `department`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `project`
--
ALTER TABLE `project`
ADD PRIMARY KEY (`id`),
ADD KEY `instructor_id` (`department_id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`),
ADD UNIQUE KEY `email` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `department`
--
ALTER TABLE `department`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `project`
--
ALTER TABLE `project`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `project`
--
ALTER TABLE `project`
ADD CONSTRAINT `project_ibfk_1` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php $page_title = "Delete Project"; ?>
<?php $user_name = "Admin"; ?>
<?php include "include/header.php"; ?>
<?php include_once('include/db_conn.php'); ?>
<?php
$message = "";
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
global $message ;
if (isset($_POST['id']) && isset($_POST['name']) && isset($_POST['supervisor'])) {
conndb();
$id = mysqli_real_escape_string($conn, $_POST['id']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$supervisor = mysqli_real_escape_string($conn, $_POST['supervisor']);
$description = "";
$book_cover = "";
if (isset($_POST['description']))
$description = $_POST['description'];
$query = "update project set name = '$name', supervisor = '$supervisor', description = '$description' where id = '$id';";
$result = executeQuery($query);
if(!$result)
$message .= "Error while executing query.<br/>Mysql Error: " . mysqli_error($conn);
else {
$message .= "The project has been updated.";
}
closedb();
} else {
$message .= "Please fill all required fileds.";
}
}
?>
<?php
if (!isset($_REQUEST['id'])) {
header('Location:admin_page.php');
}
$id = $_REQUEST['id'];
$result = executeQuery("delete from project where id = $id;");
if(!$result)
$message .= "Error while executing query.<br/>Mysql Error: " . mysqli_error($conn);
else {
$message .= "The project has been deleted.";
}
?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>Delete Project</span></h1>
</div>
</div>
</section>
<section class="form_content" id="login" style="padding: 20px 0;">
<div class="content">
<h1>Delete Project</h1>
<hr/>
<div class="form">
<?php
if(!empty($message)) {
echo "<div class=\"message\">" . $message . "</div>";
}
?>
</div>
</div>
</section>
<?php include "include/footer.php" ?><file_sep><?php $page_title = "Home"; ?>
<?php include "include/header.php" ?>
<?php include_once('include/db_conn.php'); ?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1>Welcome to<br/>
<span>Graduation Projects Space</span></h1>
</div>
</div>
</section>
<section class="departments" id="departments">
<h2 class="title">College of Computers and Information Technology</h2>
<hr/>
<div class="column-one" onclick="window.location.href='projects.php?d=1'">
<div class="circle-one"></div>
<h2>IT</h2>
<p>Information Technology</p>
</div>
<div class="column-two" onclick="window.location.href='projects.php?d=2'">
<div class="circle-two"></div>
<h2>CS</h2>
<p>Computer Science</p>
</div>
<div class="column-three" onclick="window.location.href='projects.php?d=3'">
<div class="circle-three"></div>
<h2>CE</h2>
<p>Computer Engineering</p>
</div>
</section>
<div class="clear"></div>
<section class="projects" id="projects">
<div class="projects-margin">
<h1>projects</h1>
<hr/>
<?php
$result = executeQuery("select * from project;");
?>
<ul class="grid">
<?php while ($result && $r = mysqli_fetch_array($result)) {?>
<li>
<a href="project_details.php?id=<?php echo $r['id']; ?>">
<img src="<?php echo $r['image']; ?>" alt="<?php echo $r['name']; ?>" />
<div class="text">
<p><?php echo $r['name']; ?></p>
</div>
</a>
</li>
<?php } ?>
</ul>
<div class="clear"></div>
<a href="projects.php"><div class="read-more">more projects</div></a>
</div>
</section>
<div class="clear"></div>
<section class="form_content" id="contact">
<img src="img/background/contact.jpg"/>
<div class="content">
<h1>contact</h1>
<hr/>
<div class="form">
<form action="#" method="post" enctype="text/plain">
<input name="your-name" id="your-name" placeholder="YOUR NAME" />
<input name="your-email" id="your-email" placeholder="YOUR E-MAIL" />
<textarea id="message" name="message" placeholder="MESSAGE"></textarea>
<a href="#">
<div class="button">
<span>SEND</span>
</div>
</a>
</form>
</div>
</div>
</section>
<?php include "include/footer.php" ?>
<file_sep><?php $page_title = "Add Project"; ?>
<?php $user_name = "Admin"; ?>
<?php include "include/header.php"; ?>
<?php include_once('include/db_conn.php'); ?>
<?php
$message = "";
function uplouadImage($target_dir, $file) {
global $message ;
$target_file = strtolower ($target_dir . basename($file["name"]));
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($file["tmp_name"]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$message .= "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$message .= "Sorry, file already exists.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$message .= "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$message .= "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($file["tmp_name"], $target_file)) {
//echo "The file ". basename( $file["name"]). " has been uploaded.";
return $target_file;
} else {
$message .= "Sorry, there was an error uploading your file.";
}
}
}
function uplouadFile($target_dir, $file) {
global $message;
$target_file = strtolower ($target_dir . basename($file["name"]));
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
$message .= "Sorry, file already exists.";
$uploadOk = 0;
}
// Allow certain file formats
if($fileType != "pdf") {
$message .= "Sorry, only PDF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$message .= "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($file["tmp_name"], $target_file)) {
//echo "The file ". basename( $file["name"]). " has been uploaded.";
return $target_file;
} else {
$message .= "Sorry, there was an error uploading your file.";
}
}
}
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
global $message ;
if (isset($_POST['department_id']) && isset($_POST['name']) && isset($_POST['supervisor']) && isset($_FILES["image"]["name"]) && isset($_FILES["file"]["name"])) {
conndb();
$department_id = mysqli_real_escape_string($conn, $_POST['department_id']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$supervisor = mysqli_real_escape_string($conn, $_POST['supervisor']);
$description = "";
$book_cover = "";
$target_dir = "img/projects/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
if ($_FILES["image"]["tmp_name"] != "") {
$image_name = uplouadImage($target_dir, $_FILES["image"]);
}
$target_dir = "files/projects/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if ($_FILES["file"]["tmp_name"] != "") {
$file_name = uplouadFile($target_dir, $_FILES["file"]);
}
$message = $message . "hhhh.";
if (!empty($image_name) && !empty($file_name)) {
if (isset($_POST['description']))
$description = $_POST['description'];
$query = "insert into project (department_id, name, supervisor, description, image, file) values ('$department_id', '$name', '$supervisor', '$description', '$image_name', '$file_name');";
$result = executeQuery($query);
$id = mysqli_insert_id ($conn);
if(!$result)
$message .= "Error while executing query.<br/>Mysql Error: " . mysqli_error($conn);
else {
$message .= "The project has been added.";
}
closedb();
} else {
$message = $message . "You must upload project image and file.";
}
} else {
$message .= "Please fill all required fileds.";
}
}
?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>Add Project</span></h1>
</div>
</div>
</section>
<section class="form_content" id="login" style="padding: 20px 0;">
<div class="content">
<h1>Add Project</h1>
<hr/>
<div class="form">
<form id="add_project" action="add_project.php" method="post" enctype="multipart/form-data">
<select class="text-field" name="department_id" id="department_id" placeholder="Project Supervisor">
<option selected value="<Choose Department>">Choose Department</option>
<?php
$departments = executeQuery("SELECT * FROM department;");
while ($department = mysqli_fetch_array($departments))
{
$name = $department['code'] . " " . $designer['name'] . " ";
echo "<option value=\"" . $department['id'] . "|" . $name . "\">" . $name . "</option>";
}
closedb();
?>
</select>
<input name="name" id="name" placeholder="Project Name" />
<input name="supervisor" id="supervisor" placeholder="Project Supervisor" />
<label class="field-label" for="image">Image</label>
<input type="file" name="image" id="image" />
<label class="field-label" for="file">File</label>
<input type="file" name="file" id="file" />
<textarea id="description" name="description" placeholder="Description"></textarea>
<?php
if(!empty($message)) {
echo "<div class=\"message\">" . $message . "</div>";
}
?>
<a href="#" onclick="validateProjectForm(); document.getElementById('add_project').submit()">
<div class="button">
<span>Add</span>
</div>
</a>
</form>
</div>
</div>
</section>
<?php include "include/footer.php" ?><file_sep>
<?php
$dbserver="localhost";
//username of the MySQL server
$dbusername="root";
//password
$dbpassword="";
//database name
$dbname="graduation_projects_space";
?>
<file_sep><?php $page_title = "Admin"; ?>
<?php $user_name = "Admin"; ?>
<?php include "include/header.php" ?>
<?php include_once('include/db_conn.php'); ?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>projects</span></h1>
</div>
</div>
</section>
<section class="projects" id="projects">
<div class="projects-margin">
<?php
if (isset($_REQUEST['d']) && $_REQUEST['d'] >= 1 && $_REQUEST['d'] <= 3) {
$id = $_REQUEST['d'];
$result = executeQuery("select * from project where department_id = $id;");
if ($id == 1)
echo '<h1>IT projects</h1>';
else if ($id == 2)
echo '<h1>CS projects</h1>';
else
echo '<h1>CE projects</h1>';
}
else {
$result = executeQuery("select * from project;");
echo '<h1>projects</h1>';
}
?>
<hr/>
<ul class="grid">
<?php while ($result && $r = mysqli_fetch_array($result)) {?>
<li>
<a href="#">
<img src="<?php echo $r['image']; ?>" alt="<?php echo $r['name']; ?>" />
<div class="text">
<p><?php echo $r['name']; ?></p>
<p style="color:#333"><a style="color:#333" href="edit_project.php?id=<?php echo $r['id']; ?>"> Edit </a> | <a style="color:#f66"href="delete_project.php?id=<?php echo $r['id']; ?>"> Delete </a> </p>
</div>
</a>
</li>
<?php } ?>
</ul>
<div class="clear"></div>
</div>
</section>
<?php include "include/footer.php" ?>
<file_sep><?php $page_title = "Login"; ?>
<?php include "include/header.php" ?>
<?php include_once('include/db_conn.php'); ?>
<?php
$message = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['username']) && isset($_POST['password'])) {
conndb();
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$password= md5($password);
$query = "select * from user where username='$username' and password='$password' ";
$result = executeQuery($query);
closedb();
if($result && mysqli_num_rows($result) > 0){
$user = mysqli_fetch_array($result);
header('Location:admin_page.php');
exit;
} else {
$message = "Username or password is wrong";
}
} else {
$message = "Please fill all required fileds.";
}
}
?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>Login</span></h1>
</div>
</div>
</section>
<section class="form_content" id="login" style="padding: 20px 0;">
<div class="content">
<h1>Login</h1>
<hr/>
<div class="form">
<form id="login-form" action="login.php" method="post" enctype="multipart/form-data">
<input name="username" id="username" placeholder="Username" />
<input type="<PASSWORD>" name="password" id="password" placeholder="<PASSWORD>" />
<?php
if(!empty($message)) {
echo "<div class=\"message\">" . $message . "</div>";
}
?>
<a href="#" onclick="document.getElementById('login-form').submit()">
<div class="button">
<span>Login</span>
</div>
</a>
</form>
</div>
</div>
</section>
<?php include "include/footer.php" ?>
<file_sep><?php $page_title = "About"; ?>
<?php include "include/header.php" ?>
<?php include_once('include/db_conn.php'); ?>
<section class="page-header" id="home">
<div class="opacity"></div>
<div class="content">
<div class="text">
<h1><br><span>About Us</span></h1>
</div>
</div>
</section>
<section class="page-content" id="page-content">
<h2 class="title">About University</h2><hr>
<h3 class="title">History of the College</h3>
<p>
The study started in the computer department in the first semester 20 / 1421H as one of the departments within the Faculty of Science. Whereas, the Government of the Custodian of the Two Holy Mosques has directed the establishment of a College of Computer Science and Engineering in all parts of the Kingdom to create a generation of specialists in these fields. The College has three sections: - Computer Science - Computer Engineering - information technology The actual study began with the beginning of the first semester of the academic year 1426-1427 AH. All students study a preparatory year for two semesters, and then students specialize in one of the three departments of the college, where the study continues for another four years.
</p>
<h3 class="title">Mission</h3>
<p>
To provide distinguished academic, research and consulting programs in the fields of computers and IT to deliver qualified specialists for community and human services.
</p>
<h3 class="title">Vision</h3>
<p>
To be pioneer in providing qualified specialists and distinguished scientific researches for serving the community in computers and IT fields.
</p>
</section>
<?php include "include/footer.php" ?>
|
db798f584fba0244a1e0891473a2c81e09e95332
|
[
"SQL",
"PHP"
] | 14 |
PHP
|
shatha-km1420/graduation-projects
|
cbf5ec25e149aa809033545a921382fc4808c9d1
|
4f8f5777328d0499eaf6b36e7fc357e250449cc4
|
refs/heads/master
|
<repo_name>calimax/node-por-hacer<file_sep>/app.js
//const argv = require('yargs').argv;
const { argv } = require('./config/yargs');
const { add, getListado, setUpdate, setDelete } = require('./por-hacer/por-hacer');
//console.log(argv)
let comando = argv._[0]
switch (comando) {
case 'save':
let task = add(argv.d);
console.log('Por hacer:', task.descripcion);
break;
case 'listar':
getListado();
break;
case 'update':
let actulizado = setUpdate(argv.d, argv.c);
console.log('Actualizar una tareaPor hacer:', actulizado);
break;
case 'delete':
let del = setDelete(argv.d);
console.log(del);
break;
default:
console.log('Comando no reconocido');
}
|
214ceb7ea971cb58259f716d9a7ec6b57e1398df
|
[
"JavaScript"
] | 1 |
JavaScript
|
calimax/node-por-hacer
|
982872e86bb4318cddd47ddcfcf799461ca36697
|
1c5152fa2dfdcf22df8c5e2bd7d846eead8f4e1b
|
refs/heads/master
|
<file_sep>import pytest
from app.models import User
from app import app
def test_new_user(new_user):
assert new_user.username == 'pytest'
assert new_user.password_hash != '<PASSWORD>'
assert new_user.twofactorauth != '1<PASSWORD>'
assert not new_user.authenticated
def test_home_page(test_client):
response = test_client.get("/")
assert response.status_code == 302
def test_login_page(test_client):
response = test_client.get("/login")
assert response.status_code == 200
assert b"Login" in response.data
assert b"Username" in response.data
def test_login(test_client):
response = test_client.post("/login",
data=dict(username="danny", password="<PASSWORD>", twofactorauth="<PASSWORD>"),
follow_redirects=True)
assert b"success" in response.data
def test_registration_page(test_client):
response = test_client.get("/register")
assert response.status_code == 200
assert b"Register" in response.data
assert b"Username" in response.data
assert b"2fa" in response.data
def test_registration(test_client):
response = test_client.post("/register",
data=dict(username="danny", password="<PASSWORD>", twofactorauth="<PASSWORD>"),
follow_redirects=True)
assert b"success" in response.data
<file_sep>alembic==1.2.1
attrs==19.3.0
Click==7.0
filelock==3.0.12
Flask==1.1.1
Flask-Login==0.4.1
Flask-Migrate==2.5.2
Flask-SQLAlchemy==2.4.1
Flask-WTF==0.14.2
importlib-metadata==0.23
itsdangerous==1.1.0
Jinja2==2.10.3
Mako==1.1.0
MarkupSafe==1.1.1
more-itertools==8.0.2
packaging==19.2
pkg-resources==0.0.0
pluggy==0.13.1
py==1.8.0
pyparsing==2.4.5
pytest==5.3.1
python-dateutil==2.8.0
python-dotenv==0.10.3
python-editor==1.0.4
six==1.13.0
SQLAlchemy==1.3.10
toml==0.10.0
tox==3.14.0
tox-travis==0.12
virtualenv==16.7.6
wcwidth==0.1.7
Werkzeug==0.16.0
WTForms==2.2.1
zipp==0.6.0
<file_sep>import datetime
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from app import login
from app import db
db.create_all()
@login.user_loader
def load_user(id):
return User.query.get(int(id))
class User(UserMixin, db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
twofactorauth = db.Column(db.String(64), index=True)
password_hash = db.Column(db.String(128))
def __init__(self, username, password, twofactorauth):
self.username = username
self.password_hash = generate_password_hash(password)
self.twofactorauth = twofactorauth
self.authenticated = False
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def userid(self):
return self.username
def __repr__(self):
return '{}'.format(self.username)
class SpellCheckHistory(db.Model):
id = db.Column(db.Integer, primary_key=True)
query_spelling = db.Column(db.Text())
store_spell_results = db.Column(db.Text())
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
user = db.relationship("User")
def permission_allowed(self, user):
if self.user == user or str(user) == "admin":
return True
return False
class UserHistory(db.Model):
id = db.Column(db.Integer, primary_key=True)
action = db.Column(db.String(80))
action_time = db.Column(db.DateTime, default=datetime.datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
user = db.relationship("User")
<file_sep>from flask import render_template, Flask, redirect, url_for, flash, request, Markup, abort
from app import app, db, models
from app.forms import LoginForm, RegistrationForm, Spell_Checker, SearchUsersForm
from flask_login import LoginManager, current_user, login_user, login_required, logout_user
from app.models import User, SpellCheckHistory, UserHistory
import flask
import subprocess
import os
basedir = os.path.abspath(os.path.dirname(__file__))
login_manager = LoginManager(app)
login_manager.init_app(app)
login_manager.session_protection = "strong"
@login_manager.user_loader
def user_loader(user_id):
return User.query.get(user_id)
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
user_2fa = User.query.filter_by(twofactorauth=form.twofactorauth.data).first()
if user is None or not user.check_password(form.password.data) or user_2fa is None:
flash(Markup('Invalid username, password or 2FA verification <li class="danny" id="result">failed</li>'))
return redirect(url_for('login'))
user.authenticated = True
login_user(user, remember=form.remember_me.data)
flash(Markup('Logged in successfully. <li class="danny" id="result"> success </li>'))
log_login = UserHistory(action="login", user=current_user)
db.session.add(log_login)
db.session.commit()
return redirect(url_for('spell_checker'))
return render_template('login.html', title='Sign In', user_search=str(current_user), form=form)
@app.route('/spell_check', methods=['GET', 'POST'])
def spell_checker():
if not current_user.is_authenticated:
return redirect(url_for('login'))
form = Spell_Checker()
if request.method == "POST":
if form.validate_on_submit():
f = open("check.txt", "w")
f.write(form.spellchecker.data)
f.close()
proc2 = subprocess.Popen(basedir + '/a.out check.txt wordlist.txt', stdin=None,
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc3 = proc2.stdout
output = None
for words in proc3:
words = words.decode("utf-8").split()
for word in words:
if output is None:
output = word
else:
output = output + ", " + word
if output is None:
output = "There are no misspelled words"
flash(Markup('<li id=textout>The incorrect words are: </li><li id="misspelled">' + output + ' </li>'))
save_SpellCheckHistory = SpellCheckHistory(query_spelling=form.spellchecker.data, store_spell_results=output, user=current_user)
db.session.add(save_SpellCheckHistory)
db.session.commit()
return render_template("spell_check.html", title="Spell Checker", user_search=str(current_user), form=form)
if request.method == "GET":
saved_SpellCheckHistory = SpellCheckHistory.query.filter_by(user_id=current_user.id).first()
retrieved_data = getattr(saved_SpellCheckHistory, "query_spelling", None)
login_success = request.args.get("login_success")
return render_template("spell_check.html", title="Spell Check", user_search=str(current_user), form=form, input_data=retrieved_data, login_success=True,)
@app.route('/logout')
@login_required
def logout():
user=current_user
log_logout = UserHistory(action="logout", user=user)
db.session.add(log_logout)
db.session.commit()
logout_user()
return redirect(url_for('login'))
@app.route('/')
@app.route('/index')
def index():
return render_template("index.html", title='Home Page', user_search=str(current_user), )
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
flash('Already registered!')
return redirect(url_for('index'))
form = RegistrationForm()
if request.method == 'POST' and form.validate_on_submit():
user = models.User(username=form.username.data, twofactorauth=form.twofactorauth.data, password=form.password.data)
user.authenticated = True
db.session.add(user)
db.session.commit()
flash(Markup('Registered successfully. <li id="success"> success </li>'))
return redirect(url_for('login'))
return render_template('register.html', title='Register', user_search=str(current_user), form=form)
@app.route("/history", methods=["GET", "POST"])
@app.route("/history/query<query_id>")
@login_required
def history(query_id=None):
if not current_user.is_authenticated:
return redirect(url_for('login'))
form = SearchUsersForm()
if request.method == "GET":
spellcheck_query = SpellCheckHistory.query.filter_by(user_id=current_user.id).all()
count = len(spellcheck_query)
if query_id is not None:
query = SpellCheckHistory.query.filter_by(id=query_id).first()
if not query.permission_allowed(current_user):
abort(403)
else:
query = None
return render_template("history.html", queries=spellcheck_query, count=count,
query_id=query_id,
user_search=current_user,
user=current_user,
query=query,
form=form,)
if request.method == "POST":
if str(current_user) != "admin":
abort(403)
if form.validate_on_submit():
user_search = User.query.filter_by(username=form.username.data).first()
user_history = SpellCheckHistory.query.filter_by(user_id=user_search.id)
return render_template(
"history.html",
queries=user_history,
count=len(user_history.all()),
user_search=user_search,
query_id=query_id,
user=current_user,
query=user_history,
form=form,)
@app.route("/login_history", methods=["GET", "POST"])
@login_required
def login_history():
if str(current_user) != "admin":
abort(403)
form = SearchUsersForm()
if request.method == "GET":
return render_template("login_history.html", user_search=current_user, user=current_user, form=form,)
if request.method == "POST":
if form.validate_on_submit():
user_search = User.query.filter_by(username=form.username.data).first()
user_search_history = UserHistory.query.filter_by(user_id=user_search.id).all()
return render_template("login_history.html", user_search=current_user, user=current_user, queries=user_search_history, form=form,)
<file_sep>from setuptools import find_packages, setup
setup(
name="tox_testing_appsec2",
version="0.0.1",
description = "For Assignments in CS-GY9163: Application Security",
packages=find_packages(),
)
<file_sep>import pytest
from app.models import User
from app import app
@pytest.fixture(scope='module')
def new_user():
app.config["WTF_CSRF_ENABLED"] = False
user = User('pytest', '1234', '12345')
return user
@pytest.fixture(scope='module')
def test_client():
app.config["WTF_CSRF_ENABLED"] = False
testing_client = app.test_client()
return testing_client
|
f47a21a8bf1f39a9ec28a7fe3b2c1640a1b2cda1
|
[
"Python",
"Text"
] | 6 |
Python
|
aundreas83/spell_checker_web
|
3da8ec165d05ef1fc7c0e38f06f0618cfe71990b
|
997b7babb0bb33e5d087d174603558b3de57e582
|
refs/heads/master
|
<repo_name>Borislav-ARC/my-homework-yandex<file_sep>/js/main.js
(function(){
var calcResult = true,
container = $('.container'),
icons = $('.desktop .icons'),
numberNote = 0,
noteNames = [],
drag, dialogWindow;
// Старт Windows
$('.desktop > .icons').hide();
setTimeout(function(){
container.removeClass('start-windows');
}, 2000);
setTimeout(function(){
$('.start-menu').show();
$('.play-start-windows')[0].play();
}, 3000);
setTimeout(function(){
for(var i=0; i<icons.length; i+=2) {
(function(i) {
setTimeout(function(){
$(icons[i]).show();
$(icons[i+1]).show();
}, i*70);
})(i);
}
}, 4000);
// Перетаскивание значков
function makeDraggable() {
$('.icons').draggable({
containment: 'parent',
drag: function(){
drag = $(this);
}
});
}
makeDraggable();
// Удаление в корзину
$('.icons.recycle').droppable({
drop: function() {
$(this).removeClass('empty').addClass('full');
drag.appendTo('.win-recycle .wrap')
.css({'top': '0px', 'left': '0px'})
}
});
// Очистка корзины
$('.clear-recycle').click(function(){
$('.win-recycle .wrap').html('');
$('.icons.recycle').removeClass('full').addClass('empty');
$('.play-recycle-clean')[0].play();
});
// Мой компьютер
$('.win-my-comp').dialog({
autoOpen: false,
height: 400,
width: 600,
minWidth: 250,
position: 'center',
closeOnEscape: false,
resizable: true,
title: 'Мой компьютер',
dialogClass: 'my-comp',
close: function() {
$('.task-my-comp').remove();
$(this).parents('.ui-dialog').find('.ui-dialog-titlebar-resize').data('resize', 'false');
}
});
// Корзина
$('.win-recycle').dialog({
autoOpen: false,
height: 400,
width: 600,
minWidth: 250,
position: 'center',
closeOnEscape: false,
resizable: true,
title: 'Корзина',
dialogClass: 'recycle',
close: function() {
$('.task-recycle').remove();
$(this).parents('.ui-dialog').find('.ui-dialog-titlebar-resize').data('resize', 'false');
}
});
// Калькулятор
$('.win-calculator').dialog({
autoOpen: false,
height: 'auto',
width: 184,
position: 'center',
closeOnEscape: false,
resizable: false,
draggable: true,
title: 'Калькулятор',
dialogClass: 'calculator',
close: function() {
$('.task-calculator').remove();
$('.screen').html('');
}
});
// Блокнот
function creatNotepad(title) {
var titleNote;
if(!title && !numberNote) {
titleNote = 'Блокнот';
} else if(title) {
titleNote = title;
} else {
titleNote = 'Новый текстовый документ (' + numberNote + ')';
}
$('.win-notepad-' + numberNote ).dialog({
autoOpen: false,
height: 400,
width: 600,
minWidth: 250,
position: 'center',
closeOnEscape: false,
resizable: true,
draggable: true,
title: titleNote,
dialogClass: 'notepad-' + numberNote,
close: function() {
$('.task-' + $(this).parents('.ui-dialog').find('.ui-dialog-content').data('window')).remove();
$(this).parents('.ui-dialog').find('.ui-dialog-titlebar-resize').data('resize', 'false');
}
});
noteNames.push(titleNote);
var thatWinNote = document.querySelector('.win-notepad-' + numberNote),
thatNote = document.querySelector('.notepad-' + numberNote),
textArea = thatWinNote.querySelector('textarea'),
buttonsClose, noteSaveAs, noteSaveAsName, buttonsSaveAs, buttonsQuitMes,
buttonsSettings, settingsWin, fontFamily;
textArea.addEventListener('keydown', function(e){
var event = e || window.event,
target = event.target || event.srcElement;
target.dataset.changes = true;
});
$('div[class*="notepad"] .ui-dialog-titlebar-close').unbind('click');
buttonsClose = [thatNote.querySelector('.ui-dialog-titlebar-close'), thatNote.querySelector('.note-quit')];
for(var b=0;b<buttonsClose.length;b++) {
buttonsClose[b].addEventListener('click', function(){
showQuitDialog(thatWinNote, titleNote);
})
}
// Кнопки - Закрытие блокнота
buttonsQuitMes = thatNote.querySelectorAll('.note-close');
for(i=0;i<buttonsQuitMes.length;i++){
buttonsQuitMes[i].addEventListener('click', function(e){
var event = e || window.event,
target = event.target || event.srcElement;
clickButtonsNote(target);
});
}
// Нажатия на кнопки в окне закрытия блокнота
function clickButtonsNote(target){
var messageWindow = thatWinNote.querySelector('.quit-message-wrap'),
thisNote = thatWinNote.dataset.window;
if(target.value === 'yes') {
localStorage.setItem(thisNote, textArea.value);
$('.win-' + thisNote).dialog('close');
messageWindow.style.display = 'none';
textArea.dataset.changes = false;
} else if(target.value === 'no') {
textArea.value = localStorage.getItem(thisNote);
$('.win-' + thisNote).dialog('close');
messageWindow.style.display = 'none';
textArea.dataset.changes = false;
} else {
messageWindow.style.display = 'none';
}
}
// Окно - Сохранить как
noteSaveAs = thatWinNote.querySelector('.note-save-as-wrap');
noteSaveAsName = thatWinNote.querySelector('.note-name-save-as');
thatWinNote.querySelector('.note-save-as').addEventListener('click', function() {
var content = thatWinNote.querySelector('.note-save-as-content');
content.innerHTML = '';
for(var a=0;a<noteNames.length;a++) {
content.innerHTML += '<div class="note-save-as-others">' + noteNames[a] + '</div>'
}
noteSaveAs.style.display = 'block';
noteSaveAsName.value = '';
noteSaveAsName.focus()
});
// Кнопки - Сохранить как
buttonsSaveAs = thatWinNote.querySelectorAll('.note-save-as-close');
for(var i=0;i<buttonsSaveAs.length;i++){
buttonsSaveAs[i].addEventListener('click', function(e){
var textArea = thatWinNote.querySelector('textarea'),
event = e || window.event,
target = event.target || event.srcElement;
saveAs(target)
})
}
// Нажатия на кнопки - Сохранить как
function saveAs(target) {
var replace = thatWinNote.querySelector('.note-save-as-replace');
if(target.value === 'yes') {
if(noteSaveAsName.value && noteNames.indexOf(noteSaveAsName.value) === -1 ) {
noteSaveAs.style.display = 'none';
creatNewNotepad(noteSaveAsName.value, textArea.value);
localStorage.setItem(thatWinNote.dataset.window, textArea.value);
} else if( noteNames.indexOf(noteSaveAsName.value) > -1 ) {
replace.style.display = 'block';
} else {
noteSaveAsName.focus();
}
} else if(target.value === 'no') {
noteSaveAs.style.display = 'none';
} else if(target.value === 'replace') {
replace.style.display = 'none';
noteSaveAs.style.display = 'none';
document.querySelector('.win-notepad-' + noteNames.indexOf(noteSaveAsName.value)).querySelector('textarea').value = textArea.value;
textArea.dataset.changes = false;
$(thatWinNote).dialog('close');
textArea.value = localStorage.getItem(thatWinNote.dataset.window);
$('.win-notepad-' + noteNames.indexOf(noteSaveAsName.value)).dialog('open')
} else if(target.value === 'no-replace') {
replace.style.display = 'none';
} else {
noteSaveAs.style.display = 'none';
}
}
// Кнопки - Настройки
thatWinNote.querySelector('.select-font-size').addEventListener('change', function(e){
var event = e || window.event,
target = event.target || event.srcElement;
thatWinNote.querySelector('.input-font-size').value = target.value;
});
buttonsSettings = thatWinNote.querySelectorAll('.settings-close');
settingsWin = thatWinNote.querySelector('.setting-wrap');
for(var q=0;q<buttonsSettings.length;q++){
buttonsSettings[q].addEventListener('click', function(e){
var event = e || window.event,
target = event.target || event.srcElement;
setNoteParams(target)
})
}
// Нажатия на кнопки - Настройки
function setNoteParams(target) {
var valuesStyle = thatWinNote.querySelector('.select-font-style').value.split(',');
if(target.value === 'yes') {
var textAreas = document.querySelectorAll('.notepad-text');
switch (thatWinNote.querySelector('.select-font-family').value) {
case 'Arial':
fontFamily = 'Arial, "Helvetica Neue", Helvetica, sans-serif';
break;
case 'Calibri':
fontFamily = 'Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif';
break;
case 'Futura':
fontFamily = 'Futura, "Trebuchet MS", Arial, sans-serif';
break;
case 'Geneva':
fontFamily = 'Geneva, Tahoma, Verdana, sans-serif';
break;
case 'Optima':
fontFamily = 'Optima, Segoe, "Segoe UI", Candara, Calibri, Arial, sans-serif';
break;
case 'Tahoma':
fontFamily = 'Tahoma, Verdana, Segoe, sans-serif';
break;
case 'Times New Roman':
fontFamily = 'TimesNewRoman, "Times New Roman", Times, Baskerville, Georgia, serif';
break;
case 'Trebushet':
fontFamily = '"Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif';
break;
case 'Verdana':
fontFamily = 'Verdana, Geneva, sans-serif';
break;
}
for(var z=0;z<textAreas.length;z++) {
textAreas[z].style.cssText = 'font-size:' + thatWinNote.querySelector('.input-font-size').value + 'px;' +
'font-weight:' + valuesStyle[0] + ';' +
'font-style:' + valuesStyle[1] + ';' +
'font-family:' + fontFamily + ';'
}
settingsWin.style.display = 'none';
} else {
settingsWin.style.display = 'none';
}
}
// Остальные обработчики
thatWinNote.querySelector('.creat-new-notepad').addEventListener('click', function() {
creatNewNotepad(null, false);
});
thatWinNote.querySelector('.note-save').addEventListener('click', function() {
localStorage.setItem(thatWinNote.dataset.window, textArea.value);
textArea.dataset.changes = false;
});
thatWinNote.querySelector('.note-setting').addEventListener('click', function() {
thatWinNote.querySelector('.setting-wrap').style.display = 'block';
});
// Создание новых блокнотов
function creatNewNotepad(title, content) {
numberNote++;
var titleNote = title || 'Новый текстовый документ (' + numberNote + ')',
clone = document.querySelector('.win-notepad-0').cloneNode(true),
newNote;
clone.classList.remove('win-notepad-0');
clone.classList.add('win-notepad-' + numberNote);
clone.dataset.window = 'notepad-' + numberNote;
if(content) {
clone.querySelector('textarea').value = content;
} else {
clone.querySelector('textarea').value = ''
}
document.querySelector('.created-windows').appendChild(clone);
newNote = document.querySelector('.win-notepad-' + numberNote);
localStorage.setItem(newNote.dataset.window, newNote.querySelector('textarea').value);
newNote.querySelector('textarea').dataset.changes = false;
document.querySelector('.new-elements').innerHTML += '<div class="icons notepad new-'+ numberNote +'"><span class="icon desk" data-window="notepad-'+ numberNote +'"></span><span class="icon-text">' + titleNote + '</span></div>';
creatNotepad(titleNote);
makeDraggable();
startProgs($('.win-notepad-' + numberNote), titleNote)
}
}
creatNotepad();
// Окно - Закрытие блокнота
function showQuitDialog(thatWinNote, titleNote){
thatWinNote.querySelector('.title-note').innerHTML = titleNote;
if(thatWinNote.querySelector('textarea').dataset.changes === 'true'){
thatWinNote.querySelector('.quit-message-wrap').style.display = 'block';
} else {
$(thatWinNote).dialog('close');
}
}
// Сапер
$('.win-mineweeper').dialog({
autoOpen: false,
height: 'auto',
width: 'auto',
position: 'center',
closeOnEscape: false,
resizable: false,
draggable: true,
title: 'Сапер',
dialogClass: 'mineweeper',
close: function() {
$('.task-mineweeper').remove();
}
});
// Winamp
$('.win-winamp').dialog({
autoOpen: false,
height: 'auto',
width: 'auto',
position: 'center',
closeOnEscape: false,
resizable: false,
draggable: true,
dialogClass: 'winamp',
close: function() {
$('.task-winamp').remove();
}
});
// Запуск программ Windows
$(document).on('dblclick', '.icon.desk', function() {
startProgs($(this));
});
function startProgs(obj, title){
var that = obj.data('window'),
name = title || obj.next().html();
if($('.task-' + that).html()) {
return
} else if(that === 'shri') {
window.location = 'gallery.html'
} else if(that === 'winamp') {
$('.b-player').appendTo('.win-winamp').show();
}
$('.win-' + that).dialog('open');
$('.task.active').removeClass('active');
$('.taskbar').append('<div class="task task-' +that+' active" data-window="'+that+'" data-mini="false"><span class="task-icon"></span><span class="task-text"> '+ name +' </span></div>');
}
// Завершение работы
$('.win-shutdown').dialog({
autoOpen: false,
height: 'auto',
width: 'auto',
minHeight: 0,
position: 'center',
resizable: false,
draggable: false,
title: 'Завершение работы с Windows',
dialogClass: 'shutdown',
modal: true
});
$('.but-shutdown').click(function(){
$('.win-shutdown').dialog('open');
});
// Завершение работы, нажатия на кнопки
$('.sd-but').click(function(){
var windows = [$('.win-my-comp'), $('.win-recycle'), $('.win-calculator'), $('.win-mineweeper'), $('.win-winamp')],
noteChanges = [];
if($(this).val() === 'yes') {
$('.win-shutdown').dialog('close');
function closeNotes(){
for(var i=0;i<noteNames.length;i++) {
showQuitDialog(document.querySelector('.win-notepad-'+i), noteNames[i]);
if(document.querySelectorAll('.notepad-text')[i].dataset.changes === 'true') {
noteChanges[i] = true;
} else {
noteChanges[i] = false;
}
}
}
closeNotes();
var confirmClose = setInterval(function(){
if(noteChanges.indexOf(true) > -1) {
closeNotes();
} else {
shutdown();
clearInterval(confirmClose)
}
}, 1000);
function shutdown(){
for(var i=0; i<windows.length; i++) {
(function(i) {
setTimeout(function(){
windows[i].dialog('close');
}, i*500);
})(i);
}
for(var b=0; b<icons.length; b+=2) {
(function(b) {
setTimeout(function(){
$(icons[b]).html('');
$(icons[b+1]).html('');
}, b*70);
})(b);
}
$('.start-menu').hide();
setTimeout(function(){
$('.play-shutdown')[0].play();
}, 700);
setTimeout(function(){
container.addClass('shutdown');
}, 1400);
if($('#yes').prop("checked")) {
setTimeout(function(){
container.removeClass('shutdown').addClass('poweroff');
container.html('');
}, 4000);
} else {
setTimeout(function() {
location.reload()
}, 4000)
}
}
} else if($(this).val() === 'no'){
$('.win-shutdown').dialog('close');
} else {
return;
}
});
// Акт<NAME> при нажатии на окно
dialogWindow = $('.ui-dialog');
$(document).on('mousedown', '.ui-dialog', function(){
$('.task.active').removeClass('active');
$('.task-' + $(this).find('.ui-dialog-content').data('window')).addClass('active');
});
$(document).on('resize', dialogWindow, function() {
$('.ui-dialog-content').css({'width': 100 + '%', height: 'calc(100% - 19px)'});
});
// Переключение окон по нажатию на таскбар
$(document).on('click', '.task', function() {
var dialogWindow = $('.ui-dialog.' + $(this).data('window')),
thisDialog = $('.win-' + $(this).data('window')),
thisTask = $('.task-' + $(this).data('window'));
$('.task.active').removeClass('active');
$(this).addClass('active');
if(thisTask.data('mini')) {
dialogWindow.animate({
'top': (($(window).height() / 2) - (dialogWindow.height() / 2)) + 'px',
'left': (($(window).width() / 2) - (dialogWindow.width() / 2)) + 'px'
}, 30);
thisDialog.dialog('moveToTop');
thisTask.data('mini', false)
} else {
thisDialog.dialog('moveToTop');
}
});
// Размер окон. Кнопка Resize
$('.ui-dialog-titlebar-resize').click(function(){
var parent = $(this).parents('.ui-dialog');
if(parent.hasClass('calculator') || parent.hasClass('mineweeper')) {
return;
} else {
if($(this).data('resize')) {
$(this).parents('.ui-dialog')
.css({'width': 'calc(100% - 2px)',
'height': 'calc(100% - 27px)',
'left': '0',
'top': '0' });
$(this).parents('.ui-dialog').find('.ui-dialog-content')
.css({'width': '100%',
'height': 'calc(100% - 19px)'
});
$(this).data('resize', false);
} else {
$(this).parents('.ui-dialog')
.css({'width': '600px',
'height': '400px',
'left': 'calc(50% - 300px)',
'top': 'calc(50% - 200px)' });
$(this).parents('.ui-dialog').find('.ui-dialog-content')
.css({'width': '100%',
'height': 'calc(100% - 19px)'
});
$(this).data('resize', true);
}
}
});
// Свернуть
$(document).on('click', '.ui-dialog-titlebar-mini', function(){
var that = $(this).parents('.ui-dialog');
that.animate({'top': '120%','left': '0'}, 65);
$('.task-' + $(this).parents('.ui-dialog').find('.ui-dialog-content').data('window')).data('mini', true);
});
// Часы
function digitalWatch() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
$('.time').html(hours + ":" + minutes);
setTimeout(digitalWatch, 1000);
}
digitalWatch();
// Калькулятор
$('.calc-but').click(function() {
var operators = ['+', '-', 'x', '÷'],
decimalAdded = false,
input = document.querySelector('.screen'),
inputVal = input.innerHTML,
btnVal = this.innerHTML,
lastChar, equation;
if(btnVal == 'C') {
input.innerHTML = '';
decimalAdded = false;
} else if(btnVal == '=') {
calcResult = false;
equation = inputVal;
lastChar = equation[equation.length - 1];
equation = equation.replace(/x/g, '*').replace(/÷/g, '/');
if(operators.indexOf(lastChar) > -1 || lastChar == '.') {
equation = equation.replace(/.$/, '');
}
if(equation) {
input.innerHTML = eval(equation);
}
decimalAdded = false;
} else if(operators.indexOf(btnVal) > -1) {
lastChar = inputVal[inputVal.length - 1];
calcResult = true;
if(inputVal != '' && operators.indexOf(lastChar) == -1) {
input.innerHTML += btnVal;
} else if(inputVal == '' && btnVal == '-') {
input.innerHTML += btnVal;
}
if(operators.indexOf(lastChar) > -1 && inputVal.length > 1) {
input.innerHTML = inputVal.replace(/.$/, btnVal);
}
decimalAdded = false;
} else if(btnVal == '.') {
if(!decimalAdded) {
input.innerHTML += btnVal;
decimalAdded = true;
}
} else if(btnVal == 'Back') {
input.innerHTML = inputVal.slice(0, -1);
} else {
if(!calcResult) {
calcResult = true;
input.innerHTML = btnVal;
} else {
input.innerHTML += btnVal;
}
}
});
})();<file_sep>/readme.md
<h4>Запускать файл start.html, все нужные скрипты лежат в папках, ничего дополнительно делать не нужно </h4>
Это некий симулятор Windows 95. Не полноценный Windows конечно, но я очень старался сделать как можно больше функций :) <br>
=====
Что удалось реализовать: <br>
- Запуск Windows <br>
- Перетаскивание значков <br>
- Все значки на рабочем столе открываются при двойном клике <br>
- Калькулятор (был написан ранее на нативном JS, так его и оставил) <br>
- Блокнот (возможность редактирования текста, при изменении текста <br>
перед закрытием спрашивает: "Сохранить ли изменения") <br>
Дополнительные функции блокнота (написано на чистом JS + кроссбраузерность) <br>
- (Файл - Создать) Создать новый блокнот;<br>
- (Файл - Сохранить) Сохранение текущих изменений;<br>
- (Файл - Сохранить как) Cоздание нового блокнота с введеным именем, если такое имя есть - выдает запрос на перезапись, <br>
если имя пустое - не дает сохранить и фокусирует на инпуте ввода, при подтверждении перезаписи он перезаписывает существующий файл <br>
- (Файл - Выход) Выход, тут понятно <br>
- (Вид - настройки шрифта) Настройка шрифта в блокнотах, размер, стиль, семейство <br>
Остальные функции: <br>
- <NAME> <br>
- <NAME> <br>
- <NAME> - это мое решение экзаменационного задания предыдущего курса ШРИ <br>
- Удаление (перетаскивание) в корзину <br>
- Очистка корзины (Корзина - Файл - Очистить корзину) <br>
- Выключение, перезагрузка <br>
- Управление открытыми окнами: Перемещение, Сворачивание, Разворачивание (нажатие на задачу в таскбаре внизу) <br>
Активация нужного окна, т.е. перенос окна выше остальных по оси Z (аналогично - нажатие на задачу в таскбаре внизу) <br>
и наоборот активация задачи в таскбаре при нажатии на другое открытое окно, <br>
увеличение на весь экран и возвращение к начальному размеру, <br>
ресайз окна мышкой(например: зажатие мышкой в правом нижнем углу открытого окна) <br>
- Часы <br>
- Меню Пуск, кроме кнопки Завершение работы, декоративное (в проекте его расширение и увеличение функций) <br>
Это пока beta версия, я еще буду допиливать некоторые моменты :) <br><file_sep>/js/minesweeper.min.js
function Minesweeper(t, n) {
var w = this;
var h;
var u;
var b;
var l;
var F;
var B;
var y;
var A;
var d;
var L = new x();
var D;
var f;
var a;
var M;
var E;
var o;
var j;
var v;
H();
this.newGame = function () {
var U, S;
var R, T;
var Q;
R = J();
Q = n();
h = Q.gameTypeId;
u = Q.numRows;
b = Q.numCols;
l = Q.numMines;
F = Q.zoom;
T = (J() != R);
r(F);
if (T) {
N()
}
k();
if (!T) {
for (U = 1; U <= u; U++) {
for (S = 1; S <= b; S++) {
A[U][S].setClass("square blank")
}
}
}
L.stop();
L.reset();
B = l;
y = u * b - l;
O();
D = false;
f = false;
a = 0;
M = 0;
v = false;
$("#face")[0].className = "facesmile"
};
this.resize = function (Q) {
var R = m(Q);
r(Q);
$("#game-container").removeClass("z" + F * 100).addClass("z" + Q * 100);
$("#face").css({"margin-left": Math.floor(R) + "px", "margin-right": Math.ceil(R) + "px"});
F = Q
};
function r(Q) {
$("#game-container, #game").width(Q * (b * 16 + 20));
$("#game").height(Q * (u * 16 + 30 + 26 + 6))
}
function m(Q) {
return(Q * b * 16 - 6 * Math.ceil(Q * 13) - Q * 2 * 6 - Q * 26) / 2
}
function J() {
return u + "_" + b + "_" + l
}
function N() {
var T, Q;
var R = [];
var S = m(F);
R.push('<div class="bordertl"></div>');
for (Q = 0; Q < b; Q++) {
R.push('<div class="bordertb"></div>')
}
R.push('<div class="bordertr"></div>');
R.push('<div class="borderlrlong"></div>', '<div class="time0" id="mines_hundreds"></div>', '<div class="time0" id="mines_tens"></div>', '<div class="time0" id="mines_ones"></div>', '<div class="facesmile" style="margin-left:', Math.floor(S), "px; margin-right: ", Math.ceil(S), 'px;" id="face"></div>', '<div class="time0" id="seconds_hundreds"></div>', '<div class="time0" id="seconds_tens"></div>', '<div class="time0" id="seconds_ones"></div>', '<div class="borderlrlong"></div>');
R.push('<div class="borderjointl"></div>');
for (Q = 0; Q < b; Q++) {
R.push('<div class="bordertb"></div>')
}
R.push('<div class="borderjointr"></div>');
for (T = 1; T <= u; T++) {
R.push('<div class="borderlr"></div>');
for (Q = 1; Q <= b; Q++) {
R.push('<div class="square blank" id="', T, ",", Q, '"></div>')
}
R.push('<div class="borderlr"></div>')
}
R.push('<div class="borderbl"></div>');
for (Q = 0; Q < b; Q++) {
R.push('<div class="bordertb"></div>')
}
R.push('<div class="borderbr"></div>');
for (Q = 0; Q <= b + 1; Q++) {
R.push('<div class="square blank" style="display: none;" id="', 0, ",", Q, '"></div>')
}
for (Q = 0; Q <= b + 1; Q++) {
R.push('<div class="square blank" style="display: none;" id="', u + 1, ",", Q, '"></div>')
}
for (T = 1; T <= u; T++) {
R.push('<div class="square blank" style="display: none;" id="', T, ",", 0, '"></div>');
R.push('<div class="square blank" style="display: none;" id="', T, ",", b + 1, '"></div>')
}
$("#game").html(R.join(""))
}
function q(V, R) {
var T = 0;
var S = false;
var Q = false;
var U = false;
this.addToValue = function (W) {
T += W
};
this.isMine = function () {
return T < 0
};
this.isFlagged = function () {
return S
};
this.isMarked = function () {
return Q
};
this.isRevealed = function () {
return U
};
this.isHidden = function () {
return V < 1 || V > u || R < 1 || R > b
};
this.getRow = function () {
return V
};
this.getCol = function () {
return R
};
this.getValue = function () {
return T
};
this.setRevealed = function (W) {
U = W
};
this.plantMine = function () {
T -= 10;
A[V - 1][R - 1].addToValue(1);
A[V - 1][R].addToValue(1);
A[V - 1][R + 1].addToValue(1);
A[V][R - 1].addToValue(1);
A[V][R + 1].addToValue(1);
A[V + 1][R - 1].addToValue(1);
A[V + 1][R].addToValue(1);
A[V + 1][R + 1].addToValue(1)
};
this.unplantMine = function () {
T += 10;
A[V - 1][R - 1].addToValue(-1);
A[V - 1][R].addToValue(-1);
A[V - 1][R + 1].addToValue(-1);
A[V][R - 1].addToValue(-1);
A[V][R + 1].addToValue(-1);
A[V + 1][R - 1].addToValue(-1);
A[V + 1][R].addToValue(-1);
A[V + 1][R + 1].addToValue(-1)
};
this.setClass = function (W) {
document.getElementById(V + "," + R).className = W
};
this.reveal1 = function () {
var W, X;
var Y, Z;
var aa = [];
aa.push(this);
this.pushed = true;
while (aa.length > 0) {
Y = aa.pop();
if (!Y.isRevealed() && !Y.isFlagged()) {
if (Y.isMine()) {
return false
} else {
if (!Y.isFlagged()) {
Y.setClass("square open" + Y.getValue());
Y.setRevealed(true);
if (Y.getValue() == 0) {
a++
} else {
M++
}
if (!Y.isHidden() && --y == 0) {
C();
return true
}
if (Y.getValue() == 0 && !Y.isHidden()) {
for (W = -1; W <= 1; W++) {
for (X = -1; X <= 1; X++) {
Z = A[Y.getRow() + W][Y.getCol() + X];
if (!Z.pushed && !Z.isHidden() && !Z.isRevealed()) {
aa.push(Z);
Z.pushed = true
}
}
}
}
}
}
}
}
return true
};
this.reveal9 = function () {
if (U) {
var X, Y;
var Z;
var aa = 0;
var W = [];
for (X = -1; X <= 1; X++) {
for (Y = -1; Y <= 1; Y++) {
Z = A[V + X][R + Y];
if (Z != this && Z.isFlagged()) {
aa++
}
}
}
if (aa == T) {
for (X = -1; X <= 1; X++) {
for (Y = -1; Y <= 1; Y++) {
Z = A[V + X][R + Y];
if (Z != this && !Z.reveal1()) {
W.push(Z)
}
}
}
if (W.length > 0) {
I(W)
}
}
}
};
this.flag = function () {
if (!U) {
if (S) {
if ($("#marks").attr("checked")) {
this.setClass("square question");
Q = true
} else {
this.setClass("square blank")
}
S = false;
B++;
O()
} else {
if (Q) {
this.setClass("square blank");
Q = false
} else {
this.setClass("square bombflagged");
S = true;
B--;
O()
}
}
}
}
}
function k() {
var T, Q, R;
var S;
A = [];
d = [];
E = [];
R = 0;
for (T = 0; T <= u + 1; T++) {
A[T] = [];
for (Q = 0; Q <= b + 1; Q++) {
S = new q(T, Q);
A[T][Q] = S;
d[T + "," + Q] = S;
if (!S.isHidden()) {
E[R++] = S
}
}
}
for (R = 0; R < l; R++) {
E.splice(Math.floor(Math.random() * E.length), 1)[0].plantMine()
}
}
function p(R) {
var Q = R.getRow();
var S = R.getCol();
if (R.isMine()) {
E.splice(Math.floor(Math.random() * E.length), 1)[0].plantMine();
R.unplantMine();
E.push(R)
}
L.start();
if ((Q == 1 && S == 1) || (Q == 1 && S == b) || (Q == u && S == 1) || (Q == u && S == b)) {
return 1
} else {
if (Q == 1 || Q == u || S == 1 || S == b) {
return 2
} else {
return 3
}
}
}
function P(Q) {
if (h > 0) {
i();
// $.post("start.php", {key: o, s: Q, zc: a, nzc: M})
}
}
function i() {
var Q = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var R;
o = "";
for (var R = 0; R < 3; R++) {
o += Q.charAt(Math.floor(Math.random() * Q.length))
}
o += 4 * (Math.floor(Math.random() * 225) + 25) + h;
for (var R = 0; R < 4; R++) {
o += Q.charAt(Math.floor(Math.random() * Q.length))
}
}
function x() {
var T = 0;
var Q = -1;
var S;
function R() {
var V = (new Date()).getTime();
if (Q < 0) {
S = setTimeout(R, 1000);
Q = V + 1000
} else {
S = setTimeout(R, 1000 - (V - Q));
Q += 1000
}
T++;
U()
}
function U() {
var V = s(T);
document.getElementById("seconds_hundreds").className = "time" + V[0];
document.getElementById("seconds_tens").className = "time" + V[1];
document.getElementById("seconds_ones").className = "time" + V[2]
}
this.start = function () {
R()
};
this.stop = function () {
clearInterval(S);
Q = -1
};
this.reset = function () {
T = 0;
U();
Q = -1
};
this.getTime = function () {
return T
}
}
function O() {
var Q = s(B);
document.getElementById("mines_hundreds").className = "time" + Q[0];
document.getElementById("mines_tens").className = "time" + Q[1];
document.getElementById("mines_ones").className = "time" + Q[2]
}
function s(Q) {
Q = Math.min(Q, 999);
if (Q >= 0) {
return[Math.floor(Q / 100), Math.floor((Q % 100) / 10), Q % 10]
} else {
return["-", Math.floor((-Q % 100) / 10), -Q % 10]
}
}
function I(Q) {
var U, R, S;
var T;
document.getElementById("face").className = "facedead";
L.stop();
D = true;
for (U = 1; U <= u; U++) {
columnloop:for (R = 1; R <= b; R++) {
T = A[U][R];
if (!T.isRevealed()) {
for (S = 0; S < Q.length; S++) {
if (T == Q[S]) {
T.setClass("square bombdeath");
continue columnloop
}
}
if (T.isMine() && !T.isFlagged()) {
T.setClass("square bombrevealed")
} else {
if (!T.isMine() && T.isFlagged()) {
T.setClass("square bombmisflagged")
}
}
}
}
}
}
function C() {
var V, Q;
var S;
var R;
var T;
var U = false;
document.getElementById("face").className = "facewin";
L.stop();
D = true;
B = 0;
O();
for (V = 1; V <= u; V++) {
for (Q = 1; Q <= b; Q++) {
S = A[V][Q];
if (!S.isRevealed() && !S.isFlagged()) {
S.setClass("square bombflagged")
}
}
}
if (h > 0) {
T = L.getTime();
for (R = 3; R >= 0; R--) {
if (T <= t[R][h - 1]) {
z(R + 1, true);
U = true;
break
}
}
if (!U && ((h == 1 && T <= 100) || (h == 2 && T <= 50) || (h == 3 && T <= 150))) {
z(1, false)
}
}
}
function z(T, W) {
var Q;
var R, U;
var S = (new Date()).getTime();
var V;
switch (T) {
case 1:
Q = "daily";
break;
case 2:
Q = "weekly";
break;
case 3:
Q = "monthly";
break;
case 4:
Q = "all-time";
break;
default:
Q = "";
break
}
U = (G() && !!localStorage.name) ? localStorage.name : "";
if (W) {
R = prompt("New " + Q + " high score! Please enter your name", U)
} else {
R = prompt("Please enter your name to submit your score", U)
}
R = $.trim(R);
if (R.length > 25) {
R.substring(0, 25)
}
if (G()) {
localStorage.name = R
}
V = Math.round(((new Date()).getTime() - S) / 1000);
$.post("win.php", {key: o, name: R, time: L.getTime(), s: V, i: T, h: W ? 1 : 0}, function (X) {
if (W) {
window.location.reload()
}
})
}
function G() {
try {
return"localStorage" in window && window.localStorage !== null
} catch (Q) {
return false
}
}
function K(Q) {
return Q.className.substring(0, 6) == "square"
}
function e(R) {
var Q = {};
if (j) {
Q.left = R.button == 1 || R.button == 3 || R.button == 4;
Q.right = R.button == 2 || R.button == 3 || R.button == 4
} else {
Q.left = R.button == 0 || R.button == 1;
Q.right = R.button == 2 || R.button == 1
}
return Q
}
function g(S, R, Q) {
if (!S.isRevealed()) {
if (S.isMarked()) {
S.setClass(Q)
} else {
if (!S.isFlagged()) {
S.setClass(R)
}
}
}
}
function c(U, T, S) {
var Q, R;
for (Q = -1; Q <= 1; Q++) {
for (R = -1; R <= 1; R++) {
g(A[U.getRow() + Q][U.getCol() + R], T, S)
}
}
}
function H() {
var V = false;
var U = false;
var S = false;
var T;
function R(W) {
if (W.target != T && !v) {
if (U) {
if (T) {
c(d[T.id], "square blank", "square question")
}
if (K(W.target)) {
c(d[W.target.id], "square open0", "square questionpressed")
}
} else {
if (T) {
g(d[T.id], "square blank", "square question")
}
if (K(W.target)) {
g(d[W.target.id], "square open0", "square questionpressed")
}
}
}
T = (K(W.target)) ? W.target : undefined
}
function Q(W) {
document.getElementById("face").className = (W.target.id == "face") ? "facepressed" : "facesmile"
}
// j = $.browser.msie && parseFloat($.browser.version) <= 7;
$(document).mousedown(function (X) {
var W = e(X);
V = W.left || V;
U = W.right || U;
if (V) {
if (K(X.target) && !D) {
X.preventDefault();
$(document).bind("mousemove", R);
document.getElementById("face").className = "faceooh";
T = undefined;
R(X)
} else {
if (X.target.id == "face") {
X.preventDefault();
S = true;
$(document).bind("mousemove", Q);
document.getElementById("face").className = "facepressed"
}
}
} else {
if (U) {
if (K(X.target) && !D) {
d[X.target.id].flag()
}
return false
}
}
});
$(document).mouseup(function (Z) {
var W = e(Z);
var Y;
var X;
if (W.left) {
V = false;
$(document).unbind("mousemove", R).unbind("mousemove", Q);
if (S || !D) {
document.getElementById("face").className = "facesmile"
}
if (K(Z.target) && !D) {
Y = d[Z.target.id];
if (U) {
v = true;
c(d[Z.target.id], "square blank", "square question");
Y.reveal9()
} else {
if (!v) {
if (!f) {
X = p(Y)
}
if (!Y.reveal1()) {
I([Y])
}
if (!f) {
P(X);
f = true
}
}
v = false
}
} else {
if (Z.target.id == "face" && S) {
w.newGame()
}
}
S = false
}
if (W.right) {
U = false;
if (K(Z.target) && !D) {
if (V) {
Y = d[Z.target.id];
v = true;
c(Y, "square blank", "square question");
Y.reveal9()
} else {
v = false
}
if (!D) {
document.getElementById("face").className = "facesmile"
}
}
}
});
$(document).keydown(function (W) {
if (W.keyCode == 113) {
w.newGame()
}
})
}
};
$(function () {
var gameType = 'expert';
var zoom = '100';
var position = 'center';
var hashParts, i;
var minesweeper;
if (!!location.hash && location.hash.length > 1) {
hashParts = location.hash.substring(1).split('-');
for (i = 0; i < hashParts.length; i++) {
switch (hashParts[i]) {
case 'beginner':
gameType = 'beginner';
break;
case 'intermediate':
gameType = 'intermediate';
break;
case '150':
zoom = '150';
break;
case '200':
zoom = '200';
break;
case 'center':
position = 'center';
break;
}
}
}
$('#' + gameType).attr('checked', true);
$('#zoom' + zoom).attr('checked', true);
$('#position-' + position).attr('checked', true);
document.getElementById('game-container').className = 'z' + zoom;
setPosition(position);
minesweeper = new Minesweeper([
[ 5, 27, 72],
[ 3, 24, 66],
[ 2, 21, 64],
[ 1, 18, 61]
], readOptions);
minesweeper.newGame();
// setHash();
$("#options-link, #options-close").click(function () {
$("#display").hide();
$("#options").toggle();
return false;
});
$("#options-form").submit(function () {
$("#options").hide();
minesweeper.newGame();
// setHash();
return false;
});
$("#display-link, #display-close").click(function () {
$("#options").hide();
$("#display").toggle();
return false;
});
$('input[name="zoom"]').change(function () {
var zoom = parseFloat($(this).val());
minesweeper.resize(zoom);
// setHash();
});
$('input[name="position"]').change(function () {
setPosition($(this).val());
// setHash();
});
$(document).keydown(function (e) {
if (e.keyCode == 27) { //escape
$("#options, #display").hide();
}
});
$(".scores-tab").click(function () {
var id = this.id;
$(".scores-tab-selected").removeClass("scores-tab-selected");
$(this).addClass("scores-tab-selected");
$(".scores-pane").hide();
$("#" + id.substring(0, id.length - 5)).show();
});
function setPosition(position) {
if (position == 'left') {
$('.outer-container').css({ 'vertical-align': 'top', 'text-align': 'left' });
}
else if (position == 'center') {
$('.outer-container').css({ 'vertical-align': 'middle', 'text-align': 'center' });
}
}
function readOptions() {
var gameTypeId;
var numRows;
var numCols;
var numMines;
var zoom;
if ($("#beginner").attr("checked")) {
gameTypeId = 1;
numRows = 9;
numCols = 9;
numMines = 10;
}
else if ($("#intermediate").attr("checked")) {
gameTypeId = 2;
numRows = 16;
numCols = 16;
numMines = 40;
}
else if ($("#expert").attr("checked")) {
gameTypeId = 3;
numRows = 16;
numCols = 30;
numMines = 99;
}
else if ($("#custom").attr("checked")) {
gameTypeId = 0;
numRows = parseInt($("#custom_height").val(), 10);
if (isNaN(numRows)) {
numRows = 20;
}
numRows = Math.max(1, numRows);
numRows = Math.min(99, numRows);
$("#custom_height").val(numRows);
numCols = parseInt($("#custom_width").val(), 10);
if (isNaN(numCols)) {
numCols = 30;
}
numCols = Math.max(8, numCols);
numCols = Math.min(99, numCols);
$("#custom_width").val(numCols);
numMines = parseInt($("#custom_mines").val(), 10);
if (isNaN(numMines)) {
numMines = Math.round(numRows * numCols / 5);
}
numMines = Math.max(0, numMines);
numMines = Math.min(numRows * numCols - 1, numMines);
$("#custom_mines").val(numMines);
}
zoom = parseFloat($('input[name="zoom"]:checked').val());
return {
gameTypeId: gameTypeId,
numRows: numRows,
numCols: numCols,
numMines: numMines,
zoom: zoom
};
}
// function setHash() {
// var gameType = 'expert';
// var zoom = $('input[name="zoom"]:checked').val();
// var position = $('input[name="position"]:checked').val();
// var hashParts = [];
//
// if ($("#beginner").attr("checked")) {
// hashParts.push("beginner");
// }
// else if ($("#intermediate").attr("checked")) {
// hashParts.push("intermediate");
// }
// if (zoom != 1) {
// hashParts.push(zoom * 100);
// }
// if (position != "left") {
// hashParts.push(position);
// }
// }
});
|
0e8f67ef0448183e6ac64f21efac6493d39d636d
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
Borislav-ARC/my-homework-yandex
|
194ee45be8d0a058ffdf4db9fcf11e1ba0938d97
|
f0fb480959a143ca2a3ffc8b4d7081cd8bb1ab2a
|
refs/heads/master
|
<file_sep><?php
class Some
{
public static string $id = 'id';
}
$class = Some::class;
$id = $class::$id;
var_dump($id);
<file_sep><?php
interface AWorkerInterface
{
public function a() : string;
}
interface BWorkerInterface extends AWorkerInterface
{
public function b() : string;
}
class AWorker implements AWorkerInterface
{
public function a() : string
{
return 'a';
}
}
class BWorker extends AWorker implements BWorkerInterface
{
public function a() : string
{
return 'A';
}
public function b() : string
{
return 'b';
}
}
class AConsumer
{
/** @var AWorkerInterface */
protected $worker;
public function __construct(AWorkerInterface $worker)
{
$this->worker = $worker;
}
public function doWork() : string
{
return 'A: ' . $this->worker->a();
}
}
class BConsumer extends AConsumer
{
/** @var BWorkerInterface */
protected $worker;
public function __construct(BWorkerInterface $worker)
{
parent::__construct($worker);
}
public function doWork() : string
{
return 'B: ' . $this->worker->a() . $this->worker->b();
}
}
$aWorker = new AWorker();
$bWorker = new BWorker();
$aConsumer = new AConsumer($aWorker);
$bConsumer = new BConsumer($bWorker);
var_dump($aConsumer->doWork());
var_dump($bConsumer->doWork());
<file_sep><?php
// typed properties
class Test
{
public int $num;
public string $str;
}
$test = new Test();
$test->num = 123;
$test->str = 'str';
var_dump($test);
// arrow functions
$factor = 10;
$nums = array_map(
fn ($n) => $n * $factor,
[1, 2, 3, 4]
);
var_dump($nums);
// coalescing assignment
$some ??= 'some';
var_dump($some);
// arrays unpacking
$first = [1, 2, 3];
$second = [4, 5, 6];
$merged = [...$first, ...$second];
var_dump($merged);
<file_sep><?php
$parts1 = ['aa', null];
$parts2 = [null, null];
var_dump(implode(' ', array_filter($parts1)));
var_dump(implode(' ', array_filter($parts2)));
<file_sep><?php
class C
{
}
function f(C $c) : void
{
}
function g(?C $c) : void
{
}
function h(C $c = null) : void
{
}
//f(null); // fatal error
g(null);
h(null);
h();
<file_sep><?php
$x = 1;
$o = 2;
$board = [[0,0,0],[0,0,0],[0,0,0]];
if (any input) {
turn($board, $currentPlayer, $row, $col);
$victory = checkForVictory($board, [$x, $o]);
if ($victory) {
print('Player ' . $victory . ' won!');
}
if (checkForTheEnd($board)) {
print('Game over!');
}
}
// wait for the input...
/**
* This function make a turn, validating the input first.
*
* @return array The resulting board after the turn.
*/
function turn(array $board, int $player, int $row, int $col) : array
{
if ($row < 0 || $row > 2 || $col < 0 || $col < 2) {
throw new InvalidArgumentException('Coordinates are out of range.');
}
if ($board[$row][$col] > 0) {
throw new InvalidArgumentException('The cell is already occupied.');
}
$board[$row][$col] = $player;
return $board;
}
/**
* Checks the board for any empty cells remaining. If all the cells are occupied,
* returns "true" = the end of the game.
*/
function checkForTheEnd(array $board) : bool
{
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
if ($board[$i][$j] == 0) {
return false;
}
}
}
return true;
}
/**
* Checks the board for victory and returns player's number if they have won.
*/
function checkForVictory(array $board, array $players) : int
{
foreach ($players as $player) {
if (checkBoardForPlayer($board, $player)) {
return $player;
}
}
return 0;
}
function checkBoardForPlayer(array $board, int $player) : bool
{
return checkRow($board, $player, 0)
|| checkRow($board, $player, 1)
|| checkRow($board, $player, 2)
|| checkColumn($board, $player, 0)
|| checkColumn($board, $player, 1)
|| checkColumn($board, $player, 2)
|| checkDiagonals($board, $player);
}
function checkRow(array $board, int $player, int $row) : bool
{
return $board[$row][0] == $player
&& $board[$row][1] == $player
&& $board[$row][2] == $player;
}
function checkColumn(array $board, int $player, int $col) : bool
{
return $board[0][$col] == $player
&& $board[1][$col] == $player
&& $board[2][$col] == $player;
}
function checkDiagonals(array $board, int $player) : bool
{
return $board[1][1] == $player
&& ($board[0][0] == $player && $board[2][2] == $player
|| $board[0][2] == $player && $board[2][0] == $player);
}
<file_sep># php-sandbox
Miscellaneous
<file_sep><?php
namespace Hello;
class SomeClass
{
public function getClass()
{
return static::class;
}
}
$c = new SomeClass();
var_dump(['get_class', get_class($c)]);
var_dump(['getClass()', $c->getClass()]);
var_dump(['::class', SomeClass::class]);
<file_sep><?php
class Inner
{
}
class Some
{
private ?Inner $first = null;
private Inner $second;
public function __construct()
{
}
public function first() : ?Inner
{
return $this->first;
}
public function second() : Inner
{
return $this->second;
}
}
$some = new Some();
var_dump($some->first());
//var_dump($some->second()); // fatal error
<file_sep><?php
class FnClass
{
public static int $id = 0;
public \Closure $func;
public function __construct()
{
$this->func = fn () => ++self::$id;
}
}
$fn = new FnClass();
var_dump([FnClass::$id, ($fn->func)()]);
var_dump([FnClass::$id, ($fn->func)()]);
<file_sep><?php
interface BasicInterface
{
public function method() : int;
}
interface ExtendedInterface extends BasicInterface
{
public function extendedMethod() : string;
}
class Basic implements BasicInterface
{
public function method() : int
{
return 1;
}
}
class Extended extends Basic implements ExtendedInterface
{
public function extendedMethod() : string
{
return "hey";
}
}
class BasicUsage
{
/** @var BasicInterface */
protected $inner;
public function __construct(BasicInterface $inner)
{
$this->inner = $inner;
}
public function usage() : array
{
return [
$this->inner->method()
];
}
}
class ExtendedUsage extends BasicUsage
{
/** @var ExtendedInterface */
protected $inner;
public function __construct(ExtendedInterface $inner)
{
parent::__construct($inner);
$this->inner = $inner;
}
public function usage() : array
{
return [
$this->inner->method(),
$this->inner->extendedMethod()
];
}
}
$basic = new BasicUsage(new Basic());
$extended = new ExtendedUsage(new Extended());
var_dump($basic->usage());
var_dump($extended->usage());
<file_sep><?php
$pattern = '/^(\\\\|\/)?\.\./';
$tests = [
'\\..\\log\\app.log',
'/../log/app.log',
'..\\log\\app.log',
'../log/app.log',
];
foreach ($tests as $test) {
var_dump(
[
$test,
preg_match($pattern, $test)
]
);
}
<file_sep><?php
var_dump((object)null);
var_dump((object)1);
var_dump((object)"abc");
var_dump((object)(new \DateTime()));
var_dump((object)[1, 2, 3]);
var_dump((object)['a' => 1, 'b' => 2]);
<file_sep><?php
class Base
{
public static function create() : self
{
return new static();
}
}
class Derived extends Base
{
}
var_dump(Base::create());
var_dump(Derived::create());
<file_sep><?php
class Cool
{
private $str;
public function __construct(string $str)
{
$this->str = $str;
}
public function getStr()
{
return $this->str;
}
}
class Some
{
public static $cools = [
new Cool('one'),
new Cool('two')
];
public static function do()
{
foreach (self::$cools as $cool) {
var_dump($cool->getStr());
}
}
}
Some::do();
<file_sep><?php
$d1 = new \DateTime('2020-10-10');
$d2 = new \DateTime('2020-01-01');
var_dump(
[
$d1->diff($d2),
$d2->diff($d1),
$d1 > $d2,
$d2 > $d1
]
);
<file_sep><?php
echo '1. nulls' . PHP_EOL;
$a = [0, 1];
var_dump([$a[0] ?? null, $a[1] ?? null, $a[2] ?? null]);
echo '2. implode' . PHP_EOL;
var_dump(implode('<br/><br/>', []));
echo '3. decomposition' . PHP_EOL;
$a = [1];
[$first, $second] = $a;
var_dump([$first, $second]); // notice
echo '4. merge' . PHP_EOL;
var_dump(
array_merge(
[
'one' => 1,
'two' => 2,
],
[
'two' => 3,
]
)
);
echo '5. empty' . PHP_EOL;
var_dump(
[
empty(null),
empty([]),
empty([1])
]
);
<file_sep><?php
var_dump(explode('', 'a b c'));
var_dump(explode(null, 'a b c'));
<file_sep><?php
class One
{
protected int $id;
protected string $name;
public function __construct(int $id, string $name)
{
$this->id = $id;
$this->name = $name;
}
public static function make()
{
return new static(1, 'some');
}
}
class Two extends One
{
protected string $text;
public function __construct(int $id, string $name, string $text)
{
parent::__construct($id, $name);
$this->text = $text;
}
}
var_dump(Two::make()); // fatal error
<file_sep><?php
[$a, $b] = null;
var_dump([$a, $b]);
[$a, $b] = [];
var_dump([$a, $b]);
[$a, $b] = [1];
var_dump([$a, $b]);
[$a, $b] = [2, 3];
var_dump([$a, $b]);
[$a, $b] = [4, 5, 6];
var_dump([$a, $b]);
[, $b] = [1, 2];
var_dump($b);
<file_sep><?php
$pattern = '/^[^\?#\+]+$/';
var_dump(
[
preg_match($pattern, null),
preg_match($pattern, ''),
preg_match($pattern, 'ababa'),
preg_match($pattern, 'aba?ba'),
preg_match($pattern, 'aba+ba'),
preg_match($pattern, 'aba#ba'),
]
);
<file_sep><?php
class Some
{
private $func;
public function __construct(\Closure $func)
{
$this->func = $func;
}
public function callFunc($num)
{
return ($this->func)($num);
}
}
$obj = new Some(
function ($num) {
return $num * $num;
}
);
var_dump($obj->callFunc(4));
<file_sep><?php
$a[null] = null;
var_dump($a);
var_dump(get_class(null)); // warning
$iAmNull = null;
var_dump($iAmNull instanceof \DateTime);
<file_sep><?php
abstract class Base
{
}
class Derived extends Base
{
}
abstract class BaseUser
{
public abstract function getObj() : Base;
}
class DerivedUser extends BaseUser
{
public function getObj() : Derived // works since PHP 7.4
{
return new Derived();
}
}
$du = new DerivedUser();
$duObj = $du->getObj();
var_dump($duObj);
<file_sep><?php
preg_match('/^[\w\p{Cyrillic}\s\-\']+$/u', 'aba-b\'a', $test1);
preg_match('/^[\w\p{Cyrillic}\s\-\']+$/u', 'аба-ба', $test2);
preg_match('/^[\w\s\-\']+$/u', 'aba-b\'a', $test3);
var_dump([$test1, $test2, $test3]);
$ultRegex = '/^(\w|[\p{Cyrillic}]|-|\'|\s)+$/u';
preg_match($ultRegex, 'ab a-b\'a', $test4);
preg_match($ultRegex, 'аб а-ба', $test5);
preg_match($ultRegex, 'aba a-b\'a аб а-ба', $test6);
preg_match($ultRegex, 'aba123 a-b\'a аб123 а-ба 123', $test7);
var_dump([$test4, $test5, $test6, $test7]);
<file_sep><?php
var_dump(!'ababa');
var_dump(!null);
var_dump(!false);
<file_sep><?php
trait With
{
protected $value;
public function value()
{
return $this->value;
}
public function with($value) : self
{
$this->value = $value;
return $this;
}
}
class Base
{
use With;
}
class Derived extends Base
{
}
$base = new Base();
$derived = new Derived();
var_dump($base->with('value'));
var_dump($derived->with('value'));
<file_sep><?php
var_dump(intval('asda'));
var_dump(intval(null));
<file_sep><?php
var_dump(strpos('asdasdg', '/start') == 0);
var_dump(strpos('asdasdg', '/start') === 0);
<file_sep><?php
trait SomeTrait
{
public function func() : string
{
return parent::func() . ' Trait';
}
}
class Base
{
public function func() : string
{
return 'Base';
}
}
class WithoutTrait extends Base
{
public function func() : string
{
return parent::func() . ' WithoutTrait';
}
}
class WithTrait extends Base
{
use SomeTrait
{
func as protected parentFunc;
}
public function func() : string
{
return $this->parentFunc() . ' WithTrait';
}
}
$without = new WithoutTrait();
$with = new WithTrait();
var_dump([
'without' => $without->func(),
'with' => $with->func(),
]);
<file_sep><?php
var_dump(trim(null));
<file_sep><?php
class Some
{
public const Br = '1';
public const BrBr = self::Br . self::Br;
}
var_dump([Some::Br, Some::BrBr]);
<file_sep><?php
$email = $_GET['email'];
if (strlen($email) == 0) {
die("Please, specify the email in the query string (?email=blablabla).");
}
$email = trim($email);
$email = strtolower($email);
$hash = md5($email);
?>
<p>The Gravatar for <? echo $email; ?> is:</p>
<img src="https://www.gravatar.com/avatar/<? echo $hash; ?>?s=100&d=mp" width="100" height="100" style="border-radius: 50px;" />
<p>Hash: <? echo $hash; ?></p>
<file_sep><?php
class Event
{
}
class InvokeMe
{
public function __invoke(Event $e) : string
{
return 'object';
}
}
$i = new InvokeMe();
$f = fn (Event $e) => 'closure';
var_dump(
[
'InvokeMe callable? ' . is_callable($i) ? 'Y' : 'N',
'InvokeMe object? ' . is_object($i) ? 'Y' : 'N',
'InvokeMe class? ' . get_class($i),
'Closure callable? ' . is_callable($f) ? 'Y' : 'N',
'Closure object? ' . is_object($f) ? 'Y' : 'N',
'Closure class? ' . get_class($f),
]
);
$ci = \Closure::fromCallable($i);
$cf = \Closure::fromCallable($f);
var_dump([$ci, $cf]);
$rfi = new \ReflectionFunction($ci);
$rff = new \ReflectionFunction($cf);
$pi = $rfi->getParameters()[0];
$pf = $rff->getParameters()[0];
var_dump(
[
$pi->getClass()->name,
$pf->getClass()->name,
]
);
<file_sep><?php
function i(int $id)
{
var_dump($id);
}
i(32);
i(34.7);
i('45');
i('67.7');
var_dump('abc' > 0);
|
921216d7d3857f1981e81a86047c87b3c6fbb35c
|
[
"Markdown",
"PHP"
] | 35 |
PHP
|
kapxapot/php-sandbox
|
e33d3fd9141430fb68dfe210dfc717843673abaa
|
99c626ec9514d86fb33a4d4a0e47cce13671804e
|
refs/heads/master
|
<file_sep>[](https://travis-ci.org/vanderleisilva/optile-menu)
# README #
This repo is created as a public read-only resource for coding challenges during the hiring process at optile.
For more information please visit https://www.optile.net/unternehmen/karriere/
## Local configuration
Install npm dependencies.
```sh
$ yarn install
```
Duplicate the file: **server/env.sample** and rename to **server/env.js**
In the **en.js** file add your slackbot token
### Run tests.
```sh
$ npm test
```
### Run backend server.
```sh
$ node server
```
### Run frontend development server (run simultaneously with backend server).
```sh
$ npm start
```
#### On slack with the slackbot chat ask him:
**what's for lunch?**
And then your're going to have your menu without leaving your seat ;)<file_sep>optile react.js coding challenge
================================
We have identified a major problem in our process which is keeping the company
from competing with Google.
The problem is we don't know what's for lunch unless we go to the cantina in
our office building and look at the menu bulletin in the hallway. But every
developer here is pretty lazy, so no one here would consider getting up from
their seat just to find out that the daily menu is a salad or something. So,
today at lunch, we came up with an idea and we need a new react.js engineer to
help us.
We need a specialized react.js JavaScript application that less lazy employees
from product management (or a developer who accidentally walks by the cantina)
can easily use on their mobile phone to update the weekly menu. This backend
should have an optile logo and maybe even the optile colors.
Because we really like testing, the application should have unit tests
and integration tests. Bonus points for a open-source Circle CI integration
that executes those tests on every commit and reports the commit status.
The application itself should:
* show the latest image
* have an upload button that leads to an upload dialog that accepts an
image upload of the new menu and store it on the local file system
* provide a Slack API integration that can be asked "What's for lunch?" and
then respond with the latest stored image.
We recommend using `glitch.com <https://glitch.com/>`_ for implementing this,
but feel free to use `codepen.io <https://codepen.io/>`_ or Heroku or anything
else (e.g. your own server) instead.
Provided resources
------------------
Here is a list of useful resources:
* `Glitch FAQ`_
* `Slack integration API`_
* Example images of the cantina menu are in the bitbucket repository.
* Slack integration data ::
Authentication token: <optile-slack-token>
Channel: <optile-slack-test-channel>
Expected timeframe
------------------
3-6 hours. Feel free to embellish your version with whatever fun ideas come to
mind, but please don't spend more time than the expected timeframe. This is
just a fun coding challenge after all.
.. _Slack integration API: https://api.slack.com/methods/chat.postMessage
.. _Glitch FAQ: https://glitch.com/faq/
<file_sep>const express = require('express');
const app = express();
const fs = require('fs');
const upload = require('formidable');
const token = require('./env.js').token;
const file = {
menu : __dirname.replace('/server','') + '/public/menu/1.jpg',
empty : __dirname.replace('/server','') + '/public/empty.png',
}
app.use(require('cors')());
app.get("/menu", (request, response) => {
fs.stat(file.menu, (err, stat) => {
if(err == null) {
response.sendFile(file.menu);
return;
}
response.sendFile(file.empty);
});
});
app.post("/menu", (request, response) => {
var form = new upload.IncomingForm();
form.parse(request, (err, fields, files) => {
fs.rename(files.file.path, file.menu, err => {
if (err) throw err;
response.write('File uploaded and moved!');
response.end();
});
});
});
const listener = app.listen(8080, () => {
console.log('Your app is listening on port ' + listener.address().port);
require('./slack')(file.menu, token);
});
<file_sep>import React from "react";
import Upload from "./Upload";
import { mount } from "enzyme";
describe("Upload component", () => {
let props;
const upload = () => mount(<Upload {...props} />)
beforeEach(() => {
props = {
apiUrl: '',
extensions: [],
};
});
it("always renders an image", () => {
const item = upload().find("img");
expect(item.length).toBe(1);
});
it("always renders an upload file", () => {
const item = upload().find('input[type="file"]');
expect(item.length).toBe(1);
});
});<file_sep>import React, { Component } from 'react';
import Upload from "./upload/Upload";
class App extends Component {
render() {
return (
<div className="container-fluid">
<div className="page-header">
<h1>Optile Menu <small className="hidden-sm">Optile react.js coding challenge</small></h1>
</div>
<Upload apiUrl="http://localhost:8080" extensions={[ 'image/png', 'image/jpeg' ]} />
</div>
);
}
}
export default App;
<file_sep>import React from "react";
import PropTypes from 'prop-types';
import axios from 'axios';
export default class Upload extends React.Component {
static propTypes = {
apiUrl: PropTypes.string,
extensions: PropTypes.array,
}
handleUploadFile(event, api, extensions) {
const data = new FormData(), file = event.target.files[0];
if (extensions.indexOf(file.type) === -1) {
alert('Wrong extension, valid extensions: ' + extensions.join());
return;
}
data.append('file', event.target.files[0]);
axios.post(`${api}/menu`, data);
}
render() {
const api = this.props.apiUrl;
const extensions = this.props.extensions;
return(
<div className="thumbnail">
<img src={ this.props.apiUrl + "/menu" } alt="Lunch menu" />
<div className="caption">
<p>See what we have for lunch without leave your seat</p>
<p>
<label title="Update Menu" className="btn btn-primary">
Update <span className="glyphicon glyphicon-upload" aria-hidden="true"></span>
<input type="file" className="hidden" onChange={event => this.handleUploadFile(event, api, extensions)} />
</label>
</p>
</div>
</div>
);
}
}
<file_sep>module.exports = {
token: '<KEY>'
}
|
73f74774431e2b46751080e1750f25bd736c0410
|
[
"Markdown",
"JavaScript",
"reStructuredText"
] | 7 |
Markdown
|
vanderleisilva/optile-menu
|
a756bb44d5af8046c1f450fc779e8355a5b5738c
|
09310acb6c51333dc89f7707a8039e911382e0be
|
refs/heads/master
|
<file_sep>#!/usr/bin/env node
// this plugin replaces arbitrary text in arbitrary files
// remove strange appending of integer zero to versionCode
var fs = require('fs');
var path = require('path');
var rootdir = process.argv[2];
var platform = process.env.CORDOVA_PLATFORMS;
function replace_in_file(filename, to_replace, replace_with) {
if (fs.existsSync(filename)) {
var data = fs.readFileSync(filename, 'utf8');
var result = data.replace(new RegExp(to_replace, "g"), replace_with);
fs.writeFileSync(filename, result, 'utf8');
} else {
console.log('Error replace_in_file: could not find ' + filename);
}
}
var gradle = path.join(rootdir, 'platforms/android/build.gradle');
var find = 'privateHelpers.extractIntFromManifest\\("versionCode"\\) \\+ "0"';
var repl = 'privateHelpers.extractIntFromManifest("versionCode")';
console.log('HACK GRADLE');
replace_in_file(gradle, find, repl);
<file_sep><?php
/***
* given an array of (valid SQL) field definitions
*
*/
function generate_table_definition(
$field_definitions
, $table_name
, $create_table_tpl = 'CREATE TABLE `%s` ( %s );'
) {
if( is_null($table_name)) throw new exception("generate_table_definition() requires a table name");
return sprintf($create_table_tpl, $table_name, join(', ', $field_definitions));
}
function generate_field_definitions($field_map, $field_definition_tpl = '`%s` %s NULL' ) {
$field_definitions = array();
foreach ($field_map as $field_name => $field) {
$field_definitions[] = sprintf($field_definition_tpl, $field_name, $field['data-type']);
}
return $field_definitions;
}
function generate_extended_insert($table_name, $file_array, $field_map, $first_row_is_header = TRUE, $field_names = NULL) {
if (is_null($field_names)) $field_names = '`'.join('`, `', array_keys($field_map)).'`';
$rows = array();
foreach ( $file_array as $line )
{
$row = array();
foreach ($field_map as $field_name => $field_def) {
$field = $line[$field_name];
// if value is a string, quote it:
if (strpos($field_def['data-type'], 'char') !== false) $field = "'{$field}'";
$row[] = $field;
}
$rows[] = $row;
}
if ($first_row_is_header) array_shift($rows);
$insert = "INSERT INTO ${table_name} (${field_names}) VALUES ";
$values = array();
foreach ($rows as $row) {
$values[] = "( ".join(', ', $row)." )";
}
return $insert . join(', ', $values) . ';';
}
<file_sep><?php
/***
* loops through items in array and removes the given text-qualifier
* from the beginning and end of the field
*
* return: void
* @param: &$row array
* @param: $text_qualifier string
***/
function strip_text_qualifiers_from_row(&$row, $text_qualifier) {
$full_line = join(',', $row);
if ( strpos($full_line, $text_qualifier) !== false ) {
foreach ($row as $idx => $field) {
if (strpos($field, $text_qualifier) === 0) $field = substr($field, 1);
if (strrpos($field, $text_qualifier) === (strlen($field)-1)) $field = substr($field, 0, strlen($field)-2);
$row[$idx] = $field;
}
}
}
<file_sep>#!/usr/bin/env node
var exec = require('child_process').exec;
exec("for pl in `cordova plugins | cut -f 1 -d ' '` ; do cordova plugin rm $pl; done");
<file_sep>var search = _.extend(new Controller(), {
query: new String,
whereClause: new String,
fromClause: 'FROM content',
selectClause: new String,
zeroRows: false,
renderedResults: {},
main: function() {
ctl = search;
ctl.renderTpl();
ctl.updateDisplay();
},
initialize: function() {
this.bindEvents();
},
renderTpl: function() {
var src = $('#search_form_tpl').html();
var content_tpl = _.template(src);
ctl.rendered = content_tpl();
},
handleSubmit: function(e) {
e.preventDefault();
search.zeroRows = true;
if (search.validateForm() === false) {
return;
}
search.data = {rows: [], tbody: new String, content_type: 'table-striped' };
search.doSearch($('form#search input#search_terms')[0]);
},
validateForm: function() {
search.query = $('form#search input#search_terms').val();
if (search.query === "") {
console.log('validateForm::no query received');
return false;
}
return true;
},
noResults: function() {
$('#search_results').hide();
$('#no_search_results').show();
},
showResults: function() {
if (search.zeroRows) {
search.noResults();
return;
}
var results = $('#search_results');
results.empty();
results.html(search.renderedResults);
$('#no_search_results').hide();
results.show();
},
doSearch: function() {
localDB.db.transaction(this.doQuery,
function(er){
console.log("Transaction ERROR: "+ er.message);
},
function(){
search.bindData();
search.showResults();
}
);
},
bindData: function() {
var tpl_src = $('#table_page_tpl').html();
var template = _.template(tpl_src);
var src = $('#content_list_table_row_tpl').html();
var row_tpl = _.template(src);
$.each(search.data.rows, function() {
search.data.tbody += row_tpl(this);
});
search.renderedResults = template(search.data);
},
doQuery: function(tx) {
tx.executeSql(search.buildQuery(), [],
search.queryCallback);
},
queryCallback: function(tx, result) {
search.zeroRows = (result.rows.length === 0);
for(var i=0; i < result.rows.length; i++) {
var item = result.rows.item(i);
search.data.rows.push(
{ title_text: item.title,
link_url: '#node/' + item.import_id,
icon_class: null,
icon_inner: null,
id: item.import_id,
checkmark_class: null
});
}
},
buildQuery: function() {
search.buildWhere(search.query.split(' '));
search.selectClause = 'SELECT import_id, title';
return search.selectClause+' '+search.fromClause+' '+search.whereClause;
},
buildWhere: function(searchTerms) {
search.whereClause = 'WHERE ';
search.whereClause += search.formatTerms('content.title', searchTerms);
search.whereClause += ' OR '+ search.formatTerms('content.body', searchTerms);
return search.whereClause;
},
formatTerms: function(field, searchTerms) {
tplWhere = _.template("<%= field %> LIKE '%<%= search_term %>%'");
parts = [];
for(i=0; i< searchTerms.length; i++) {
term = searchTerms[i];
parts[i] = tplWhere({field: field, search_term: term});
}
return '('+parts.join(' AND ')+')';
},
bindEvents: function() {
$('body').on('submit', 'form#search',this.handleSubmit);
},
setContentClasses: function() {
return '';
}
});
$(document).ready(function () {
search.initialize();
});
<file_sep><?php
include_once('strip-text-qualifiers-from-row.inc.php');
/*
$filename = $argv[1];
$field_delimiter = $argv[2];
$text_qualifier = $argv[3];
var_dump( generate_field_declaration_from_csv($filename, $field_delimiter, $text_qualifier));
*/
/***
* first row must contain column names
* generates an array of field declarations from column labels
***/
function generate_field_declarations_from_csv($filename, $field_delimiter, $text_qualifier) {
$field_declaration_tpl = <<<HEREDOC
"%s": { "index": %s, "data-type": "%s" }
HEREDOC;
$file = fopen($filename, 'r');
$line = fgetcsv($file, null, $field_delimiter, $text_qualifier);
fclose($file);
strip_text_qualifiers_from_row($line, $text_qualifier);
$declarations = array();
foreach ($line as $idx => $field) {
if (strpos($field, "\n") !== false) $field = str_replace("\n", '', $field);
$data_type = (strpos(strtoupper($field), 'ID') !== false)? 'int' : 'varchar(512)';
$declarations[] = sprintf( $field_declaration_tpl, $field, $idx, $data_type );
}
// var_dump($declarations);
// var_dump(json_decode('{'.join(', ', $declarations).'}'));
return json_decode(str_replace("\r", '', str_replace("\n", '', '{'.join(', ', $declarations).'}')), TRUE);
}
<file_sep>var ask = _.extend(new Controller(), {
activePath: '#ask',
formFields: {},
formErrors: {},
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
$('body').on('submit', 'form#ask', this.handleSubmit);
},
/**
* Handles the submission of the ask a question form
*
* @param {jQuery event} e
* @returns {undefined}
*/
handleSubmit: function(e){
e.preventDefault();
// reset error registry
ask.formErrors = {};
ask.formFields.email = {
element: $('form#ask [name="email"]'),
googleName: "entry.853271876"
};
ask.formFields.question = {
element: $('form#ask [name="question"]'),
googleName: "entry.1272122560"
};
ask.getFormValues();
if (ask.formValidate() === true) {
ask.formPost();
} else {
$('#modal .modal-title').empty().html('<h1>Question not submitted</h1>');
$('#modal .modal-body').empty().html('<p>Please correct the following errors:</p><ul></ul>');
$.each(ask.formErrors, function (k, v){
$('#modal .modal-body ul').append('<li>' + v + '</li>');
});
$('#modal').modal('show');
}
},
/**
* Get values for each form field.
*/
getFormValues: function() {
$.each(this.formFields, function(k, v) {
ask.formFields[k].value = v.element.val();
});
},
main: function() {
this.fetchData();
},
fetchData: function() {
this.data = {};
localDB.db.transaction(
ask.buildQueries,
// TODO: we need a generic error handler
function(tx, er) {
console.log("Transaction ERROR: "+ er.message);
},
function() {
ask.bindData();
ask.updateDisplay();
}
);
},
bindData: function() {
this.data.query = search.query;
var src = $('#ask_form_tpl').html();
var content_tpl = _.template(src);
this.rendered = content_tpl(this.data);
this.updateDisplay();
},
buildQueries: function(tx) {
tx.executeSql(
'SELECT "value" FROM "personal_info" WHERE "key"="email"',
[],
ask.parseResult
);
},
parseResult: function(tx, result) {
ask.data.email = '';
if (result.rows.length === 1) {
ask.data.email = result.rows.item(0).value || '';
}
},
/**
* Posts the data to YI's Google Form
*/
formPost: function() {
var data = {};
$.each(this.formFields, function() {
data[this.googleName] = this.value;
});
var result = $.post(
'https://docs.google.com/forms/d/1y1ciX5QJkfPN5T2M0_FZWJVlwmPP78vB2bYSDTkBtFo/formResponse',
data,
function() {
$('#modal .modal-title').empty().html('<h1>Question Submitted</h1>');
$('#modal .modal-body').empty().html('<p>Thanks for your question. We will respond within two (2) business days.</p>');
$('#modal').modal('show');
$('form#ask .form-control').val('');
}
).fail(function(jqXHR, status, error) {
$('#modal .modal-title').empty().html('<h1>Connection Error</h1>');
$('#modal .modal-body').empty().html('<p>Could not connect to server. Check your network connection.</p>');
$('#modal').modal('show');
});
},
/**
* Checks for a valid email address and question at least one character long.
*
* @return {Boolean}
*/
formValidate: function() {
if (validateEmail(this.formFields.email.value) === false) {
this.formErrors.email = 'Please enter a valid email address';
}
if (this.formFields.question.value.length < 1) {
this.formErrors.question = 'Please enter a question';
}
return (Object.keys(this.formErrors).length === 0);
}
});
$(document).ready(function () {
ask.initialize();
});<file_sep>#!/usr/bin/env node
//this hook installs all your plugins
// add your plugins to this list--either the identifier, the filesystem location or the URL
var pluginlist = [
// appear to be built in reverse
// putting net-info here to be built-later to resolve problem on ios -- MZD
"cordova-plugin-network-information",
"cordova-plugin-inappbrowser",
"https://github.com/ginkgostreet/phonegap-parse-plugin.git#healthyi-1.1 --variable APP_ID=Fb0w8YZ8IzTKaNtLT7AYNsBNUlR8fAwWKbIvMKwW --variable CLIENT_KEY=<KEY>",
"com.ionic.keyboard",
"nl.x-services.plugins.socialsharing",
"cordova-plugin-whitelist"
];
// no need to configure below
var fs = require('fs');
var path = require('path');
var sys = require('sys');
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
sys.puts(stdout);
}
pluginlist.forEach(function(plug) {
exec("cordova plugin add " + plug, puts);
});
<file_sep>#!/usr/bin/env node
// this plugin replaces arbitrary text in arbitrary files
var fs = require('fs');
var path = require('path');
var request = require('request');
var rootdir = process.argv[2];
function replace_string_in_file(filename, to_replace, replace_with) {
if (fs.existsSync(filename)) {
var data = fs.readFileSync(filename, 'utf8');
var result = data.replace(new RegExp(to_replace, "g"), replace_with);
fs.writeFileSync(filename, result, 'utf8');
} else {
console.log('Error prepopulating content: could not find ' + filename);
}
}
if (rootdir) {
var cnt_fetched = 0;
var content = [];
var urls = [
'http://healthyi.yidata.org/healthy/json',
'http://healthyi.yidata.org/listing/json'
];
var platform_path = (process.env.CORDOVA_PLATFORMS === 'android') ? 'platforms/android/assets/www' : 'platforms/ios/www';
urls.forEach(function(url) {
request({url: url, json: true}, function (error, response, json) {
if (!error && response.statusCode === 200) {
console.log('Content successfully retrieved from ' + url);
content = content.concat(json.nodes);
if (++cnt_fetched === urls.length) {
var content_string = JSON.stringify(content);
var datafile = path.join(rootdir, platform_path, 'js/localDB.js');
replace_string_in_file(datafile, 'GSL_INITIAL_DATA', content_string);
var currentTimestamp = new Date().getTime();
// convert from milliseconds to seconds
currentTimestamp = Math.floor(currentTimestamp / 1000);
var appfile = path.join(rootdir, platform_path, 'js/app.js');
replace_string_in_file(appfile, 'GSL_BUILD_TIME', currentTimestamp);
}
}
});
});
}
<file_sep>var content_leaf = _.extend(new Controller(), {
main: function(id) {
content_leaf.id = id;
content_leaf.fetchData();
},
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
$('body').on('tap', '.btn.share', function(e){
e.preventDefault();
content_leaf.socialShare();
});
},
socialShare: function() {
var url = "http://app.healthyyoungamerica.org/";
var file = null;
var msgBody = $(content_leaf.data.body).text().substr(0, 296 - content_leaf.data.title_text.length);
var lastSpace = msgBody.lastIndexOf(" ");
msgBody = msgBody.substring(0, lastSpace);
msgBody = "Check out what I learned from the HealthYI app:\n\n" + content_leaf.data.title_text + "\n" + msgBody + "...\n";
window.plugins.socialsharing.share(
msgBody,
content_leaf.data.title_text,
file,
url,
function(result) {
//onSuccess
},
function(result) {
//onFailure
}
);
},
fetchData: function() {
content_leaf.data = {};
localDB.db.transaction(content_leaf.buildQueries,
// TODO: we need a generic error handler
function(tx, er){
console.log("Transaction ERROR: "+ er.message);
},
function(){
content_leaf.bindData();
content_leaf.updateDisplay();
}
);
},
bindData: function(data) {
var btn_src = $('#bookmark_btn_tpl').html();
var btn_tpl = _.template(btn_src);
content_leaf.data.bookmark_btn = btn_tpl({
content_id: content_leaf.id,
content_table: 'content',
status: content_leaf.data.status
});
var share_src = $('#share_btn_tpl').html();
var share_tpl = _.template(share_src);
content_leaf.data.share_btn = share_tpl({
content_id: content_leaf.id,
content_table: 'content'
});
var src = $('#content_leaf_tpl').html();
var content_tpl = _.template(src);
content_leaf.rendered = content_tpl(content_leaf.data);
},
buildQueries: function(tx) {
tx.executeSql(
'SELECT * FROM content \
LEFT JOIN bookmark \
ON content.import_id = bookmark.content_id \
WHERE import_id = ?',
[content_leaf.id],
content_leaf.parseResult
);
},
parseResult: function(tx, result) {
for(var i=0; i < result.rows.length; i++) {
content_leaf.data.title_text = result.rows.item(i).title;
content_leaf.data.body = result.rows.item(i).body;
content_leaf.data.status = (result.rows.item(i).content_id === null ? 0 : 1);
}
},
usesBackButton: true
});
$(document).ready(function () {
content_leaf.initialize();
});<file_sep>#!/usr/bin/php
<?php
include_once('generate-field-declarations-from-csv.inc.php');
include_once('strip-text-qualifiers-from-row.inc.php');
include_once('generate-sql-create-utils.inc.php');
$filename = $argv[1];
$DELIMITER = ',';
$TEXT_QUALIFIER = '"';
$REQUIRED = array('title'); #skip rows if required fields are present but empty
/*** END CONFIG ***/
$field_map = generate_field_declarations_from_csv($filename, $DELIMITER, $TEXT_QUALIFIER);
/***
* probe field_map:
***/
$deleted = false;
if (key_exists('deleted', $field_map)) {
$deleted = $field_map['deleted']['index'];
// remove from meta data to avoid confusion:
unset($field_map['deleted']);
}
if (key_exists('Related content tags', $field_map)) {
unset($field_map['Related content tags']);
}
$required = array();
foreach($REQUIRED as $key) {
if (key_exists($key, $field_map)) {
$required[] = $field_map[$key]['index'];
}
}
$type = false;
if (key_exists('type', $field_map)) {
$type = $field_map['type']['index'];
}
$link = false;
if (key_exists('link', $field_map)) {
$link = $field_map['link']['index'];
}
$fd = fopen ($filename, "r");
while (!feof($fd) ) {
/***
* validate fields
***/
$line = fgetcsv($fd, null, $DELIMITER, $TEXT_QUALIFIER);
if ($line === false) {
continue;
}
$skip = false;
if (is_numeric($deleted)) {
if ($line[$deleted]) {
$skip = true;
}
}
foreach ($required as $req) {
if (trim($line[$req]) == '') {
$skip = true;
}
}
if ($skip) {
continue;
}
/***
* transform fields
***/
if (is_numeric($type)) {
$line[$type] = str_replace(' ', '_', strtolower(trim($line[$type])));
}
if(is_numeric($link)) {
/*** '{"controller": "content_list", "content_type": "compare_costs", "page_title": "Compare Costs"}' ***/
$fmt = '{"controller": "content_list", "content_type": "%s", "page_title": "%s"}';
$page_title = $line[$field_map['title']['index']];
$line[$link] = sprintf($fmt, str_replace(' ', '_', strtolower(trim($page_title))), $page_title);
}
/* content_leaf?id= */
if (key_exists('body', $field_map)) {
$body_idx = $field_map['body']['index'];
$body = $line[$body_idx];
// rewrite internal links
$body = preg_replace('#href="([0-9]*[^"])"#m', 'href="content_leaf?id=$1"', $body );
//remove line-breaks
$body = str_replace("\n", '', $body);
//escape single-quotes:
$body = str_replace("'", "\\'", $body);
//save xforms
$line[$body_idx] = $body;
}
/***
* concatenate fields:
***/
$line_arr = array();
foreach ($field_map as $field_name => $field_def) {
// create associative array:
$line_arr[$field_name] = $line[$field_def['index']];
}
$file_array[] = $line_arr;
}
fclose($fd);
echo generate_sqlite_insert('content', $file_array, $field_map);
//DONE
/***
* Generate HealthYI app db insert statements (SQLite) w/ tx.executeSql()
***/
function generate_sqlite_insert($table_name, $file_array, $field_map, $first_row_is_header = TRUE, $field_names = NULL) {
if (is_null($field_names)) $field_names = '"'.join('", "', array_keys($field_map)).'"';
$rows = array();
foreach ( $file_array as $line )
{
$row = array();
foreach ($field_map as $field_name => $field_def) {
$field = $line[$field_name];
// if value is a string, quote it:
if (strpos($field_def['data-type'], 'char') !== false) $field = "'{$field}'";
$row[] = $field;
}
$rows[] = $row;
}
if ($first_row_is_header) array_shift($rows);
$prefix = "tx.executeSql('INSERT INTO \"${table_name}\" (${field_names}) VALUES ";
$tokens = array();
for($n=0; $n<count($field_map); $n++) {
$tokens[] = '?';
}
$prefix .= '('. join(',', $tokens) .')';
$prefix .= "'";
$statements = array();
foreach ($rows as $row) {
foreach ($row as $field) {
if (!is_numeric($field)) {
$field = "'$field'";
}
}
$statements[] = $prefix . ", [".join(', ', $row)."]";
}
return join(");\n", $statements) . ");\n";
}
<file_sep>var content_list = _.extend(new Controller(), {
main: function(id) {
content_list.id = id;
content_list.fetchData();
},
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
$('body').on('tap', 'td.icon', function(e){
if (content_list.data.content_type === "health_checklist") {
var el = $(this);
var id = el.data("id");
if(content_list.data.checklist[id]) {
content_list.data.checklist[id] = false;
el.removeClass("checked");
} else {
content_list.data.checklist[id] = true;
el.addClass("checked");
}
content_list.saveChecklist();
}
e.preventDefault();
});
},
fetchData: function() {
content_list.data = {};
content_list.data.rows = [];
localDB.db.transaction(content_list.fetchListNode,
// TODO: we need a generic error handler
function(tx, er){
console.log("Transaction ERROR: "+ er.message);
}
);
},
bindData: function(data) {
var tpl_src = $('#table_page_tpl').html();
var template = _.template(tpl_src);
if(content_list.data.content_type == "health_checklist") {
content_list.data.pre_table = '<p>When you\'ve completed an item, tap its number in the list to check it off.</p>';
}
content_list.data.tbody = '';
var src = $('#content_list_table_row_tpl').html();
var row_tpl = _.template(src);
var i = 1;
$.each(content_list.data.rows, function() {
var row_data = this;
row_data.checkmark_class = '';
row_data.icon_inner = (row_data.icon_class !== null ? '' : i++);
if(content_list.data.content_type == "health_checklist") {
row_data.icon_class = "checkIndex";
if(content_list.data.checklist[ row_data.id ]) {
row_data.checkmark_class = 'checked';
}
}
content_list.data.tbody += row_tpl(row_data);
});
content_list.rendered = template(content_list.data);
},
fetchListNode: function(tx) {
tx.executeSql('SELECT "type", "title", "list_contains" FROM "content" WHERE "import_id" = ?',
[content_list.id],
function(tx, result) {
if (result.rows.length < 1) {
console.log('Could not route request; node ID invalid or no such node.');
} else {
var item = result.rows.item(0);
content_list.data.page_title = item.title;
content_list.data.content_type = item.list_contains;
content_list.fetchList();
}
}
);
},
fetchList: function(tx) {
localDB.db.transaction(content_list.buildQueries,
// TODO: we need a generic error handler
function(tx, er){
console.log("Transaction ERROR: "+ er.message);
},
function(){
if(content_list.data.content_type === "health_checklist") {
content_list.fetchChecklist();
} else {
content_list.bindData();
content_list.updateDisplay();
}
}
);
},
buildQueries: function(tx) {
tx.executeSql('SELECT "import_id", "title", "icon_class" FROM "content" WHERE "type" = ?',
[content_list.data.content_type],
content_list.parseResult
);
},
parseResult: function(tx, result) {
for(var i=0; i < result.rows.length; i++) {
var item = result.rows.item(i);
content_list.data.rows.push({title_text: item.title, link_url: '#node/' + item.import_id, id: item.import_id, icon_class: item.icon_class});
}
},
fetchChecklist: function() {
localDB.db.transaction(
function(tx){
tx.executeSql(
'SELECT "value" FROM "settings" WHERE key="health_checklist"',
[],
function(tx, result) {
if(result.rows.length > 0) {
var item = result.rows.item(0);
content_list.data.checklist = JSON.parse(item.value);
} else {
content_list.data.checklist = {};
}
content_list.bindData();
content_list.updateDisplay();
},
function(tx, er){
console.log("Transaction ERROR: "+ er.message);
}
)
}
);
},
saveChecklist: function() {
//Not 100% why data has to be a var and not called inline,
//but that is the only way it works.
var data = JSON.stringify(content_list.data.checklist);
localDB.db.transaction(
function(tx) {
tx.executeSql('REPLACE INTO "settings" ("key", "value") VALUES (?,?)', ['health_checklist', data]);
},
function() {console.log('Checklist::Update SQL ERROR');}
);
},
usesBackButton: true,
/**
* @returns {String} One or more space-separated classes to be added to the class
* attribute of the content element
*/
setContentClasses: function() {
return 'content_list';
}
});
$(document).ready(function () {
content_list.initialize();
});<file_sep>Router = function() {
/**
* @see this.setClickStack
*/
this.clickStack = [];
this.initialize = function() {
var router = this;
routie({
'content_leaf/:id': function(id) {
content_leaf.control(id);
},
'content_list/:id': function(id) {
content_list.control(id);
},
'node/:id': this.routeNode,
'*': function(controllerName) {
app.logUsage.apply(this, arguments);
controller = router.getControllerByName(controllerName);
if (controller !== false) {
controller.control();
} else if (controllerName !== '') {
console.log('Route for ' + controllerName + ' not implemented');
}
}
});
};
/**
* Determines whether a node is a list or a leaf and routes it accordingly
*
* @param {Int} id Node ID
*/
this.routeNode = function(id) {
app.logUsage.apply(this, arguments);
localDB.db.transaction(
function(tx) {
tx.executeSql(
'SELECT "list_contains" FROM "content" WHERE "import_id" = ?',
[id],
function(tx, result) {
if (result.rows.length < 1) {
console.log('Could not route request; node ID invalid or no such node.');
} else {
var item = result.rows.item(0);
if (item.list_contains === null) {
routie('content_leaf/' + id);
} else {
routie('content_list/' + id);
}
}
}
);
},
function() {console.log('Could not route request; node lookup failed.');}
);
};
/**
* Duck test, since we can't really check inheritance
*
* @param {string} controller name
* @returns {mixed} The controller object on success, boolean false otherwise
*/
this.getControllerByName = function (controller) {
// window[controller] is a variable variable, like double dollar signs in PHP
var c = window[controller];
if (c !== null && typeof c === "object" && 'updateDisplay' in c) {
return c;
} else {
return false;
}
};
/**
* Maintains the list of paths the user has visited. This is used to provide back-button
* functionality where needed. Note that when a user visits a path for the second time,
* the stack is truncated at that point to prevent the user from being caught in an
* endless loop of click "back" between just two pages.
*
* @param {string} destination
* @returns {undefined}
*/
this.setClickStack = function () {
var route = '#' + window.location.hash.substring(1);
var index = this.clickStack.indexOf(route);
if (index === -1) {
this.clickStack.push(route);
} else {
this.clickStack = this.clickStack.slice(0, index + 1);
}
};
};<file_sep>var coverage_info = _.extend(new Controller(), {
activePath: '#coverage_info',
main: function() {
this.fetchData();
},
fetchData: function() {
this.data = {};
this.data.rows = []; // supplies data to the rows of the table
localDB.db.transaction(this.buildQueries,
// TODO: we need a generic error handler
function(tx, er){
console.log("Transaction ERROR: "+ er.message);
},
function(){
coverage_info.render();
}
);
},
buildQueries: function(tx) {
tx.executeSql(
'SELECT "import_id", "title", "icon_class" FROM "content" \
WHERE "type" = ? ORDER BY import_id',
['coverage_info'],
coverage_info.buildRows
);
},
buildRows: function(tx, result) {
for(var i = 0; i < result.rows.length; i++) {
var item = result.rows.item(i);
coverage_info.data.rows.push({
id: item.import_id,
content_type: item.type,
title: item.title,
class: item.icon_class
});
}
},
render: function(data) {
var src = $('#coverage_info_row_tpl').html();
var row_tpl = _.template(src);
this.rendered = "";
$.each(this.data.rows, function() {
coverage_info.rendered += row_tpl({
container_class: this.class,
link_url: '#node/' + this.id,
link_text: this.title
});
});
this.updateDisplay();
},
/**
* Overrides "parent" method.
*
* @returns {String} One or more space-separated classes to be added to the class
* attribute of the content element
*/
setContentClasses: function() {
return 'coverage_info';
}
});<file_sep>var settingsBase = {
insurance_carriers: {},
activePath: '#settings',
formFields: {},
formErrors: {},
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
$('body').on('submit', 'form#settings', this.handleSubmit);
$('body').on('change', 'form#settings select[name="insurance_carrier"]', settings.populateInsurancePlans);
},
/**
* Handles the submission of the settings a question form
*
* @param {jQuery event} e
* @returns {undefined}
*/
handleSubmit: function(e){
e.preventDefault();
// reset error registry
settings.formErrors = {};
settings.getFormValues();
if (settings.formValidate() === true) {
settings.saveProfileData();
} else {
$('#modal .modal-title').empty().html('<h1>Settings not saved</h1>');
$('#modal .modal-body').empty().html('<p>Please correct the following errors:</p><ul></ul>');
$.each(settings.formErrors, function (k, v){
$('#modal .modal-body ul').append('<li>' + v + '</li>');
});
$('#modal').modal('show');
}
},
/**
* Fetches all settings
* @returns {undefined}
*/
fetchProfileData: function(success, error) {
if (!error) {
error = function(er){
console.log("Transaction ERROR: "+ er.message);
}
}
localDB.db.transaction(
function(tx){
tx.executeSql(
'SELECT "key", "value" FROM "personal_info" \
WHERE profile_id = "0"',
[],
success
)
},
error
);
},
/**
* Save profile Data (contents of the model - use getFormValues first)
* @returns {undefined}
*/
saveProfileData: function() {
var profile_id = '0';
localDB.db.transaction(
function(tx) {
tx.executeSql('INSERT or REPLACE into personal_info (profile_id, key, value) VALUES (?, ?, ?)',
[profile_id, 'email', settings.formFields.email.value]);
tx.executeSql('INSERT or REPLACE into personal_info (profile_id, key, value) VALUES (?, ?, ?)',
[profile_id, 'provider', settings.formFields.provider.value]);
tx.executeSql('INSERT or REPLACE into personal_info (profile_id, key, value) VALUES (?, ?, ?)',
[profile_id, 'plan', settings.formFields.plan.value]);
tx.executeSql('INSERT or REPLACE into personal_info (profile_id, key, value) VALUES (?, ?, ?)',
[profile_id, 'zipcode', settings.formFields.zipcode.value]);
},
function() {console.log('settings::saveProfileData SQL ERROR');},
settings.confirmSaved()
);
},
confirmSaved: function() {
$('#modal .modal-title').empty().html('<h1>Personal Settings</h1>');
$('#modal .modal-body').empty().html('<p>Your settings have been saved.</p>');
$('#modal').modal('show');
},
bindData: function(tx, result) {
settings.setFormValues(result.rows);
settings.populateInsuranceCarriers();
settings.populateInsurancePlans();
},
/**
* Update form model from user entry
* @returns none
*/
getFormValues: function() {
if (Object.keys(settings.formFields).length === 0) {
settings.findFormElements();
}
$.each(this.formFields, function(k, v) {
settings.formFields[k].value = v.element.val();
});
},
/**
* Assign values to form model, update elements with model;
* @param array values
* @returns none
*/
setFormValues: function(values) {
settings.findFormElements();
if (values !== null) {
for(var i = 0; i < values.length; i++) {
var item = values.item(i);
switch (item.key) {
case 'email':
settings.formFields.email.value = item.value;
settings.formFields.email.element.val(item.value);
break;
case 'provider':
settings.formFields.provider.value = item.value;
break;
case 'plan':
settings.formFields.plan.value = item.value;
break;
case 'zipcode':
settings.formFields.zipcode.value = item.value;
settings.formFields.zipcode.element.val(item.value);
break;
}
}
}
},
/**
* Initialize form model with references to DOM elements
* @returns {undefined}
*/
findFormElements: function() {
settings.formFields.email = {
element: $('form [name="email"]')
};
settings.formFields.provider = {
element: $('form [name="insurance_carrier"]'),
};
settings.formFields.plan = {
element: $('form [name="insurance_plan"]'),
};
settings.formFields.zipcode = {
element: $('form [name="zipcode"]'),
};
},
main: function() {
this.renderTpl();
schedule.fetchInsuranceCarriers(this.fillInsuranceCarriers);
this.fetchProfileData(settings.bindData);
},
renderTpl: function() {
var src = $('#settings_form_tpl').html();
var content_tpl = _.template(src);
this.rendered = content_tpl();
this.updateDisplay();
},
/**
* Checks for a valid email address and question at least one character long.
*
* @return {Boolean}
*/
formValidate: function() {
var email = this.formFields.email.value;
if (email != '' && validateEmail(email) === false) {
this.formErrors.email = 'Please enter a valid email address';
}
var zipcode = this.formFields.zipcode.value;
var zipIsValid = validateZIP(zipcode);
if (this.formFields.zipcode.value != '' && zipIsValid !== true) {
this.formErrors.zip = zipIsValid;
}
return (Object.keys(this.formErrors).length === 0);
},
fillInsuranceCarriers: function(tx, result) {
var item = result.rows.item(0);
settings.insurance_carriers = JSON.parse(item.value);
},
/**
* This is a placeholder function to populate the list of insurance carriers the user may select.
*/
populateInsuranceCarriers: function() {
var select = $('form select[name="insurance_carrier"]');
$.each(settings.insurance_carriers, function(){
var opt = '<option value="' + this.id + '">' + this.name + '</option>';
select.append(opt);
});
select.val(settings.formFields.provider.value);
select.select2();
},
/**
* This is a placeholder function to populate the list of insurance plans the user may select.
*/
populateInsurancePlans: function() {
$('form select[name="insurance_plan"] option:not(:first)').remove();
var plans = schedule.getInsurancePlans(settings.insurance_carriers);
var select = $('form select[name="insurance_plan"]');
$.each(plans, function(){
var opt = '<option value="' + this.id + '">' + this.name + '</option>';
select.append(opt);
});
select.val(settings.formFields.plan.value);
select.select2();
}
};
var settings = _.extend(new Controller(), settingsBase);
$(document).ready(function () {
settings.initialize();
});<file_sep>var bookmark = _.extend(new Controller(), {
activePath: '#bookmark',
// Application Constructor
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
$('body').on('tap', '.toggle-fave', function(e){
e.preventDefault();
var el = $(e.currentTarget);
if (el.is('.active')) {
bookmark.delete(el);
} else {
bookmark.save(el);
}
});
$('body').on('tap', '.btn.toggle-fave', function(e){
e.preventDefault();
$(this).find('span').animate({marginLeft: "0px"}, "slow");
});
},
/**
* @param {object} el The clicked element. Must have content_id and content_table
* properties for the DB interaction. The element is passed along to
* bookmark.updateButton, which handles representing state to the user.
*/
delete: function(el) {
localDB.db.transaction(
function(tx) {
tx.executeSql('DELETE FROM bookmark WHERE content_id = ? AND content_table = ?',
[el.data('id'), el.data('table')]);
},
function() {console.log('bookmarks::delete SQL ERROR');},
bookmark.updateButton(el)
);
},
/**
* @param {object} el The clicked element. Must have content_id and content_table
* properties for the DB interaction. The element is passed along to
* bookmark.updateButton, which handles representing state to the user.
*/
save: function(el) {
localDB.db.transaction(
function(tx) {
tx.executeSql('INSERT INTO bookmark (content_id, content_table) VALUES (?, ?)',
[el.data('id'), el.data('table')]);
},
function() {console.log('bookmarks::save SQL ERROR');},
bookmark.updateButton(el)
);
Parse.Analytics.track('save_bookmark', {action: 'save', node: String(el.data('id')), table: el.data('table') });
},
updateButton: function(button) {
// do this for both buttons and stars on the bookmarks page
button.toggleClass('active');
// check to make sure this is a button (i.e., at the bottom of a page of content),
// not a star on the bookmarks page
if (button.is('button')) {
// use a little animation to clue in the user that something is happening
var fontsize = button.css('font-size');
var txt = button.is('.active') ? 'Remove from favorites' : 'Add to favorites';
// we don't want the button to resize, just the text within it
var height = button.css('height');
button.css('min-height', height);
button.animate({"font-size": '0px'}, {duration: 100, complete: function() {
button.text(txt).animate({"font-size": fontsize}, 100);
}});
} else {
// clean up the bookmarks page
bookmark.removeUnfavoritedItems();
}
},
main: function() {
this.fetchData();
},
/**
* Fetches all bookmarks
*
* @returns {undefined}
*/
fetchData: function() {
this.data = {};
this.data.rows = []; // supplies data to the rows of the table
this.data.page_title = 'Bookmarks';
this.data.content_type = 'table-striped'; // this has a funny name; it's used to set a class on the table
localDB.db.transaction(this.buildQueries,
// TODO: we need a generic error handler
function(tx, er){
console.log("Transaction ERROR: "+ er.message);
},
function(){
bookmark.bindData();
bookmark.updateDisplay();
}
);
},
buildQueries: function(tx) {
tx.executeSql(
'SELECT DISTINCT "import_id", "title", "type" FROM "content" \
INNER JOIN "bookmark" \
ON "import_id" = "content_id"',
[],
bookmark.buildRows
);
},
buildRows: function(tx, result) {
for(var i = 0; i < result.rows.length; i++) {
var item = result.rows.item(i);
bookmark.data.rows.push({
id: item.import_id,
title: item.title
});
}
},
bindData: function(data) {
var bookmark_cell_src = $('#bookmark_cell').html();
var bookmark_cell_tpl = _.template(bookmark_cell_src);
var src = $('#bookmark_table_row_tpl').html();
var row_tpl = _.template(src);
this.data.tbody = '';
$.each(this.data.rows, function() {
this.link_url = '#node/' + this.id;
this.bookmark_cell = bookmark_cell_tpl({
content_id: this.id,
content_table: 'content',
status: 1
});
bookmark.data.tbody += row_tpl(this);
});
var tpl_src = $('#table_page_tpl').html();
var template = _.template(tpl_src);
this.rendered = template(this.data);
},
removeUnfavoritedItems: function() {
// TODO: this selector should be... more selective
$('table.table .toggle-fave').not('.active').parent('tr').remove();
}
});
$(document).ready(function () {
bookmark.initialize();
});<file_sep>Healthy New York
================
This is a mobile app in progress, built using PhoneGap/Cordova and Bootstrap.
Presently we are focusing on an Android release and testing against the Nexus 4.
Eventually we will target various devices and platforms.
TODOS
-----
* Package management for jQuery and Bootstrap, probably involving Grunt, Bower,
and/or Cordova hooks. For the time being, files from other libraries (i.e.,
jQuery and Bootstrap) have been committed to the www/js and www/css directories.
This is suboptimal.
* Remove cruft from the Cordova Hello World app.
* Consider using LESS for nesting CSS rules, etc.
|
e36f2daf3c6d29a91c59fe748f7b8a2e433fc569
|
[
"JavaScript",
"Markdown",
"PHP"
] | 17 |
JavaScript
|
ginkgomzd/healthynewyork
|
9e6c751f733fd461ac54a6749ddeadd59038a912
|
76d96aa0d0278ef302c17e3a1e2c6ca095a21dbb
|
refs/heads/master
|
<repo_name>NeuronRobotics/c-bowler<file_sep>/Sample/native/Makefile
#@ Author <NAME>
SHELL := /bin/bash -e
CFILES := $(wildcard *.c)
OFILES := $(CFILES:%.c=%.o)
BIN :=BowlerImplimentationExample.exe
ifndef CC_Bowler_Arch
CC_Bowler_Arch :=gcc -Os -g3 -Wall -fmessage-length=0 -MMD -MP
endif
all:clean $(OFILES)
$(CC_Bowler_Arch) $(OFILES) -L../../lib/native/linux -lNRLIB_debug -o $(BIN)
chmod +x $(BIN)
%.o: %.c
$(CC_Bowler_Arch) -I../../Platform/include/ -I../../BowlerStack/include/ -c $< -o $@
clean:
rm -rf $(OFILES)
rm -rf *.d
rm -rf $(BIN)<file_sep>/BowlerStack/include/Bowler/BowlerRPCRegestration.h
/*
* BowlerRPCRegestration.h
*
* Created on: Sep 29, 2010
* Author: hephaestus
*/
#ifndef BOWLERRPCREGESTRATION_H_
#define BOWLERRPCREGESTRATION_H_
#define MAX_NUM_RPC 15
uint8_t addRPC(uint8_t method,const char * rpc,void( *_callback)(BowlerPacket*));
#if !defined(USE_LINKED_LIST_NAMESPACE)
uint8_t setMethodCallback(uint8_t method,BYTE( *_callback)(BowlerPacket*));
#endif
typedef void rpcCallback(BowlerPacket *);
typedef struct _RPC_HANDLER{
unsigned long rpc;
rpcCallback * callback;
} RPC_HANDLER;
typedef struct _RPC_HANDLER_SET{
unsigned char numRPC;
RPC_HANDLER handlers[MAX_NUM_RPC];
} RPC_HANDLER_SET;
typedef uint8_t methodCallback(BowlerPacket *);
typedef struct _METHOD_HANDLER{
unsigned char set;
methodCallback * callback;
} METHOD_HANDLER;
#endif /* BOWLERRPCREGESTRATION_H_ */
<file_sep>/BowlerStack/src/PID/PidVelocity.c
/*
* PidVelocity.c
*
* Created on: Feb 14, 2014
* Author: hephaestus
*/
#include "Bowler/Bowler.h"
void RunVel(void){
uint8_t i;
for (i=0;i<getNumberOfPidChannels();i++){
//println_I("Checking velocity on ");p_int_I(i);
if(!getPidGroupDataTable(i)->config.Enabled){
RunPDVel(i);
}
}
}
float runPdVelocityFromPointer(PD_VEL* vel, float currentState,float KP, float KD){
float currentTime = getMs();
float timeMsDiff = (currentTime -vel->lastTime);
float timeDiff = timeMsDiff/1000;
float posDiff=currentState -vel->lastPosition;
float currentVelocity = posDiff/timeDiff;
//float velocityDiff = currentVelocity-vel->lastVelocity;
float velocityDiff=0;
float proportional = currentVelocity-vel->unitsPerSeCond;
float set = (proportional*KP)+(velocityDiff*KD)*timeMsDiff;
vel->currentOutputVel-=(set);
if (vel->currentOutputVel>200){
vel->currentOutputVel=200;
}else if(vel->currentOutputVel<-200){
vel->currentOutputVel=-200;
}
println_I("\t Velocity: set= ");p_fl_I(vel->unitsPerSeCond );print_I(" ticks/seCond" );
println_I("\t current state= ");p_fl_I(currentState );print_I(" ticks" );
println_I("\t last state= ");p_fl_I(vel->lastPosition );print_I(" ticks" );
println_I("\t position diff= ");p_fl_I(posDiff );print_I(" ticks" );
println_I("\t MS diff= ");p_fl_I(timeMsDiff );
println_I("\t current= ");p_fl_I(currentVelocity );print_I(" ticks/seCond" );
println_I("\t Velocity offset= ");p_fl_I(set );
println_I("\t Velocity set= ");p_fl_I(vel->currentOutputVel );
//cleanup
vel->lastPosition=currentState;
vel->lastVelocity=currentVelocity;
vel->lastTime=currentTime;
return vel->currentOutputVel;
}
void RunPDVel(uint8_t chan){
//println_I("Running PID vel");
if(getPidVelocityDataTable(chan)->enabled==true) {
getPidGroupDataTable(chan)->Output=runPdVelocityFromPointer(getPidVelocityDataTable(chan),
getPidGroupDataTable(chan)->CurrentState,
getPidGroupDataTable(chan)->config.V.P,
getPidGroupDataTable(chan)->config.V.D
);
if(GetPIDCalibrateionState(chan)<=CALIBRARTION_DONE)
setOutput(chan,getPidGroupDataTable(chan)->Output);
}
}
void StartPDVel(uint8_t chan,float unitsPerSeCond,float ms){
if(ms<.1){
//println_I("Starting Velocity");
getPidVelocityDataTable(chan)->enabled=true;
getPidGroupDataTable(chan)->config.Enabled=false;
getPidVelocityDataTable(chan)->lastPosition=GetPIDPosition(chan);
getPidVelocityDataTable(chan)->lastTime=getMs();
getPidVelocityDataTable(chan)->unitsPerSeCond=unitsPerSeCond;
getPidVelocityDataTable(chan)->currentOutputVel =0;
}else{
//println_I("Starting Velocity Timed");
float seConds = ms/1000;
int32_t dist = (int32_t) unitsPerSeCond*(int32_t) seConds;
int32_t delt = ((int32_t) (GetPIDPosition(chan))-dist);
SetPIDTimed(chan, delt, ms);
}
}
<file_sep>/Platform/src/pic32/Tick.c
/*********************************************************************
*
* Tick Manager for Timekeeping
*
*********************************************************************
* FileName: Tick.c
* Dependencies: Timer 0 (PIC18) or Timer 1 (PIC24F, PIC24H,
* dsPIC30F, dsPIC33F, PIC32)
* Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32
* Compiler: Microchip C32 v1.00 or higher
* Microchip C30 v3.01 or higher
* Microchip C18 v3.13 or higher
* HI-TECH PICC-18 STD 9.50PL3 or higher
* Company: Microchip Technology, Inc.
*
* Software License Agreement
*
* Copyright (C) 2002-2008 Microchip Technology Inc. All rights
* reserved.
*
* Microchip licenses to you the right to use, modify, copy, and
* distribute:
* (i) the Software when embedded on a Microchip microcontroller or
* digital signal controller product ("Device") which is
* integrated into Licensee's product; or
* (ii) ONLY the Software driver source files ENC28J60.c and
* ENC28J60.h ported to a non-Microchip device used in
* conjunction with a Microchip ethernet controller for the
* sole purpose of interfacing with the ethernet controller.
*
* You should refer to the license agreement accompanying this
* Software for additional information regarding your rights and
* obligations.
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
* PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
* BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
* THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
* SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
*
*
* Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* <NAME> 6/28/01 Original (Rev 1.0)
* <NAME> 2/9/02 Cleanup
* <NAME> 5/22/02 Rev 2.0 (See version.log for detail)
* <NAME> 6/13/07 Changed to use timer without
* writing for perfect accuracy.
********************************************************************/
#define __TICK_C
#include "arch/pic32/BowlerConfig.h"
#include "Bowler/Bowler.h"
#if defined(__PIC32MX__)
#define SYS_FREQ (80000000L)
#define PB_DIV 1
#define PRESCALE 256
#define TOGGLES_PER_SEC 10000
#define T1_TICK (SYS_FREQ/PB_DIV/PRESCALE/TOGGLES_PER_SEC)
#endif
// Internal counter to store Ticks.
uint32_t dwInternalTicks = 0;
uint32_t dwInternalTicksUpper = 0;
/*****************************************************************************
Function:
void TickInit(void)
Summary:
Initializes the Tick manager module.
Description:
Configures the Tick module and any necessary hardware resources.
Precondition:
None
Parameters:
None
Returns:
None
Remarks:
This function is called only one during lifetime of the application.
***************************************************************************/
void TickInit(void)
{
OpenTimer1(T1_ON | T1_SOURCE_INT | T1_PS_1_256, T1_TICK);
ConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_7);
}
/*****************************************************************************
Function:
uint32_t TickGet(void)
Summary:
Obtains the current Tick value.
Description:
This function retrieves the current Tick value, allowing timing and
measurement code to be written in a non-blocking fashion. This function
retrieves the least significant 32 bits of the internal tick counter,
and is useful for measuring time increments ranging from a few
microseconds to a few hours. Use TickGetDiv256 or TickGetDiv64K for
longer periods of time.
Precondition:
None
Parameters:
None
Returns:
Lower 32 bits of the current Tick value.
***************************************************************************/
uint32_t TickGet(void)
{
return (TickGetLower())+TMR1;
}
uint32_t TickGetUpper()
{
return dwInternalTicksUpper;
}
uint32_t TickGetLower()
{
return dwInternalTicks;
}
/*****************************************************************************
Function:
uint32_t TickConvertToMilliseconds(uint32_t dwTickValue)
Summary:
Converts a Tick value or difference to milliseconds.
Description:
This function converts a Tick value or difference to milliseconds. For
example, TickConvertToMilliseconds(32768) returns 1000 when a 32.768kHz
clock with no prescaler drives the Tick module interrupt.
Precondition:
None
Parameters:
dwTickValue - Value to convert to milliseconds
Returns:
Input value expressed in milliseconds.
Remarks:
This function performs division on DWORDs, which is slow. Avoid using
it unless you absolutely must (such as displaying data to a user). For
timeout comparisons, compare the current value to a multiple or fraction
of TICK_SECOND, which will be calculated only once at compile time.
***************************************************************************/
float MyTickConvertToMilliseconds(float dwTickValue)
{
float ret;
do{
ret = (
(
( dwTickValue)+
(TICKS_PER_SECOND/2000ul)
)/
( (float) (TICKS_PER_SECOND/1000ul) )
);
if(isnan(ret)){
println_E("Timer NaN, recalculating..");
}
}while(isnan(ret));
return ret;
}
float TickGetMS(void)
{
return MyTickConvertToMilliseconds((float)TickGet()
+(((float)TickGetUpper())*((float) 4294967295ul )))
;
}
/*****************************************************************************
Function:
void TickUpdate(void)
Description:
Updates the tick value when an interrupt occurs.
Precondition:
None
Parameters:
None
Returns:
None
***************************************************************************/
//void __ISR(_TIMER_1_VECTOR, TICKIPL) Timer1Handler(void)
void __ISR(_TIMER_1_VECTOR, IPL7AUTO) Timer1Handler(void)
{
//mPORTDToggleBits(BIT_3);
uint32_t before = TickGetLower();
dwInternalTicks+=TICKS_PER_SECOND/TOGGLES_PER_SEC;
if(TickGetLower()<before){
dwInternalTicks=0;
dwInternalTicksUpper++;
}
mT1ClearIntFlag();
//println("@%@%@%@%Tick");
}
<file_sep>/Platform/src/pic32/Bowler_USB_HAL.c
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
// USB values
#include "arch/pic32/BowlerConfig.h"
#include "Bowler/Bowler.h"
boolean GetPacketUSB(uint8_t * packet,uint16_t size){
USBGetArray(packet, size);
return true;
}
void SendPacketUSB(uint8_t * packet,uint16_t size){
if (USBPutArray(packet, size)){
//println_I("Sent to USB");
}else{
//println_E("Failed to send to USB");
}
}
uint16_t Get_USB_Byte_Count(void){
return GetNumUSBBytes();
}
<file_sep>/Platform/include/arch/pic32/Pizo.h
/*
* Pizo.h
*
* Created on: Aug 7, 2010
* Author: hephaestus
*/
#ifndef PIZO_H_
#define PIZO_H_
#define RED_LED_TRIS (_TRISB1) //
#define RED_LED_IO (_RB1)
#define GREEN_LED_TRIS (_TRISB2) //
#define GREEN_LED_IO (_RB2)
#define BLUE_LED_TRIS (_TRISB3) //
#define BLUE_LED_IO (_RB3)
#define startLED() AD1CHS = 0x0000;AD1PCFG = 0xFFFF;AD1CON1 = 0x0000;AD1CON2 = 0x0000;AD1CON3 = 0x0000;AD1CSSL = 0x0000;PORTSetPinsDigitalOut(IOPORT_B,BIT_1|BIT_2|BIT_3)
#define SET_RED(a) (a==0?PORTSetBits(IOPORT_B,BIT_1):PORTClearBits(IOPORT_B,BIT_1))
#define SET_GREEN(a) (a==0?PORTSetBits(IOPORT_B,BIT_2):PORTClearBits(IOPORT_B,BIT_2))
#define SET_BLUE(a) (a==0?PORTSetBits(IOPORT_B,BIT_3):PORTClearBits(IOPORT_B,BIT_3))
#endif /* PIZO_H_ */
<file_sep>/BowlerStack/src/PID/PidAsync.c
/*
* PidAsync.c
*
* Created on: Feb 14, 2014
* Author: hephaestus
*/
#include "Bowler/Bowler.h"
RunEveryData pidAsyncTimer ={0,100};
void updatePidAsync(BowlerPacket *Packet,boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet)){
if(RunEvery(&pidAsyncTimer)){
int i;
int update = false;
for (i=0;i<getNumberOfPidChannels();i++){
if(getPidGroupDataTable(i)->config.Async){
if(getPidGroupDataTable(i)->CurrentState != getPidGroupDataTable(i)->lastPushedValue){
//println_E("Async because of ");p_int_E(i);
update = true;
}
}
}
if(update){
pushAllPIDPositions(Packet,pidAsyncCallbackPtr);
}
}
}
void pushAllPIDPositions(BowlerPacket *Packet,boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet)){
//float time = getMs();
// for(i=0;i<getNumberOfPidChannels();i++){
// pushPID(i,getPidGroupDataTable(i)->CurrentState, time);
// }
INT32_UNION PID_Temp;
LoadCorePacket(Packet);
Packet->use.head.DataLegnth=5;
Packet->use.head.RPC = GetRPCValue("apid");
int i;
for(i=0;i<getNumberOfPidChannels();i++){
PID_Temp.Val=getPidGroupDataTable(i)->CurrentState;
Packet->use.data[0+(i*4)]=PID_Temp.byte.FB;
Packet->use.data[1+(i*4)]=PID_Temp.byte.TB;
Packet->use.data[2+(i*4)]=PID_Temp.byte.SB;
Packet->use.data[3+(i*4)]=PID_Temp.byte.LB;
Packet->use.head.DataLegnth+=4;
}
Packet->use.head.Method=BOWLER_ASYN;
FixPacket(Packet);
if(pidAsyncCallbackPtr!=NULL)
pidAsyncCallbackPtr(Packet);
}
void pushPIDLimitEvent(BowlerPacket *Packet,boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet),PidLimitEvent * event){
if(event->type == NO_LIMIT){
return;
}
event->latchTickError=0;
if(event->type == INDEXEVENT){
if(getPidGroupDataTable(event->group)->config.useIndexLatch){
event->latchTickError = event->value-GetPIDPosition(event->group);
event->value = getPidGroupDataTable(event->group)->config.IndexLatchValue;
if(getPidGroupDataTable(event->group)->config.stopOnIndex){
pidReset(event->group,event->value);
}else{
event->value = pidResetNoStop(event->group,event->value);
}
}
}else{
//println_I("ABSTRACTPID: End stop limit, setting new PID setpoint");
event->value=GetPIDPosition(event->group);
event->latchTickError=0;
event->time = getMs();
SetPID(event->group,event->value);
}
getPidGroupDataTable(event->group)->lastPushedValue=event->value;
LoadCorePacket(Packet);
Packet->use.head.MessageID = 0;
Packet->use.head.Method=BOWLER_ASYN;
Packet->use.head.RPC = GetRPCValue("pidl");
Packet->use.data[0]=event->group;
Packet->use.data[1]=event->type;
INT32_UNION tmp;
tmp.Val=event->value;
Packet->use.data[2]=tmp.byte.FB;
Packet->use.data[3]=tmp.byte.TB;
Packet->use.data[4]=tmp.byte.SB;
Packet->use.data[5]=tmp.byte.LB;
tmp.Val=event->time;
Packet->use.data[6]=tmp.byte.FB;
Packet->use.data[7]=tmp.byte.TB;
Packet->use.data[8]=tmp.byte.SB;
Packet->use.data[9]=tmp.byte.LB;
tmp.Val=event->latchTickError;
Packet->use.data[10]=tmp.byte.FB;
Packet->use.data[11]=tmp.byte.TB;
Packet->use.data[12]=tmp.byte.SB;
Packet->use.data[13]=tmp.byte.LB;
Packet->use.head.DataLegnth = 4+1+1+(4*3);
event->type = NO_LIMIT;
FixPacket(Packet);
if(pidAsyncCallbackPtr!=NULL)
pidAsyncCallbackPtr(Packet);
}
void pushPID(BowlerPacket *Packet,boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet),uint8_t chan, int32_t value, float time){
LoadCorePacket(Packet);
Packet->use.head.Method=BOWLER_ASYN;
Packet->use.head.MessageID = 0;
Packet->use.head.RPC = GetRPCValue("_pid");
Packet->use.head.DataLegnth = 4+1+4+4+4;
Packet->use.data[0]=chan;
INT32_UNION tmp;
tmp.Val=value;
Packet->use.data[1]=tmp.byte.FB;
Packet->use.data[2]=tmp.byte.TB;
Packet->use.data[3]=tmp.byte.SB;
Packet->use.data[4]=tmp.byte.LB;
tmp.Val=time;
Packet->use.data[5]=tmp.byte.FB;
Packet->use.data[6]=tmp.byte.TB;
Packet->use.data[7]=tmp.byte.SB;
Packet->use.data[8]=tmp.byte.LB;
float diffTime = time-getPidGroupDataTable(chan)->lastPushedValue;
float diffVal = value -getPidGroupDataTable(chan)->lastPushedTime;
tmp.Val = (int32_t) (diffVal/diffTime);
Packet->use.data[9]=tmp.byte.FB;
Packet->use.data[10]=tmp.byte.TB;
Packet->use.data[11]=tmp.byte.SB;
Packet->use.data[12]=tmp.byte.LB;
FixPacket(Packet);
if(pidAsyncCallbackPtr !=NULL){
if(pidAsyncCallbackPtr(Packet)){
getPidGroupDataTable(chan)->lastPushedValue =value;
getPidGroupDataTable(chan)->lastPushedTime=time;
}
}
}
<file_sep>/BowlerStack/include/Bowler/BowlerTransport.h
/*
* BowlerTransport.h
*
* Created on: May 27, 2010
* Author: hephaestus
*/
#ifndef BOWLERTRANSPORT_H_
#define BOWLERTRANSPORT_H_
#include "FIFO.h"
boolean GetBowlerPacket_arch(BowlerPacket * Packet);
boolean GetBowlerPacket(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo);
boolean PutBowlerPacket(BowlerPacket * Packet);
void FixPacket(BowlerPacket * Packet);
boolean GetBowlerPacketDebug(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo);
boolean _getBowlerPacket(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo, boolean debug);
#endif /* BOWLERTRANSPORT_H_ */
<file_sep>/BowlerStack/Makefile
#@ Author <NAME>
SHELL := /bin/bash -e
CFILES := $(wildcard src/*.c) $(wildcard src/*/*.c)
OFILES := $(CFILES:%.c=%.o)
DFILES := $(CFILES:%.c=%.d)
#ifndef CC_Bowler_Arch
# $(error CC_Bowler_Arch is undefined)
#endif
all:clean $(OFILES)
echo ok
%.o: %.c
$(CC_Bowler_Arch) -Iinclude -c $< -o $@
clean:
rm -rf $(OFILES)
rm -rf $(DFILES)
lib:$(OFILES)
$(AR) rcs libNRLIB.a $(OFILES)<file_sep>/Platform/Makefile
# Generated Makefile
#@ Author <NAME>
SHELL := /bin/bash -e
-include ../toolchain/pic32/toolchain.mk
-include ../toolchain/avr/toolchain.mk
CCP_pic32MX440F128H = $(GCCP) -mprocessor=32MX440F128H
CCP_pic32MX460F512L = $(GCCP) -mprocessor=32MX460F512L
CCP_pic32MX795F512L = $(GCCP) -mprocessor=32MX795F512L
CPU_SPD = 18432000UL
GCCA_full = $(GCCA) -DF_CPU=$(CPU_SPD) -I/usr/lib/avr/include/
CCA_avratmega324p = $(GCCA_full) -mmcu=atmega324p
CCA_avratmega644p = $(GCCA_full) -mmcu=atmega644p
CCNAT = gcc -Os -g3 -Wall -fmessage-length=0 -MMD -MP
LIBDIR = ../lib
AVR_CFILES :=$(wildcard src/avr/*.c) $(wildcard ../BowlerStack/src/*.c) $(wildcard ../BowlerStack/src/*/*.c)
AVR_FILTERED:=$(filter-out $(wildcard ../BowlerStack/src/PID/*.c), $(AVR_CFILES))
AVR_OFILES := $(AVR_FILTERED:%.c=%.o)
PIC_CFILES :=$(wildcard src/pic32/*.c) $(wildcard src/pic32/*/*.c) $(wildcard ../BowlerStack/src/*.c) $(wildcard ../BowlerStack/src/*/*.c)
PIC_OFILES := $(PIC_CFILES:%.c=%.o)
NATIVE_CFILES :=$(wildcard src/native/*.c) $(wildcard ../BowlerStack/src/*.c) $(wildcard ../BowlerStack/src/*/*.c)
NATIVE_OFILES := $(NATIVE_CFILES:%.c=%.o)
all: COMPILE
echo "Done!"
clean:
rm -rf $(AVR_OFILES) $(PIC_OFILES) $(NATIVE_OFILES)
COMPILE: pic32MX440F128H AVR644p
#COMPILE: pic32MX440F128H AVR324p AVR644p pic32MX460F512L pic32MX795F512L Native
#COMPILE: pic32MX440F128H
echo OK
Native:
mkdir -p $(LIBDIR)/native/linux/
make -C src/native/ CC_Bowler_Arch="$(CCNAT)"
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCNAT) -DNO_PRINTING -I../Platform/include/"
$(AR) rcs $(LIBDIR)/native/linux/libNRLIB.a $(NATIVE_OFILES)
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCNAT) -I../Platform/include/"
$(AR) rcs $(LIBDIR)/native/linux/libNRLIB_debug.a $(NATIVE_OFILES)
make -C ../BowlerStack/ clean
make -C src/native/ clean
AVR644p:
echo $(AVR_OFILES)AVR644p
mkdir -p $(LIBDIR)/AVR/atmega644p/
rm -f $(LIBDIR)/AVR/atmega644p/libNRLIB.a
rm -f $(LIBDIR)/AVR/atmega644p/libNRLIB_debug.a
make -C src/avr/ CC_Bowler_Arch="$(CCA_avratmega644p)"
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCA_avratmega644p) -DNO_PRINTING -I../Platform/include/"
$(ARAVR) rcs $(LIBDIR)/AVR/atmega644p/libNRLIB.a $(AVR_OFILES)
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCA_avratmega644p) -I../Platform/include/"
$(ARAVR) rcs $(LIBDIR)/AVR/atmega644p/libNRLIB_debug.a $(AVR_OFILES)
rm -rf o
mkdir o
cd o/;ar x ../$(LIBDIR)/AVR/atmega644p/libNRLIB.a
ls -al o/*
make -C ../BowlerStack/ clean
make -C src/avr/ clean
AVR324p:
mkdir -p $(LIBDIR)/AVR/atmega324p/
make -C src/avr/ CC_Bowler_Arch="$(CCA_avratmega324p)"
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCA_avratmega324p) -DNO_PRINTING -I../Platform/include/"
$(ARAVR) rcs $(LIBDIR)/AVR/atmega324p/libNRLIB.a $(AVR_OFILES)
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCA_avratmega324p) -I../Platform/include/"
$(ARAVR) rcs $(LIBDIR)/AVR/atmega324p/libNRLIB_debug.a $(AVR_OFILES)
make -C ../BowlerStack/ clean
make -C src/avr/ clean
pic32MX440F128H:
mkdir -p $(LIBDIR)/PIC32/32MX440F128H/
rm -f $(LIBDIR)/PIC32/32MX440F128H/*.a
make -C src/pic32/ CC_Bowler_Arch="$(CCP_pic32MX440F128H)"
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCP_pic32MX440F128H) -DNO_PRINTING -I../Platform/include/"
$(ARP) rcs $(LIBDIR)/PIC32/32MX440F128H/libNRLIB.a $(PIC_OFILES)
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCP_pic32MX440F128H) -I../Platform/include/"
$(ARP) rcs $(LIBDIR)/PIC32/32MX440F128H/libNRLIB_debug.a $(PIC_OFILES)
make -C ../BowlerStack/ clean
make -C src/pic32/ clean
pic32MX460F512L:
mkdir -p $(LIBDIR)/PIC32/32MX460F512L/
rm -f $(LIBDIR)/PIC32/32MX460F512L/*.a
make -C src/pic32/ CC_Bowler_Arch="$(CCP_pic32MX460F512L)"
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCP_pic32MX460F512L) -DNO_PRINTING -I../Platform/include/"
$(ARP) rcs $(LIBDIR)/PIC32/32MX460F512L/libNRLIB.a $(PIC_OFILES)
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCP_pic32MX460F512L) -I../Platform/include/"
$(ARP) rcs $(LIBDIR)/PIC32/32MX460F512L/libNRLIB_debug.a $(PIC_OFILES)
make -C ../BowlerStack/ clean
make -C src/pic32/ clean
pic32MX795F512L:
mkdir -p $(LIBDIR)/PIC32/32MX795F512L/
rm -f $(LIBDIR)/PIC32/32MX795F512L/*.a
make -C src/pic32/ CC_Bowler_Arch="$(CCP_pic32MX795F512L)"
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCP_pic32MX795F512L) -DNO_PRINTING -I../Platform/include/"
$(ARP) rcs $(LIBDIR)/PIC32/32MX795F512L/libNRLIB.a $(PIC_OFILES)
make -C ../BowlerStack/ CC_Bowler_Arch="$(CCP_pic32MX795F512L) -I../Platform/include/"
$(ARP) rcs $(LIBDIR)/PIC32/32MX795F512L/libNRLIB_debug.a $(PIC_OFILES)
make -C ../BowlerStack/ clean
make -C src/pic32/ clean
<file_sep>/Platform/include/arch/pic32/USB/usb_fifo.h
/*
* usb_fifo.h
*
* Created on: Jun 3, 2010
* Author: hephaestus
*/
#ifndef USB_FIFO_H_
#define USB_FIFO_H_
#include "arch/pic32/Compiler.h"
#include "arch/pic32/GenericTypeDefs.h"
#include "arch/pic32/usb_config.h"
#include "arch/pic32/USB/usb_common.h"
#include "arch/pic32/USB/usb.h"
#include "arch/pic32/USB/usb_function_cdc.h"
//#include "USB/usb_function_hid.h"
#include "Bowler/Bowler.h"
#define USB_BUFFER_SIZE BOWLER_PacketSize
//BYTE_FIFO_STORAGE * GetPICUSBFifo(void);
void USBDeviceTasksLocal(void);
BOOL GotUSBData(void);
void SetPICUSBFifo(BYTE_FIFO_STORAGE * s);
void resetUsbSystem();
void usb_CDC_Serial_Init(char * DevStr,char * SerialStr,UINT16 vid,UINT16 pid);
WORD USBGetArray(BYTE* stream, WORD count);
int USBPutArray(BYTE* stream, int Len);
WORD GetNumUSBBytes(void);
void WriteUSBDeviceString(char * b);
void WriteUSBSerialNumber(char * b);
void SetUSB_VID_PID(WORD vid,WORD pid);
void usb_Buffer_Update(void);
#define USB_TIMEOUT 150
/**
* Checks to see if the USB port is opened by a host
*/
BYTE isUSBActave();
/**
* Forces open the USB for transmit
*/
void forceOpenUSB();
#endif /* USB_FIFO_H_ */
<file_sep>/Sample/native/SimpleExample.c
/**
* @file SimpleExample.c
*
* Created on: Feb 28, 2013
* @author hephaestus
*/
#include <stdio.h>
#include "Bowler/Bowler.h"
void simpleBowlerExample(){
/**
* User code must implement a few functions needed by the stack internally
* This Platform specific code can be stored in the Platform directory if it is universal for all
* implementations on the given Platform.
* float getMs(void) Returns the current milliseconds since the application started
* StartCritical() Starts a critical protected section of code
* EndCritical() Ends the critical section and returns to normal operation
*/
printf("\r\nStarting Sample Program\r\n");
/**
* First we are going to put together dummy array of packet data. These are examples of a _png receive and a custom response.
* These would not exist in your implementation but would come in from the physical layer
*/
BYTE received[] = {0x03, 0x74 , 0xf7 , 0x26 , 0x80 , 0x00 , 0x79 , 0x10 , 0x00 , 0x04 , 0xa1 , 0x5f , 0x70 , 0x6e , 0x67 };
/**
* Now we begin to set up the stack features. The first step is to set up the FIFO to receive the data coming in asynchronously
*
*/
BYTE privateRXCom[sizeof(BowlerPacket)];//make the buffer at least big enough to hold one full sized packet
BYTE_FIFO_STORAGE store;//this is the FIFO data storage struct. All interactions with the circular buffer will go through this.
/**
* Next we initialize the buffer
*/
InitByteFifo(&store,// the pointer to the storage struct
privateRXCom,//pointer the the buffer
sizeof(privateRXCom));//the size of the buffer
/**
* Now we load the buffer with the the packet that we "Received"
* This step would come in from the physical layer, usually on
* an interrupt on a mcu.
*/
int i=0;
for (i=0;i<sizeof(received);i++){
BYTE err;// this is a stack error storage byte. See Bowler/FIFO.h for response codes
BYTE b= received[i];// This would be a new byte from the physical layer
FifoAddByte(&store, b, &err);// This helper function adds the byte to the storage buffer and manages the read write pointers.
}
printf("\r\nData loaded into packet\r\n");
/**
* We have now loaded a packet into the storage struct 'store'
* All the while we can be polling the storage struct for a new packet
*/
BowlerPacket myLocalPacket; // Declare a packet struct to catch the parsed packet from the asynchronous storage buffer
while(GetBowlerPacket(&myLocalPacket,// pointer to the local packet into which to store the parsed packet
&store// storage struct from which the packet will be checked and parsed.
) == FALSE){// Returns true when a packet is found and pulled out of the buffer
// wait because there is no packet yet
}
/**
* At this point the packet has been parsed and pulled out of the buffer
*/
setPrintLevelInfoPrint();// enable the stack specific printer. If you wish to use this feature putCharDebug(char c) needs to be defined
printf("\r\nGot new Packet:\r\n");
printPacket(&myLocalPacket, INFO_PRINT);
/**
* Here is where you would read the packet data and perform some operation based on that data
*/
if(myLocalPacket.use.head.RPC == _PNG){
printf("\r\nPacket is a _png packet.. OK!\r\n");
}
/**
* Now the packet has bee read, we re-use the memory for the response to the host
*/
myLocalPacket.use.head.RPC = GetRPCValue("myrp");//set the RPC
myLocalPacket.use.head.Method = BOWLER_POST; // set the method as a status
INT32_UNION temp;//a 32 bit integer struct to allow for easy breaking up into bytes for transport
temp.Val=3742;//put some data into the packet
myLocalPacket.use.data[0]=temp.byte.FB;
myLocalPacket.use.data[1]=temp.byte.TB;
myLocalPacket.use.data[2]=temp.byte.SB;
myLocalPacket.use.data[3]=temp.byte.LB;
// load a single byte
myLocalPacket.use.data[4] = 128;
myLocalPacket.use.head.DataLegnth = 4+ // BYTES in the RPC field
4+ // BYTES in the 32 bit integer
1; // The last single byte
FixPacket(&myLocalPacket);// This is a helper function to validate the packet before sending. It makes sure the MAC address is correct and the CRC is correct
int packetLength = GetPacketLegnth(&myLocalPacket); // helper function to get packet length
printf("\r\nPreparing to send:\r\n");
printPacket(&myLocalPacket, INFO_PRINT);
printf("\r\nSending Packet Data back out: [ ");
for(i=0;i< packetLength;i++){
//This would be sending to the physical layer. For this example we are just printing out the data
printf(" %i ",myLocalPacket.stream[i]);
}
printf(" ] \r\n");
}
<file_sep>/BowlerStack/include/Bowler/Bowler.h
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#ifndef WASP_H_
#define WASP_H_
#include <stdint.h>
#include <math.h>
#include "Defines.h"
#include "Bowler_Struct_Def.h"
#include "Debug.h"
#include "Bowler_Helper.h"
#include "Bowler_Server.h"
#include "RPC_Process.h"
#include "Scheduler.h"
#include "AbstractPID.h"
#include "FIFO.h"
#include "BowlerTransport.h"
#include "namespace.h"
#include "BowlerRPCRegestration.h"
#include "Namespace_bcs_core.h"
#if defined(__PIC32MX__)
#include "arch/pic32/BowlerConfig.h"
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) || defined(__AVR_ATmega324P__)
#include "arch/AVR/BowlerConfig.h"
#elif defined (__i386__) || defined (__ia64__) || defined (__amd64__)
#include "arch/native/BowlerConfig.h"
#elif defined(__MICROBLAZE__)
#include "arch/xilinx/BowlerConfig.h"
#else
//#error Unknown archetecture!! See Bowler.h
//#warning this is a hacky work around
#include "BowlerConfig.h"
#endif
#include "BowlerServerHardwareAbstraction.h"
#endif /* WASP_H_ */
<file_sep>/release.sh
#!/bin/bash
svn update
if (test -d ../NR-ClibRelease/); then
cd ../NR-ClibRelease/;
svn update;
cd ..;
else
cd ..;
svn checkout https://nr-sdk.googlecode.com/svn/trunk/firmware/library/NR-Clib/release NR-ClibRelease;
fi
cd NR-ClibRelease/;
svn delete lib
svn delete include
svn delete toolchain
svn commit -m="removing src"
rsync -rapE --exclude=.svn* ../NR-Clib/lib .
rsync -rapE --exclude=.svn* ../NR-Clib/include .
rsync -rapE --exclude=.svn* ../NR-Clib/toolchain .
svn add lib
svn add lib/*/*/*.a
svn add include
svn add toolchain
svn commit -m="Updating rbe fork to trunk"
<file_sep>/BowlerStack/src/BCS/BowlerPacketParser.c
/*
* Bowler_Transport.c
*
* Created on: May 27, 2010
* Author: hephaestus
*/
#include "Bowler/Bowler.h"
//#define minSize ((BowlerHeaderSize)+4)
#define minSize 1
void allign(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo){
int first = 0;
do
{
FifoReadByteStream(Packet->stream,1,fifo);
if((Packet->use.head.ProtocolRevision != BOWLER_VERSION)){
if(first==0){
println("bad first byte. Fifo=",INFO_PRINT); // SPI ISR shits out messages when 0xAA fails to match. making this info.
p_int(calcByteCount(fifo),INFO_PRINT);
print_nnl(" [",INFO_PRINT);
}
first++;
print_nnl(" 0x",INFO_PRINT);
prHEX8(Packet->use.head.ProtocolRevision,INFO_PRINT);
uint8_t b;
if(getNumBytes(fifo)==0)
return;
//StartCritical();
getStream(& b,1,fifo);
//EndCritical();
}
}while(getNumBytes(fifo)>0 && (Packet->use.head.ProtocolRevision != BOWLER_VERSION));
if(first>0){
//println("##Junked total:",INFO_PRINT);p_int(first,INFO_PRINT);
}
}
boolean _getBowlerPacket(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo, boolean debug){
boolean PacketCheck=false;
//uint16_t PacketLegnth=0;
Packet->stream[0]=0;
if (getNumBytes(fifo) == 0 ) {
return false; //Not enough bytes to even be a header, try back later
}
allign(Packet,fifo);
if (getNumBytes(fifo) < ((_BowlerHeaderSize)+4)) {
if(debug){
//println("Current num bytes: ",ERROR_PRINT);p_int(getNumBytes(fifo),ERROR_PRINT);
}
return false; //Not enough bytes to even be a header, try back later
}
FifoReadByteStream(Packet->stream,_BowlerHeaderSize,fifo);
PacketCheck=false;
while(PacketCheck==false) {
if( (Packet->use.head.ProtocolRevision != BOWLER_VERSION)
|| (CheckCRC(Packet)==false)
){
if(Packet->use.head.ProtocolRevision != BOWLER_VERSION){
println("first",ERROR_PRINT);
}else if(CheckCRC(Packet)==false) {
println("crc",ERROR_PRINT);
}
//prHEX8(Packet->use.head.ProtocolRevision,ERROR_PRINT);print_nnl(" Fifo Size=",ERROR_PRINT);p_int(calcByteCount(fifo),ERROR_PRINT);
uint8_t b;
if(getNumBytes(fifo)==0)
return false;
//StartCritical();
getStream(& b,1,fifo);//junk out one
//EndCritical();
FifoReadByteStream(Packet->stream,_BowlerHeaderSize,fifo);
}else{
if(debug){
//println("Got header");
}
PacketCheck=true;
}
if (getNumBytes(fifo) < minSize) {
println("allign packet",ERROR_PRINT);
allign(Packet,fifo);
return false; //Not enough bytes to even be a header, try back later
}
}
//PacketLegnth = Packet->use.head.DataLegnth;
uint16_t totalLen = GetPacketLegnth(Packet);
// See if all the data has arived for this packet
int32_t num = getNumBytes(fifo);
if (num >=(totalLen) ){
if(debug){
//println("**Found packet, ");p_int(totalLen);//print_nnl(" Bytes, pulling out of buffer");
}
//StartCritical();
getStream(Packet->stream,totalLen,fifo);
//EndCritical();
if(CheckDataCRC(Packet)){
return true;
}else{
println_E("Data CRC Failed ");printBowlerPacketDEBUG(Packet,ERROR_PRINT);
}
}
if(debug){
//println("Header ready, but data is not. Need: ",INFO_PRINT);p_int(totalLen,INFO_PRINT);print_nnl(" have: ",INFO_PRINT);p_int(num ,INFO_PRINT);
}
return false;
}
boolean GetBowlerPacket(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo){
return _getBowlerPacket(Packet,fifo, false) ;
}
boolean GetBowlerPacketDebug(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo){
//enableDebug();
return _getBowlerPacket( Packet, fifo, true) ;
}
/**
* @return returns the number of bytes in the fifo
*/
uint16_t getNumBytes(BYTE_FIFO_STORAGE * fifo){
return (uint16_t)calcByteCount(fifo);
}
/**
* get a stream of this length from the connection
*/
uint16_t getStream(uint8_t *packet,uint16_t size,BYTE_FIFO_STORAGE * fifo){
return FifoGetByteStream(fifo,packet,size);
}
void FixPacket(BowlerPacket * Packet){
extern MAC_ADDR MyMAC;
uint8_t i;
//Ensure the packet going upstream is valid
for (i=0;i<6;i++){
Packet->use.head.MAC.v[i]=MyMAC.v[i];
}
Packet->use.head.ProtocolRevision=BOWLER_VERSION;
SetCRC(Packet);
SetDataCRC(Packet);
}
boolean PutBowlerPacket(BowlerPacket * Packet){
Packet->use.head.ResponseFlag=1;
FixPacket(Packet);
return putStream(Packet->stream,GetPacketLegnth(Packet));
}
<file_sep>/Platform/src/pic32/usb/usb_interrupt.c
/*
* usb_interrupt.c
*
* Created on: Nov 17, 2011
* Author: hephaestus
*/
#include "arch/pic32/USB/usb_fifo.h"
////DOM-IGNORE-END
//#if !defined(__PIC32MX__)
//#define __PIC32MX__
//#endif
//
//
//#if defined(USB_INTERRUPT)
// #if defined(__18CXX)
// void USBDeviceTasks(void)
// #elif defined(__C30__)
// //void __attribute__((interrupt,auto_psv,address(0xA800))) _USB1Interrupt()
// void __attribute__((interrupt,auto_psv,nomips16)) _USB1Interrupt()
// #elif defined(__PIC32MX__)
// //#pragma interrupt _USB1Interrupt ipl4 vector 45
// //void __attribute__((nomips16)) _USB1Interrupt( void )
// void __ISR(_USB_1_VECTOR, ipl4) USB1_ISR(void)
// #endif
//#else
//void USBDeviceTasks(void)
//#endif
//{
// USBDeviceTasks();
//}
<file_sep>/Platform/include/arch/native/BowlerConfig.h
/**
* @file BowlerConfig.h
*
* Created on: May 27, 2010
* @author hephaestus
*/
#ifndef BOWLERCONFIG_H_
#define BOWLERCONFIG_H_
#include <stdio.h>
#include <stdlib.h>
#define USE_DYN_RPC
#define StartCritical()
#define EndCritical()
void Linux_Bowler_HAL_Init(void);
#define Bowler_HAL_Init Linux_Bowler_HAL_Init
#define SetColor(a,b,c)
#endif /* BOWLERCONFIG_H_ */
<file_sep>/BowlerStack/src/Helper/Bowler_Helper.c
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#include "Bowler/Bowler.h"
#if defined(__PIC32MX__)
extern MAC_ADDR MyMAC __attribute__((section(".scs_global_var")));
#else
extern MAC_ADDR MyMAC;
#endif
void LoadCorePacket(BowlerPacket * Packet) {
//SetColor(0,1,0);
uint8_t i;
Packet->use.head.ProtocolRevision = BOWLER_VERSION;
for (i = 0; i < 6; i++) {
Packet->use.head.MAC.v[i] = 0;
}
Packet->use.head.MessageID = 1;
Packet->use.head.ResponseFlag = 1;
Packet->use.head.Method = BOWLER_STATUS;
Packet->use.head.RPC = GetRPCValue("****");
Packet->use.head.DataLegnth = 4;
}
/*
* Calculate waht the CRC should be for a given data section
*/
uint8_t CalcCRC(BowlerPacket *Packet) {
uint32_t v = 0;
int i;
for (i = 0; i < 10; i++)
v += (uint32_t) Packet->stream[i];
return (uint8_t)(v & 0x000000ff);
}
/*
* Returns true if the data crc in the packet matches the one calculated fromthe packet
*/
uint8_t CheckCRC(BowlerPacket *Packet) {
uint8_t v = CalcCRC(Packet);
if (Packet->use.head.CRC == v)
return true;
return false;
}
/*
* Calculates and sets the CRC in the packet
*/
void SetCRC(BowlerPacket * Packet) {
uint8_t v = CalcCRC(Packet);
Packet->use.head.CRC = v;
}
/*
* Calculate waht the CRC should be for a given data section
*/
uint8_t CalcDataCRC(BowlerPacket *Packet) {
uint32_t v = 0;
int i;
for (i = 0; i < Packet->use.head.DataLegnth; i++)
v +=(uint32_t) Packet->stream[i+_BowlerHeaderSize];
return (uint8_t)(v & 0x000000ff);
}
/*
* Returns true if the data crc in the packet matches the one calculated fromthe packet
*/
uint8_t CheckDataCRC(BowlerPacket *Packet) {
uint8_t v = CalcDataCRC(Packet);
if (GetDataCRC( Packet) == v)
return true;
return false;
}
/*
* Calculates and sets the CRC in the packet
*/
void SetDataCRC(BowlerPacket * Packet) {
//println_W("data CRC");
uint8_t v = CalcDataCRC(Packet);
Packet->stream[Packet->use.head.DataLegnth+_BowlerHeaderSize] = v;
}
/*
* Calculates and sets the CRC in the packet
*/
uint8_t GetDataCRC(BowlerPacket * Packet) {
return Packet->stream[Packet->use.head.DataLegnth+_BowlerHeaderSize] ;
}
inline unsigned long GetRPCValue(char * data) {
UINT32_UNION l;
l.byte.FB = data[3];
l.byte.TB = data[2];
l.byte.SB = data[1];
l.byte.LB = data[0];
return l.Val;
}
uint16_t READY(BowlerPacket *Packet, uint8_t code, uint8_t trace) {
Packet->use.head.Method = BOWLER_STATUS;
Packet->use.head.RPC = GetRPCValue("_rdy");
Packet->use.head.MessageID = 0;
Packet->use.head.DataLegnth = 6;
Packet->use.data[0] = code;
Packet->use.data[1] = trace;
return 6;
}
uint16_t ERR(BowlerPacket *Packet, uint8_t code, uint8_t trace) {
Packet->use.head.Method = BOWLER_STATUS;
Packet->use.head.RPC = GetRPCValue("_err");
Packet->use.head.MessageID = 0;
Packet->use.head.DataLegnth = 6;
Packet->use.data[0] = code;
Packet->use.data[1] = trace;
return 6;
}
uint16_t SetPacketLegnth(BowlerPacket *Packet, uint8_t len) {
//Packet.stream[DataSizeIndex]=(BYTE)(len&0x00ff);
Packet->use.head.DataLegnth = len;
return len;
}
uint16_t GetPacketLegnth(BowlerPacket *Packet) {
return _BowlerHeaderSize + Packet->use.head.DataLegnth+1;
}
uint16_t DataLegnthFromPacket(BowlerPacket *Packet) {
return Packet->use.head.DataLegnth;
}
void copyPacket(BowlerPacket * from, BowlerPacket * to) {
uint8_t i;
for (i = 0; i < GetPacketLegnth(from); i++) {
to->stream[i] = from->stream[i];
}
}
uint32_t Bytes2Int32(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
return ( (((uint32_t) a) << 24) + (((uint32_t) b) << 16) + (((uint32_t) c) << 8) + ((uint32_t) d));
}
uint8_t CheckAddress(uint8_t * one, uint8_t * two) {
int i;
for (i = 0; i < 6; i++) {
if (one[i] != two[i])
return false;
}
return true;
}
float interpolate(INTERPOLATE_DATA * data, float currentTime) {
float totalDistance=0, elapsed=0,currentDistance=0, currentLocation=0;
float set = data->set;
float start = data->start;
float setTime = data->setTime;
float startTime = data->startTime;
if(isnan(set)){
setPrintLevelErrorPrint();
println_E("set NaN");
return 0;
}
if(isnan(start)){
setPrintLevelErrorPrint();
println_W("start NaN");
return set;
}
if(isnan(setTime)){
setPrintLevelErrorPrint();
println_W("setTime NaN");
return set; // can not divide by zero
}
if(isnan(startTime)){
setPrintLevelErrorPrint();
println_W("startTime NaN");
return set;
}
if(isnan(currentTime)){
setPrintLevelErrorPrint();
println_W("currentTime NaN");
return set;
}
//
// If the time is imediate, then the target should be returned no matter what.
if(setTime<=0)
return set;
elapsed = currentTime - (startTime);
//interpolation is done
if(elapsed >= setTime || elapsed < 0)
return set;
totalDistance = set-start;
// elapsed must always be greater than the set time, current distance will be lower then
// total distance
currentDistance = totalDistance * (elapsed/setTime);
// location will be an offset from the start
currentLocation = currentDistance+start;
if(isnan(currentLocation))
return set;
if(between(set,currentLocation,start)){
return currentLocation;
}
// println_E("Time= ");p_fl_E(currentTime);
// print_W(" Set= ");p_fl_W(set);
// print_E(" start= ");p_fl_E(start);
// print_W(" setTime= ");p_fl_W(setTime);
// print_E(" startTime= ");p_fl_E(startTime);
// println_W("elapsedTime = ");p_fl_W(elapsed);
// print_E(" incremental distance = ");p_fl_E(currentDistance);
// print_W(" Target = ");p_fl_W(currentLocation);
return set;
}
boolean bound(float target, float actual, float plus, float minus) {
return ((actual)<(target + plus) && (actual)>(target - minus));
}
boolean between(float targetupper, float actual, float targetLower) {
if(targetupper>targetLower ){
return (actual>targetLower) && (actual<targetupper) ;
}else{
return (actual<targetLower) && (actual>targetupper) ;
}
}
void set8bit(BowlerPacket * Packet, uint8_t val, uint8_t offset) {
Packet->use.data[0 + offset] = val;
}
void set16bit(BowlerPacket * Packet, int16_t val, uint8_t offset) {
UINT16_UNION wval;
wval.Val = val;
Packet->use.data[0 + offset] = wval.byte.SB;
Packet->use.data[1 + offset] = wval.byte.LB;
}
void set32bit(BowlerPacket * Packet, int32_t val, uint8_t offset) {
INT32_UNION lval;
lval.Val = val;
Packet->use.data[0 + offset] = lval.byte.FB;
Packet->use.data[1 + offset] = lval.byte.TB;
Packet->use.data[2 + offset] = lval.byte.SB;
Packet->use.data[3 + offset] = lval.byte.LB;
}
void setString(BowlerPacket * Packet, char * val, uint8_t offset) {
int i=0;
while(val[i]){
Packet->use.data[offset + i] = val[i];
i++;
if(i+offset>=sizeof(BowlerPacket)){
//println_E("Writing over the size of the packet!!");
return;
}
}
Packet->use.data[offset + i] = 0;
}
int32_t get32bit(BowlerPacket * Packet, uint8_t offset) {
INT32_UNION lval;
lval.byte.FB = Packet->use.data[0 + offset];
lval.byte.TB = Packet->use.data[1 + offset];
lval.byte.SB = Packet->use.data[2 + offset];
lval.byte.LB = Packet->use.data[3 + offset];
return lval.Val;
}
int32_t get16bit(BowlerPacket * Packet, uint8_t offset) {
UINT16_UNION wval;
wval.byte.SB = Packet->use.data[0 + offset];
wval.byte.LB = Packet->use.data[1 + offset];
return wval.Val;
}
<file_sep>/BowlerStack/src/Helper/Debug.c
/**
* "getPidGroupDataTable(i)->"
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#include "Bowler/Bowler.h"
void sendStr(const char *str);
Print_Level level = NO_PRINT;
#define bufferSize 10
boolean DebugINIT = false;
const char AsciiHex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
//#if !defined(NO_PRINTING)
//const char packet[] = "\tPacket = \t";
//const char get[] = "Get";
//const char post[]="Post ";
//const char stat[]= "Status";
//const char crit[]="Critical";
//const char unknown[] = "Unknown ";
//const char ver[] ="\tVersion = \t";
//const char mac[] = "\tMAC = \t\t";
//const char meth[] = "\tMethod = \t";
//const char id[] = "\tNamespace Index = \t";
//const char dataSise[] ="\tData Size = \t";
//const char crcval []= "\tCRC Value = \t";
// const char dval[] = "\tData = \t\t";
// const char rpc []="\tRPC code = \t";
// const char nodata[] = " no data";
//const char streamsize[] = " Stream: size=";
//#endif
const char errorColor[] = "\033[31m";
const char infoColor[] = "\033[94m";
const char warningColor[] = "\033[93m";
const char debugColor[]="\033[95m ";
const char clearErrorColor[] = "\033[39m";
int (*sendToStream)(uint8_t *, int);
void setColor(Print_Level l) {
switch (l) {
case NO_PRINT:
return;
case INFO_PRINT:
sendStr(infoColor);
return;
case WARN_PRINT:
sendStr(warningColor);
return;
case DEBUG_PRINT:
sendStr(debugColor);
return;
case ERROR_PRINT:
sendStr(errorColor);
return;
default:
return;
}
}
int sendToStreamMine(uint8_t * data, int num) {
int i;
i = 0;
if (num >= bufferSize) {
num = bufferSize - 1;
}
for (i = 0; i < num; i++) {
putCharDebug(data[i]);
}
return i;
}
void setPrintStream(int (*sendToStreamPtr)(uint8_t *, int)) {
if (sendToStreamPtr == 0) {
sendToStreamPtr = &sendToStreamMine;
}
sendToStream = sendToStreamPtr;
}
void sendToStreamLocal(uint8_t * data, int num) {
if (sendToStream == 0) {
sendToStream = &sendToStreamMine;
}
sendToStream(data, num);
}
Print_Level getPrintLevel() {
return level;
}
Print_Level setPrintLevel(Print_Level l) {
#if defined(NO_PRINTING)
level = NO_PRINT;
#else
level = l;
#endif
return getPrintLevel();
}
boolean okToprint(Print_Level l) {
if (getPrintLevel() >= l) {
if (DebugINIT == false) {
DebugINIT = true;
EnableDebugTerminal();
}
return true;
}
return false;
}
//
//void enableDebug(void){
// setPrintLevel(INFO_PRINT);
//}
//void disableDebug(void){
// setPrintLevel(NO_PRINT);
//}
char GetLowNib(uint8_t b) {
return AsciiHex[b & 0x0f];
}
char GetHighNib(uint8_t b) {
return AsciiHex[((b & 0xF0) >> 4)];
}
void printfDEBUG(char *str, Print_Level l) {
if (!okToprint(l)) {
return;
}
putCharDebug('\n');
putCharDebug('\r');
printfDEBUG_NNL(str, l);
//sendToStreamLocal(data,i);
}
void sendStr(const char *str) {
int x = 0;
while (str[x] != '\0') {
putCharDebug(str[x++]);
}
}
void printfDEBUG_BYTE(char b, Print_Level l) {
if (!okToprint(l)) {
return;
}
setColor(l);
putCharDebug(b);
//sendToStreamLocal((uint8_t *)&b,1);
}
void printfDEBUG_NNL(char *str, Print_Level l) {
if (!okToprint(l)) {
return;
}
setColor(l);
sendStr(str);
//sendToStreamLocal(data,i);
}
void printfDEBUG_INT(int32_t val, Print_Level l) {
if (!okToprint(l)) {
return;
}
setColor(l);
int x;
x = 0;
if (val < 0) {
val *= -1;
putCharDebug('-');
}
uint8_t byteStr[12];
ultoaMINE(val, byteStr);
while (byteStr[x] != '\0') {
putCharDebug(byteStr[x++]);
if (x == 12) {
if (l == ERROR_PRINT) {
sendStr(clearErrorColor);
}
return;
}
}
//sendToStreamLocal(data,i);
}
void printfDEBUG_FL(float f, Print_Level l) {
if (!okToprint(l)) {
return;
}
if(isnan(f)){
print_nnl("NaN", l);
return;
}
int32_t upper = (int32_t) f; // set up the upper section of the decimal by int casting to clip off the decimal places
int32_t shift = (int32_t) (f * 1000.0f); //shift up the decaml places as a float 3 places
int32_t clip = upper * 1000; //clip off the upper section of the decimal
printfDEBUG_INT(upper, l);
printfDEBUG_BYTE('.', l);
int32_t dec = shift - clip;
//make positive and print zeros
if (dec < 0)
dec *= -1;
if (dec < 100)
printfDEBUG_BYTE('0', l);
if (dec < 10)
printfDEBUG_BYTE('0', l);
printfDEBUG_INT(dec, l);
}
#if defined(BOWLERSTRUCTDEF_H_)
void printPIDvalsPointer(AbsPID * conf) {
print_nnl(" Enabled=", INFO_PRINT);
p_int(conf->config.Enabled, INFO_PRINT);
print_nnl(" Polarity=", INFO_PRINT);
p_int(conf->config.Polarity, INFO_PRINT);
print_nnl(" SET=", INFO_PRINT);
p_int(conf->SetPoint, INFO_PRINT);
print_nnl(" Kp=", INFO_PRINT);
p_fl(conf->config.K.P, INFO_PRINT);
print_nnl(" Ki=", INFO_PRINT);
p_fl(conf->config.K.I, INFO_PRINT);
print_nnl(" Kd=", INFO_PRINT);
p_fl(conf->config.K.D, INFO_PRINT);
print_nnl("\t Setpoint=", INFO_PRINT);
p_fl(conf->SetPoint, INFO_PRINT);
print_nnl("\t Current State=", INFO_PRINT);
p_fl(conf->CurrentState, INFO_PRINT);
print_nnl("\t Offset=", INFO_PRINT);
p_fl(conf->config.offset, INFO_PRINT);
print_nnl("\t Control Output: ", INFO_PRINT);
p_fl(conf->Output, INFO_PRINT);
print_nnl("\t Output Set: ",INFO_PRINT); p_fl(conf->OutputSet ,INFO_PRINT);
}
//void printPIDvals(int i) {
//
// println("PID chan=", INFO_PRINT);
// p_int(i, INFO_PRINT);
// printPIDvalsPointer(getPidGroupDataTable(i));
//}
void printBowlerPacketDEBUG(BowlerPacket * Packet, Print_Level l) {
#if !defined(NO_PRINTING)
if (!okToprint(l)) {
return;
}
int i;
uint8_t s;
println("\tPacket = \t", l);
s = GetPacketLegnth(Packet);
printfDEBUG_BYTE('[', l);
for (i = 0; i < s; i++) {
//print_nnl("0x", l);
prHEX8(Packet->stream[i], l);
// print_nnl(" ( ", l);
// p_int(Packet->stream[i],l);
// print_nnl(" ) ", l);
if (i < s - 1)
printfDEBUG_BYTE(',', l);
}
printfDEBUG_BYTE(']', l);
println("\tVersion = \t\t0x", l);
prHEX8(Packet->stream[0], l);
println("\tMAC = \t\t\t", l);
for (i = 0; i < 6; i++) {
//print_nnl("0x", l);
prHEX8(Packet->stream[1 + i], l);
if (i < 5)
printfDEBUG_BYTE(':', l);
}
println("\tMethod = \t\t", l);
switch (Packet->stream[MethodIndex]) {
case BOWLER_STATUS:
print_nnl(" Status", l);
break;
case BOWLER_GET:
print_nnl(" Get", l);
break;
case BOWLER_POST:
print_nnl(" Post ", l);
break;
case BOWLER_CRIT:
print_nnl(" Critical", l);
break;
case BOWLER_ASYN:
print_nnl("ASYNCHRONUS", l);
break;
default:
print_nnl("Unknown 0x", l);
prHEX8(Packet->stream[MethodIndex], l);
break;
}
println("\tNs Index = \t", l);
p_int((Packet->stream[SessionIDIndex]&0x7f), l);
println("\tSize = \t\t", l);
p_int((Packet->stream[DataSizeIndex]), l);
//CRC Value
println("\tCRC Value = \t\t0x", l);
prHEX8((Packet->stream[CRCIndex]), l);
println("\tC CRC = \t0x", l);
prHEX8(CalcCRC(Packet), l);
//Data CRC
println("\tData CRC = \t0x", l);
prHEX8(GetDataCRC(Packet), l);
println("\tC Data CRC = \t0x", l);
prHEX8(CalcDataCRC(Packet), l);
if (Packet->use.head.DataLegnth >= 4) {
println("\tRPC code = \t\t", l);
for (i = 0; i < 4; i++) {
printfDEBUG_BYTE(Packet->stream[RPCCodeStart + i], l);
}
}
print_nnl(" ( ", l);
prHEX32(Packet->use.head.RPC,l);
print_nnl(" ) ", l);
if (Packet->use.head.DataLegnth > 4) {
s = (Packet->use.head.DataLegnth - 4);
println("\tData = \t\t\t", l);
for (i = 0; i < s; i++) {
prHEX8(Packet->use.data[i], l);
if (i < (s - 1))
printfDEBUG_BYTE(',', l);
}
} else {
println(" no data", l);
}
println("\n", l);
#endif
}
#endif
void printByteArray(uint8_t * stream, uint16_t len, Print_Level l) {
//#if !defined(NO_PRINTING)
if (!okToprint(l)) {
return;
}
uint16_t i;
print_nnl(" Stream: size=", l);
p_int(len, l);
print_nnl(" [", l);
for (i = 0; i < len; i++) {
prHEX8(stream[i], l);
if (i < (len - 1))
printfDEBUG_BYTE(',', l);
}
print_nnl("]", l);
//#endif
}
void ultoaMINE(uint32_t Value, uint8_t* Buffer) {
uint8_t i;
uint32_t Digit;
uint32_t Divisor;
boolean Printed = false;
if (Value) {
for (i = 0, Divisor = 1000000000; i < 10; i++) {
Digit = Value / Divisor;
if (Digit || Printed) {
*Buffer++ = '0' + Digit;
Value -= Digit*Divisor;
Printed = true;
}
Divisor /= 10;
}
} else {
*Buffer++ = '0';
}
*Buffer = 0; //null terminator
}
<file_sep>/README.md
c-bowler
========
A library for controlling Bowler devices with C
#Theory Of Operation
The Bowler stack is based off of a pair of abstract data streams. These streams can be passed to the Bowler Server stack to be processed into packets.
The streams are contained in the "BYTE_FIFO_STORAGE" struct. The FIFO is initialized by the stack by passing it a buffer and the size.
```C
static BYTE privateRXCom[comBuffSize];
static BYTE_FIFO_STORAGE store;
InitByteFifo(&store,privateRXCom,comBuffSize);
```
Once the FIFO for receiving packets is established, bytes can be added from whatever physical layer is needed:
```C
BYTE err;
BYTE b= getLatestByte();
FifoAddByte(&store, b, &err);
```
The FiFO can be checked for a packet by calling a GetBowlerPacket(), then processed by the stack:
```C
BowlerPacket Packet;
if(GetBowlerPacket(&Packet,&store)){
//Now the Packet struct contains the parsed packet data
Process_Self_Packet(&Packet);
// The call backs for processing the packet have been called
// and the Packet struct now contains the data
// to be sent back to the client as a response.
}
int i=0;
for(i=0;i< GetPacketLegnth(&Packet);i++){
//Grab the response packet one byte at a time and push it out the physical layer
writeToPyhsicalLayerImp(Packet.stream[i]);
}
```
To add new RPC's to the stack, we create a linked list element called a Namespace.
For a detailed example of different types of functionality take a look at the PID namespace:
https://github.com/NeuronRobotics/c-bowler/blob/master/firmware/library/NR-Clib/development/BowlerStack/src/PID/Namespace_bcs_pid.c
To add a standard namespace, such as PID, to the stack, call addNamespaceToList:
```C
addNamespaceToList((NAMESPACE_LIST * ) getBcsPidNamespace());
```
This new namespace and its call backs will be added to the Process_Self_Packet function call.
To make a custom namespace, first you define the NAMESPACE_LIST linked list struct element. This also requires a call back function for asynchronus packets.
```C
BOOL pidAsyncEventCallbackLocal(BowlerPacket *Packet,BOOL (*pidAsyncCallbackPtr)(BowlerPacket *Packet)){
//Run any cooperative tasks
//Pack and send any packets, more then one is ok
}
static NAMESPACE_LIST bcsPid ={ "bcs.pid.*;1.0;;",// The string defining the namespace
NULL,// the first element in the RPC list
&pidAsyncEventCallbackLocal,// async for this namespace
NULL// no initial elements to the other namesapce field.
};
```
Next you define an RPC struct element. This element includes the callback for processing the specified RPC packet.
```C
static RPC_LIST bcsPid__PID={ BOWLER_GET,
"_pid",
&processPIDGet,
((const char [2]){ BOWLER_I08,//channel
0}),// Response arguments
BOWLER_POST,// response method
((const char [3]){ BOWLER_I08,//channel
BOWLER_I32,//current position
0}),// Response arguments
NULL //Termination
};
```
Finally you add the new RPC's to the namespace and the new namespace to the processing stack:
```C
addRpcToNamespace(&bcsPid,& bcsPid__PID);
addNamespaceToList(&bcsPid);
```
# Compilers
## Pic32 V 1.0.0
```bash
wget http://ww1.microchip.com/downloads/en/DeviceDoc/xc32-v1.00-linux.zip
unzip xc32-v1.00-linux.zip
sudo chmod +x xc32-v1.00-linux-installer.run
sudo ./xc32-v1.00-linux-installer.run
```
## AVR
```bash
sudo apt-get install -y --force-yes avr-libc gcc-avr git build-essential
```
<file_sep>/Platform/src/pic32/HAL_P32.c
/*
* HAL.c
*
* Created on: Jan 4, 2010
* Author: hephaestus
*/
#include "arch/pic32/BowlerConfig.h"
#include "Bowler/Bowler.h"
enum {
EXCEP_IRQ = 0, // interrupt
EXCEP_AdEL = 4, // address error exception (load or ifetch)
EXCEP_AdES, // address error exception (store)
EXCEP_IBE, // bus error (ifetch)
EXCEP_DBE, // bus error (load/store)
EXCEP_Sys, // syscall
EXCEP_Bp, // breakpoint
EXCEP_RI, // reserved instruction
EXCEP_CpU, // coprocessor unusable
EXCEP_Overflow, // arithmetic overflow
EXCEP_Trap, // trap (possible divide by zero)
EXCEP_IS1 = 16, // implementation specfic 1
EXCEP_CEU, // CorExtend Unuseable
EXCEP_C2E // coprocessor 2
} _excep_code;
void __attribute__((nomips16)) _general_exception_handler() {
// unsigned int _epc_code;
unsigned int _excep_addr;
asm volatile("mfc0 %0,$13" : "=r" (_excep_code));
asm volatile("mfc0 %0,$14" : "=r" (_excep_addr));
_excep_code = (_excep_code & 0x0000007C) >> 2;
setPrintLevelInfoPrint();
print_E("\r\nException ");
switch (_excep_code) {
case EXCEP_IRQ: print_E("interrupt");
break;
case EXCEP_AdEL: print_E("address error exception (load or ifetch)");
break;
case EXCEP_AdES: print_E("address error exception (store)");
break;
case EXCEP_IBE: print_E("bus error (ifetch)");
break;
case EXCEP_DBE: print_E("bus error (load/store)");
break;
case EXCEP_Sys: print_E("syscall");
break;
case EXCEP_Bp: print_E("breakpoint");
break;
case EXCEP_RI: print_E("reserved instruction");
break;
case EXCEP_CpU: print_E("coprocessor unusable");
break;
case EXCEP_Overflow: print_E("arithmetic overflow");
break;
case EXCEP_Trap: print_E("trap (possible divide by zero)");
break;
case EXCEP_IS1: print_E("implementation specfic 1");
break;
case EXCEP_CEU: print_E("CorExtend Unuseable");
break;
case EXCEP_C2E: print_E("coprocessor 2");
break;
}
print_E(" at 0x");
prHEX32(_excep_addr, ERROR_PRINT);
print_E("\r\n");
DelayMs(1000);
Reset();
}
BYTE_FIFO_STORAGE storeUSB;
uint8_t privateRXUSB[BOWLER_PacketSize ];
BYTE_FIFO_STORAGE storeUART;
uint8_t privateRXUART[BOWLER_PacketSize];
boolean isPic32Initialized = false;
boolean usbComs = false;
boolean uartComs = false;
boolean disableSerial = false;
void disableSerialComs(boolean state) {
disableSerial = state;
uartComs = !state;
}
void Pic32_Bowler_HAL_Init(void) {
isPic32Initialized = true;
// println_W("Init ADC");
// int i = 0;
// for (i = 0; i < 16; i++) InitADCHardware(i);
// measureAdcOffset();
//println_W("Init USB fifo");
InitByteFifo(&storeUSB, privateRXUSB, sizeof (privateRXUSB));
// println_W("Init UART fifo");
InitByteFifo(&storeUART, privateRXUART, sizeof (privateRXUART));
// println_W("Setting Serial FIFO buffer");
SetPICUARTFifo(&storeUART);
// println_W("Setting USB FIFO buffer");
SetPICUSBFifo(&storeUSB);
//println_W("Init UART hal");
Pic32UART_HAL_INIT(PRINT_BAUD);
TickInit();
//println_W("Pic32 is initialized...");
}
void setPicIOTristateInput(char port,int pin){
setPicIOTristate( INPUT, port, pin);
}
void setPicIOTristateOutput(char port,int pin){
setPicIOTristate( OUTPUT, port, pin);
}
void setPicIOTristate(boolean state,char port,int pin){
switch (port) {
case 'B':
if(state){TRISBSET=(1<<pin);}else{ TRISBCLR=(1<<pin);}
break;
case 'C':
if(state){TRISCSET=(1<<pin);}else{ TRISCCLR=(1<<pin);}
break;
case 'D':
if(state){TRISDSET=(1<<pin);}else{ TRISDCLR=(1<<pin);}
break;
case 'E':
if(state){TRISESET=(1<<pin);}else{ TRISECLR=(1<<pin);}
break;
case 'F':
if(state){TRISFSET=(1<<pin);}else{ TRISFCLR=(1<<pin);}
break;
case 'G':
if(state){TRISGSET=(1<<pin);}else{ TRISGCLR=(1<<pin);}
break;
default:
println_E("INVALID PIN ID");
while(1);
}
}
boolean getPicIOPin(char port,int pin){
switch (port) {
case 'B':
return PORTB & (1<<pin)?1:0;
case 'C':
return PORTC & (1<<pin)?1:0;
case 'D':
return PORTD & (1<<pin)?1:0;
case 'E':
return PORTE & (1<<pin)?1:0;
case 'F':
return PORTF & (1<<pin)?1:0;
case 'G':
return PORTG & (1<<pin)?1:0;
default:
println_E("INVALID PIN ID");
while(1);
}
}
void setPicIOPin(boolean state, char port, int pin) {
switch (port) {
case 'B':
ioPortB(state, pin);
break;
case 'C':
ioPortC(state, pin);
break;
case 'D':
ioPortD(state, pin);
break;
case 'E':
ioPortE(state, pin);
break;
case 'F':
ioPortF(state, pin);
break;
case 'G':
ioPortG(state, pin);
break;
default:
println_E("INVALID PIN ID");
while(1);
}
}
boolean Send_HAL_Packet(uint8_t * packet, uint16_t size) {
if (usbComs)
SendPacketUSB(packet, size);
if (uartComs){
Pic32UARTPutArray(packet, size);
}
return true;
}
uint16_t Get_HAL_Byte_Count() {
#if defined(USB_POLLING)
USBDeviceTasks();
#endif
if (isPic32Initialized == false) {
//println_W("***Initializing the PIC hal***");
Pic32_Bowler_HAL_Init();
}
//println_I("Getting the USB bytes");
if (GetNumUSBBytes() > 0) {
usbComs = true;
uartComs = false;
SetGreen(0);
//println_I("Found USB bytes");
return FifoGetByteCount(&storeUSB);
} else {
//println_I("Getting the UART bytes");
if (Pic32Get_UART_Byte_Count() > 0) {
//println_I("Found the UART bytes");
if (!disableSerial){
usbComs = false;
uartComs = true;
SetGreen(1);
}
return Pic32Get_UART_Byte_Count();
}else{
}
}
return 0;
}
boolean GetBowlerPacket_arch(BowlerPacket * Packet) {
//println_I("Checking packet from HAL");
Get_HAL_Byte_Count(); //This runs other update tasks for the HAL
//println_I("Getting packet from HAL");
if (usbComs)
if (GetBowlerPacketDebug(Packet, &storeUSB))
return true;
if (uartComs){
if (GetBowlerPacketDebug(Packet, &storeUART)){
SetGreen(0);
return true;
}
//SetGreen(0);
}
return false;
}
/**
* send the array out the connection
*/
uint16_t putStream(uint8_t *packet, uint16_t size) {
// Print_Level l = getPrintLevel();
// setPrintLevelInfoPrint();
// println_I("UP>> ");printPacket((BowlerPacket *)packet,INFO_PRINT);
// setPrintLevel(l);
Send_HAL_Packet(packet, size);
return true;
}
/**
* get the time in ms
*/
float getMs(void) {
return TickGetMS();
}
/**
* send this char to the //print terminal
*/
void putCharDebug(char c) {
WriteUART_DEBUG(c);
}
/**
* Start the scheduler
*/
void startScheduler(void) {
TickInit();
}
void EnableDebugTerminal(void) {
Pic32UART_HAL_INIT(PRINT_BAUD);
}
<file_sep>/toolchain/avr/toolchain.mk
#Unix systems
GCCA=avr-gcc -Wall -Os -fpack-struct -fshort-enums -funsigned-char -funsigned-bitfields
ARAVR= avr-ar
BIN2HEXAVR=avr-objcopy<file_sep>/Platform/src/pic32/UART.c
#ifndef __UART_C
#define __UART_C
#include "arch/pic32/BowlerConfig.h"
#include "Bowler/Bowler.h"
boolean useUart2 = false;
boolean useUart1 = false;
#define delayUart 50000
boolean Write32UART2(uint8_t data) {
UART2ClearAllErrors();
int tick = delayUart;
while (!UARTTransmissionHasCompleted(UART2)) {
if (tick-- < 0) {
return false;
}
}
while (!UARTTransmitterIsReady(UART2)) {
if (tick-- < 0) {
return false;
}
}
UARTSendDataByte(UART2, data);
return true;
}
boolean Write32UART1(uint8_t data) {
UART1ClearAllErrors();
int tick = delayUart;
while (!UARTTransmissionHasCompleted(UART1)) {
if (tick-- < 0) {
return false;
}
}
while (!UARTTransmitterIsReady(UART1)) {
if (tick-- < 0) {
return false;
}
}
UARTSendDataByte(UART1, data);
return true;
}
#endif //STACK_USE_UART
<file_sep>/BowlerStack/src/BCS/Namespace_bcs_core.c
#include "Bowler/Bowler.h"
/**
* Initializes core and returns a pointer to the namespace list
*/
boolean _nms(BowlerPacket * Packet);
boolean _png(BowlerPacket * Packet);
#define USE_LINKED_LIST_NAMESPACE
#if defined(USE_LINKED_LIST_NAMESPACE)
//char coreName[] = "bcs.core.*;0.3;;";
RPC_LIST bcsCore_nms = {BOWLER_GET,
"_nms",
&_nms,
{ BOWLER_I08,
0}, // Calling arguments
BOWLER_POST, // response method
{ BOWLER_ASCII,
BOWLER_I08,
0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsCore_png = {BOWLER_GET,
"_png",
&_png,
{0}, // Calling arguments
BOWLER_POST, // response method
{0}, // Calling arguments
NULL //Termination
};
NAMESPACE_LIST bcsCore = {"bcs.core.*;0.3;;", // The string defining the namespace
NULL, // the first element in the RPC string
NULL, // no async for this namespace
NULL// no initial elements to the other namesapce field.
};
uint8_t getNumberOfNamespaces() {
int i = 1;
NAMESPACE_LIST * tmp = getBcsCoreNamespace();
while (tmp->next != NULL) {
tmp = tmp->next;
i++;
}
return i;
}
uint8_t getNumberOfRpcs(int namespaceIndex) {
int i = 1;
RPC_LIST * tmp = getNamespaceAtIndex(namespaceIndex)->rpcSet;
if (tmp == NULL) {
return 0;
}
while (tmp->next != NULL) {
tmp = tmp->next;
i++;
}
return i;
}
NAMESPACE_LIST * getNamespaceAtIndex(int index) {
if (index >= getNumberOfNamespaces()) {
return NULL;
}
int i = 0;
NAMESPACE_LIST * tmp = getBcsCoreNamespace();
while (i != index) {
if (tmp->next != NULL) {
tmp = tmp->next;
i++;
} else {
//walked off the end of the list
return NULL;
}
}
return tmp;
}
boolean _png(BowlerPacket * Packet) {
Packet->use.head.Method = BOWLER_POST;
Packet->use.head.RPC = GetRPCValue("_png");
Packet->use.head.DataLegnth = 4;
return true;
}
boolean _nms(BowlerPacket * Packet) {
if (Packet->use.head.DataLegnth == 4) {
Packet->use.head.DataLegnth = 5;
Packet->use.head.Method = BOWLER_POST;
Packet->use.data[0] = getNumberOfNamespaces();
//println("Have ");
//p_int(namespace.numNamespaces);
//println(" namespaces");
} else if (Packet->use.head.DataLegnth == 5) {
if (Packet->use.data[0] < getNumberOfNamespaces()) {
//print("\nSending: ");
Packet->use.head.DataLegnth = 4;
Packet->use.head.Method = BOWLER_POST;
//NAMESPACE tmp = namespace.names[Packet->use.data[0]];
NAMESPACE_LIST * tmpList = getNamespaceAtIndex(Packet->use.data[0]);
//print((char *)tmp.name);
unsigned char i = 0;
while (tmpList->namespaceString[i] != '\0') {
Packet->use.data[i] = tmpList->namespaceString[i];
Packet->use.head.DataLegnth++;
i++;
}
Packet->use.data[i++] = 0; //null terminate the string
Packet->use.head.DataLegnth++;
Packet->use.data[i++] = getNumberOfNamespaces(); //Append the number of namespaces
Packet->use.head.DataLegnth++;
} else {
ERR(Packet, 0, 5);
}
} else {
ERR(Packet, 0, 4);
}
return true;
}
void addRpcToNamespace(NAMESPACE_LIST * namespace, RPC_LIST * rpc) {
if (namespace == NULL || rpc == NULL) {
setPrintLevelErrorPrint();
println_E("null RPC or Null namespace");
while (1);
}
rpc->next = NULL;
if (namespace->rpcSet == NULL) {
namespace->rpcSet = rpc;
return;
}
RPC_LIST * tmp = namespace->rpcSet;
do {
if (tmp == rpc) {
//this pointer has already been added
return;
}
if (tmp->next != NULL)
tmp = tmp->next;
} while (tmp->next != NULL);
tmp->next = rpc;
}
void addNamespaceToList(NAMESPACE_LIST * newNs) {
if (newNs == NULL) {
setPrintLevelErrorPrint();
println_E("Null namespace");
while (1);
}
newNs->next = NULL;
NAMESPACE_LIST * tmp = getBcsCoreNamespace();
do {
if (tmp == newNs) {
//this namespace is already regestered
return;
}
if (tmp->next != NULL)
tmp = tmp->next;
} while (tmp->next != NULL);
tmp->next = newNs;
}
RPC_LIST * getRpcByID(NAMESPACE_LIST * namespace, unsigned long rpcId, uint8_t bowlerMethod) {
if (namespace == NULL)
return NULL;
RPC_LIST * rpc = namespace->rpcSet;
//null check
if (rpc != NULL) {
//Loop over the RPC list looking for a match to the RPC
do {
if (rpcId == GetRPCValue((char*) rpc->rpc) &&
bowlerMethod == rpc->bowlerMethod) {
//Found matching RPC and Method to parse
return rpc;
}
//null check and move to the next RPC
rpc = rpc->next;
} while (rpc != NULL);
}
return NULL;
}
RPC_LIST * getRpcByIndex(NAMESPACE_LIST * namespace, uint8_t index) {
if (namespace == NULL)
return NULL;
RPC_LIST * rpc = namespace->rpcSet;
int iterator = 0;
//null check
if (rpc != NULL) {
//Loop over the RPC list looking for a match to the RPC
do {
if (iterator++ == index) {
//Found matching RPC and Method to parse
return rpc;
}
//null check and move to the next RPC
rpc = rpc->next;
} while (rpc != NULL);
}
return NULL;
}
void RunNamespaceAsync(BowlerPacket *Packet, boolean(*pidAsyncCallbackPtr)(BowlerPacket *Packet)) {
if (pidAsyncCallbackPtr != NULL) {
NAMESPACE_LIST * tmp = getBcsCoreNamespace();
if (tmp == NULL)
return;
int i = 0;
do {
if (tmp->asyncEventCheck != NULL) {
//println_I("Async for ");print_I(getNamespaceAtIndex(i)->namespaceString);
tmp->asyncEventCheck(Packet, pidAsyncCallbackPtr);
}
tmp = tmp->next;
i++;
} while (tmp != NULL);
}
}
boolean BcsCorenamespcaedAdded = false;
NAMESPACE_LIST * getBcsCoreNamespace() {
if (!BcsCorenamespcaedAdded) {
BcsCorenamespcaedAdded = true;
addRpcToNamespace(&bcsCore, & bcsCore_png);
addRpcToNamespace(&bcsCore, & bcsCore_nms);
}
return &bcsCore;
}
#endif
<file_sep>/toolchain/pic32/toolchain.mk
#http://ww1.microchip.com/downloads/mplab/X_Beta/installer.html
UNAME := $(shell uname)
ifeq ($(UNAME), Linux)
# http://ww1.microchip.com/downloads/en/DeviceDoc/xc32-v1.00-linux.zip
# http://ww1.microchip.com/downloads/en/DeviceDoc/xc32-v1.00-osx.dmg
# http://ww1.microchip.com/downloads/en/DeviceDoc/xc32-v1.00-windows.exe
PICTOOLCHAIN = /opt/microchip/xc32/v1.00/bin/
#PICTOOLCHAIN = /opt/microchip/xc32/v1.31/bin/
else
endif
GCCP =$(PICTOOLCHAIN)xc32-gcc -mips16 -O1 -s
ARP =$(PICTOOLCHAIN)xc32-ar
BIN2HEX =$(PICTOOLCHAIN)xc32-bin2hex
#PICTOOLCHAIN = /usr/local/bin/
#GCCP =$(PICTOOLCHAIN)pic32mx-gcc -D_SUPPRESS_PLIB_WARNING -O3 -mips16 -s
#ARP =$(PICTOOLCHAIN)pic32mx-ar
#BIN2HEX =$(PICTOOLCHAIN)pic32mx-bin2hex
<file_sep>/Platform/include/arch/NXP/BowlerConfig.h
/*
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#ifndef BOWLERCONFIG_H_
#define BOWLERCONFIG_H_
#include <NXP/crp.h>
#if !defined(__AVR_ATmega324P__)
#define USE_DYN_RPC
#endif
// GPIO pin masking defines
#define OUTPUT 1
#define INPUT 0
#define OFF 0
#define ON 1
#define Nop() Nop()//__asm__("nop\n\t")
#define nop() Nop()
//void WriteAVRUART0(BYTE val);
//void WriteAVRUART1(BYTE val);
#define WriteUART_COM Nop() //WriteAVRUART0
#define WriteUART_DEBUG Nop() //WriteAVRUART1
#define StartCritical() Nop() //cli()
#define EndCritical() Nop() //sei()
#define USE_UART
void AVR_Bowler_HAL_Init(void);
#define Bowler_HAL_Init() AVR_Bowler_HAL_Init()
#define SetColor(a,b,c)
#endif /* BOWLERCONFIG_H_ */
<file_sep>/Platform/src/pic32/bootloader/AVRInterface.c
/*
* AVRInterface.c
*
* Created on: May 23, 2010
* Author: acamilo
*/
#include "Bowler/Bowler.h"
uint8_t cmd[4];
uint8_t avrFlashSize;
boolean firstPage=true;
uint32_t firstPageBase=0;
#define ATMEGA324P 0x95
#define ATMEGA644P 0x96
union page_buff{
uint16_t words[100];
uint8_t bytes[200];
} page;
void getCmd(uint8_t comand, uint8_t addrHigh, uint8_t addrLow, uint8_t data) {
cmd[0] = GetByteSPI(comand);
cmd[1] = GetByteSPI(addrHigh);
cmd[2] = GetByteSPI(addrLow);
cmd[3] = GetByteSPI(data);
}
uint8_t progmode [] ={0xAC,0x53,0x00,0x00};
uint8_t readVendorCode [] ={0x30,0x00,0x00,0x00};
uint8_t readPartFamilyandFlashSize [] ={0x30,0x00,0x01,0x00};
uint8_t readPartNumber [] ={0x30,0x00,0x02,0x00};
uint8_t eraseChip [] ={0xAC,0x80,0x00,0x00};
#define BytesAtATime 2
// float pageTime;
boolean programing=false;
boolean initialized=false;
uint8_t getCommand(uint8_t * b);
uint8_t readByte(uint16_t address);
void writeAVRPageToFlash(uint16_t address);
void writeAVRTempFlashPage(uint16_t addr, uint16_t value);
boolean writeWord(uint16_t data,uint16_t address);
uint16_t readWord(uint16_t address);
void eraseAVR(void){
getCommand(eraseChip);
DelayMs(20);
writeLowFuse();
writeHighFuse();
writeExtendedFuse();
}
void avrSPIProg(BowlerPacket * Packet){
if (programing==false) {
programing=true;
//programMode();
}
//uint8_t data,set;
uint32_t i,numWords;
UINT32_UNION baseAddress;
baseAddress.byte.FB=Packet->use.data[1];
baseAddress.byte.TB=Packet->use.data[2];
baseAddress.byte.SB=Packet->use.data[3];
baseAddress.byte.LB=Packet->use.data[4];
numWords = (Packet->use.head.DataLegnth-4-1-4);
for (i=0;i<numWords;i++){
page.bytes[i]=Packet->use.data[5+i];
}
for (;i<128;i++){
//Pad the end with junk data in case there aren't the right number of bytes
page.bytes[i]=0xff;
}
for (i=0; i<64; i++ ){
if(avrFlashSize==ATMEGA324P)
writeAVRTempFlashPage(i,page.words[i]);
else if (avrFlashSize==ATMEGA644P){
if(firstPage)
writeAVRTempFlashPage(i,page.words[i]);
else
writeAVRTempFlashPage(i+64,page.words[i]);
}
}
if(avrFlashSize==ATMEGA324P)
writeAVRPageToFlash(baseAddress.Val);
else if (avrFlashSize==ATMEGA644P){
if(firstPage){
firstPage=false;
firstPageBase=baseAddress.Val;
}else{
firstPage=true;
writeAVRPageToFlash(firstPageBase);
}
}
}
uint8_t avrID[]={0,0,0};
uint8_t getVendorCode(void){
//#if defined(DYIO)
if(avrID[0]!=0x1E)
avrID[0]= getCommand(readVendorCode);
return avrID[0];
//#else
// return 0x1E;
//#endif
}
void GetAVRid(uint8_t * buffer){
//printfDEBUG("AVR getting ID");
//InitUINT32Fifo(&storeAddr,privateAddr,sizeof(privateAddr));
programMode();
avrID[0]= getCommand(readVendorCode);
buffer[0]=GetHighNib(avrID[0]);
buffer[1]=GetLowNib(avrID[0]);
avrID[1] = getCommand(readPartFamilyandFlashSize);
avrFlashSize=avrID[1];
buffer[2]=GetHighNib(avrID[1]);
buffer[3]=GetLowNib(avrID[1]);
avrID[2] = getCommand(readPartNumber);
buffer[4]=GetHighNib(avrID[2]);
buffer[5]=GetLowNib(avrID[2]);
buffer[6]=0;
}
void programMode(void){
HoldAVRReset();
getCommand(progmode);
DelayMs(20);
}
uint8_t getCommand(uint8_t * b){
DelayMs(15);
int i;
uint8_t back;
for (i=0;i<4;i++){
back=GetByteSPI(b[i]);
}
DelayMs(15);
return back;
}
void PowerCycleAVR(){
println_I("Power cycling the AVR");
HoldAVRReset();
// getCommand(progmode);
// writeLowFuse();
// writeHighFuse();
// writeExtendedFuse();
ReleaseAVRReset();
}
void HoldAVRReset(void){
AVR_RST_IO(0);
DelayMs(5);
}
void ReleaseAVRReset(void){
AVR_RST_IO(1);
println_E("Starting AVR...");
DelayMs(1000);
println_W("AVR started");
}
void writeAVRTempFlashPage(uint16_t addr, uint16_t value)
{
UINT16_UNION val;
val.Val=value;
getCmd(0x40, 0, addr, val.byte.LB);
getCmd(0x48, 0, addr, val.byte.SB);
}
void writeAVRPageToFlash(uint16_t address){
//uint32_t i,offset;
//uint8_t data,set;
UINT16_UNION addr;
addr.Val=address>>1;
getCmd(0x4c,addr.byte.SB,addr.byte.LB,0x00);
//printfDEBUG("AVR Writing page to:");
//printfDEBUG_UL(address);
DelayMs(30);
}
uint16_t readWord(uint16_t address){
uint16_t low,high;
UINT16_UNION addr;
addr.Val=address;
getCmd(0x20, addr.byte.SB, addr.byte.LB, 0x00);
low=cmd[3];
getCmd(0x28, addr.byte.SB, addr.byte.SB, 0x00);
high=cmd[3];
return (high<<8)|low;
}
void writeLowFuse()
{
getCmd(0xac, 0xa0, 0, AVR_LOW);
DelayMs(5);
}
void writeHighFuse()
{
getCmd(0xac, 0xa8, 0,AVR_HIGH);
DelayMs(5);
}
void writeExtendedFuse()
{
getCmd(0xac, 0xa4, 0, AVR_EXT);
DelayMs(5);
}
uint8_t readLowFuse(void)
{
getCmd(0x50, 0x00, 0, 0);
return cmd[3];
}
uint8_t readExtFuse(void)
{
getCmd(0x50, 0x08, 0, 0);
return cmd[3];
}
uint8_t readHighFuse(void)
{
getCmd(0x58, 0x08, 0, 0);
return cmd[3];
}
void InitSPI(void){
if(initialized)
return;
initialized=true;
//printfDEBUG("Initializing SPI interface");
mPORTGOpenDrainOpen(BIT_6);// Clock is output
mPORTGOpenDrainOpen(BIT_8);// Data Out is an output
mPORTEOpenDrainOpen(BIT_3);// AVR SS pin
OpenSPI2(SPI_MODE8_ON|ENABLE_SDO_PIN|SLAVE_ENABLE_OFF|SPI_CKE_ON|MASTER_ENABLE_ON|SEC_PRESCAL_8_1|PRI_PRESCAL_64_1, SPI_ENABLE);
}
void StopSPI(void){
CloseSPI2();
_RG6=1;
_RG8=1;
ReleaseAVRReset();
}
uint8_t GetByteSPI(uint8_t b){
InitSPI();
putcSPI2(b); // Start sending
return getcSPI2();
}
<file_sep>/Platform/src/pic32/LED.c
/*
* LED.c
*
* Created on: Nov 22, 2009
* Author: hephaestus
*/
#include "arch/pic32/BowlerConfig.h"
#include "Bowler/Bowler.h"
void InitLEDS(void){
startLED();
}
void SetGreen(uint16_t Duty){
SET_GREEN(Duty);
}
void SetRed(uint16_t Duty){
SET_RED(Duty);
}
void SetBlue(uint16_t Duty){
SET_BLUE(Duty);
}
void SetColor(uint16_t r,uint16_t g,uint16_t b){
//startLED();
SetGreen(g);
SetRed(r);
SetBlue(b);
}
<file_sep>/BowlerStack/include/Bowler/BowlerServerHardwareAbstraction.h
/**
* @file BowlerHardwareAbstraction.h
*
* Created on: May 27, 2010
* @author hephaestus
*
* This header defines the FIFO's for the bowler server.
*/
#ifndef BOWLERHARDWAREABSTRACTION_H_
#define BOWLERHARDWAREABSTRACTION_H_
/**
* @Depricated use library function FifoGetByteCount
*
* This function extracts the number of bytes stored in the given FIFO.
*
* @param fifo This is a pointer to a data struct containing an initialized FIFO
* Prerequsites:
* The fifo must be initialized by calling InitByteFifo with valid data.
*
* @return returns the number of bytes in the fifo
*/
uint16_t getNumBytes(BYTE_FIFO_STORAGE * fifo);
/**
* @Depricated use library function FifoGetByteStream
*
* This function will get a stream of this length from the connection.
* @param buffer this is the data buffer where the data retrieved from the physical connection is stored.
* @param the number of bytes to retrieve from the physical connection.
*/
uint16_t getStream(uint8_t * buffer,uint16_t datalength,BYTE_FIFO_STORAGE * fifo);
/**
* @Depricated use library FifoAddByte
*
* Adds a byte from the physical connection to the fifo storage struct.
*
* This function should be called when new data is retrieved from the physical connection.
*/
uint32_t addbyte(BYTE_FIFO_STORAGE * fifo,uint8_t b, uint8_t * errorCode);
/**
* This function is used to send data from a buffer to the physical connection.
*
* @param buffer this is a pointer to the buffer containing the data to be sent
* @param dataLength this is the number of bytes to send to the physical connection.
*
*/
uint16_t putStream(uint8_t * buffer,uint16_t datalength);
/**
* get the time in ms
* @return This should return a float of milliseconds since the processor started.
*/
float getMs(void);
/**
* send this char to the print terminal
*
* If this feature is not needed, it can be empty
*/
void putCharDebug(char c);
/**
* Start the scheduler. This should set up any timers needed to access the current time.
*/
void startScheduler(void);
#endif /* BOWLERHARDWAREABSTRACTION_H_ */
<file_sep>/Sample/native/BowlerImplimentationExample.c
/**
* This is a sample to demonstrate using the Bowler embedded C stack.
*/
#include <stdio.h>
#include "Bowler/Bowler.h"
void simpleBowlerExample();
void advancedBowlerExample();
int main(void){
/**
* This example shows how to integrate the Framework using the built in bcs.core namespace handler
*/
advancedBowlerExample();
/**
* This is a simple example of using the BowlerStack interfaces to interact with a host entirely in user code
*/
//simpleBowlerExample();
return 0;
}
<file_sep>/c-bowler.X/nbproject/Makefile-variables.mk
#
# Generated - do not edit!
#
# NOCDDL
#
CND_BASEDIR=`pwd`
# default configuration
CND_ARTIFACT_DIR_default=dist/default/production
CND_ARTIFACT_NAME_default=c-bowler.X.a
CND_ARTIFACT_PATH_default=dist/default/production/c-bowler.X.a
CND_PACKAGE_DIR_default=${CND_DISTDIR}/default/package
CND_PACKAGE_NAME_default=c-bowler.X.tar
CND_PACKAGE_PATH_default=${CND_DISTDIR}/default/package/c-bowler.X.tar
<file_sep>/Platform/src/native/Bowler_HAL_Native.c
/**
* @file Bowler_HAL_Linux.c
*
* Created on: May 27, 2010
* @author hephaestus
*/
#include "Bowler/Bowler.h"
#include <time.h>
static float start;
boolean GetBowlerPacket_arch(BowlerPacket * Packet){
return false;
}
/**
* send the array out the connection
*/
uint16_t putStream(uint8_t *packet,uint16_t size){
return true;
}
/**
* get the time in ms
*/
float getMs(void){
return (time(NULL) * 1000)-start;
}
/**
* send this char to the print terminal
*/
void putCharDebug(char c){
putchar(c);
}
/**
* Start the scheduler
*/
void startScheduler(void){
start = time(NULL) * 1000;
}
void Linux_Bowler_HAL_Init(void){
}
void EnableDebugTerminal(void){
puts("Native EnableDebugTerminal"); /* prints test */
}
<file_sep>/BowlerStack/src/PID/Namespace_bcs_pid.c
/*
* Namespace_bcs_pid.c
*
* Created on: Mar 7, 2013
* Author: hephaestus
*/
#include "Bowler/Bowler.h"
//const char pidNSName[] = "bcs.pid.*;1.0;;";
boolean pidAsyncEventCallbackLocal(BowlerPacket *Packet, boolean(*pidAsyncCallbackPtr)(BowlerPacket *Packet)) {
// println_I("\n");
// printPIDvals(0);
RunPIDComs(Packet, pidAsyncCallbackPtr);
return false;
}
//Get RPC's
RPC_LIST bcsPid_APID = {BOWLER_GET,
"apid",
&processPIDGet,
{0}, // Calling arguments
BOWLER_POST, // response method
{ BOWLER_I32STR, //All current values
0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid__PID = {BOWLER_GET,
"_pid",
&processPIDGet,
{ BOWLER_I08, //channel
0}, // Calling arguments
BOWLER_POST, // response method
{ BOWLER_I08, //channel
BOWLER_I32, //current position
0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid_CPID = {BOWLER_GET,
"cpid",
&processPIDGet,
{ BOWLER_I08, //channel
0}, // Calling arguments
BOWLER_POST, // response method
{ BOWLER_I08, //channel
BOWLER_I08, //enabled
BOWLER_I08, //Polarity
BOWLER_I08, //async
BOWLER_FIXED100, //Kp
BOWLER_FIXED100, //Ki
BOWLER_FIXED100, //Kd
BOWLER_I32, //Latch value
BOWLER_I08, //Use index latch
BOWLER_I08, //Stop On latch
BOWLER_FIXED1K, //stop
BOWLER_FIXED1K, //upper
BOWLER_FIXED1K, //lower
0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid_CPDV = {BOWLER_GET,
"cpdv",
&processPIDGet,
{ BOWLER_I08, //channel
0}, // Calling arguments
BOWLER_POST, // response method
{ BOWLER_I08, //channel
BOWLER_FIXED100, //Kp
BOWLER_FIXED100, //Kd
0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid_GPDC = {BOWLER_GET,
"gpdc",
&processPIDGet,
{0}, // Calling arguments
BOWLER_POST, // response method
{ BOWLER_I32, //channel
0}, // Calling arguments
NULL //Termination
};
//Post RPC's
RPC_LIST bcsPid_APID_p = {BOWLER_POST,
"apid",
&processPIDPost,
{ BOWLER_I32, //Time in ms for transition to take
BOWLER_I32STR, //All current set point values
0}, // Calling arguments
BOWLER_STATUS, // response method
{ BOWLER_I08, //location
BOWLER_I08, //trace
0}, // Calling arguments, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid__PID_p = {BOWLER_POST,
"_pid",
&processPIDPost,
{ BOWLER_I08, //channel
BOWLER_I32, //set point value
BOWLER_I32, //Time in ms for transition to take
0}, // Calling arguments, // Calling arguments
BOWLER_STATUS, // response method
{ BOWLER_I08, //location
BOWLER_I08, //trace
0}, // Calling arguments, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid__VPD = {BOWLER_POST,
"_vpd",
&processPIDPost,
{ BOWLER_I08, //channel
BOWLER_I32, //velocity set point value
BOWLER_I32, //Time in ms for transition to take
0}, // Calling arguments, // Calling arguments
BOWLER_STATUS, // response method
{ BOWLER_I08, //location
BOWLER_I08, //trace
0}, // Calling arguments, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid_RPID = {BOWLER_POST,
"rpid",
&processPIDPost,
{ BOWLER_I08, //channel
BOWLER_I32, //value to reset encoding to
0}, // Calling arguments, // Calling arguments
BOWLER_STATUS, // response method
{ BOWLER_I08, //location
BOWLER_I08, //trace
0}, // Calling arguments, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid_ACAL = {BOWLER_CRIT,
"acal",
&processRunAutoCal,
{ BOWLER_I08, //group
0}, // no arguments, kills all PID's
BOWLER_STATUS, // response method
{ BOWLER_I08, //location
BOWLER_I08, //trace
0}, // Calling arguments
NULL //Termination
};
//Critical
RPC_LIST bcsPid_KPID = {BOWLER_CRIT,
"kpid",
&processPIDCrit,
{0}, // no arguments, kills all PID's
BOWLER_STATUS, // response method
{ BOWLER_I08, //location
BOWLER_I08, //trace
0}, // Calling arguments, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid_CPID_c = {BOWLER_CRIT,
"cpid",
&processPIDCrit,
{ BOWLER_I08, //channel
BOWLER_I08, //enabled
BOWLER_I08, //Polarity
BOWLER_I08, //async
BOWLER_FIXED100, //Kp
BOWLER_FIXED100, //Ki
BOWLER_FIXED100, //Kd
BOWLER_I32, //Latch value
BOWLER_I08, //Use index latch
BOWLER_I08, //Stop On latch
BOWLER_FIXED1K, //stop
BOWLER_FIXED1K, //upper
BOWLER_FIXED1K, //lower
0}, // Calling arguments
BOWLER_STATUS, // response method
{ BOWLER_I08, //location
BOWLER_I08, //trace
0}, // Calling arguments, // Calling arguments
NULL //Termination
};
RPC_LIST bcsPid_CPDV_c = {BOWLER_CRIT,
"cpdv",
&processPIDCrit,
{ BOWLER_I08, //channel
BOWLER_FIXED100, //Kp
BOWLER_FIXED100, //Kd
0}, // Calling arguments
BOWLER_STATUS, // response method
{ BOWLER_I08, //location
BOWLER_I08, //trace
0}, // Calling arguments, // Calling arguments
NULL //Termination
};
NAMESPACE_LIST bcsPid = {"bcs.pid.*;1.0;;", // The string defining the namespace
NULL, // the first element in the RPC list
&pidAsyncEventCallbackLocal, // async for this namespace
NULL// no initial elements to the other namesapce field.
};
boolean bcsPidnamespcaedAdded = false;
NAMESPACE_LIST * getBcsPidNamespace() {
if (!bcsPidnamespcaedAdded) {
//GET
addRpcToNamespace(&bcsPid, & bcsPid_APID);
addRpcToNamespace(&bcsPid, & bcsPid__PID);
addRpcToNamespace(&bcsPid, & bcsPid_CPID);
addRpcToNamespace(&bcsPid, & bcsPid_CPDV);
addRpcToNamespace(&bcsPid, & bcsPid_GPDC);
//Post
addRpcToNamespace(&bcsPid, & bcsPid_APID_p);
addRpcToNamespace(&bcsPid, & bcsPid__PID_p);
addRpcToNamespace(&bcsPid, & bcsPid__VPD);
addRpcToNamespace(&bcsPid, & bcsPid_RPID);
//Critical
addRpcToNamespace(&bcsPid, & bcsPid_KPID);
addRpcToNamespace(&bcsPid, & bcsPid_CPID_c);
addRpcToNamespace(&bcsPid, & bcsPid_CPDV_c);
addRpcToNamespace(&bcsPid, & bcsPid_ACAL);
bcsPidnamespcaedAdded = true;
}
return &bcsPid;
}
<file_sep>/BowlerStack/include/Bowler/Debug.h
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#ifndef DEBUG_H_
#define DEBUG_H_
#include "Defines.h"
#include "AbstractPID.h"
typedef enum _Print_Level{
NO_PRINT=0,
ERROR_PRINT=1,
WARN_PRINT=2,
DEBUG_PRINT=3,
INFO_PRINT=4
}Print_Level;
#define setPrintLevelNoPrint() setPrintLevel(NO_PRINT)
#define setPrintLevelErrorPrint() setPrintLevel(ERROR_PRINT)
#define setPrintLevelWarningPrint() setPrintLevel(WARN_PRINT)
#define setPrintLevelInfoPrint() setPrintLevel(INFO_PRINT)
Print_Level setPrintLevel(Print_Level l);
boolean okToprint(Print_Level l);
Print_Level getPrintLevel();
/**
* Lets you set a custom printstream function pointer
*/
void setPrintStream(int (*sendToStreamPtr)(uint8_t * ,int));
void EnableDebugTerminal(void);
///**
// * enable printing (Defaults to enabled)
// */
//void enableDebug(void);
///**
// * disable printing (Defaults to enabled)
// */
//void disableDebug(void);
/**
* print a given value as a 16 bit hex value
*/
#define prHEX(A,B) prHEX16(A,B)
#define prHEX8(A,B) printfDEBUG_BYTE(GetHighNib(A&0x000000ff),B); printfDEBUG_BYTE(GetLowNib(A&0x000000ff),B)
#define prHEX16(A,B) printfDEBUG_BYTE(GetHighNib((A&0x0000ff00)>>8),B); printfDEBUG_BYTE(GetLowNib((A&0x0000ff00)>>8),B); prHEX8(A,B);
#define prHEX24(A,B) printfDEBUG_BYTE(GetHighNib((A&0x00ff0000)>>16),B); printfDEBUG_BYTE(GetLowNib((A&0x00ff0000)>>16),B); prHEX16(A,B);
#define prHEX32(A,B) printfDEBUG_BYTE(GetHighNib((A&0xff000000)>>24),B); printfDEBUG_BYTE(GetLowNib((A&0xff000000)>>24),B); prHEX24(A,B);
/**
* print the ascii of a float. No new line
*/
#define p_fl(A,B) printfDEBUG_FL(A,B)
/**
* print the ascii of an unsigned long/int. No new line
*/
#define p_int(A,B) printfDEBUG_INT(A,B)
/**
* print the null terminated string with no new lines
*/
#define print_nnl(A,B) printfDEBUG_NNL(A,B)
/**
* print the null terminated string with a newline inserted at the begining of the string
*/
//#define println(A,B) printfDEBUG(__FILE__,DEBUG_PRINT);printfDEBUG(A,B)
#define println(A,B) printfDEBUG(A,B)
#define printStream(A,B,C) printByteArray(A,B,C);
/*Errors*/
/**
* print the ascii of a float. No new line
*/
#define p_fl_E(A) printfDEBUG_FL(A,ERROR_PRINT)
/**
* print the ascii of an unsigned long/int. No new line
*/
#define p_int_E(A) p_int(A,ERROR_PRINT)
/**
* print the null terminated string with no new lines
*/
#define print_E(A) printfDEBUG_NNL(A,ERROR_PRINT)
/**
* print the null terminated string with a newline inserted at the begining of the string
*/
#define println_E(A) println(A,ERROR_PRINT);
#define printStream_E(A,B) printByteArray(A,B,ERROR_PRINT);
/*Warning*/
/**
* print the ascii of a float. No new line
*/
#define p_fl_W(A) printfDEBUG_FL(A,WARN_PRINT)
/**
* print the ascii of an unsigned long/int. No new line
*/
#define p_int_W(A) p_int(A,WARN_PRINT)
/**
* print the null terminated string with no new lines
*/
#define print_W(A) printfDEBUG_NNL(A,WARN_PRINT)
/**
* print the null terminated string with a newline inserted at the begining of the string
*/
#define println_W(A) println(A,WARN_PRINT)
#define printStream_W(A,B) printByteArray(A,B,WARN_PRINT);
/*Info*/
/**
* print the ascii of a float. No new line
*/
#define p_fl_I(A) printfDEBUG_FL(A,INFO_PRINT)
/**
* print the ascii of an unsigned long/int. No new line
*/
#define p_int_I(A) p_int(A,INFO_PRINT)
/**
* print the null terminated string with no new lines
*/
#define print_I(A) printfDEBUG_NNL(A,INFO_PRINT)
/**
* Clears the print termainal
*/
#define clearPrint() sendStr("\e[1;1H\e[2J")
/**
* print the null terminated string with a newline inserted at the begining of the string
*/
#define println_I(A) println(A,INFO_PRINT)
#define printStream_I(A,B) printByteArray(A,B,INFO_PRINT);
/**
* sends the charrector to the serial port if it is ascii, if it is not ascii, it is converted to a number then sent
*/
void printfDEBUG_BYTE(char b,Print_Level l);
/**
* print the null terminated string with a newline inserted at the begining of the string
*/
void printfDEBUG( char *str,Print_Level l);
/**
* print the null terminated string with no new lines
*/
void printfDEBUG_NNL(char *str,Print_Level l);
/**
* print the ascii of a signed long/int. No new line
*/
void printfDEBUG_INT(int32_t val,Print_Level l);
/**
* convert a long into an ascii string and place the string into the Buffer
*/
void ultoaMINE(uint32_t Value, uint8_t* Buffer);
/**
* print all the bytes in a byte array. The legnth of the array must be correct
*/
void printByteArray(uint8_t * stream,uint16_t len,Print_Level l);
/**
* convert a float into an ascii string and place the string into the outbuf
*/
void ftoa(float f, char * outbuf);
/**
* print the ascii of a float. No new line
*/
void printfDEBUG_FL(float f,Print_Level l);
/**
* return the char of the hex value of the low 4 bits of the given byte
*/
char GetLowNib(uint8_t b);
/**
* return the char of the hex value of the high 4 bits of the given byte
*/
char GetHighNib(uint8_t b);
#define printPIDvals(i) printPIDvalsPointer(getPidGroupDataTable(i))
void printPIDvalsPointer(AbsPID * conf);
void sendStr(const char *str) ;
//Bowler Stack Specific:
#if defined(BOWLERSTRUCTDEF_H_)
#if !defined(NO_PRINTING)
#define printPacket(a,b) printBowlerPacketDEBUG(a,b)
#else
#define printPacket(a,b) Nop();
#endif
void printBowlerPacketDEBUG(BowlerPacket * packet,Print_Level l);
void printfDEBUG_BYTE(char b,Print_Level l);
#endif
boolean okToPrint(Print_Level l);
void setColor(Print_Level l);
#endif /* DEBUG_H_ */
<file_sep>/BowlerStack/src/Helper/FIFO.c
/**
* @file FIFO.c
*
* Created on: May 27, 2010
* @author hephaestus
*/
#include "Bowler/Bowler.h"
void clearByteFifo(BYTE_FIFO_STORAGE * fifo);
//const char * fifoinit = "Initializing FIFO, Buffer Size: ";
//const char * error = "@##ERROR fifo is overflown! Size, buffer: ";
void printFiFoState(BYTE_FIFO_STORAGE * fifo,Print_Level l){
int i;
print_nnl("\nFifo state: \tBytes:",l);
p_int(calcByteCount(fifo),l);
print_nnl("\tData [ ",l);
for(i=0;i<calcByteCount(fifo);i++){
p_int(FifoReadByteAtIndex(fifo,i),l);print_nnl(" ",l);
}
print_nnl(" ]\n",l);
}
boolean lockFifo(BYTE_FIFO_STORAGE * fifo){
// if(fifo->mutex != false) {
// return false;
// }
// fifo->mutex=true;
return true;
}
boolean unLockFifo(BYTE_FIFO_STORAGE * fifo){
//fifo->mutex=false;
//EndCritical();
return true;
}
void InitByteFifo(BYTE_FIFO_STORAGE * fifo,uint8_t * buff,uint32_t size){
if(fifo == 0 || buff == 0){
println("@#@#FIFO FAILED TO INITIALIZE",ERROR_PRINT);p_int(size,ERROR_PRINT);
}
fifo->buffer=buff;
fifo->bufferSize=size;
fifo->readPointer=0;
fifo->writePointer=0;
//fifo->byteCount=0;
fifo->mutex=false;
clearByteFifo(fifo);
//println(fifoinit);p_int(size);
}
void clearByteFifo(BYTE_FIFO_STORAGE * fifo){
int i;
for (i=0;i < fifo->bufferSize;i++){
fifo->buffer[i]=0;
}
//EndCritical();
}
uint8_t ReadFirstByte(BYTE_FIFO_STORAGE * fifo){
return fifo->buffer[fifo->readPointer];
}
uint32_t calcByteCount(BYTE_FIFO_STORAGE * fifo){
int w =fifo->writePointer;
int r = fifo->readPointer;
if(w>r){
fifo->byteCount= w-r;
}else if(w==r){
fifo->byteCount= 0;
}else{
fifo->byteCount= (w+fifo->bufferSize)-r;
}
return fifo->byteCount;
}
uint32_t FifoGetByteCount(BYTE_FIFO_STORAGE * fifo){
return calcByteCount(fifo);
}
uint32_t FifoAddByte(BYTE_FIFO_STORAGE * fifo,uint8_t b, uint8_t * errorCode){
// if(calcByteCount(fifo) >= (fifo->bufferSize-2)){
// //println(error);p_int(fifo->bufferSize);print_nnl(",");p_int(fifo->byteCount);
// errorCode[0]=FIFO_OVERFLOW;
// return 0;
// }
// if(lockFifo(fifo)==false) {
// errorCode[0]=FIFO_FAILED_TO_SET;
// //return 0;
// }
// if(fifo->buffer == NULL){
// setPrintLevelErrorPrint();
// println_E("Null buffer in fifo call");
// //return 0;
// }
fifo->buffer[fifo->writePointer]=b;
fifo->writePointer++;
if (fifo->writePointer == fifo->bufferSize){
fifo->writePointer=0;
}
//fifo->byteCount++;
//calcByteCount(fifo);
errorCode[0]=FIFO_OK;
//unLockFifo(fifo);
return (calcByteCount(fifo)<=fifo->bufferSize);
}
uint8_t FifoGetByte(BYTE_FIFO_STORAGE * fifo, uint8_t * errorCode){
if(lockFifo(fifo)==false) {
errorCode[0]=FIFO_FAILED_TO_GET;
return 0;
}
uint8_t b = fifo->buffer[fifo->readPointer];
fifo->readPointer++;
if (fifo->readPointer==fifo->bufferSize){
fifo->readPointer=0;
}
errorCode[0]=FIFO_OK;
calcByteCount(fifo);
unLockFifo(fifo);
return b;
}
uint8_t FifoReadByteAtIndex(BYTE_FIFO_STORAGE * fifo,uint32_t offset ){
uint32_t index=fifo->readPointer +offset;
if(index >=fifo->bufferSize )
index -= fifo->bufferSize;
return fifo->buffer[index];
}
uint32_t FifoGetByteStream(BYTE_FIFO_STORAGE * fifo,uint8_t *packet,uint32_t size){
uint8_t err;
int i;
int count = calcByteCount(fifo);
if(size>count)
size = count;
for (i=0;i<size;i++){
if(count > 0){
uint8_t b;
do{
b = FifoGetByte(fifo,&err);
}while(err != FIFO_OK);
packet[i] = b;
}else{
packet[i]=0;
}
}
return i;
}
uint32_t FifoReadByteStream(uint8_t *packet,uint32_t size,BYTE_FIFO_STORAGE * fifo){
uint32_t read=fifo->readPointer;
uint32_t count = calcByteCount(fifo);
int i;
if(size>count)
size = count;
for (i=0;i<size;i++){
if(count > 0){
packet[i] = fifo->buffer[read];
read++;
if (read==fifo->bufferSize){
read=0;
}
}else{
packet[i]=0;
}
}
return i;
}
void InitPacketFifo(PACKET_FIFO_STORAGE * fifo,BowlerPacket * buff,uint32_t size){
if(fifo == 0 || buff == 0){
println("@#@#FIFO FAILED TO INITIALIZE",ERROR_PRINT);p_int(size,ERROR_PRINT);
}
fifo->buffer=buff;
fifo->bufferSize=size;
fifo->readPointer=0;
fifo->writePointer=0;
//fifo->byteCount=0;
fifo->mutex=false;
}
uint32_t FifoAddPacket(PACKET_FIFO_STORAGE * fifo,BowlerPacket * toBeAdded){
if(FifoGetPacketCount(fifo) >= (fifo->bufferSize)){
println_E("Packet FIFO overflow");p_int_E(fifo->bufferSize);print_E(",");p_int_E(fifo->byteCount);
return 0;
}
copyPacket(toBeAdded,&fifo->buffer[fifo->writePointer]);
fifo->writePointer++;
if (fifo->writePointer == fifo->bufferSize){
fifo->writePointer=0;
}
//fifo->byteCount++;
FifoGetPacketCount(fifo);
//EndCritical();
return (FifoGetPacketCount(fifo)<=fifo->bufferSize);
}
uint32_t FifoGetPacketCount(PACKET_FIFO_STORAGE * fifo){
int w =fifo->writePointer;
int r = fifo->readPointer;
if(w>r){
fifo->byteCount= w-r;
}else if(w==r){
fifo->byteCount= 0;
}else{
fifo->byteCount= (w+fifo->bufferSize)-r;
}
return fifo->byteCount;
}
uint32_t FifoGetPacketSpaceAvailible(PACKET_FIFO_STORAGE * fifo){
return fifo->bufferSize - FifoGetPacketCount(fifo)-1;
}
uint32_t FifoGetPacket(PACKET_FIFO_STORAGE * fifo,BowlerPacket * retrived){
if(FifoGetPacketCount(fifo)>0)
copyPacket(&fifo->buffer[fifo->readPointer],retrived);
else
return false;
fifo->readPointer++;
if (fifo->readPointer==fifo->bufferSize){
fifo->readPointer=0;
}
FifoGetPacketCount(fifo);
//EndCritical();
return true;
}
<file_sep>/BowlerStack/include/Bowler/Bowler_Server.h
/*
* Bowler_Server.h
*
* Created on: Jun 18, 2010
* Author: hephaestus
*/
#ifndef BOWLER_SERVER_H_
#define BOWLER_SERVER_H_
#include "FIFO.h"
/**
* Initialize the server
*/
void Bowler_Init(void);
/**
* Run an instance of the server. This uses user defined memory
*/
uint8_t Bowler_Server_Static(BowlerPacket * Packet,BYTE_FIFO_STORAGE * fifo);
/**
* Run an instance of the server. TThis assumes tight hardware integrations
*/
uint8_t Bowler_Server(BowlerPacket * Packet, boolean debug);
/*
RUn the stack processor of all regestered namespaces
*/
boolean process(BowlerPacket * Packet);
#endif /* BOWLER_SERVER_H_ */
<file_sep>/BowlerStack/include/Bowler/Namespace_bcs_core.h
/*
* Namespace_bcs_core.h
*
* Created on: Mar 1, 2013
* Author: hephaestus
*/
#ifndef NAMESPACE_BCS_CORE_H_
#define NAMESPACE_BCS_CORE_H_
#include "namespace.h"
#include "Defines.h"
//bcs.core
#define _ERR 0x7272655f // '_err' The Error RPC
#define _RDY 0x7964725f // '_rdy' The ready RPC
#define _PNG 0x676E705F // '_png' Generic ping
#define _NMS 0x736d6e5f // '_nms' Namespace RPC
/**
* Initializes core and returns a pointer to the namespace list
*/
NAMESPACE_LIST * getBcsCoreNamespace();
NAMESPACE_LIST * getBcsRpcNamespace();
#endif /* NAMESPACE_BCS_CORE_H_ */
<file_sep>/Platform/src/pic32/Makefile
#@ Author <NAME>
SHELL := /bin/bash -e
CFILES := $(wildcard *.c) $(wildcard */*.c)
OFILES := $(CFILES:%.c=%.o)
all:clean $(OFILES)
echo ok
%.o: %.c
$(CC_Bowler_Arch) -I../../../Platform/include/ -I../../../BowlerStack/include/ -c $< -o $@
clean:
rm -rf *.o
rm -rf *.d
rm -rf usb/*.o
rm -rf usb/*.d<file_sep>/Platform/include/arch/pic32/FlashStorage.h
/*
* FlashStorage.h
*
* Created on: Jul 15, 2010
* Author: hephaestus
*/
#ifndef FLASHSTORAGE_H_
#define FLASHSTORAGE_H_
#define FLASH_PAGE_SIZE 0x1000
#define BootloaderStartStorePhysical 0x1D009000 ///End of the bootloader page
#define VirtualAddress (0x80000000)
#define DefaultStartStorePhysical 0x1D01F000 //end of the chip
//#define StartAppVectVirtual (BootloaderStartStorePhysical | VirtualAddress)
#define LOCKBYTE 37
typedef struct __attribute__((__packed__)) _FLASH_STORE{
uint8_t mac [6];
uint8_t name[20];
uint8_t lock;
uint8_t blSet;
uint8_t fwSet;
uint8_t bl[3];
uint8_t fw[4];
}FlashStorageStruct;
#define FLASHSTORE sizeof(FlashStorageStruct)
uint8_t FlashSetMac(uint8_t * mac);
//void FlashSetName(char * name);
void FlashGetMac(uint8_t * mac);
void FlashGetName(char * name);
//uint8_t FlashSetBlRev(uint8_t * mac);
//void FlashGetBlRev(uint8_t * mac);
//uint8_t FlashSetFwRev(uint8_t * mac);
//void FlashGetFwRev(uint8_t * mac);
void FlashSwitchMemoryToBootloader();
void enableFlashStorage(boolean enabled);
#endif /* FLASHSTORAGE_H_ */
<file_sep>/typeChange.sh
find $1 -type f -exec sed -i 's/B_B_B_BOOL /boolean /g' {} \;
find $1 -type f -exec sed -i 's/B_B_B_TRUE /true /g' {} \;
find $1 -type f -exec sed -i 's/B_B_B_FALSE /false /g' {} \;
find $1 -type f -exec sed -i 's/B_B_BOOL /boolean /g' {} \;
find $1 -type f -exec sed -i 's/B_B_TRUE /true /g' {} \;
find $1 -type f -exec sed -i 's/B_B_FALSE /false /g' {} \;
find $1 -type f -exec sed -i 's/B_BOOL /boolean /g' {} \;
find $1 -type f -exec sed -i 's/B_TRUE /true /g' {} \;
find $1 -type f -exec sed -i 's/B_FALSE /false /g' {} \;
find $1 -type f -exec sed -i 's/BOOL(/boolean(/g' {} \;
find $1 -type f -exec sed -i 's/BOOL /boolean /g' {} \;
find $1 -type f -exec sed -i 's/TRUE /true /g' {} \;
find $1 -type f -exec sed -i 's/FALSE /false /g' {} \;
find $1 -type f -exec sed -i 's/TRUE;/true; /g' {} \;
find $1 -type f -exec sed -i 's/FALSE;/false; /g' {} \;
find $1 -type f -exec sed -i 's/TRUE)/true) /g' {} \;
find $1 -type f -exec sed -i 's/FALSE)/false) /g' {} \;
find $1 -type f -exec sed -i 's/QWORD /uint64_t /g' {} \;
find $1 -type f -exec sed -i 's/DWORD /uint32_t /g' {} \;
find $1 -type f -exec sed -i 's/WORD /uint16_t /g' {} \;
find $1 -type f -exec sed -i 's/Ptr)uint8_t/Ptr)(uint8_t /g' {} \;
find $1 -type f -exec sed -i 's/ocal)uint8_t/ocal)(uint8_t /g' {} \;
find $1 -type f -exec sed -i 's/BYTE /uint8_t /g' {} \;
find $1 -type f -exec sed -i 's/(BYTE/(uint8_t /g' {} \;
find $1 -type f -exec sed -i 's/(BYTE)/(uint8_t) /g' {} \;
find $1 -type f -exec sed -i 's/BYTE,/uint8_t,/g' {} \;
find $1 -type f -exec sed -i 's/UINT /uint32_t /g' {} \;
find $1 -type f -exec sed -i 's/UINT8 /uint8_t /g' {} \;
find $1 -type f -exec sed -i 's/UINT16 /uint16_t /g' {} \;
find $1 -type f -exec sed -i 's/(UINT16)/(uint16_t)/g' {} \;
find $1 -type f -exec sed -i 's/UINT32 /uint32_t /g' {} \;
find $1 -type f -exec sed -i 's/UINT64 /uint64_t /g' {} \;
find $1 -type f -exec sed -i 's/INT8 /int8_t /g' {} \;
find $1 -type f -exec sed -i 's/INT16 /int16_t /g' {} \;
find $1 -type f -exec sed -i 's/INT32 /int32_t /g' {} \;
find $1 -type f -exec sed -i 's/(INT32)/(int32_t)/g' {} \;
find $1 -type f -exec sed -i 's/INT64 /int64_t /g' {} \;
find $1 -type f -exec sed -i 's/LONG /int64_t /g' {} \;
<file_sep>/Platform/src/NXP/HAL_nxp.c
/*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#include "Bowler/Bowler.h"
#include <avr/interrupt.h>
#if defined(__AVR_ATmega324P__)
#define comBuffSize (MiniPacketDataSize+4+BowlerHeaderSize)
#else
#define comBuffSize (FullPacketDataSize+4+BowlerHeaderSize)
#endif
static uint8_t privateRXCom[comBuffSize];
static BYTE_FIFO_STORAGE store;
static uint32_t TimerOFcount=0;
static uint32_t TimerOFcountUpper=0;
boolean GetBowlerPacket_arch(BowlerPacket * Packet){
return GetBowlerPacket(Packet,&store);
}
/**
* send the array out the connection
*/
uint16_t putStream(uint8_t *packet,uint16_t size){
uint16_t i;
for (i=0;i<size;i++){
WriteAVRUART0(packet[i]);
}
return i;
}
/**
* get the time in ms
*/
float getMs(void){
float upper = (((float)TimerOFcountUpper)*((float)4294967294ul))/18.0;
return (((float)GetTimeTicks())/18.0)+upper;
}
/**
* send this char to the print terminal
*/
void EnableDebugTerminal(void);
void putCharDebug(char c){
WriteAVRUART1(c);
//return true;
}
/**
* Start the scheduler
*/
void startScheduler(void){
TimerOFcount=0;
TCCR1Abits._WGM =0x00;// Fast WPM, 0xff top, 0x00 bottom
TCCR1Bbits._CS = 5;// Clock select 1-5 are valid values
TIMSK1bits._TOIE1=1;
}
void serial_init(unsigned int bittimer);
/**
* Private helpers
*/
uint64_t GetTimeTicks(void){
return (UINT64) (TimerOFcount+TCNT1);
}
ISR(TIMER1_OVF_vect){//timer 1 overflow interrupt
uint32_t before = TimerOFcount;
TimerOFcount+=0x10000;
if(TimerOFcount<before){
TimerOFcount=0;
TCNT1=0;
TimerOFcountUpper++;
}
}
// Communication HAL
/**
* Public functions, must be filled
*/
void AVR_Bowler_HAL_Init(void){
StartCritical();
serial_init( (( F_CPU /INTERNAL_BAUD / 16 ) - 1));
#if defined(DEBUG)
EnableDebugTerminal();
#endif
//print("com:");
InitByteFifo(&store,privateRXCom,comBuffSize);
InitFlagPins();
EndCritical();
}
void WriteAVRUART0(uint8_t val){
while(FlagAsync == 0 ); // Wait for controller to be ready
while ((UCSR0A & (1<<UDRE0)) == 0 );
UDR0 = val;
_delay_us(UARTDELAY);
}
void WriteAVRUART1(uint8_t val){
if (UCSR1B == 0)
return;
while ((UCSR1A & (1<<UDRE1)) == 0 );
UDR1 = val;
_delay_us(UARTDELAY);
}
/**
* Private helpers
*/
ISR(USART0_RX_vect){
StartCritical();
uint8_t err;
uint8_t b= UDR0;
FifoAddByte(&store, b, &err);
EndCritical();
//print("Got [0x");prHEX8(b);print("]\n");
}
void serial_init(unsigned int bittimer)
{
/* Set the baud rate */
UBRR0H = (unsigned char) (bittimer >> 8);
UBRR0L = (unsigned char) bittimer;
//UBRR0H = 0;
//UBRR0L = 64;
/* set the framing to 8E1 */
UCSR0C = (_BV(UCSZ00)|_BV(UCSZ01)| _BV(UPM01));
// /* set the framing to 8N1 */
// UCSR0C = (_BV(UCSZ00)|_BV(UCSZ01));
/* rx interrupts enabled, rx and tx enabled, 8-bit data */
UCSR0B =( _BV(RXCIE0) | _BV(RXEN0) | _BV(TXEN0) ) ;
UCSR0A = 0x00;
//EnableDebugTerminal();
}
void EnableDebugTerminal(void){
unsigned int bittimer;
bittimer=(( F_CPU / 115200 / 16 ) - 1);
/* Set the baud rate */
UBRR1H = (unsigned char) (bittimer >> 8);
UBRR1L = (unsigned char) bittimer;
/* set the framing to 8N1 */
UCSR1C = ((1<< UCSZ10)|(1<< UCSZ11));
/* tx enabled, 8-bit data */
UCSR1B =( _BV(TXEN1));
UCSR1A = 0x00;
}
<file_sep>/BowlerStack/include/Bowler/Scheduler.h
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#ifndef SCHEDULER_H_
#define SCHEDULER_H_
/**
* GetTImeTicks
* @return The number of timer ticks since the chip started running
*/
uint64_t GetTimeTicks(void);
/**
* StartScheduler
* This is run before the user code starts and initiates the timer based clock
*/
void StartScheduler(void);
/**
* SchedulerGetStep
* @param chan This is the channel to test if it is time for it to run. This value is from 0-5
* @return This is a boolean that returns true if the channel is scheduled to run.
* The time slices are 3.3 ms each, and there are 6 of them in total. That means each slice runs every 20Ms.
* Basic architecture is 6 blocks of 3.3 Ms each.
* The GetStep function will check if it is within that channel's time slice AND that slice has not run yet this cycle.
* If it is in the time slice and it has not run, the function returns true
* If it is in the time slice, and the slice has run, the it returns false
* If it is not in the time slice, it returns false
*/
unsigned char SchedulerGetStep(unsigned char chan);
/**
* Private function used by Bowler Stack.
*/
unsigned char ClearForCom(void);
/**
* Retrurns B_B_true if the timer has timed out
*/
unsigned char GetTimeoutState(void);
void TimeoutCounterReset(void);
/**
* Start a timeout session, pass in MS to wait
*/
void TimeoutCounterInit(float timeout);
void TimeoutCounterStop(void);
/**
* Data storage for scheduling events.
*/
typedef struct __attribute__((__packed__)) _RUN_EVERY{
//The start time for the schedule
float MsTime;
//The time from the start time to loop over
float setPoint;
} RunEveryData;
/**
* RunEvery
* This function returns not 0 if it has been at least as long as the "setPoint" field says since the last time it returned not 0.
* All timeing is handeled internally
* @param data Pointer to a data storage table
* @return float of MS after the assigned time that this function is running. A value of 0 means it has not been long enough
*/
float RunEvery(RunEveryData * data);
#endif /* SCHEDULER_H_ */
<file_sep>/Platform/src/pic32/ADC.c
/*
* ADC.c
*
* Created on: Feb 12, 2010
* Author: hephaestus
*/
#include "arch/pic32/BowlerConfig.h"
#include "Bowler/Bowler.h"
float getVoltage(uint8_t chan);
int ADCMask = 0;
int ADCOffset = 0;
void InitADCHardware(uint8_t chan){
//return ;
DDPCONbits.JTAGEN=0;
AD1CHS = 0x0000;
AD1PCFG = 0xFFFF;
AD1CON1 = 0x0000;
AD1CON2 = 0x0000;
AD1CON3 = 0x0000;
AD1CSSL = 0x0000;// Auto Sample only pins that can be ADC
AD1CHS = 0x0000;
AD1CON1bits.ASAM = 0;// Enable automatic sampling by setting
AD1CON1bits.SSRC = 0;
AD1CON1bits.FORM = 0; // Output in Integer Format
AD1CON1bits.ADON = 1; // Start the ADC module
AD1CON2bits.VCFG = 0;
AD1CON2bits.SMPI = 0;// Samples before an interupt
AD1CON2bits.CSCNA = 0;// Sequentially scan MUXA by setting
AD1CON3bits.SAMC = 0;// number of A/D clocks between the start of acquisition and the start of conversion
AD1CON3bits.ADCS = 13;// A/D Conversion clock
AD1CON3bits.ADRC = 1;// Use RC osscilator for conversion clock by setting
switch(chan){
case 0:
ADCMask= ENABLE_AN0_ANA;
break;
case 1:
ADCMask= ENABLE_AN1_ANA;
break;
case 2:
ADCMask= ENABLE_AN2_ANA;
break;
case 3:
ADCMask= ENABLE_AN3_ANA;
break;
case 4:
ADCMask= ENABLE_AN4_ANA;
break;
case 5:
ADCMask= ENABLE_AN5_ANA;
break;
case 6:
ADCMask= ENABLE_AN6_ANA;
break;
case 7:
ADCMask= ENABLE_AN7_ANA;
break;
case 8:
ADCMask= ENABLE_AN8_ANA;
break;
case 9:
ADCMask= ENABLE_AN9_ANA;
break;
case 10:
ADCMask= ENABLE_AN10_ANA;
break;
case 11:
ADCMask= ENABLE_AN11_ANA;
break;
case 12:
ADCMask= ENABLE_AN12_ANA;
break;
case 13:
ADCMask= ENABLE_AN13_ANA;
break;
case 14:
ADCMask= ENABLE_AN14_ANA;
break;
case 15:
ADCMask= ENABLE_AN15_ANA;
break;
}
mPORTBSetPinsAnalogIn(ADCMask);
//Use sample channel A
AD1CHSbits.CH0NA=1;
EnableADC10();
//println_I("Initialized ADC chan ");p_int_I(chan);
}
int getAdcRaw(uint8_t chan, int samples){
//return 0;
InitADCHardware( chan);
int i=0;
int back = 0;
do{
AD1CHSbits.CH0SA = chan;
AD1CON1bits.SAMP = 1;
Delay10us(5);
AD1CON1bits.SAMP = 0;
while (AD1CON1bits.DONE == 0){
// Wait for ADC to finish
}
AD1CHS =0;
back= back + (ADC1BUF0-ADCOffset);
}while(i++<samples);
CloseADC10();
back = back/(i);
return back;
}
//#define ADC_TO_VOLTS 0.003145631
#define ADC_TO_VOLTS 0.00322265625 // AC: this shouldn't be here
float getAdcVoltage(uint8_t chan, int samples){
int back = getAdcRaw( chan, samples);
return ((float)back)*ADC_TO_VOLTS;
}
void measureAdcOffset(){
AD1CON2bits.OFFCAL=1; // enable ofsset detection mode
AD1CHSbits.CH0SA = 0;
AD1CON1bits.SAMP = 1;
Delay10us(5);
AD1CON1bits.SAMP = 0;
while (AD1CON1bits.DONE == 0);
AD1CHS =0;
ADCOffset = ADC1BUF0;
AD1CON2bits.OFFCAL=0; // disable ofsset detection mode
CloseADC10();
// Print_Level l = getPrintLevel();
// setPrintLevelInfoPrint();
// println_I("Measured ADC Offset as: ");p_int_I(ADCOffset);
// setPrintLevel(l);
}
int getAdcOffset(){
return ADCOffset;
}<file_sep>/Platform/src/pic32/FlashStorage.c
/*
* FlashStorage.c
*
* Created on: Jul 15, 2010
* Author: hephaestus
*/
#include "arch/pic32/BowlerConfig.h"
#include "Bowler/Bowler.h"
//#include <stddef.h>
FlashStorageStruct flash;
uint32_t * externalStream=0;
uint32_t streamSize=0;
uint32_t * stream;
uint8_t defMac[] ={0x74,0xf7,0x26,0x00,0x00,0x00} ;
uint32_t MEMORY_BASE =DefaultStartStorePhysical;
uint32_t VirtualBase = DefaultStartStorePhysical+VirtualAddress;
boolean disableFlash =true;
void enableFlashStorage(boolean enabled){
disableFlash = enabled?false:true;
}
void FlashSwitchMemoryToBootloader(){
VirtualBase = BootloaderStartStorePhysical+VirtualAddress;
MEMORY_BASE = BootloaderStartStorePhysical;
}
void SetFlashData(uint32_t * s,uint32_t size){
if(((size*4)+FLASHSTORE) > FLASH_PAGE_SIZE ){
//println_E("This data page is too big for the flash page!");
SoftReset();
}
streamSize=size;
externalStream=s;
//println_W("Setting external flash data ");p_int_W(size);
}
void FlashLoad(void){
if(disableFlash == true)
return;
if (FLASHSTORE % 4) {
println_E("BAD FLASH size = ");
p_int_W(FLASHSTORE % 4);
while (1);
}
int i;
stream = (uint32_t *) &flash;
for (i=0;i<FLASHSTORE/4;i++){
stream[i]=*((uint32_t *)(VirtualBase +(i*4)));
}
if(externalStream != 0 && streamSize!=0){
for (i=0;i<streamSize;i++){
externalStream[i]=*((uint32_t *)(VirtualBase +((i+FLASHSTORE)*4)));
}
}else{
//println_E("External storage not availible!");
}
}
void FlashSync(void){
if(disableFlash == true)
return;
//return;
uint32_t i;
uint32_t data=0, read=0,addr=0;
// println_I("Erasing Storage page");
if(disableFlash==false)
NVMErasePage( (uint32_t *) MEMORY_BASE);
// println_I("Writing new data Storage page");
stream = (uint32_t *) &flash;
for (i=0;i<FLASHSTORE/4;i++){
if(disableFlash==false)
NVMWriteWord((uint32_t *)(VirtualBase +(i*4)), stream[i]);
}
if(externalStream != 0 && streamSize!=0){
for (i=0;i<streamSize;i++){
data = externalStream[i];
addr = (VirtualBase +((i+FLASHSTORE)*4));
if(disableFlash==false){
NVMWriteWord((uint32_t *)(addr), data );
read=*((uint32_t *)(addr));
if(data != read){
// println_E("Data write failed! ");prHEX32(read,ERROR_PRINT);
// print_E(" expected ");prHEX32(data,ERROR_PRINT);
// print_E(" at ");prHEX32(addr,ERROR_PRINT);
}
}
}
}else{
//println_E("External storage not availible!");
}
//println_I("Storage synced");
}
uint8_t FlashSetMac(uint8_t * mac){
FlashLoad();
if(flash.lock==LOCKBYTE){
return false;
}
int i;
for (i=0;i<6;i++){
flash.mac[i]=mac[i];
}
flash.lock=LOCKBYTE;
FlashSync();
return true;
}
//void FlashSetName(char * name){
// FlashLoad();
// int i;
// for (i=0;i<17;i++){
// flash.name[i]=name[i];
// }
// FlashSync();
//}
void FlashGetMac(uint8_t * mac){
int i;
FlashLoad();
if(flash.lock == 0xff){
for (i=0;i<6;i++){
mac[i]=defMac[i];
}
return;
}
for (i=0;i<6;i++){
mac[i]=flash.mac[i];
}
}
//
//void FlashGetName(char * name){
// FlashLoad();
// int i;
// for (i=0;i<17;i++){
// name[i]=flash.name[i];
// }
//}
//
//void FlashGetBlRev(uint8_t * mac){
// int i;
// FlashLoad();
// for (i=0;i<3;i++){
// mac[i]=flash.bl[i];
// }
//}
//void FlashGetFwRev(uint8_t * mac){
// int i;
// FlashLoad();
// for (i=0;i<3;i++){
// mac[i]=flash.fw[i];
// }
//}
//
//uint8_t FlashSetFwRev(uint8_t * mac){
// //println("Loading fw from flash");
// FlashLoad();
// //println("Loading fw new data");
// int i;
// boolean sync=false;
// for (i=0;i<3;i++){
// if(flash.fw[i]!=mac[i]){
// flash.fw[i]=mac[i];
// sync=true;
// }
// }
// if(sync){
// //println("Syncing fw ");
// FlashSync();
// //println("Syncing fw done");
// }
// return true;
//}
//
//uint8_t FlashSetBlRev(uint8_t * mac){
// //println("Loading bl flash page");
// FlashLoad();
// //println("Loading bl new data");
// int i;
// boolean sync=false;
// for (i=0;i<3;i++){
// if(flash.bl[i]!=mac[i]){
// flash.bl[i]=mac[i];
// sync=true;
// }
// }
// if(sync){
// //println("Syncing bl ");
// FlashSync();
// //println("Syncing bl done");
// }
// return true;
//}
<file_sep>/Platform/src/avr/HAL_xxx4p.c
/*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#include "Bowler/Bowler.h"
#include "arch/AVR/BowlerConfig.h"
//#include "reg_structs.h"
//#include <util/delay.h>
//#include <avr/io.h>
//#include <avr/interrupt.h>
//#include <string.h>
//#include <avr/pgmspace.h>
//#include "Bowler/Debug.h"
//# include <avr/iom644p.h>
boolean okToPrint(Print_Level l);
#define comBuffSize (FullPacketDataSize+4+_BowlerHeaderSize)
static uint8_t privateRXCom[comBuffSize];
static BYTE_FIFO_STORAGE store;
static uint64_t TimerOFcount=0;
static uint32_t TimerOFcountUpper=0;
//static uint32_t currentTimer=0;
static uint8_t err;
static uint8_t tmp;
boolean GetBowlerPacket_arch(BowlerPacket * Packet){
return GetBowlerPacket(Packet,&store);
}
/**
* send the array out the connection
*/
uint16_t putStream(uint8_t *packet,uint16_t size){
uint16_t i;
for (i=0;i<size;i++){
WriteAVRUART0(packet[i]);
}
return i;
}
/**
* get the time in ms
*/
float getMs(void){
float upper = (((float)TimerOFcountUpper)*((float)4294967294ul))/18.0;
float ret;
do{
ret = ((((float)GetTimeTicks())/18.0)+upper)/128;
if(isnan(ret)){
println_E("Timer NaN, recalculating..");
}
}while(isnan(ret));
return ret;
}
/**
* send this char to the print terminal
*/
void putCharDebug(char c){
WriteAVRUART1(c);
//return true;
}
/**
* Start the scheduler
*/
void startScheduler(void){
TimerOFcount=0;
TCCR1Abits._WGM =0x00;// Normal , 0xffff top, 0x0000 bottom
TCCR1Bbits._CS = 2;// value CLslk I/O/8 (From prescaler)
TIMSK1bits._TOIE1=1;
}
void serial_init(unsigned int bittimer);
/**
* Private helpers
*/
uint64_t GetTimeTicks(void){
return (uint64_t) ((TimerOFcount)+TCNT1);
}
void updateTimer(uint64_t value){
TimerOFcount+=value;
}
ISR(TIMER1_OVF_vect){//timer 1 overflow interrupt
//TCCR1Bbits._CS=0;// stop the clock
//FlagBusy_IO=1;
updateTimer(0xffff);
TCNT1 = 0; // re-load the state value
//EndCritical();
//TCCR1Bbits._CS = 2;// value CLslk I/O/8 (From prescaler)
//FlagBusy_IO=0;
}
// Communication HAL
/**
* Public functions, must be filled
*/
void AVR_Bowler_HAL_Init(void){
StartCritical();
//serial_init( (( F_CPU /INTERNAL_BAUD / 16 ) - 1));
serial_init( INTERNAL_BAUD_AVR );
#if defined(DEBUG)
EnableDebugTerminal();
#endif
//print("com:");
InitByteFifo(&store,privateRXCom,comBuffSize);
InitFlagPins();
}
void WriteAVRUART0(uint8_t val){
UCSR0Bbits._TXEN0 = 1;
while(FlagAsync == 0 ); // Wait for controller to be ready
while ((UCSR0A & (1<<UDRE0)) == 0 );
UDR0 = val;
_delay_us(UARTDELAY);
}
void WriteAVRUART1(uint8_t val){
UCSR1Bbits._TXEN1 = 1;
while (UCSR1Abits._UDRE1 == 0 );
UDR1 = val;
_delay_us(UARTDELAY);
}
#define timerSpacer 5
void fixTimers(int currentTimerLocal){
/*
* When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are dis-
* abled. The user software can write logic one to the I-bit to enable nested interrupts.
*/
EndCritical();
int after = TCNT1;
//
if((currentTimerLocal <= OCR1B && after >= OCR1B)){
// OCR1B detect
OCR1B = after+timerSpacer;
//println_E("B");p_int_E(after -currentTimerLocal-(2*timerSpacer) );
return;
}
if((currentTimerLocal <= OCR1A && after >= OCR1A)){
// OCR1A detect
OCR1A = after+timerSpacer;
//println_E("A");p_int_E(after -currentTimerLocal-(2*timerSpacer) );
return;
}
}
/**
* Private helpers
*/
#define UART_ON ( _BV(RXEN0) | _BV(TXEN0) )
ISR(USART0_RX_vect){
//currentTimer = TCNT1;
UCSR0Bbits._RXCIE0=0;
//fixTimers(currentTimer);
sei();
//int flag = FlagBusy_IO;
//FlagBusy_IO=1;
tmp = UDR0;
FifoAddByte(&store, tmp, &err);
UCSR0Bbits._RXCIE0=1;
//UCSR0B =( _BV(RXCIE0) | UART_ON ) ;
//FlagBusy_IO=flag;
//FlagBusy_IO=0;
}
void serial_init(unsigned int bittimer)
{
/* Set the baud rate */
UBRR0H = (unsigned char) (bittimer >> 8);
UBRR0L = (unsigned char) bittimer;
//UBRR0H = 0;
//UBRR0L = 64;
/* set the framing to 8E1 */
UCSR0C = (_BV(UCSZ00)|_BV(UCSZ01)| _BV(UPM01));
// /* set the framing to 8N1 */
// UCSR0C = (_BV(UCSZ00)|_BV(UCSZ01));
/* rx interrupts enabled, rx and tx enabled, 8-bit data */
UCSR0B =( _BV(RXCIE0) | _BV(RXEN0) | _BV(TXEN0) ) ;
UCSR0A = 0x00;
//EnableDebugTerminal();
}
void EnableDebugTerminal(void){
unsigned int bittimer;
bittimer=(( F_CPU / 115200 / 16 ) - 1);
/* Set the baud rate */
UBRR1H = (unsigned char) (bittimer >> 8);
UBRR1L = (unsigned char) bittimer;
/* set the framing to 8N1 */
UCSR1C = ((1<< UCSZ10)|(1<< UCSZ11));
/* tx enabled, 8-bit data */
UCSR1B =( _BV(TXEN1));
UCSR1A = 0x00;
}
void showString (PGM_P s,Print_Level l,char newLine) {
if(!okToprint(l)){
return;
}
if(newLine){
putCharDebug('\n');
putCharDebug('\r');
}
setColor(l);
char c;
while ((c = pgm_read_byte(s++)) != 0)
putCharDebug(c);
}
<file_sep>/Platform/include/arch/pic32/bootloader/BLdefines.h
/*
* BLdefines.h
*
* Created on: May 30, 2010
* Author: hephaestus
*/
#ifndef BLDEFINES_H_
#define BLDEFINES_H_
#define StartAppVectVirtual 0x9D00B000
#define StartAppVectPhysical 0x1D00A000
#define EndAppVectPhysical 0x1D01FFFF
// acamilo:
// change fuses to f7
// SUT changed to int64_t to increase oscilator stabalization time.
// Oscilator drive method changed to FullSwing from Low Power.
// SEE DS section 8.4 (p. 34)
#define AVR_LOW 0xf7
#define AVR_HIGH 0xd1
#define AVR_EXT 0xff
#endif /* BLDEFINES_H_ */
<file_sep>/BowlerStack/include/Bowler/Bowler_Struct_Def.h
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#ifndef BOWLERSTRUCTDEF_H_
#define BOWLERSTRUCTDEF_H_
// typedef union _RPC_VALUE {
// unsigned char ASCII[4];
// unsigned long int value;
// }RPC_VALUE;
#if !defined(__STACK_TSK_H) && !defined(_SOCKET_H_)
typedef struct __attribute__((__packed__)) _MAC_ADDR
{
uint8_t v[6];
} MAC_ADDR;
#endif
typedef struct __attribute__((__packed__)) _HEADER
{
unsigned char ProtocolRevision;
MAC_ADDR MAC; // The MAC address of the packet
unsigned char Method; // The method type
unsigned MessageID :7; // Semi unique Transaction ID
unsigned ResponseFlag :1; // Is this packet a response packet
unsigned char DataLegnth; // Length of data to come
unsigned char CRC; // CRC for packet
unsigned long int RPC; // 4 byte RPC stored as a 32 bit int for single compare;
} HEADER;
#define FullPacketDataSize 252
typedef union _BowlerPacket{
unsigned char stream[FullPacketDataSize+sizeof(HEADER)];
struct
{
HEADER head;
unsigned char data[FullPacketDataSize];
} use;
}BowlerPacket;
//#define MiniPacketDataSize FullPacketDataSize
// typedef union _BowlerPacketMini{
// unsigned char stream[MiniPacketDataSize+sizeof(HEADER)];
// struct
// {
// HEADER head;
// unsigned char data[MiniPacketDataSize];
// } use;
// }BowlerPacketMini;
typedef struct __attribute__((__packed__)) _INTERPOLATE_DATA
{
//Target value for the interpolator to get to
float set;
//Initial starting point value of target
float start;
//How many ms the interpolation should take
float setTime;
//The timestamp of when the interpolation began.
float startTime;
} INTERPOLATE_DATA;
#endif /* WASPSTRUCTDEF_H_ */
<file_sep>/BowlerStack/include/Bowler/FIFO.h
/**
* @file FIFO.h
*
* Created on: May 27, 2010
* @author hephaestus
*/
#ifndef FIFO_H_
#define FIFO_H_
#include "Bowler_Struct_Def.h"
#define FIFO_OK 0
#define FIFO_FAILED_TO_SET 1
#define FIFO_FAILED_TO_GET 2
#define FIFO_OVERFLOW 3
#define FIFO_UNDERFLOW 4
typedef struct _BYTE_FIFO_STORAGE{
uint32_t bufferSize;
uint8_t * buffer;
uint32_t readPointer;
uint32_t writePointer;
uint32_t byteCount;
boolean mutex;
}BYTE_FIFO_STORAGE;
void InitByteFifo(BYTE_FIFO_STORAGE * fifo,uint8_t * buff,uint32_t size);
uint32_t calcByteCount(BYTE_FIFO_STORAGE * fifo);
uint8_t ReadFirstByte(BYTE_FIFO_STORAGE * fifo);
/**
*
* This function extracts the number of bytes stored in the given FIFO.
*
* @param fifo This is a pointer to a data struct containing an initialized FIFO
* Prerequsites:
* The fifo must be initialized by calling InitByteFifo with valid data.
*
* @return returns the number of bytes in the fifo
*/
uint32_t FifoGetByteCount(BYTE_FIFO_STORAGE * fifo);
uint8_t FifoGetByte(BYTE_FIFO_STORAGE * fifo, uint8_t * errorCode);
uint32_t FifoAddByte(BYTE_FIFO_STORAGE * fifo,uint8_t b, uint8_t * errorCode);
void printFiFoState(BYTE_FIFO_STORAGE * fifo, Print_Level l);
#define printFiFoState_E(A) printFiFoState(A,ERROR_PRINT)
#define printFiFoState_W(A) printFiFoState(A, WARN_PRINT)
#define printFiFoState_I(A) printFiFoState(A, INFO_PRINT)
uint32_t FifoGetByteStream(BYTE_FIFO_STORAGE * fifo,uint8_t *packet,uint32_t size);
uint8_t FifoReadByteAtIndex(BYTE_FIFO_STORAGE * fifo,uint32_t offset );
uint32_t FifoReadByteStream(uint8_t *packet,uint32_t size,BYTE_FIFO_STORAGE * fifo);
typedef struct _UINT32_FIFO_STORAGE{
uint32_t bufferSize;
uint32_t * buffer;
uint32_t readPointer;
uint32_t writePointer;
uint32_t count;
}UINT32_FIFO_STORAGE;
/**
* Packet FIFO
*/
typedef struct _PACKET_FIFO_STORAGE{
uint32_t bufferSize;
BowlerPacket * buffer;
uint32_t readPointer;
uint32_t writePointer;
uint32_t byteCount;
boolean mutex;
}PACKET_FIFO_STORAGE;
void InitPacketFifo(PACKET_FIFO_STORAGE * fifo,BowlerPacket * buff,uint32_t size);
uint32_t FifoAddPacket(PACKET_FIFO_STORAGE * fifo,BowlerPacket * toBeAdded);
uint32_t FifoGetPacketCount(PACKET_FIFO_STORAGE * fifo);
uint32_t FifoGetPacketSpaceAvailible(PACKET_FIFO_STORAGE * fifo);
uint32_t FifoGetPacket(PACKET_FIFO_STORAGE * fifo,BowlerPacket * retrived);
#endif /* FIFO_H_ */
<file_sep>/Platform/include/arch/pic32/GenericTypeDefs.h
/*******************************************************************
Generic Type Definitions
********************************************************************
FileName: GenericTypeDefs.h
Dependencies: None
Processor: PIC10, PIC12, PIC16, PIC18, PIC24, dsPIC, PIC32
Compiler: MPLAB C Compilers for PIC18, PIC24, dsPIC, & PIC32
Hi-Tech PICC PRO, Hi-Tech PICC18 PRO
Company: Microchip Technology Inc.
Software License Agreement
The software supplied herewith by Microchip Technology Incorporated
(the "Company") is intended and supplied to you, the Company's
customer, for use solely and exclusively with products manufactured
by the Company.
The software is owned by the Company and/or its supplier, and is
protected under applicable copyright laws. All rights are reserved.
Any use in violation of the foregoing restrictions may subject the
user to criminal sanctions under applicable laws, as well as to
civil liability for the breach of the terms and conditions of this
license.
THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION. NO WARRANTIES,
WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
********************************************************************
File Description:
Change History:
Rev Date Description
1.1 09/11/06 Add base signed types
1.2 02/28/07 Add QWORD, LONGLONG, QWORD_VAL
1.3 02/06/08 Add def's for PIC32
1.4 08/08/08 Remove LSB/MSB Macros, adopted by Peripheral lib
1.5 08/14/08 Simplify file header
Draft 2.0 07/13/09 Updated for new release of coding standards
*******************************************************************/
#ifndef __GENERIC_TYPE_DEFS_H_
#define __GENERIC_TYPE_DEFS_H_
#ifdef __cplusplus
extern "C"
{
#endif
/* Specify an extension for GCC based compilers */
#if defined(__GNUC__)
#define __EXTENSION __extension__
#else
#define __EXTENSION
#endif
/* get compiler defined type definitions (NULL, size_t, etc) */
#include <stddef.h>
#include <stdint.h>
//typedef enum _BOOL { FALSE = 0, TRUE } BOOL; /* Undefined size */
typedef unsigned char BOOL;
#define TRUE 1
#define FALSE 0
typedef enum _BIT { CLEAR = 0, SET } BIT;
#define PUBLIC /* Function attributes */
#define PROTECTED
#define PRIVATE static
/* INT is processor specific in length may vary in size */
typedef int32_t INT;
typedef int8_t INT8;
typedef int16_t INT16;
typedef int32_t INT32;
/* MPLAB C Compiler for PIC18 does not support 64-bit integers */
#if !defined(__18CXX)
//__EXTENSION typedef signed long long INT64;
#endif
/* UINT is processor specific in length may vary in size */
typedef uint32_t UINT;
typedef uint8_t UINT8;
typedef uint16_t UINT16;
typedef uint32_t UINT32;
/* 24-bit type only available on C18 */
#if defined(__18CXX)
typedef unsigned short long UINT24;
#endif
//typedef unsigned long int UINT32; /* other name for 32-bit integer */
/* MPLAB C Compiler for PIC18 does not support 64-bit integers */
#if !defined(__18CXX)
//__EXTENSION typedef unsigned long long UINT64;
#endif
typedef union
{
uint8_t Val;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
} bits;
} UINT8_VAL, UINT8_BITS;
typedef union
{
uint16_t Val;
uint8_t v[2];
struct
{
uint8_t LB;
uint8_t HB;
} byte;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
__EXTENSION uint8_t b8:1;
__EXTENSION uint8_t b9:1;
__EXTENSION uint8_t b10:1;
__EXTENSION uint8_t b11:1;
__EXTENSION uint8_t b12:1;
__EXTENSION uint8_t b13:1;
__EXTENSION uint8_t b14:1;
__EXTENSION uint8_t b15:1;
} bits;
} UINT16_VAL, UINT16_BITS;
/* 24-bit type only available on C18 */
#if defined(__18CXX)
typedef union
{
UINT24 Val;
uint8_t v[3];
struct
{
uint8_t LB;
uint8_t HB;
uint8_t UB;
} byte;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
__EXTENSION uint8_t b8:1;
__EXTENSION uint8_t b9:1;
__EXTENSION uint8_t b10:1;
__EXTENSION uint8_t b11:1;
__EXTENSION uint8_t b12:1;
__EXTENSION uint8_t b13:1;
__EXTENSION uint8_t b14:1;
__EXTENSION uint8_t b15:1;
__EXTENSION uint8_t b16:1;
__EXTENSION uint8_t b17:1;
__EXTENSION uint8_t b18:1;
__EXTENSION uint8_t b19:1;
__EXTENSION uint8_t b20:1;
__EXTENSION uint8_t b21:1;
__EXTENSION uint8_t b22:1;
__EXTENSION uint8_t b23:1;
} bits;
} UINT24_VAL, UINT24_BITS;
#endif
typedef union
{
uint32_t Val;
uint16_t w[2];
uint8_t v[4];
struct
{
uint16_t LW;
uint16_t HW;
} word;
struct
{
uint8_t LB;
uint8_t HB;
uint8_t UB;
uint8_t MB;
} byte;
struct
{
UINT16_VAL low;
UINT16_VAL high;
}wordUnion;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
__EXTENSION uint8_t b8:1;
__EXTENSION uint8_t b9:1;
__EXTENSION uint8_t b10:1;
__EXTENSION uint8_t b11:1;
__EXTENSION uint8_t b12:1;
__EXTENSION uint8_t b13:1;
__EXTENSION uint8_t b14:1;
__EXTENSION uint8_t b15:1;
__EXTENSION uint8_t b16:1;
__EXTENSION uint8_t b17:1;
__EXTENSION uint8_t b18:1;
__EXTENSION uint8_t b19:1;
__EXTENSION uint8_t b20:1;
__EXTENSION uint8_t b21:1;
__EXTENSION uint8_t b22:1;
__EXTENSION uint8_t b23:1;
__EXTENSION uint8_t b24:1;
__EXTENSION uint8_t b25:1;
__EXTENSION uint8_t b26:1;
__EXTENSION uint8_t b27:1;
__EXTENSION uint8_t b28:1;
__EXTENSION uint8_t b29:1;
__EXTENSION uint8_t b30:1;
__EXTENSION uint8_t b31:1;
} bits;
} UINT32_VAL;
/* MPLAB C Compiler for PIC18 does not support 64-bit integers */
#if !defined(__18CXX)
typedef union
{
uint64_t Val;
uint32_t d[2];
uint16_t w[4];
uint8_t v[8];
struct
{
uint32_t LD;
uint32_t HD;
} dword;
struct
{
uint16_t LW;
uint16_t HW;
uint16_t UW;
uint16_t MW;
} word;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
__EXTENSION uint8_t b8:1;
__EXTENSION uint8_t b9:1;
__EXTENSION uint8_t b10:1;
__EXTENSION uint8_t b11:1;
__EXTENSION uint8_t b12:1;
__EXTENSION uint8_t b13:1;
__EXTENSION uint8_t b14:1;
__EXTENSION uint8_t b15:1;
__EXTENSION uint8_t b16:1;
__EXTENSION uint8_t b17:1;
__EXTENSION uint8_t b18:1;
__EXTENSION uint8_t b19:1;
__EXTENSION uint8_t b20:1;
__EXTENSION uint8_t b21:1;
__EXTENSION uint8_t b22:1;
__EXTENSION uint8_t b23:1;
__EXTENSION uint8_t b24:1;
__EXTENSION uint8_t b25:1;
__EXTENSION uint8_t b26:1;
__EXTENSION uint8_t b27:1;
__EXTENSION uint8_t b28:1;
__EXTENSION uint8_t b29:1;
__EXTENSION uint8_t b30:1;
__EXTENSION uint8_t b31:1;
__EXTENSION uint8_t b32:1;
__EXTENSION uint8_t b33:1;
__EXTENSION uint8_t b34:1;
__EXTENSION uint8_t b35:1;
__EXTENSION uint8_t b36:1;
__EXTENSION uint8_t b37:1;
__EXTENSION uint8_t b38:1;
__EXTENSION uint8_t b39:1;
__EXTENSION uint8_t b40:1;
__EXTENSION uint8_t b41:1;
__EXTENSION uint8_t b42:1;
__EXTENSION uint8_t b43:1;
__EXTENSION uint8_t b44:1;
__EXTENSION uint8_t b45:1;
__EXTENSION uint8_t b46:1;
__EXTENSION uint8_t b47:1;
__EXTENSION uint8_t b48:1;
__EXTENSION uint8_t b49:1;
__EXTENSION uint8_t b50:1;
__EXTENSION uint8_t b51:1;
__EXTENSION uint8_t b52:1;
__EXTENSION uint8_t b53:1;
__EXTENSION uint8_t b54:1;
__EXTENSION uint8_t b55:1;
__EXTENSION uint8_t b56:1;
__EXTENSION uint8_t b57:1;
__EXTENSION uint8_t b58:1;
__EXTENSION uint8_t b59:1;
__EXTENSION uint8_t b60:1;
__EXTENSION uint8_t b61:1;
__EXTENSION uint8_t b62:1;
__EXTENSION uint8_t b63:1;
} bits;
} UINT64_VAL;
#endif /* __18CXX */
/***********************************************************************************/
/* Alternate definitions */
typedef void VOID;
typedef char CHAR8;
typedef unsigned char UCHAR8;
typedef unsigned char BYTE; /* 8-bit unsigned */
typedef unsigned short int WORD; /* 16-bit unsigned */
typedef unsigned long DWORD; /* 32-bit unsigned */
/* MPLAB C Compiler for PIC18 does not support 64-bit integers */
#if !defined(__18CXX)
__EXTENSION
typedef unsigned long long QWORD; /* 64-bit unsigned */
#endif /* __18CXX */
typedef signed char CHAR; /* 8-bit signed */
typedef signed short int SHORT; /* 16-bit signed */
typedef signed long LONG; /* 32-bit signed */
/* MPLAB C Compiler for PIC18 does not support 64-bit integers */
#if !defined(__18CXX)
__EXTENSION
typedef signed long long LONGLONG; /* 64-bit signed */
#endif /* __18CXX */
typedef union
{
uint8_t Val;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
} bits;
} BYTE_VAL, BYTE_BITS;
typedef union
{
int16_t Val;
uint8_t v[2];
struct
{
uint8_t LB;
uint8_t HB;
} byte;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
__EXTENSION uint8_t b8:1;
__EXTENSION uint8_t b9:1;
__EXTENSION uint8_t b10:1;
__EXTENSION uint8_t b11:1;
__EXTENSION uint8_t b12:1;
__EXTENSION uint8_t b13:1;
__EXTENSION uint8_t b14:1;
__EXTENSION uint8_t b15:1;
} bits;
} WORD_VAL, WORD_BITS;
typedef union
{
int32_t Val;
int16_t w[2];
uint8_t v[4];
struct
{
int16_t LW;
int16_t HW;
} word;
struct
{
uint8_t LB;
uint8_t HB;
uint8_t UB;
uint8_t MB;
} byte;
struct
{
WORD_VAL low;
WORD_VAL high;
}wordUnion;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
__EXTENSION uint8_t b8:1;
__EXTENSION uint8_t b9:1;
__EXTENSION uint8_t b10:1;
__EXTENSION uint8_t b11:1;
__EXTENSION uint8_t b12:1;
__EXTENSION uint8_t b13:1;
__EXTENSION uint8_t b14:1;
__EXTENSION uint8_t b15:1;
__EXTENSION uint8_t b16:1;
__EXTENSION uint8_t b17:1;
__EXTENSION uint8_t b18:1;
__EXTENSION uint8_t b19:1;
__EXTENSION uint8_t b20:1;
__EXTENSION uint8_t b21:1;
__EXTENSION uint8_t b22:1;
__EXTENSION uint8_t b23:1;
__EXTENSION uint8_t b24:1;
__EXTENSION uint8_t b25:1;
__EXTENSION uint8_t b26:1;
__EXTENSION uint8_t b27:1;
__EXTENSION uint8_t b28:1;
__EXTENSION uint8_t b29:1;
__EXTENSION uint8_t b30:1;
__EXTENSION uint8_t b31:1;
} bits;
} DWORD_VAL;
/* MPLAB C Compiler for PIC18 does not support 64-bit integers */
#if !defined(__18CXX)
typedef union
{
int64_t Val;
int32_t d[2];
int16_t w[4];
uint8_t v[8];
struct
{
int32_t LD;
int32_t HD;
} dword;
struct
{
int16_t LW;
int16_t HW;
int16_t UW;
int16_t MW;
} word;
struct
{
__EXTENSION uint8_t b0:1;
__EXTENSION uint8_t b1:1;
__EXTENSION uint8_t b2:1;
__EXTENSION uint8_t b3:1;
__EXTENSION uint8_t b4:1;
__EXTENSION uint8_t b5:1;
__EXTENSION uint8_t b6:1;
__EXTENSION uint8_t b7:1;
__EXTENSION uint8_t b8:1;
__EXTENSION uint8_t b9:1;
__EXTENSION uint8_t b10:1;
__EXTENSION uint8_t b11:1;
__EXTENSION uint8_t b12:1;
__EXTENSION uint8_t b13:1;
__EXTENSION uint8_t b14:1;
__EXTENSION uint8_t b15:1;
__EXTENSION uint8_t b16:1;
__EXTENSION uint8_t b17:1;
__EXTENSION uint8_t b18:1;
__EXTENSION uint8_t b19:1;
__EXTENSION uint8_t b20:1;
__EXTENSION uint8_t b21:1;
__EXTENSION uint8_t b22:1;
__EXTENSION uint8_t b23:1;
__EXTENSION uint8_t b24:1;
__EXTENSION uint8_t b25:1;
__EXTENSION uint8_t b26:1;
__EXTENSION uint8_t b27:1;
__EXTENSION uint8_t b28:1;
__EXTENSION uint8_t b29:1;
__EXTENSION uint8_t b30:1;
__EXTENSION uint8_t b31:1;
__EXTENSION uint8_t b32:1;
__EXTENSION uint8_t b33:1;
__EXTENSION uint8_t b34:1;
__EXTENSION uint8_t b35:1;
__EXTENSION uint8_t b36:1;
__EXTENSION uint8_t b37:1;
__EXTENSION uint8_t b38:1;
__EXTENSION uint8_t b39:1;
__EXTENSION uint8_t b40:1;
__EXTENSION uint8_t b41:1;
__EXTENSION uint8_t b42:1;
__EXTENSION uint8_t b43:1;
__EXTENSION uint8_t b44:1;
__EXTENSION uint8_t b45:1;
__EXTENSION uint8_t b46:1;
__EXTENSION uint8_t b47:1;
__EXTENSION uint8_t b48:1;
__EXTENSION uint8_t b49:1;
__EXTENSION uint8_t b50:1;
__EXTENSION uint8_t b51:1;
__EXTENSION uint8_t b52:1;
__EXTENSION uint8_t b53:1;
__EXTENSION uint8_t b54:1;
__EXTENSION uint8_t b55:1;
__EXTENSION uint8_t b56:1;
__EXTENSION uint8_t b57:1;
__EXTENSION uint8_t b58:1;
__EXTENSION uint8_t b59:1;
__EXTENSION uint8_t b60:1;
__EXTENSION uint8_t b61:1;
__EXTENSION uint8_t b62:1;
__EXTENSION uint8_t b63:1;
} bits;
} QWORD_VAL;
#endif /* __18CXX */
#undef __EXTENSION
#ifdef __cplusplus
}
#endif
#endif /* __GENERIC_TYPE_DEFS_H_ */
<file_sep>/BowlerStack/src/PID/PidRpc.c
/*
* PidRpc.c
*
* Created on: Feb 14, 2014
* Author: hephaestus
*/
/**
* @file AbstractPID.c
*
* Created on: Apr 9, 2010
* @author <NAME>
*/
#include "Bowler/Bowler.h"
//#include "arch/pic32/BowlerConfig.h"
void GetConfigPDVelocity(BowlerPacket * Packet){
// 2700 4 8 2712 a98 output/o/PidRpc.o
set32bit(Packet,getPidGroupDataTable(Packet->use.data[0])->config.V.P*100, 1);
set32bit(Packet,getPidGroupDataTable(Packet->use.data[0])->config.V.D*100, 5);
Packet->use.head.DataLegnth=4+9;
Packet->use.head.Method=BOWLER_POST;
}
uint8_t ConfigPDVelovity(BowlerPacket * Packet){
uint8_t chan = Packet->use.data[0];
float KP=0;
float KD=0;
KP=(float)get32bit(Packet,1);
KD=(float)get32bit(Packet,5);
getPidGroupDataTable(chan)->config.V.P=KP/100.0;
getPidGroupDataTable(chan)->config.V.D=KD/100.0;
OnPidConfigure(chan);
return true;
}
void GetConfigPID(BowlerPacket * Packet){
uint8_t chan = Packet->use.data[0];
Packet->use.data[1]=getPidGroupDataTable(chan)->config.Enabled;// = ((Packet->use.data[1]==0)?0:1);
Packet->use.data[2]=getPidGroupDataTable(chan)->config.Polarity;// = ((Packet->use.data[2]==0)?0:1);
Packet->use.data[3]=getPidGroupDataTable(chan)->config.Async;//= ((Packet->use.data[3]==0)?0:1);
set32bit(Packet,getPidGroupDataTable(chan)->config.K.P*100,4);
set32bit(Packet,getPidGroupDataTable(chan)->config.K.I*100,8);
set32bit(Packet,getPidGroupDataTable(chan)->config.K.D*100,12);
set32bit(Packet,getPidGroupDataTable(chan)->config.IndexLatchValue,16);
//latching data
Packet->use.data[20]=getPidGroupDataTable(chan)->config.useIndexLatch;//
Packet->use.data[21]=getPidGroupDataTable(chan)->config.stopOnIndex;//
set32bit(Packet,getPidGroupDataTable(chan)->config.stop*1000,22);
set32bit(Packet,getPidGroupDataTable(chan)->config.upperHistoresis*1000,26);
set32bit(Packet,getPidGroupDataTable(chan)->config.lowerHistoresis*1000,30);
Packet->use.head.DataLegnth=4+22+(3*4);
Packet->use.head.Method=BOWLER_POST;
}
uint8_t ConfigPID(BowlerPacket * Packet){
uint8_t chan = Packet->use.data[0];
// int i;
// println_W("Starting config");
// for(i=0;i<getNumberOfPidChannels();i++){
// printPIDvals(i);
// }
getPidGroupDataTable(chan)->config.Polarity = ((Packet->use.data[2]==0)?0:1);
getPidGroupDataTable(chan)->config.Async = ((Packet->use.data[3]==0)?0:1);
float KP=0;
float KI=0;
float KD=0;
float temp=0;
KP=(float)get32bit(Packet,4);
KI=(float)get32bit(Packet,8);
KD=(float)get32bit(Packet,12);
if(Packet->use.head.DataLegnth>(4+16)){
temp=(float)get32bit(Packet,16);
getPidGroupDataTable(chan)->config.useIndexLatch= Packet->use.data[20];
getPidGroupDataTable(chan)->config.stopOnIndex = Packet->use.data[21];
getPidGroupDataTable(chan)->config.stop=(float)get32bit(Packet,22)/1000.0;
getPidGroupDataTable(chan)->config.upperHistoresis=(float)get32bit(Packet,26)/1000.0;
getPidGroupDataTable(chan)->config.lowerHistoresis=(float)get32bit(Packet,30)/1000.0;
getPidGroupDataTable(chan)->config.calibrationState = CALIBRARTION_DONE;
}else{
temp=0;
getPidGroupDataTable(chan)->config.useIndexLatch= true;
getPidGroupDataTable(chan)->config.stopOnIndex = true;
getPidGroupDataTable(chan)->config.stop=0;
getPidGroupDataTable(chan)->config.upperHistoresis=0;
getPidGroupDataTable(chan)->config.lowerHistoresis=0;
}
getPidGroupDataTable(chan)->config.IndexLatchValue=(float)temp;
getPidGroupDataTable(chan)->config.K.P=KP/100;
getPidGroupDataTable(chan)->config.K.I=KI/100;
getPidGroupDataTable(chan)->config.K.D=KD/100;
//println("Resetting PID channel from Config:",INFO_PRINT);printBowlerPacketDEBUG(Packet,INFO_PRINT);
//println("From Config Current setpoint:",INFO_PRINT);p_fl(getPidGroupDataTable(chan)->SetPoint,INFO_PRINT);
OnPidConfigure(chan);
getPidGroupDataTable(chan)->config.Enabled = ((Packet->use.data[1]==0)?0:1);
return true;
}
int zone = 66;
boolean processPIDGet(BowlerPacket * Packet){
int i;
switch (Packet->use.head.RPC){
case APID:
Packet->use.head.DataLegnth=5;
Packet->use.data[0]=getNumberOfPidChannels();
for(i=0;i<getNumberOfPidChannels();i++){
set32bit(Packet,GetPIDPosition(i),1+(i*4));
Packet->use.head.DataLegnth+=4;
}
Packet->use.head.Method=BOWLER_POST;
break;
case _PID:
set32bit(Packet,GetPIDPosition(Packet->use.data[0]),1);
Packet->use.head.DataLegnth=4+1+4;
Packet->use.head.Method=BOWLER_POST;
break;
case CPID:
GetConfigPID(Packet);
break;
case CPDV:
GetConfigPDVelocity(Packet);
break;
case GPDC:
set32bit(Packet,getNumberOfPidChannels(),0);
Packet->use.head.DataLegnth=4+4;
Packet->use.head.Method=BOWLER_POST;
break;
default:
return false;
}
return true;
}
boolean processPIDPost(BowlerPacket * Packet){
int chan, val;
float time;
switch (Packet->use.head.RPC){
case APID:
time = (float)get32bit(Packet,0);
uint8_t i=0;
for(i=0;i<Packet->use.data[4];i++){
SetPIDTimed(i,get32bit(Packet,5+(i*4)),time);
}
READY(Packet,zone,3);
break;
case _VPD:
chan = Packet->use.data[0];
val = get32bit(Packet,1);
time=get32bit(Packet,5);
StartPDVel(chan,val,time);
READY(Packet,zone,4);
break;
case _PID:
chan = Packet->use.data[0];
val = get32bit(Packet,1);
time=get32bit(Packet,5);
SetPIDTimed(chan,val,time);
READY(Packet,zone,5);
break;
case RPID:
chan = Packet->use.data[0];
println("Resetting PID channel from packet:",ERROR_PRINT);printBowlerPacketDEBUG(Packet,ERROR_PRINT);
pidReset(chan, get32bit(Packet,1));
READY(Packet,zone,6);
break;
default:
return false;
}
return true;
}
boolean processPIDCrit(BowlerPacket * Packet){
uint8_t i=0;
switch (Packet->use.head.RPC){
case KPID:
for(i=0;i<getNumberOfPidChannels();i++){
getPidGroupDataTable(i)->config.Enabled = true;
setOutput(i,0.0);
getPidGroupDataTable(i)->config.Enabled = false;
getPidVelocityDataTable(i)->enabled=false;
getPidGroupDataTable(i)->Output=0.0;
}
READY(Packet,zone,0);
break;
case CPID:
if(ConfigPID(Packet)){
READY(Packet,zone,1);
}else
ERR(Packet,zone,1);
break;
case CPDV:
if(ConfigPDVelovity(Packet)){
READY(Packet,zone,1);
}else
ERR(Packet,zone,1);
break;
default:
return false;
}
return true;
}
/**
* Handle a PID packet.
* @return True if the packet was processed, False if it was not PID packet
*/
boolean ProcessPIDPacket(BowlerPacket * Packet){
switch(Packet->use.head.Method){
case BOWLER_GET:
return processPIDGet(Packet);
case BOWLER_POST:
return processPIDPost(Packet);
case BOWLER_CRIT:
return processPIDCrit(Packet);
default:
return false;
}
}
<file_sep>/BowlerStack/include/Bowler/namespace.h
/*
* namespace.h
*
* Created on: Aug 15, 2010
* Author: hephaestus
*/
#ifndef NAMESPACE_H_
#define NAMESPACE_H_
#define USE_LINKED_LIST_NAMESPACE
typedef boolean packetEventCallback(BowlerPacket *);
typedef boolean asyncEventCallback(BowlerPacket *,boolean (*pidAsyncCallbackPtr)(BowlerPacket *));
typedef struct _RPC_LIST{
//This is the bowler method for this RPC
uint8_t bowlerMethod;
//This is the 4 byte code for of the RPC
char rpc[4];
//This is the callback function pointer for execution of the method
packetEventCallback * callback;
//This is the array of argument data types
uint8_t arguments [17] ;
//This is the bowler method for this RPC
uint8_t responseMethod;
//This is the array of argument data types
uint8_t responseArguments[17];
//This is the linked list field
struct _RPC_LIST * next;
} RPC_LIST;
typedef struct _NAMESPACE_LIST{
//This is the string that identifies the names pace
char namespaceString[34];
//This is the linked list of the RPC's
RPC_LIST * rpcSet;
//This is the callback function pointer for checking for async.
asyncEventCallback * asyncEventCheck;
//This is the linked list field
struct _NAMESPACE_LIST * next;
} NAMESPACE_LIST;
RPC_LIST * getRpcByID(NAMESPACE_LIST * namespace,unsigned long rpcId, uint8_t bowlerMethod);
RPC_LIST * getRpcByIndex(NAMESPACE_LIST * namespace,uint8_t index);
void addNamespaceToList(NAMESPACE_LIST * newNs);
void addRpcToNamespace(NAMESPACE_LIST * namespace,RPC_LIST * rpc );
NAMESPACE_LIST * getNamespaceAtIndex(int index);
uint8_t getNumberOfNamespaces();
uint8_t getNumberOfRpcs(int namespaceIndex);
void RunNamespaceAsync(BowlerPacket *Packet,boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet));
//bcs.safe
#define SAFE 0x65666173 // 'safe' Get/Set the safe-mode parameters
#endif /* NAMESPACE_H_ */
<file_sep>/README.txt
This lib is set up to build on BASH compliant shells only. <file_sep>/Platform/include/arch/pic32/bootloader/Prototypes.h
/*
* Prototypes.h
*
* Created on: May 30, 2010
* Author: hephaestus
*/
#ifndef PROTOTYPES_H_
#define PROTOTYPES_H_
void InitializeSystem(void);
void RunApplications(void);
void writeLine(BowlerPacket * Packet);
void writeWordFlash(uint32_t address,uint32_t data);
void eraseFlash(void);
void BlinkUSBStatus(void);
void InitSPI(void);
void StopSPI(void);
uint8_t GetByteSPI(uint8_t b);
void avrSPIProg(BowlerPacket * Packet);
void eraseAVR(void);
void GetAVRid(uint8_t * buffer);
void HoldAVRReset(void);
void PowerCycleAVR();
void ReleaseAVRReset(void);
boolean AVRDone(void);
void AVRFlush(void);
void runAVRByteWrites(void);
boolean writeAVRLowByte(uint8_t data, uint16_t address);
boolean writeAVRHighByte(uint8_t data, uint16_t address);
boolean writeAVRTempFlashPageHighByte(uint8_t data, uint8_t address);
boolean writeAVRTempFlashPageLowByte(uint8_t data, uint8_t address);
void writeLowFuse();
void writeHighFuse();
void writeExtendedFuse();
void programMode(void);
#endif /* PROTOTYPES_H_ */
<file_sep>/Sample/native/AdvancedBowlerExample.c
/**
* @file AdvancedBowlerExample.c
*
* Created on: Feb 28, 2013
* @author hephaestus
*/
#include <stdio.h>
#include "Bowler/Bowler.h"
#include "Bowler/AbstractPID.h"
BOOL test__png(BowlerPacket * Packet);
BOOL test_rtst(BowlerPacket * Packet);
const char testName[] = "bcs.test.*;0.3;;";
static NAMESPACE_LIST bcsTest ={ testName,// The string defining the namespace
NULL,// the first element in the RPC string
NULL,// no async for this namespace
NULL// no initial elements to the other namesapce field.
};
static RPC_LIST bcsTest__png={ BOWLER_GET,
"apid",
&test__png,
NULL
};
static RPC_LIST bcsTest_rtst={ BOWLER_GET,
"rtst",
&test_rtst,
NULL
};
BOOL test__png(BowlerPacket * Packet){
printf("\r\nMy Overloaded RPC callback \r\n");
Packet->use.head.Method = BOWLER_POST;
Packet->use.head.RPC = GetRPCValue("Mpng");
Packet->use.head.DataLegnth = 4;
return TRUE;
}
BOOL test_rtst(BowlerPacket * Packet){
printf("\r\ntest_rtst callback \r\n");
Packet->use.head.DataLegnth=5;
Packet->use.head.Method = BOWLER_POST;
Packet->use.data[0]=37;
return TRUE;
}
NAMESPACE_LIST * getBcsTestNamespace(){
addRpcToNamespace(&bcsTest,& bcsTest__png);
addRpcToNamespace(&bcsTest,& bcsTest_rtst);
return &bcsTest;
}
void advancedBowlerExample(){
/**
* User code must implement a few functions needed by the stack internally
* This Platform specific code can be stored in the Platform directory if it is universal for all
* implementations on the given Platform.
* float getMs(void) Returns the current milliseconds since the application started
* StartCritical() Starts a critical protected section of code
* EndCritical() Ends the critical section and returns to normal operation
*/
setPrintLevelInfoPrint();// enable the stack specific printer. If you wish to use this feature putCharDebug(char c) needs to be defined
printf("\r\nStarting Sample Program\r\n");
int pngtmp = GetRPCValue("_png");
if(pngtmp != _PNG){
printf("\r\nFAIL Expected: ");
prHEX32(_PNG,INFO_PRINT);
printf(" got: ");
prHEX32(pngtmp,INFO_PRINT);
return;
}
/**
* First we are going to put together dummy array of packet data. These are examples of a _png receive and a custom response.
* These would not exist in your implementation but would come in from the physical layer
*/
BowlerPacket myPngPacket;
myPngPacket.use.head.RPC = GetRPCValue("apid");
myPngPacket.use.head.MessageID = 2;// Specify namespace 2 for the collision detect
myPngPacket.use.head.Method = BOWLER_GET;
myPngPacket.use.head.DataLegnth=4;
FixPacket(&myPngPacket);// Set up the stack content
BowlerPacket myNamespacTestPacket;
myNamespacTestPacket.use.head.RPC = GetRPCValue("rtst");
myNamespacTestPacket.use.head.Method = BOWLER_GET;
myNamespacTestPacket.use.data[0] = 37;
myNamespacTestPacket.use.head.DataLegnth=4+1;
FixPacket(&myNamespacTestPacket);// Set up the stack content
/**
* Now we begin to set up the stack features. The first step is to set up the FIFO to receive the data coming in asynchronously
*
*/
BYTE privateRXCom[sizeof(BowlerPacket)];//make the buffer at least big enough to hold one full sized packet
BYTE_FIFO_STORAGE store;//this is the FIFO data storage struct. All interactions with the circular buffer will go through this.
/**
* Next we initialize the buffer
*/
InitByteFifo(&store,// the pointer to the storage struct
privateRXCom,//pointer the the buffer
sizeof(privateRXCom));//the size of the buffer
Bowler_Init();// Start the Bowler stack
/**
* Now we are going to regester what namespaces we implement with the framework
*/
NAMESPACE_LIST * tmp =getBcsPidNamespace();
addNamespaceToList(tmp);
tmp = getBcsTestNamespace();
addNamespaceToList(tmp);
printf("\r\n# of namespaces declared= %i",getNumberOfNamespaces());
int i=0;
for(i=0;i<getNumberOfNamespaces();i++){
NAMESPACE_LIST * nsPtr = getNamespaceAtIndex(i);
printf("\r\nNamespace %s at index %i",nsPtr->namespaceString,i);
}
/**
* Now we load the buffer with the the packet that we "Received"
* This step would come in from the physical layer, usually on
* an interrupt on a mcu.
*/
for (i=0;i<GetPacketLegnth(&myPngPacket);i++){
BYTE err;// this is a stack error storage byte. See Bowler/FIFO.h for response codes
BYTE b= myPngPacket.stream[i];// This would be a new byte from the physical layer
FifoAddByte(&store, b, &err);// This helper function adds the byte to the storage buffer and manages the read write pointers.
}
/**
* Next we load the new namespace packet
*/
i=0;
for (i=0;i<GetPacketLegnth(&myNamespacTestPacket);i++){
BYTE err;// this is a stack error storage byte. See Bowler/FIFO.h for response codes
BYTE b= myNamespacTestPacket.stream[i];// This would be a new byte from the physical layer
FifoAddByte(&store, b, &err);// This helper function adds the byte to the storage buffer and manages the read write pointers.
}
printf("\r\nData loaded into packet\r\n");
/**
* We have now loaded a packet into the storage struct 'store'
* All the while we can be polling the storage struct for a new packet
*/
BowlerPacket myLocalPacket; // Declare a packet struct to catch the parsed packet from the asynchronous storage buffer
while(getNumBytes(&store)>0){
while(Bowler_Server_Static(&myLocalPacket,// pointer to the local packet into which to store the parsed packet
&store// storage struct from which the packet will be checked and parsed.
) == FALSE){// Returns true when a packet is found and pulled out of the buffer
// wait because there is no packet yet
}
/**
* At this point the packet has been parsed and pulled out of the buffer
* The Static server will have also called the call backs to pars the packet, so
* the response should be loaded up to send back
*/
int packetLength = GetPacketLegnth(&myLocalPacket); // helper function to get packet length
printf("\r\nPreparing to send:\r\n");
printPacket(&myLocalPacket, INFO_PRINT);
printf("\r\nSending Packet Data back out: [ ");
for(i=0;i< packetLength;i++){
//This would be sending to the physical layer. For this example we are just printing out the data
printf(" %i ",myLocalPacket.stream[i]);
}
printf(" ] \r\n");
}
}
<file_sep>/BowlerStack/src/BCS/Namespace_bcs_rpc.c
#include "Bowler/Bowler.h"
#if !defined(NULL)
#define NULL 0
#endif
//const char rpcNSName[] = "bcs.rpc.*;0.3;;";
boolean _rpc(BowlerPacket * Packet) {
Packet->use.head.Method = BOWLER_POST;
Packet->use.head.RPC = GetRPCValue("_rpc");
int index = 0;
int nsIndex = Packet->use.data[index++];
int rpcIndex = Packet->use.data[index++];
Packet->use.data[index++] = getNumberOfRpcs(nsIndex);
NAMESPACE_LIST * list = getNamespaceAtIndex(nsIndex);
if (list == NULL) {
ERR(Packet, 0, 9);
return false;
}
RPC_LIST * rpc = getRpcByIndex(list, rpcIndex);
if (rpc == NULL) {
ERR(Packet, 0, 10);
return false;
}
UINT32_UNION rpcValue;
rpcValue.Val = GetRPCValue((char*) rpc->rpc);
int i;
for (i = 0; i < 4; i++) {
Packet->use.data[index++] = rpcValue.v[i];
}
Packet->use.head.DataLegnth = 4 + index;
return true;
}
boolean _rpcArgs(BowlerPacket * Packet) {
Packet->use.head.Method = BOWLER_POST;
Packet->use.head.RPC = GetRPCValue("args");
int index = 0;
int nsIndex = Packet->use.data[index++];
int rpcIndex = Packet->use.data[index++];
RPC_LIST * rpc = getRpcByIndex(getNamespaceAtIndex(nsIndex), rpcIndex);
if (rpc == NULL) {
ERR(Packet, 0, 10);
return false;
}
//UINT32_UNION rpcValue;
//rpcValue.Val = GetRPCValue((char*)rpc->rpc);
int i;
Packet->use.data[(index++)] = rpc->bowlerMethod;
int argNumIndex = index;
Packet->use.data[(index++)] = 0; // place holder for number of arguments
if (rpc->arguments != NULL) {
//add non NULL arguments
i = 0;
while (rpc->arguments[i] != 0) {
Packet->use.data[(index++)] = rpc->arguments[i++];
Packet->use.data[argNumIndex]++;
}
}
//Packet->use.data[(index++)] = 0;
Packet->use.data[(index++)] = rpc->responseMethod;
argNumIndex = index;
Packet->use.data[(index++)] = 0; // place holder for number of arguments
if (rpc->responseArguments != NULL) {
//add non NULL arguments
i = 0;
while (rpc->responseArguments[i] != 0) {
Packet->use.data[(index++)] = rpc->responseArguments[i++];
Packet->use.data[argNumIndex]++;
}
}
//Packet->use.data[(index++)] = 0;
Packet->use.head.DataLegnth = 4 + index;
return true;
}
//Get RPC's
RPC_LIST bcsRpc__RPC = {BOWLER_GET,
"_rpc",
&_rpc,
{ BOWLER_I08,
BOWLER_I08,
0}, // Calling arguments
BOWLER_POST, // response method
{ BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
BOWLER_ASCII,
0}, // Calling arguments
NULL //Termination
};
//Get RPC's
RPC_LIST bcsRpc_ARGS = {BOWLER_GET,
"args",
&_rpcArgs,
{BOWLER_I08, //namespace index
BOWLER_I08, //rpc index
0}, // Calling arguments
BOWLER_POST, // response method
{ BOWLER_I08, //namespace index
BOWLER_I08, //rpc index
BOWLER_I08, //Downstream method
BOWLER_STR, //downstream arguments
BOWLER_I08, //upstream method
BOWLER_STR, //upstream arguments
0}, // Calling arguments
NULL //Termination
};
NAMESPACE_LIST bcsRpc = {"bcs.rpc.*;0.3;;", // The string defining the namespace
NULL, // the first element in the RPC list
NULL, // async for this namespace
NULL// no initial elements to the other namesapce field.
};
boolean BcsRpcnamespcaedAdded = false;
NAMESPACE_LIST * getBcsRpcNamespace() {
if (!BcsRpcnamespcaedAdded) {
//GET
addRpcToNamespace(&bcsRpc, & bcsRpc__RPC);
addRpcToNamespace(&bcsRpc, & bcsRpc_ARGS);
BcsRpcnamespcaedAdded = true;
}
return &bcsRpc;
}
<file_sep>/BowlerStack/src/PID/AbstractPID.c
/**
* @file AbstractPID.c
*
* Created on: Apr 9, 2010
* @author <NAME>
*/
#include "Bowler/Bowler.h"
int number_of_pid_groups = 0;
AbsPID * pidGroupsInternal = NULL;
float (*getPosition)(int);
void (*setOutputLocal)(int, float);
void setOutput(int group, float val);
int (*resetPosition)(int, int);
void (*onPidConfigureLocal)(int);
void (*MathCalculationPosition)(AbsPID *, float);
void (*MathCalculationVelocity)(AbsPID *, float);
PidLimitEvent* (*checkPIDLimitEvents)(uint8_t group);
//BowlerPacket packetTemp;
void OnPidConfigure(int v) {
onPidConfigureLocal(v);
}
int getNumberOfPidChannels() {
return number_of_pid_groups;
}
INTERPOLATE_DATA * getPidInterpolationDataTable(int group) {
if (pidGroupsInternal == NULL|| group<0 || group >= number_of_pid_groups) {
println_E("Velocity data table is null");
while(1);
}
return &pidGroupsInternal[group].interpolate;
}
PD_VEL * getPidVelocityDataTable(int group) {
if (pidGroupsInternal == NULL|| group<0 || group >= number_of_pid_groups) {
println_E("Velocity data table is null");
while(1);
}
return &pidGroupsInternal[group].vel;
}
AbsPID * getPidGroupDataTable(int group) {
if (pidGroupsInternal == NULL || group<0 || group >= number_of_pid_groups) {
println_E("PID data table is null");
while(1);
}
// Internal reference stores the address of the base of the array
// Add to that the size of the struct times the index. THis should create
// a pointer to the address of this specific array address
return &pidGroupsInternal[group];
}
boolean isPidEnabled(uint8_t i) {
return getPidGroupDataTable(i)->config.Enabled;
}
void SetPIDEnabled(uint8_t index, boolean enabled) {
AbsPID * tmp = getPidGroupDataTable(index);
tmp->config.Enabled = enabled;
}
void SetControllerMath(void (*math)(AbsPID *, float)) {
if (math != 0)
MathCalculationPosition = math;
else
MathCalculationPosition = &RunAbstractPIDCalc;
}
void InitilizePidController(AbsPID * groups, int numberOfGroups,
float (*getPositionPtr)(int),
void (*setOutputPtr)(int, float),
int (*resetPositionPtr)(int, int),
void (*onPidConfigurePtr)(int),
PidLimitEvent* (*checkPIDLimitEventsPtr)(uint8_t group)) {
if (groups == 0 ||
getPositionPtr == 0 ||
setOutputPtr == 0 ||
resetPositionPtr == 0 ||
checkPIDLimitEventsPtr == 0 ||
onPidConfigurePtr == 0) {
println("Null pointer exception in PID Configure", ERROR_PRINT);
while (1);
}
pidGroupsInternal =groups;
number_of_pid_groups = numberOfGroups;
getPosition = getPositionPtr;
setOutputLocal = setOutputPtr;
resetPosition = resetPositionPtr;
onPidConfigureLocal = onPidConfigurePtr;
checkPIDLimitEvents = checkPIDLimitEventsPtr;
SetControllerMath(&RunAbstractPIDCalc);
int i;
for (i = 0; i < numberOfGroups; i++) {
int enabled = getPidGroupDataTable(i)->config.Enabled;
pidReset(i, 0);
//getPidGroupDataTable(i)->config.Enabled = enabled;
SetPIDEnabled(i, enabled);
//println_I("PID ");p_int_I(i);print_I(" enabled");
}
}
void SetPIDCalibrateionState(int group, PidCalibrationType state) {
getPidGroupDataTable(group)->config.calibrationState = state;
//OnPidConfigure(group);
}
PidCalibrationType GetPIDCalibrateionState(int group) {
return getPidGroupDataTable(group)->config.calibrationState;
}
uint8_t ZeroPID(uint8_t chan) {
//println("Resetting PID channel from zeroPID:",INFO_PRINT);
pidReset(chan, 0);
return true;
}
uint8_t ClearPID(uint8_t chan) {
if (chan >= getNumberOfPidChannels())
return false;
getPidGroupDataTable(chan)->config.Enabled = false;
return true;
}
uint8_t SetPIDTimedPointer(AbsPID * conf, float val, float current, float ms) {
if (ms < .01)
ms = 0;
//local_groups[chan].config.Enabled=true;
conf->interpolate.set = val;
conf->interpolate.setTime = ms;
conf->interpolate.start = current;
conf->interpolate.startTime = getMs();
conf->SetPoint = val;
//conf->config.Enabled=true;
InitAbsPIDWithPosition(conf, conf->config.K.P, conf->config.K.I, conf->config.K.D, getMs(), current);
return true;
}
uint8_t SetPIDTimed(uint8_t chan, float val, float ms) {
//println_I("@#@# PID channel Set chan=");p_int_I(chan);print_I(" setpoint=");p_int_I(val);print_I(" time=");p_fl_I(ms);
if (chan >= getNumberOfPidChannels())
return false;
getPidVelocityDataTable(chan)->enabled = false;
return SetPIDTimedPointer(getPidGroupDataTable(chan), val, GetPIDPosition(chan), ms);
}
uint8_t SetPID(uint8_t chan, float val) {
SetPIDTimed(chan, val, 0);
return true;
}
int GetPIDPosition(uint8_t chan) {
if (chan >= getNumberOfPidChannels())
return 0;
//getPidGroupDataTable(chan)->CurrentState=(int)getPosition(chan);
return getPidGroupDataTable(chan)->CurrentState;
}
float pidResetNoStop(uint8_t chan, int32_t val) {
AbsPID * data = getPidGroupDataTable(chan);
//float value = (float)resetPosition(chan,val);
float current = data->CurrentState;
float raw = current + data->config.offset;
float value = (float) val;
data->config.offset = (raw - value);
data->CurrentState = raw - data->config.offset;
// println_E("From pidReset Current State: ");
// p_fl_E(current);
// print_E(" Target value: ");
// p_fl_E(value);
// print_E(" Offset: ");
// p_int_E(data->config.offset);
// print_E(" Raw: ");
// p_int_E(raw);
float time = getMs();
data->lastPushedValue = val;
InitAbsPIDWithPosition(getPidGroupDataTable(chan), data->config.K.P, data->config.K.I, data->config.K.D, time, val);
getPidVelocityDataTable(chan)->lastPosition = val;
getPidVelocityDataTable(chan)->lastTime = time;
return val;
}
void pidReset(uint8_t chan, int32_t val) {
float value = pidResetNoStop(chan, val);
AbsPID * data = getPidGroupDataTable(chan);
data->interpolate.set = value;
data->interpolate.setTime = 0;
data->interpolate.start = value;
data->interpolate.startTime = getMs();
data->SetPoint = value;
uint8_t enabled = data->config.Enabled;
data->config.Enabled = true; //Ensures output enabled to stop motors
data->Output = 0.0;
setOutput(chan, data->Output);
getPidVelocityDataTable(chan)->enabled = enabled;
}
void InitAbsPID(AbsPID * state, float KP, float KI, float KD, float time) {
InitAbsPIDWithPosition(state, KP, KI, KD, time, 0);
}
void setPIDConstants(int group, float p, float i, float d) {
getPidGroupDataTable(group)->config.K.P = p;
getPidGroupDataTable(group)->config.K.I = i;
getPidGroupDataTable(group)->config.K.D = d;
}
/**
* RunAbstractPIDCalc
* @param state A pointer to the AbsPID struct to run the calculations on
* @param CurrentTime a float of the time it is called in MS for use by the PID calculation
*/
void InitAbsPIDWithPosition(AbsPID * state, float KP, float KI, float KD, float time, float currentPosition) {
state->config.K.P = KP;
state->config.K.I = KI;
state->config.K.D = KD;
//state->integralCircularBufferIndex = 0;
state->integralTotal = 0.0;
state->integralSize = 20.0;
state->SetPoint = currentPosition;
state->PreviousError = 0;
state->Output = 0.0;
state->PreviousTime = time;
}
boolean isPIDInterpolating(int index) {
return getPidGroupDataTable(index)->interpolate.setTime != 0;
}
boolean isPIDArrivedAtSetpoint(int index, float plusOrMinus) {
if (getPidGroupDataTable(index)->config.Enabled)
return bound(getPidGroupDataTable(index)->SetPoint,
getPidGroupDataTable(index)->CurrentState,
plusOrMinus,
plusOrMinus);
return true;
}
void RunPIDControl() {
int i;
for (i = 0; i < getNumberOfPidChannels(); i++) {
//println_E(" PID Loop ");p_int_E(i);
getPidGroupDataTable(i)->CurrentState = getPosition(i) - getPidGroupDataTable(i)->config.offset;
if (getPidGroupDataTable(i)->config.Enabled == true) {
getPidGroupDataTable(i)->SetPoint = interpolate(getPidInterpolationDataTable(i), getMs());
MathCalculationPosition(getPidGroupDataTable(i), getMs());
if (GetPIDCalibrateionState(i) <= CALIBRARTION_DONE) {
setOutput(i, getPidGroupDataTable(i)->Output);
} else if (GetPIDCalibrateionState(i) == CALIBRARTION_hysteresis) {
pidHysterisis(i);
} else if ((GetPIDCalibrateionState(i) == CALIBRARTION_home_down) ||
(GetPIDCalibrateionState(i) == CALIBRARTION_home_up) ||
(GetPIDCalibrateionState(i) == CALIBRARTION_home_velocity)) {
checkLinkHomingStatus(i);
}
}
}
}
void RunPIDComs(BowlerPacket *Packet, boolean(*pidAsyncCallbackPtr)(BowlerPacket *Packet)) {
int i;
for (i = 0; i < getNumberOfPidChannels(); i++) {
pushPIDLimitEvent(Packet, pidAsyncCallbackPtr, checkPIDLimitEvents(i));
}
updatePidAsync(Packet, pidAsyncCallbackPtr);
}
void RunPID(BowlerPacket *Packet, boolean(*pidAsyncCallbackPtr)(BowlerPacket *Packet)) {
RunPIDControl();
RunPIDComs(Packet, pidAsyncCallbackPtr);
}
/**
* InitAbsPID
* @param state A pointer to the AbsPID the initialize
* @param KP the Proportional Constant
* @param KI the Integral Constant
* @param KD the Derivative Constant
* @param time the starting time
*/
void RunAbstractPIDCalc(AbsPID * state, float CurrentTime) {
float error;
float derivative;
//calculate set error
error = state->SetPoint - state->CurrentState;
//remove the value that is INTEGRALSIZE cycles old from the integral calculation to avoid overflow
//state->integralTotal -= state->IntegralCircularBuffer[state->integralCircularBufferIndex];
//add the latest value to the integral
state->integralTotal = (error * (1.0 / state->integralSize)) +
(state->integralTotal * ((state->integralSize - 1.0) / state->integralSize));
//This section clears the integral buffer when the zero is crossed
if ((state->PreviousError >= 0 && error < 0) ||
(state->PreviousError < 0 && error >= 0)) {
state->integralTotal = 0;
}
//calculate the derivative
derivative = (error - state->PreviousError); // / ((CurrentTime-state->PreviousTime));
state->PreviousError = error;
//do the PID calculation
state->Output = ((state->config.K.P * error) +
(state->config.K.D * derivative) +
(state->config.K.I * state->integralTotal)
);
if (state->config.Polarity == false)
state->Output *= -1.0;
//Store the current time for next iterations previous time
state->PreviousTime = CurrentTime;
}
void setOutput(int group, float val) {
if(bound(0,getPidGroupDataTable(group)->config.tipsScale, .001, .001)){
println_W("PID TPS Sclale close to zero");p_fl_W(getPidGroupDataTable(group)->config.tipsScale);
}
val *= getPidGroupDataTable(group)->config.tipsScale;
val += getPidStop(group);
if (val > getPidStop(group) && val < getUpperPidHistoresis(group) ){
val = getUpperPidHistoresis(group);
println_E("Upper histerisys");
}
if (val < getPidStop(group) && val > getLowerPidHistoresis(group)){
val = getLowerPidHistoresis(group);
println_E("Lower histerisys");
}
getPidGroupDataTable(group)->OutputSet = val;
//
setOutputLocal(group, val);
}
<file_sep>/BowlerStack/include/Bowler/AbstractPID.h
/**
* @file AbstractPID.h
*
* Created on: Apr 9, 2010
* @author <NAME>
*/
#ifndef ABSTRACTPID_H_
#define ABSTRACTPID_H_
#include "Bowler_Helper.h"
#include "namespace.h"
#include "Scheduler.h"
#define IntegralSize 10
//bcs.pid
#define _PID 0x6469705f // '_pid' Get/Set the pid setpoint
#define CPID 0x64697063 // 'cpid' Configure PID
#define CPDV 0x76647063 // 'cpdv' Configure PD Velocity controler
#define APID 0x64697061 // 'apid' Get/Set all PID channels
#define RPID 0x64697072 // 'rpid' Reset a PID channel
#define _VPD 0x6470765f // '_vpd' PID velocity command
#define KPID 0x6469706b // 'kpid' Kill all PID controllers
#define PIDL 0x6c646970 // 'pidl' PID limit event
#define GPDC 0x63647067 // 'gpdc' Get PID count
typedef enum _PidLimitType {
//NO_LIMIT(0x00),
/** The lowerlimit. */
//LOWERLIMIT(0x01),
/** The indexevent. */
//INDEXEVENT(0x02),
/** The upperlimit. */
//UPPERLIMIT(0x04),
/** The overcurrent. */
//OVERCURRENT(0x08),
//CONTROLLER_ERROR(0x10),
//HOME_EVENT(0x20)
NO_LIMIT = (0x00),
LOWERLIMIT = (0x01),
INDEXEVENT = (0x02),
UPPERLIMIT = (0x04),
OVERCURRENT = (0x08),
CONTROLLER_ERROR = (0x10),
HOME_EVENT = (0x20)
} PidLimitType;
typedef enum _PidCalibrationType {
CALIBRARTION_Uncalibrated = (0),
CALIBRARTION_DONE = (1),
CALIBRARTION_hysteresis = (2),
CALIBRARTION_home_up = (3),
CALIBRARTION_home_down = (4),
CALIBRARTION_home_velocity = (5)
} PidCalibrationType;
typedef struct __attribute__((__packed__)) _PidLimitEvent {
int group;
PidLimitType type;
float time;
signed long int value;
signed long int latchTickError;
// boolean stopOnIndex;
}
PidLimitEvent;
/**
* These are your Control Constants
*/
typedef enum _CAL_STATE {
forward = 0,
backward = 1,
done = 2
} CAL_STATE;
/**
* This is the storage struct for all the information needed to run the PID calculation
* Note that this has no assumptions on the type of inputs or type of outputs
* It also has no assumptions on the time step it is run over. It stores previous time and
* will calculate scaling based on that and the current time
*/
typedef struct __attribute__((__packed__)) _AbsPID_Config {
unsigned char Enabled;
unsigned char Polarity;
float IndexLatchValue;
unsigned char stopOnIndex;
unsigned char useIndexLatch;
unsigned char Async;
struct __attribute__((__packed__)) {
float P;
float I;
float D;
}
K;
struct __attribute__((__packed__)) {
float P;
float D;
}
V;
int upperHistoresis;
int lowerHistoresis;
int stop;
PidCalibrationType calibrationState;
float offset;
float tipsScale;
}
AbsPID_Config;
typedef struct __attribute__((__packed__)) _PD_VEL {
boolean enabled;
float unitsPerSeCond;
float lastPosition;
float lastVelocity;
float lastTime;
float currentOutputVel;
}
PD_VEL;
typedef struct __attribute__((__packed__)) _AbsPID {
//unsigned char channel;
float SetPoint;
float CurrentState;
float PreviousError;
//unsigned int integralCircularBufferIndex;
float integralTotal;
float integralSize;
float Output;
float OutputSet;
// This must be in MS
float PreviousTime;
float lastPushedValue;
float lastPushedTime;
struct __attribute__((__packed__)) {
unsigned char calibrating;
unsigned char calibrated;
CAL_STATE state;
//RunEveryData timer;
} calibration;
struct __attribute__((__packed__)) {
//RunEveryData timer;
float homingStallBound;
float previousValue;
float lastTime;
float homedValue;
} homing;
RunEveryData timer;
AbsPID_Config config;
INTERPOLATE_DATA interpolate;
PD_VEL vel;
}
AbsPID;
typedef struct __attribute__((__packed__)) _DYIO_PID {
unsigned char inputMode;
unsigned char inputChannel;
unsigned char outputMode;
unsigned char outputChannel;
unsigned char outVal;
boolean flagValueSync;
}
DYIO_PID;
/**
* RunAbstractPIDCalc
* @param state A pointer to the AbsPID struct to run the calculations on
* @param CurrentTime a float of the time it is called in MS for use by the PID calculation
*/
void RunAbstractPIDCalc(AbsPID * state, float CurrentTime);
/**
* Set the PID constants
* @param group which group to set
* @param p constant
* @param i constant
* @param d constant
*/
void setPIDConstants(int group, float p, float i, float d);
/**
* InitAbsPID
* @param state A pointer to the AbsPID the initialize
* @param KP the Proportional Constant
* @param KI the Integral Constant
* @param KD the Derivative Constant
* @param time the starting time
*/
void InitAbsPIDWithPosition(AbsPID * state, float KP, float KI, float KD, float time, float currentPosition);
void InitAbsPID(AbsPID * state, float KP, float KI, float KD, float time);
/**
* Handle a PID packet.
* @return True if the packet was processed, False if it was not PID packet
*/
boolean ProcessPIDPacket(BowlerPacket * Packet);
/**
* @param groups a pointer the the array of PID groups
* @param the number of PID groups
* @param getPositionPtr function pointer to the get position function
* @param setPositionPtr function pointer to the set position function
* @param resetPositionPtr function pointer to the re-set position function
* @param pidAsyncCallbackPtr function pointer to push an async value
*/
void InitilizePidController(AbsPID * groups,
int numberOfGroups,
float (*getPositionPtr)(int),
void (*setOutputPtr)(int, float),
int (*resetPositionPtr)(int, int),
void (*onPidConfigurePtr)(int),
PidLimitEvent * (*checkPIDLimitEventsPtr)(uint8_t group));
/**
* This sets a different set of control loop math.
* @param math a function pointer to the math calculation to be used in place of the PID math
*/
void SetControllerMath(void (*math)(AbsPID *, float));
int getNumberOfPidChannels();
void SetPIDEnabled(uint8_t index, boolean enabled);
boolean isPidEnabled(uint8_t i);
uint8_t SetPIDTimedPointer(AbsPID * conf,float val, float current,float ms);
uint8_t SetPIDTimed(uint8_t chan, float val, float ms);
uint8_t SetPID(uint8_t chan, float val);
int GetPIDPosition(uint8_t chan);
uint8_t ZeroPID(uint8_t chan);
/**
* Runs both Control and Coms
*/
void RunPID(BowlerPacket *Packet, boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet));
/**
* THis function runs the Comunication for the PID controller
*/
void RunPIDComs(BowlerPacket *Packet, boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet));
/**
* This runs the get input/math/set output for the PID controller
*/
void RunPIDControl();
void RunPDVel(uint8_t chan);
void RunVel(void);
float runPdVelocityFromPointer(PD_VEL* vel, float currentState,float KP, float KD);
void StartPDVel(uint8_t chan, float unitsPerSeCond, float ms);
void pushPID(BowlerPacket *Packet, boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet), uint8_t chan, int32_t value, float time);
void pushPIDLimitEvent(BowlerPacket *Packet, boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet), PidLimitEvent * event);
void checkLinkHomingStatus(int group);
/***
* This is a getter for the interpolation state
*/
boolean isPIDInterpolating(int index);
/**
* This function checks the PID channel to see if it has settled at the setpoint plus or minus a bound
* @param index
* @param plusOrMinus
* @return
*/
boolean isPIDArrivedAtSetpoint(int index, float plusOrMinus);
boolean processPIDGet(BowlerPacket * Packet);
boolean processPIDPost(BowlerPacket * Packet);
boolean processPIDCrit(BowlerPacket * Packet);
NAMESPACE_LIST * getBcsPidNamespace();
AbsPID * getPidGroupDataTable(int group);
PD_VEL * getPidVelocityDataTable(int group);
INTERPOLATE_DATA * getPidInterpolationDataTable(int group);
void pushAllPIDPositions(BowlerPacket *Packet, boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet));
void SetPIDCalibrateionState(int group, PidCalibrationType state);
PidCalibrationType GetPIDCalibrateionState(int group);
int getUpperPidHistoresis(int group);
int getLowerPidHistoresis(int group);
int getPidStop(int group);
float getMs();
void updatePidAsync();
void pidReset(uint8_t chan, int32_t val);
float pidResetNoStop(uint8_t chan, int32_t val);
void pushAllPIDPositions(BowlerPacket *Packet, boolean (*pidAsyncCallbackPtr)(BowlerPacket *Packet));
CAL_STATE pidHysterisis(int group);
void startHomingLink(int group, PidCalibrationType type,float homedValue);
void runPidHysterisisCalibration(int group);
boolean processRunAutoCal(BowlerPacket * Packet);
void OnPidConfigure(int v);
void setOutput(int group, float val);
#endif /* ABSTRACTPID_H_ */
<file_sep>/Platform/include/arch/pic32/EthHardware.h
/*********************************************************************
*
* Hardware specific definitions
*
*********************************************************************
* FileName: HardwareProfile.h
* Dependencies: None
* Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32
* Compiler: Microchip C32 v1.10 or higher
* Microchip C30 v3.12 or higher
* Microchip C18 v3.34 or higher
* HI-TECH PICC-18 PRO 9.63PL2 or higher
* Company: Microchip Technology, Inc.
*
* Software License Agreement
*
* Copyright (C) 2002-2010 Microchip Technology Inc. All rights
* reserved.
*
* Microchip licenses to you the right to use, modify, copy, and
* distribute:
* (i) the Software when embedded on a Microchip microcontroller or
* digital signal controller product ("Device") which is
* integrated into Licensee's product; or
* (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
* ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
* used in conjunction with a Microchip ethernet controller for
* the sole purpose of interfacing with the ethernet controller.
*
* You should refer to the license agreement accompanying this
* Software for additional information regarding your rights and
* obligations.
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
* PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
* BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
* THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
* SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
*
*
* Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* <NAME> 10/03/06 Original, copied from Compiler.h
* <NAME> 01/xx/10 Added MRF24WB0M-specific features
********************************************************************/
#ifndef __HARDWARE_PROFILE_H
#define PIC32_ENET_SK_DM320004 // PIC32MX795F512L Ethernet Starter Kit board with embedded Ethernet controller
// PIC32 Ethernet Starter Kit (04-02146) with PIC32MX795F512L processor and National DP83848 10/100 PHY
// External SMSC PHY configuration
#define PHY_RMII // external PHY runs in RMII mode
#define PHY_CONFIG_ALTERNATE // alternate configuration used
#define PHY_ADDRESS 0x1 // the address of the National DP83848 PHY
// Hardware mappings
#define RED_LED_TRIS LED0_TRIS //
#define RED_LED_IO LED0_IO
#define GREEN_LED_TRIS LED1_TRIS //
#define GREEN_LED_IO LED1_IO
#define BLUE_LED_TRIS LED2_TRIS //
#define BLUE_LED_IO LED2_IO
#define startLED() mPORTDSetPinsDigitalOut(BIT_1|BIT_2|BIT_0)
#define SET_RED(a) (a==0?mPORTASetBits(BIT_0):mPORTAClearBits(BIT_0))
#define SET_GREEN(a) (a==0?mPORTASetBits(BIT_2):mPORTAClearBits(BIT_2))
#define SET_BLUE(a) (a==0?mPORTASetBits(BIT_1):mPORTAClearBits(BIT_1))
//#define initLed() startLED()
//#define setLed(a,b,c) SET_RED(a);SET_GREEN(b);SET_BLUE(c)
#define LED0_TRIS (TRISDbits.TRISD0) // Ref LED1
#define LED0_IO (LATDbits.LATD0)
#define LED1_TRIS (TRISDbits.TRISD1) // Ref LED2
#define LED1_IO (LATDbits.LATD1)
#define LED2_TRIS (TRISDbits.TRISD2) // Ref LED3
#define LED2_IO (LATDbits.LATD2)
#define LED3_TRIS (LED2_TRIS) // No such LED
#define LED3_IO (LATDbits.LATD6)
#define LED4_TRIS (LED2_TRIS) // No such LED
#define LED4_IO (LATDbits.LATD6)
#define LED5_TRIS (LED2_TRIS) // No such LED
#define LED5_IO (LATDbits.LATD6)
#define LED6_TRIS (LED2_TRIS) // No such LED
#define LED6_IO (LATDbits.LATD6)
#define LED7_TRIS (LED2_TRIS) // No such LED
#define LED7_IO (LATDbits.LATD6)
#define LED_GET() ((BYTE)LATD & 0x07)
#define LED_PUT(a) do{LATD = (LATD & 0xFFF8) | ((a)&0x07);}while(0)
#define BUTTON0_TRIS (TRISDbits.TRISD6) // Ref SW1
#define BUTTON0_IO (PORTDbits.RD6)
#define BUTTON1_TRIS (TRISDbits.TRISD7) // Ref SW2
#define BUTTON1_IO (PORTDbits.RD7)
#define BUTTON2_TRIS (TRISDbits.TRISD13) // Ref SW3
#define BUTTON2_IO (PORTDbits.RD13)
#define BUTTON3_TRIS (TRISDbits.TRISD13) // No BUTTON3 on this board
#define BUTTON3_IO (1)
#if !defined(INPUT)
#define INPUT 1
#endif
//Set buttons to be inputs and enable the weak pull-ups
#define initButtons() BUTTON0_TRIS=INPUT;BUTTON1_TRIS=INPUT;BUTTON2_TRIS=INPUT;CNPUESET=0x00098000;
//#define initButton() initButtons()
//#define isPressed() ( _RD6==0 || _RD7==0 || _RD13==0)
// Select which UART the STACK_USE_UART and STACK_USE_UART2TCP_BRIDGE
// options will use. You can change these to U1BRG, U1MODE, etc. if you
// want to use the UART1 module instead of UART2.
#define UBRG U2BRG
#define UMODE U2MODE
#define USTA U2STA
#define BusyUART() BusyUART2()
#define CloseUART() CloseUART2()
#define ConfigIntUART(a) ConfigIntUART2(a)
#define DataRdyUART() DataRdyUART2()
#define OpenUART(a,b,c) OpenUART2(a,b,c)
#define ReadUART() ReadUART2()
#define WriteUART(a) WriteUART2(a)
#define getsUART(a,b,c) getsUART2(a,b,c)
#if defined(__C32__)
#define putsUART(a) putsUART2(a)
#else
#define putsUART(a) putsUART2((unsigned int*)a)
#endif
#define getcUART() getcUART2()
#define putcUART(a) do{while(BusyUART()); WriteUART(a); while(BusyUART()); }while(0)
#define putrsUART(a) putrsUART2(a)
#endif
<file_sep>/Platform/include/arch/pic32/HardwareProfile.h
/*********************************************************************
*
* Hardware specific definitions
*
*********************************************************************
* FileName: HardwareProfile.h
* Dependencies: None
* Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32
* Compiler: Microchip C32 v1.00 or higher
* Microchip C30 v3.01 or higher
* Microchip C18 v3.13 or higher
* HI-TECH PICC-18 STD 9.50PL3 or higher
* Company: Microchip Technology, Inc.
*
* Software License Agreement
*
* Copyright (C) 2002-2008 Microchip Technology Inc. All rights
* reserved.
*
* Microchip licenses to you the right to use, modify, copy, and
* distribute:
* (i) the Software when embedded on a Microchip microcontroller or
* digital signal controller product ("Device") which is
* integrated into Licensee's product; or
* (ii) ONLY the Software driver source files ENC28J60.c and
* ENC28J60.h ported to a non-Microchip device used in
* conjunction with a Microchip ethernet controller for the
* sole purpose of interfacing with the ethernet controller.
*
* You should refer to the license agreement accompanying this
* Software for additional information regarding your rights and
* obligations.
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
* PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
* BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
* THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
* SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
*
*
* Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* <NAME> 10/03/06 Original, copied from Compiler.h
********************************************************************/
#ifndef __HARDWARE_PROFILE_H
#define __HARDWARE_PROFILE_H
#include "Compiler.h"
#define EM_PCB_V0p3
#if defined(ubw32)
#warning Using UBW32 PIN mapping
#else
#endif
// Set configuration fuses (but only once)
#if defined(THIS_IS_STACK_APPLICATION)
#if defined(__18CXX)
#if defined(__EXTENDED18__)
#pragma config XINST=ON
#elif !defined(HI_TECH_C)
#pragma config XINST=OFF
#endif
#if defined(__18F8722) && !defined(HI_TECH_C)
// PICDEM HPC Explorer or PIC18 Explorer board
#pragma config OSC=HSPLL, FCMEN=OFF, IESO=OFF, PWRT=OFF, WDT=OFF, LVP=OFF
#elif defined(_18F8722) // HI-TECH PICC-18 compiler
// PICDEM HPC Explorer or PIC18 Explorer board with HI-TECH PICC-18 compiler
__CONFIG(1, HSPLL);
__CONFIG(2, WDTDIS);
__CONFIG(3, MCLREN);
__CONFIG(4, XINSTDIS & LVPDIS);
#elif defined(__18F87J10) && !defined(HI_TECH_C)
// PICDEM HPC Explorer or PIC18 Explorer board
#pragma config WDTEN=OFF, FOSC2=ON, FOSC=HSPLL
#elif defined(__18F87J11) && !defined(HI_TECH_C)
// PICDEM HPC Explorer or PIC18 Explorer board
#pragma config WDTEN=OFF, FOSC=HSPLL
#elif defined(__18F87J50) && !defined(HI_TECH_C)
// PICDEM HPC Explorer or PIC18 Explorer board
#pragma config WDTEN=OFF, FOSC=HSPLL, PLLDIV=3, CPUDIV=OSC1
#elif (defined(__18F97J60) || defined(__18F96J65) || defined(__18F96J60) || defined(__18F87J60) || defined(__18F86J65) || defined(__18F86J60) || defined(__18F67J60) || defined(__18F66J65) || defined(__18F66J60)) && !defined(HI_TECH_C)
// PICDEM.net 2 or any other PIC18F97J60 family device
#pragma config WDT=OFF, FOSC2=ON, FOSC=HSPLL, ETHLED=ON
#elif defined(_18F97J60) || defined(_18F96J65) || defined(_18F96J60) || defined(_18F87J60) || defined(_18F86J65) || defined(_18F86J60) || defined(_18F67J60) || defined(_18F66J65) || defined(_18F66J60)
// PICDEM.net 2 board with HI-TECH PICC-18 compiler
__CONFIG(1, WDTDIS & XINSTDIS);
__CONFIG(2, HSPLL);
__CONFIG(3, ETHLEDEN);
#elif defined(__18F4620) && !defined(HI_TECH_C)
#pragma config OSC=HSPLL, WDT=OFF, MCLRE=ON, PBADEN=OFF, LVP=OFF
#endif
#elif defined(__PIC24F__)
// Explorer 16 board
_CONFIG2(FNOSC_PRIPLL & POSCMOD_XT) // Primary XT OSC with 4x PLL
_CONFIG1(JTAGEN_OFF & FWDTEN_OFF) // JTAG off, watchdog timer off
#elif defined(__dsPIC33F__) || defined(__PIC24H__)
// Explorer 16 board
_FOSCSEL(FNOSC_PRIPLL) // PLL enabled
_FOSC(OSCIOFNC_OFF & POSCMD_XT) // XT Osc
_FWDT(FWDTEN_OFF) // Disable Watchdog timer
// JTAG should be disabled as well
#elif defined(__dsPIC30F__)
// dsPICDEM 1.1 board
//_FOSC(XT_PLL16) // XT Osc + 16X PLL
_FOSC(FRC_PLL16) // Internal Osc + 16X PLL
_FWDT(WDT_OFF) // enable Watchdog timer
//_FBORPOR(MCLR_EN & PBOR_OFF & PWRT_OFF)
_FBORPOR(MCLR_EN & PWRT_64 & PBOR_ON & BORV_27);
#elif defined(__PIC32MX__)
#if defined( __32MX440F128H__)
/*
#pragma config FPLLMUL = MUL_20 // PLL Multiplier
#pragma config FPLLIDIV = DIV_2 // PLL Input Divider
#pragma config FPLLODIV = DIV_1 // PLL Output Divider
#pragma config FPBDIV = DIV_1 // Peripheral Clock divisor
#pragma config FWDTEN = OFF // Watchdog Timer
#pragma config WDTPS = PS1 // Watchdog Timer Postscale
#pragma config FCKSM = CSDCMD // Clock Switching & Fail Safe Clock Monitor
#pragma config OSCIOFNC = OFF // CLKO Enable
#pragma config IESO = ON // Internal/External Switch-over
#pragma config POSCMOD = HS // Oscillator Selection
#pragma config FNOSC = PRIPLL
//#pragma config FNOSC = FRC
//#pragma config FRCDIV = DIV_1
#pragma config CP = OFF // Code Protect
#pragma config FSOSCEN = OFF // Secondary Oscillator Enable (KLO was off)
*/
#pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1, FWDTEN = OFF
#pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_1
#pragma config FCKSM = CSDCMD, IESO = ON, PWP = OFF
#pragma config FSOSCEN = OFF, CP = OFF, BWP = OFF, ICESEL = ICS_PGx1
#elif defined( __32MX360F512L__)
#pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1, FWDTEN = OFF
#pragma config POSCMOD = OFF, FNOSC = FRCPLL, FPBDIV = DIV_1
//#pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_1
#pragma config FCKSM = CSDCMD, IESO = ON, PWP = OFF, DEBUG = OFF
#pragma config FSOSCEN = OFF, CP = OFF, BWP = OFF, ICESEL = ICS_PGx1
#elif defined( __32MX460F512L__)
#ifdef USB_A0_SILICON_WORK_AROUND
#pragma config UPLLEN = OFF // USB PLL Enabled (A0 bit inverted)
#else
#pragma config UPLLEN = ON // USB PLL Enabled
#endif
#pragma config FPLLMUL = MUL_20 // PLL Multiplier
#pragma config UPLLIDIV = DIV_2 // USB PLL Input Divider
#pragma config FPLLIDIV = DIV_2 // PLL Input Divider
#pragma config FPLLODIV = DIV_1 // PLL Output Divider
#pragma config FPBDIV = DIV_1 // Peripheral Clock divisor
#pragma config FWDTEN = OFF // Watchdog Timer
#pragma config WDTPS = PS1 // Watchdog Timer Postscale
#pragma config FCKSM = CSDCMD // Clock Switching & Fail Safe Clock Monitor
#pragma config OSCIOFNC = OFF // CLKO Enable
#pragma config POSCMOD = HS // Primary Oscillator
#pragma config IESO = OFF // Internal/External Switch-over
#pragma config FSOSCEN = OFF // Secondary Oscillator Enable (KLO was off)
#pragma config FNOSC = PRIPLL // Oscillator Selection
#pragma config CP = OFF // Code Protect
#pragma config BWP = OFF // Boot Flash Write Protect
#pragma config PWP = OFF // Program Flash Write Protect
#pragma config ICESEL = ICS_PGx2 // ICE/ICD Comm Channel Select
#pragma config DEBUG = OFF // Background Debugger Enable
#else
#error No hardware board defined, see "HardwareProfile.h" and __FILE__
#endif
#else
#error no fuses set, check HardwareProfile.h
#endif
#endif // Prevent more than one set of config fuse definitions
// Clock frequency value.
// This value is used to calculate Tick Counter value
#if defined(__18CXX)
// All PIC18 processors
#if defined(PICDEMNET2) || defined(INTERNET_RADIO)
#define GetSystemClock() (41666667ul) // Hz
#define GetInstructionClock() (GetSystemClock()/4)
#define GetPeripheralClock() GetInstructionClock()
#elif defined(__18F87J50) || defined(_18F87J50)
#define GetSystemClock() (48000000ul) // Hz
#define GetInstructionClock() (GetSystemClock()/4)
#define GetPeripheralClock() GetInstructionClock()
#else
#define GetSystemClock() (40000000ul) // Hz
#define GetInstructionClock() (GetSystemClock()/4)
#define GetPeripheralClock() GetInstructionClock()
#endif
#elif defined(__PIC24F__)
// PIC24F processor
#define GetSystemClock() (32000000ul) // Hz
#define GetInstructionClock() (GetSystemClock()/2)
#define GetPeripheralClock() GetInstructionClock()
#elif defined(__PIC24H__)
// PIC24H processor
#define GetSystemClock() (80000000ul) // Hz
#define GetInstructionClock() (GetSystemClock()/2)
#define GetPeripheralClock() GetInstructionClock()
#elif defined(__dsPIC33F__)
// dsPIC33F processor
#define GetSystemClock() (80000000ul) // Hz
#define GetInstructionClock() (GetSystemClock()/2)
#define GetPeripheralClock() GetInwasp/structionClock()
#elif defined(__dsPIC30F__)
// dsPIC30F processor
#define GetSystemClock() (117920000ul) // Hz
#define GetInstructionClock() (GetSystemClock()/4)
#define GetPeripheralClock() GetInstructionClock()
#elif defined(__PIC32MX__)
// PIC32MX processor
#define GetSystemClock() (80000000ul) // Hz (80 mhz)
#define GetInstructionClock() (GetSystemClock()/1)
#define GetPeripheralClock() (GetInstructionClock()/1) // Set your divider according to your Peripheral Bus Frequency configuration fuse setting
//#pragma config FPLLODIV = DIV_1, FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FWDTEN = OFF, FPBDIV = DIV_1, POSCMOD = XT, FNOSC = PRIPLL, CP = OFF
#endif
#if defined(__32MX795F512L__)
#include "arch/pic32/EthHardware.h"
#endif
#if defined(__32MX460F512L__)
#include "arch/pic32/Pizo.h"
#endif
#if !defined(RED_LED_TRIS)
#define RED_LED_TRIS (_TRISD10) //
#define RED_LED_IO (_RD10)
#define GREEN_LED_TRIS (_TRISD11) //
#define GREEN_LED_IO (_RD11)
#define BLUE_LED_TRIS (_TRISD0) //
#define BLUE_LED_IO (_RD0)
#define startLED() PORTSetPinsDigitalOut(IOPORT_B,BIT_1|BIT_2|BIT_3)
#define SET_RED(a) (a==0?PORTSetBits(IOPORT_B,BIT_3):PORTClearBits(IOPORT_B,BIT_3))
#define SET_GREEN(a) (a==0?PORTSetBits(IOPORT_B,BIT_2):PORTClearBits(IOPORT_B,BIT_2))
#define SET_BLUE(a) (a==0?PORTSetBits(IOPORT_B,BIT_1):PORTClearBits(IOPORT_B,BIT_1))
#endif
#define FLAG_BUSY_TRIS (_TRISD5)
#define FLAG_BUSY (_RD5)
#define FLAG_ASYNC_TRIS (_TRISD7)
#define FLAG_ASYNC (_RD7)
#define Init_FLAG_BUSY_ASYNC() FLAG_ASYNC_TRIS=INPUT;FLAG_BUSY_TRIS=INPUT;
//
// #define AVR_RST_TRIS (_TRISE3)
#define AVR_RST_IO(a) setPicIOPin(a, 'E', 3)
#define InitAVR_RST() mPORTEOpenDrainOpen(BIT_3);setPicIOTristateOutput('E',3);AVR_RST_IO(0);
//#define InitAVR_RST() mPORTEOpenDrainOpen(BIT_3);AVR_RST_IO=1;
#define SPI_SCK_IO (_RG6)
#define SPI_SDI_IO (_RG7)
#define SPI_SDI_TRIS (_TRISG7)
#define SPI_SDO_IO (_RG8)
#define InitSPI_AVR() mPORTGOpenDrainOpen(BIT_8);mPORTGOpenDrainOpen(BIT_6);SPI_SCK_IO=1;SPI_SDO_IO=1;SPI_SDI_TRIS=INPUT;
#define RTS_HO_TRIS (_TRISD4)
//#define RTS_HO_IO (_RD4)
#define CTS_HO_TRIS (_TRISD0)
#define CTS_HO_IO (_RD0)
#define InitCTS_RTS_HO() CTS_HO_TRIS=INPUT;RTS_HO_IO=NOT_ASSERTED;
#define UART2TX_TRIS (_TRISF5)
#define UART2TX_IO (_RF5)
#define UART2RX_TRIS (_TRISF4)
#define UART2RX_IO (_RF4)
#define UART1TX_TRIS (_TRISD3)
#define UART1TX_IO (_RD3)
#define UART1RX_TRIS (_TRISD2)
#define UART1RX_IO (_RD2)
#define ConfigUARTOpenCollector() mPORTFOpenDrainOpen(BIT_5);
#define ConfigUARTRXTristate() UART1RX_TRIS=INPUT;UART2RX_TRIS=INPUT;
#define InitBankLEDs()
//#define InitDS_IO()
#define configsw _RF5
#define configswtris _TRISF5
#endif
void InitADCHardware(BYTE chan);
float getAdcVoltage(BYTE chan, int samples);
int getAdcRaw(BYTE chan, int samples);
void measureAdcOffset();
int getAdcOffset();
<file_sep>/BowlerStack/include/Bowler/Bowler_Helper.h
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#ifndef BOWLER_HELPER_H_
#define BOWLER_HELPER_H_
#include "Defines.h"
#include "Bowler_Struct_Def.h"
uint16_t READY(BowlerPacket * Packet,uint8_t code,uint8_t trace);
uint16_t ERR(BowlerPacket * Packet,uint8_t code,uint8_t trace);
uint16_t GetDataLegnth(uint8_t *buffer);
uint16_t SetPacketLegnth(BowlerPacket * Packet,uint8_t len);
uint16_t GetPacketLegnth(BowlerPacket * Packet);
uint32_t Bytes2Int32(uint8_t a,uint8_t b,uint8_t c,uint8_t d);
unsigned long GetRPCValue(char * data);
unsigned char CheckAddress(uint8_t * one,uint8_t * two);
void LoadCorePacket(BowlerPacket * Packet);
uint8_t CalcCRC(BowlerPacket *Packet);
void SetCRC(BowlerPacket * Packet);
unsigned char CheckCRC(BowlerPacket * Packet);
/*
* Calculate waht the CRC should be for a given data section
*/
uint8_t CalcDataCRC(BowlerPacket *Packet);
/*
* Returns true if the data crc in the packet matches the one calculated fromthe packet
*/
uint8_t CheckDataCRC(BowlerPacket *Packet);
/*
* Calculates and sets the CRC in the packet
*/
void SetDataCRC(BowlerPacket * Packet);
/*
* Retreives the CRC in the packet
*/
uint8_t GetDataCRC(BowlerPacket * Packet) ;
void copyPacket(BowlerPacket * from,BowlerPacket * to);
float interpolate(INTERPOLATE_DATA * data, float currentTime);
boolean bound(float target, float actual, float plus, float minus);
boolean between(float targetupper, float actual, float targetLower);
void set8bit(BowlerPacket * Packet,uint8_t val, uint8_t offset);
void set16bit(BowlerPacket * Packet,int16_t val, uint8_t offset);
void set32bit(BowlerPacket * Packet,int32_t val, uint8_t offset);
void setString(BowlerPacket * Packet, char * val, uint8_t offset);
int32_t get32bit(BowlerPacket * Packet, uint8_t offset);
int32_t get16bit(BowlerPacket * Packet, uint8_t offset);
#endif /* BOWLER_HELPER_H_ */
<file_sep>/Makefile
all:clean directories
make -C Platform/ all
sample:
make -C Platform/ Native
make -C Sample/native/ all
./Sample/native/BowlerImplimentationExample
clean:
make -C Platform/ clean
make -C Sample/native/ clean
release: all
sh release.sh
commit:
svn update;
make -C Platform/ all
directories:
mkdir -p ./lib/PIC32/32MX440F128H/
mkdir -p ./lib/AVR/atmega324p/
mkdir -p ./lib/AVR/atmega644p/
mkdir -p ./lib/PIC32/32MX460F512L/
mkdir -p ./lib/PIC32/32MX795F512L/
mkdir -p ./lib/native/linux/
<file_sep>/BowlerStack/src/BCS/Bowler_Server.c
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#include "Bowler/Bowler.h"
#define __WASP2_C
MAC_ADDR Broadcast = {
{0, 0, 0, 0, 0, 0}
};
MAC_ADDR MyMAC = {
{0x74, 0xf7, 0x26, 0x01, 0x01, 0x01}
};
boolean ignoreAddressing = false;
void setIgnoreAddressing(boolean v){
ignoreAddressing =v;
}
float lastPacketTime=0;
float getLastPacketTime() {
if (lastPacketTime > getMs())
lastPacketTime = 0;
return lastPacketTime;
}
void Process_Self_Packet(BowlerPacket * Packet) {
int namespaceIndex = 0;
int foundRpc = 0;
int currentNamespaceIndexForPacket = namespaceIndex;
NAMESPACE_LIST * tmp = getBcsCoreNamespace();
// First locate all Namespaces for the given RPC
do {
//Start the list with the first one
RPC_LIST * rpc = getRpcByID(tmp, Packet->use.head.RPC, Packet->use.head.Method);
//null check
if (rpc != NULL) {
//Found matching RPC and Method to parse
foundRpc++;
currentNamespaceIndexForPacket = namespaceIndex;
println_I("Rpc: ");
print_I((char *)rpc->rpc);
print_I(" found in namespace: ");
print_I((char *)tmp->namespaceString);
}
//Null check and move to next namespace
tmp = tmp->next;
namespaceIndex++;
} while (tmp != NULL);
// Now the namespace should have been found or not
if (foundRpc == 0) {
Print_Level l = getPrintLevel();
setPrintLevelErrorPrint();
println_E("##ERROR Rpc not found!");
setPrintLevel(l);
ERR(Packet, 0, 0);
return;
} else if (foundRpc > 0) {
//println_I("Namespace found: ");print_I(getNamespaceAtIndex(currentNamespaceIndexForPacket)->namespaceString);
if (foundRpc > 1) {
if (Packet->use.head.MessageID == 0) {
//RPC overlap but no resolution defined
println_E("##ERROR Rpc not resolved! Multiple implementations");
printPacket(Packet, ERROR_PRINT);
ERR(Packet, 0, 1);
return;
} else {
//RPC resolution is specified
currentNamespaceIndexForPacket = Packet->use.head.MessageID;
//println_I("Rpc resolved to: ");print_I(getNamespaceAtIndex(currentNamespaceIndexForPacket)->namespaceString);
}
}
RPC_LIST * rpc = getRpcByID(getNamespaceAtIndex(currentNamespaceIndexForPacket),
Packet->use.head.RPC,
Packet->use.head.Method);
if (rpc != NULL) {
rpc->callback(Packet);
Packet->use.head.DataLegnth = 4;
if (rpc->responseArguments != 0) {
int argIndex = 0;
int dataIndex = 0;
int packetDataStart;
while (rpc->responseArguments[argIndex] != 0) {
switch (rpc->responseArguments[argIndex]) {
case BOWLER_ASCII:
dataIndex = 0;
packetDataStart = Packet->use.head.DataLegnth - 4;
while (Packet->use.data[packetDataStart + dataIndex++]) {
Packet->use.head.DataLegnth++;
}
Packet->use.head.DataLegnth++; // null terminator
break;
case BOWLER_BOOL:
case BOWLER_I08:
Packet->use.head.DataLegnth++;
break;
case BOWLER_I16:
Packet->use.head.DataLegnth += 2;
break;
case BOWLER_I32:
case BOWLER_FIXED100:
case BOWLER_FIXED1K:
Packet->use.head.DataLegnth += 4;
break;
case BOWLER_STR:
packetDataStart = Packet->use.head.DataLegnth - 4;
Packet->use.head.DataLegnth += Packet->use.data[packetDataStart] + 1;
break;
case BOWLER_I32STR:
case BOWLER_FIXED1K_STR:
packetDataStart = Packet->use.head.DataLegnth - 4;
Packet->use.head.DataLegnth += Packet->use.data[packetDataStart]*4 + 1;
break;
}
argIndex++;
}
}
}
Packet->use.head.MessageID = currentNamespaceIndexForPacket;
Packet->use.head.ResponseFlag = 1;
FixPacket(Packet);
lastPacketTime = getMs();
}
}//finish processing the Packet
void Bowler_Init(void) {
addNamespaceToList( getBcsCoreNamespace());
addNamespaceToList( getBcsRpcNamespace());
}
boolean process(BowlerPacket * Packet) {
int i;
//if(debug){
if (Packet->use.head.RPC != GetRPCValue("_pwr") &&
Packet->use.head.RPC != GetRPCValue("_png") &&
Packet->use.head.RPC != GetRPCValue("_rpc") &&
Packet->use.head.RPC != GetRPCValue("_nms") &&
Packet->use.head.RPC != GetRPCValue("args")
) {//Ignore Power Packet
println("Got:", INFO_PRINT);
printPacket(Packet, INFO_PRINT);
}
//}
if ( CheckAddress(MyMAC.v, Packet->use.head.MAC.v) == true ||
CheckAddress(Broadcast.v, Packet->use.head.MAC.v) == true||
ignoreAddressing ==true
) {
Process_Self_Packet(Packet);
for (i = 0; i < 6; i++) {
Packet->use.head.MAC.v[i] = MyMAC.v[i];
}
SetCRC(Packet);
return true;
} else {
println("Packet not addressed to me: ", ERROR_PRINT);
printByteArray(Packet->use.head.MAC.v, 6, ERROR_PRINT);
print_nnl(" is not mine: ", ERROR_PRINT);
printByteArray(MyMAC.v, 6, ERROR_PRINT);
}
return false;
}
/**
* Run an instance of the server. This uses user defined memory
*/
uint8_t Bowler_Server_Static(BowlerPacket * Packet, BYTE_FIFO_STORAGE * fifo) {
boolean back = GetBowlerPacket(Packet, fifo);
if (back) {
return process(Packet);
;
}//Have a packet
return false;
}
uint8_t Bowler_Server(BowlerPacket * Packet, boolean debug) {
boolean back = GetBowlerPacket_arch(Packet);
if (back) {
//SetColor(0, 1, 0);
if (process(Packet)) {
//Packet found, sending
PutBowlerPacket(Packet);
if (Packet->use.head.RPC != GetRPCValue("_pwr") &&
Packet->use.head.RPC != GetRPCValue("_png")&&
Packet->use.head.RPC != GetRPCValue("_rpc") &&
Packet->use.head.RPC != GetRPCValue("_nms") &&
Packet->use.head.RPC != GetRPCValue("args")
) {//Ignore Power Packet
println("Response:", INFO_PRINT);
printPacket(Packet, INFO_PRINT);
}
//SetColor(0, 0, 1);
return true;
}
}//Have a packet
return false;
}
<file_sep>/Platform/src/pic32/usb/usb_fifo.c
/*
* usb_fifo.c
*
* Created on: Jun 3, 2010
* Author: hephaestus
*/
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#include "arch/pic32/USB/usb_fifo.h"
#include "Bowler/Bowler.h"
#define USBNotOk (USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)
#define TxPrivateSize BOWLER_PacketSize
BYTE RxTmpBuffer[BOWLER_PacketSize];
//BYTE privateRX[BOWLER_PacketSize];
BYTE TxBuffer[TxPrivateSize + 1 ];
UINT16 gotData = 0;
BOOL bufferSet = FALSE;
WORD txSize;
//BYTE_FIFO_STORAGE store;
BYTE_FIFO_STORAGE * usb_fifo_my_store = NULL;
BYTE_FIFO_STORAGE * last_my_store = NULL;
BOOL usbActive = TRUE;
//BYTE tmp [64];
extern BYTE cdc_trf_state;
extern USB_HANDLE CDCDataInHandle;//i would have called it out handle, but the stack uses In handle for tx
#define isUSBTxBlocked() ((cdc_trf_state != CDC_TX_READY) || (USBHandleBusy(CDCDataInHandle)!=0))
BOOL GotUSBData(void) {
return gotData > 0;
}
void printBufferState(BYTE_FIFO_STORAGE * s) {
println_E("\tFIFO state ");
p_int_E((int) s);
println_E("\tBuffer state ");
p_int_E((int) s->buffer);
println_E("\tBuffer size ");
p_int_E((int) s->bufferSize);
println_E("\tBuffer count ");
p_int_E((int) s->byteCount);
println_E("\tRead Pointer ");
p_int_E((int) s->readPointer);
println_E("\tWrite Pointer ");
p_int_E((int) s->writePointer);
}
BYTE_FIFO_STORAGE * GetPICUSBFifo(void) {
if (usb_fifo_my_store == NULL || usb_fifo_my_store != last_my_store) {
//setPrintLevelInfoPrint();
println_E("Usb storage changed!! was");
printBufferState(last_my_store);
println_E("Is: ");
printBufferState(usb_fifo_my_store);
while (1);
}
last_my_store = usb_fifo_my_store;
return usb_fifo_my_store;
}
void SetPICUSBFifo(BYTE_FIFO_STORAGE * s) {
Print_Level l = getPrintLevel();
//setPrintLevelInfoPrint();
println_E("Starting To set FIFO ");
if (bufferSet == TRUE)
return;
bufferSet = TRUE;
//printBufferState(s);
usb_fifo_my_store = s;
last_my_store = s;
//printBufferState(GetPICUSBFifo());
setPrintLevel(l);
}
void resetUsbSystem() {
U1CON = 0x0000;
DelayMs(100);
USBDeviceInit();
//InitByteFifo(&store,privateRX,sizeof(privateRX));
// if(bufferSet==FALSE)
// usb_fifo_my_store=&store;
#if defined(USB_INTERRUPT)
USBDeviceAttach();
#endif
INTEnableSystemMultiVectoredInt();
GetNumUSBBytes();
println_W("Initialized the USB");
}
void usb_CDC_Serial_Init(char * DevStr, char * SerialStr, UINT16 vid, UINT16 pid) {
//unsigned char i;
DelayMs(100);
SetUSB_VID_PID(vid, pid);
WriteUSBSerialNumber(SerialStr);
WriteUSBDeviceString(DevStr);
resetUsbSystem();
}
WORD USBGetArray(BYTE* stream, WORD num) {
if (USBNotOk) {
return 0;
}
usb_Buffer_Update();
gotData -= num;
BYTE n = FifoGetByteStream(GetPICUSBFifo(), stream, num);
return n;
}
void waitForTxToBeFree() {
//USBEnableInterrupts();
USBUnmaskInterrupts();
USBTransactionCompleteIE=1;
INTEnableSystemMultiVectoredInt();
INTEnableInterrupts();
RunEveryData timeout = {getMs(), USB_TIMEOUT};
while (isUSBTxBlocked()) {
Delay1us(5);
if (RunEvery(&timeout) > 0) {
// println_E("#*#*USB timeout before transmit");
// if ((cdc_trf_state != CDC_TX_READY)) {
// println_E("cdc_trf_state = ");
// p_int_E(cdc_trf_state);
// }
// if ((USBHandleBusy(CDCDataInHandle) != 0)) {
// println_E("CDCDataInHandle State = ");
// p_int_E(USBHandleBusy(CDCDataInHandle));
// println_E("CDCDataInHandle = ");
// p_int_E((int32_t)CDCDataInHandle);
// }
usbActive = FALSE;
//resetUsbSystem();
return;
}
if (USBNotOk) {
println_E("#*#*USB Not ok");
usbActive = FALSE;
resetUsbSystem();
return;
}
usb_Buffer_Update();
}
}
void flush() {
float start = getMs();
waitForTxToBeFree();
float end = getMs() - start;
if(end>(USB_TIMEOUT/10)){
println_W("USB Buffer ready, took:");p_fl_W(end);
}
start = getMs();
if (txSize > 0) {
putUSBUSART((char *) TxBuffer, txSize);
//DelayMs(2);
txSize = 0;
} else {
println_W("Zero length packet to send, ignoring");
}
waitForTxToBeFree();
end = getMs() - start;
if(end>(USB_TIMEOUT/10)){
println_W("USB Flushed OK, took:");p_fl_W(end);
}
}
BYTE isUSBActave() {
return usbActive;
}
void forceOpenUSB() {
usbActive = TRUE;
}
int USBPutArray(BYTE* stream, int num) {
if (isUSBActave() == FALSE) {
//println_I("USB inactive, bailing out");
return 0;
}
//UINT16 i;
usb_Buffer_Update();
if (USBNotOk) {
usbActive = FALSE;
return 0;
} else {
int packetLen = num;
int packetIndex = 0;
int i;
//if(num>(TxPrivateSize)) {
if (num > TxPrivateSize) {
println_I("Packet too large for USB buffer");
while (packetLen > TxPrivateSize) {
for (i = 0; i < TxPrivateSize; i++) {
TxBuffer[i] = stream[packetIndex++];
packetLen--;
}
println_W("Sending chunk ");
printStream_I(TxBuffer, i);
txSize = i;
flush();
}
for (i = 0; i < packetLen; i++) {
TxBuffer[i] = stream[packetIndex++];
}
println_I("Sending chunk ");
printStream_I(TxBuffer, i);
txSize = i;
flush();
} else {
//println_I("Packet small enough for USB buffer");
for (i = 0; i < num; i++) {
TxBuffer[i] = stream[i];
}
//println_I("Sending all ");printStream_I(TxBuffer,num);
txSize = i;
flush();
}
}
return TRUE;
}
WORD GetNumUSBBytes(void) {
usb_Buffer_Update();
//printBufferState(GetPICUSBFifo());
//println_I("Update Buffer = ");
// BYTE_FIFO_STORAGE* fifo = GetPICUSBFifo();
WORD data = FifoGetByteCount(GetPICUSBFifo());
//p_int_I(data);
return data;
}
static WORD i,gSize;
static BYTE err;
void usb_Buffer_Update(void) {
if (USBNotOk) {
usbActive = FALSE;
return;
}
//USBMaskInterrupts();
//USBDeviceTasksLocal();
CDCTxService();
gSize = getsUSBUSART((char *) RxTmpBuffer, USB_BUFFER_SIZE);
//USBUnmaskInterrupts();
if (gSize > 0) {
for (i = 0; i < gSize; i++) {
do {
FifoAddByte(GetPICUSBFifo(), RxTmpBuffer[i], & err);
} while (err != FIFO_OK);
gotData++;
usbActive = TRUE;
}
}
}
<file_sep>/BowlerStack/src/Helper/Scheduler.c
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#include "Bowler/Bowler.h"
#define schedSet 18
#define stepSize (schedSet/6.0)
//RunEveryData sched[]={{0.0,schedSet},{stepSize,schedSet},{stepSize*2,schedSet},{stepSize*3,schedSet},{stepSize*4,schedSet},{stepSize*5,schedSet}};
//
//uint8_t SchedulerGetStep(uint8_t chan){
// if(RunEvery(&sched[chan])>0){
// //sched[chan].MsTime=getMs();
// return true;
// }
// return false;
//
//}
//uint8_t ClearForCom(void){
// return true;
//}
/**
* RunEvery
* This function returns not 0 if it has been at least as long as the "setPoint" field says since the last time it returned not 0.
* All timeing is handeled internally
* @return float of MS after the assigned time that this function is running. A value of 0 means it has not been long enough
*/
float RunEvery(RunEveryData * data){
float currentTime;
float diff;
currentTime = getMs();
if(currentTime< data->MsTime)
data->MsTime=currentTime;//Check and fix overflow
diff =(currentTime-data->MsTime);
if (diff > data->setPoint){
if(data->MsTime+data->setPoint<currentTime)
data->MsTime = currentTime;
else
data->MsTime += data->setPoint;
return diff-data->setPoint;
}
return 0;
}
<file_sep>/Platform/include/arch/AVR/BowlerConfig.h
/*
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#ifndef BOWLERCONFIG_H_
#define BOWLERCONFIG_H_
#include "reg_structs.h"
#include <util/delay.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <string.h>
#include <avr/pgmspace.h>
#include "Bowler/Debug.h"
# include <avr/iom644p.h>
#if !defined(__AVR_ATmega324P__)
#define USE_DYN_RPC
#endif
#define FlagBusy_DDR DDRCbits._P7
#define FlagAsync_DDR DDRCbits._P6
#define FlagBusy_IO PORTCbits._P7
#define FlagAsync PINCbits._P6
#define InitFlagPins() FlagBusy_DDR=OUTPUT;FlagAsync_DDR=INPUT;FlagBusy_IO=0;PORTCbits._P6=1;
#define OUTPUT 1
#define INPUT 0
#define OFF 0
#define ON 1
#define ALLOUTPUT 0xFF
#define ALLINPUT 0x00
#define SDK_LED_ALLON 0x00
#define SDK_LED_ALLOFF 0xff
#define SDK_LED_ON 0
#define SDK_LED_OFF 1
#define UARTDELAY 20
#define Nop() __asm__("nop\n\t")
#define nop() Nop()
void WriteAVRUART0(uint8_t val);
void WriteAVRUART1(uint8_t val);
void updateTimer(uint64_t value);
void fixTimers(int currentTimer);
//#define WriteUART_COM WriteAVRUART0
//#define WriteUART_DEBUG WriteAVRUART1
#define StartCritical() cli()
#define EndCritical() sei()
#define USE_UART
void AVR_Bowler_HAL_Init(void);
#define Bowler_HAL_Init() AVR_Bowler_HAL_Init()
#define SetColor(a,b,c)
void showString (PGM_P s,Print_Level l,char newLine);
#undef print
#undef println
/**
* print the null terminated string with no new lines
*/
#define print(A,B) showString(PSTR(A),B,0)
/**
* print the null terminated string with a newline inserted at the begining of the string
*/
#define println(A,B) showString(PSTR(A),B,1)
#endif /* BOWLERCONFIG_H_ */
<file_sep>/Platform/include/arch/pic32/bootloader/Namespace_bcs_bootloader.h
/*
* File: Namespace_bcs_bootloader.h
* Author: hephaestus
*
* Created on September 17, 2014, 7:26 PM
*/
#ifndef NAMESPACE_BCS_BOOTLOADER_H
#define NAMESPACE_BCS_BOOTLOADER_H
#include "BLdefines.h"
#include "Prototypes.h"
#ifdef __cplusplus
extern "C" {
#endif
NAMESPACE_LIST * get_bcsBootloaderNamespace();
boolean getBootloaderResetFlag();
void callBootloaderReset();
BYTE getVendorCode(void);
#define BLID 0x64696c62 // 'blid' Boot loader ID
#define PROG 0x676f7270 // 'prog' Program a section of flash
#define ERFL 0x6c667265 // 'erfl' Erase flash
#define REST 0x74736572 // 'rest' Reset device
#define _REV 0x7665725f // '_rev' Get the revision number
#ifdef __cplusplus
}
#endif
#endif /* NAMESPACE_BCS_BOOTLOADER_H */
<file_sep>/BowlerStack/include/Bowler/Defines.h
/**
*
* Copyright 2009 Neuron Robotics, LLC
*
* 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.
*
*/
#ifndef DEFINES_H_
#define DEFINES_H_
#include <stddef.h>
#include <stdint.h>
#define BOWLER_VERSION 3
#define _BowlerHeaderSize 11
#define CRCIndex 10
#define DataSizeIndex 9
#define SessionIDIndex 8
#define ResponseFlagIndex 8
#define MethodIndex 7
#define RPCDataStart 15
#define RPCCodeStart _BowlerHeaderSize
#define PRINT_BAUD 115200
/**
AVR Baud = 115200 Pic Baud = 114942 Percent = 0.22349936143040042 AVR Baud = 9 Pic Baud = 173
AVR Baud = 115200 Pic Baud = 115606 Percent = -0.35324341682722765 AVR Baud = 9 Pic Baud = 172
AVR Baud = 128000 Pic Baud = 127388 Percent = 0.4777070063694282 AVR Baud = 8 Pic Baud = 156
AVR Baud = 128000 Pic Baud = 128205 Percent = -0.1602564102564088 AVR Baud = 8 Pic Baud = 155
AVR Baud = 144000 Pic Baud = 143884 Percent = 0.07993605115906476 AVR Baud = 7 Pic Baud = 138
AVR Baud = 164571 Pic Baud = 163934 Percent = 0.387067395264128 AVR Baud = 6 Pic Baud = 121
AVR Baud = 164571 Pic Baud = 165289 Percent = -0.4361799816345233 AVR Baud = 6 Pic Baud = 120
AVR Baud = 192000 Pic Baud = 192307 Percent = -0.1602564102564126 AVR Baud = 5 Pic Baud = 103
AVR Baud = 230400 Pic Baud = 229885 Percent = 0.22349936143040042 AVR Baud = 4 Pic Baud = 86
AVR Baud = 384000 Pic Baud = 384615 Percent = -0.1602564102564126 AVR Baud = 2 Pic Baud = 51
AVR Baud = 576000 Pic Baud = 571428 Percent = 0.793650793650785 AVR Baud = 1 Pic Baud = 34
*/
//#define INTERNAL_BAUD 384000 // 0.160% difference
//#define INTERNAL_BAUD 144000 // 0.079% difference
//#define INTERNAL_BAUD 192000 // 0.160% difference
#define INTERNAL_BAUD_AVR 2
#define INTERNAL_BAUD_PIC 51
#define BOWLER_PacketSize (_BowlerHeaderSize+255+1)
#define ASSERTED 0
#define NOT_ASSERTED 1
//Method Codes
#define BOWLER_STATUS 0x00
#define BOWLER_GET 0x10
#define BOWLER_POST 0x20
#define BOWLER_CRIT 0x30
#define BOWLER_ASYN 0x40
// 1 uint8_t
#define BOWLER_I08 8 // 8 bit integer
#define BOWLER_BOOL 43// a boolean value
//2 uint8_t
#define BOWLER_I16 16//16 bit integer
//4 uint8_t
#define BOWLER_I32 32//32 bit integer
#define BOWLER_FIXED100 41// float
#define BOWLER_FIXED1K 42// float
//streams
#define BOWLER_STR 37// first uint8_t is number of values, next is uint8_t values
#define BOWLER_I32STR 38// first uint8_t is number of values, next is 32 bit values
#define BOWLER_FIXED1K_STR 44// first uint8_t is number of values, next is floats
// ASCII
#define BOWLER_ASCII 39// ASCII string, null terminated
#define true 1
#define false 0
typedef uint8_t boolean;
//#if !defined(__GENERIC_TYPE_DEFS_H_)
////#define B_B_true 1
////#define B_B_false 0
//// typedef unsigned char BOOL;
// typedef enum _boolean { B_B_false = 0, B_B_true } BOOL; /* Undefined size */
// typedef unsigned char uint8_t ;
// typedef signed int INT;
// typedef signed char INT8;
// typedef signed short int INT16;
// typedef signed long int INT32;
// typedef signed long long INT64;
//
// typedef unsigned int UINT;
// typedef unsigned char UINT8;
// typedef unsigned short int UINT16;
// typedef unsigned long int UINT32;
// typedef unsigned long long UINT64;
//#endif
typedef union _INT16_UNION {
int16_t Val;
uint8_t v[2];
struct {
uint8_t LB;
uint8_t SB;
} byte;
} INT16_UNION;
typedef union _UINT16_UNION {
uint16_t Val;
uint8_t v[2];
struct {
uint8_t LB;
uint8_t SB;
} byte;
} UINT16_UNION;
typedef union _INT32_UNION {
int32_t Val;
uint8_t v[4];
struct {
uint8_t LB;
uint8_t SB;
uint8_t TB;
uint8_t FB;
} byte;
float f;
} INT32_UNION;
/*
typedef union _UINT64_UNION_DOUBLE
{
uint64_t Val;
uint8_t v[8];
struct
{
UINT32_UNION LI;
UINT32_UNION SI;
} uint;
double d;
} UINT64_UNION_DOUBLE;*/
typedef union _UINT32_UNION {
uint32_t Val;
uint8_t v[4];
struct {
uint8_t LB;
uint8_t SB;
uint8_t TB;
uint8_t FB;
} byte;
} UINT32_UNION;
#if !defined(NULL)
#define NULL 0
#endif
#endif /* DEFINES_H_ */
<file_sep>/Platform/src/pic32/bootloader/Namespace_bcs_bootloader.c
#include "Bowler/Bowler.h"
// int getHeartBeatTime();
// boolean getHeartBeatLock();
//void setHeartBeatState(boolean hb, int time);
boolean resetFlag = false;
//char safeNSName[] = "bcs.bootloader.*;0.3;;";
uint8_t core0str[] = "pic32mx440f128h";
uint8_t core1str[] = "avr_atmegaXX4p_";
uint8_t avrID[7];
boolean singleCoreMode = false;
void callBootloaderReset() {
resetFlag = true;
}
boolean getBootloaderResetFlag() {
return resetFlag;
}
boolean bcsBootloaderAsyncEventCallback(BowlerPacket *Packet, boolean(*pidAsyncCallbackPtr)(BowlerPacket *Packet)) {
//println_W("Async ");print_W(safeNSName);
return false;
}
uint8_t bcsBootloaderProcessor_g(BowlerPacket *Packet) {
int i;
int offset = 0;
uint8_t rev[3];
switch (Packet->use.head.RPC) {
case BLID:
Packet->use.head.Method = BOWLER_POST;
for (i = 0; i<sizeof (core0str); i++) {
Packet->use.data[i] = core0str[i];
}
offset = sizeof (core0str);
#if defined(DYIO)
//#error
for (i = 0; i<sizeof (core1str); i++) {
Packet->use.data[i + offset] = core1str[i];
}
GetAVRid(avrID);
offset = sizeof (core0str) + sizeof (core1str);
for (i = 0; i < 6; i++) {
Packet->use.data[i + offset - 1] = avrID[i];
}
#else
Packet->use.data[0 + offset]=0;// null first string
Packet->use.data[1 + offset]=0;// null second string
#endif
break;
case _REV:
//FlashGetFwRev(rev);
for (i = 0; i < 3; i++) {
Packet->use.data[i] = rev[i];
}
//FlashGetBlRev(rev);
for (i = 0; i < 3; i++) {
Packet->use.data[i + 3] = rev[i];
}
break;
}
return true;
}
uint8_t bcsBootloaderProcessor_c(BowlerPacket *Packet) {
switch (Packet->use.head.RPC) {
case PROG:
if (Packet->use.data[0] == 0) {
writeLine(Packet);
} else {
#if !defined(DYIO)
ERR(Packet, 0, 1);
break;
#endif
}
#if defined(DYIO)
if (Packet->use.data[0] == 1) {
avrSPIProg(Packet);
}
#endif
READY(Packet, 0, 0);
break;
case ERFL:
if (Packet->use.data[0] == 0) {
eraseFlash();
} else {
#if !defined(DYIO)
ERR(Packet, 0, 2);
break;
#endif
}
#if defined(DYIO)
if (Packet->use.data[0] == 1) {
eraseAVR();
}
#endif
READY(Packet, 0, 1);
//printfDEBUG("#Erasing device");
break;
case REST:
//printfDEBUG("#Resetting device");
resetFlag = true;
READY(Packet, 0, 3);
}
return true;
}
RPC_LIST bcsBootloader_blid_g = {BOWLER_GET, // Method
"blid", //RPC as string
&bcsBootloaderProcessor_g, //function pointer to a packet parsinf function
{0}, // Calling arguments
BOWLER_POST, // response method
{
BOWLER_ASCII,
BOWLER_ASCII,
BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsBootloader__rev_g = {BOWLER_GET, // Method
"_rev", //RPC as string
&bcsBootloaderProcessor_g, //function pointer to a packet parsinf function
{0}, // Calling arguments
BOWLER_POST, // response method
{
BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
BOWLER_I08,
0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsBootloader_prog_c = {BOWLER_CRIT, // Method
"prog", //RPC as string
&bcsBootloaderProcessor_c, //function pointer to a packet parsinf function
{0}, // Calling arguments
BOWLER_POST, // response method
{0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsBootloader_erfl_c = {BOWLER_CRIT, // Method
"erfl", //RPC as string
&bcsBootloaderProcessor_c, //function pointer to a packet parsinf function
{0}, // Calling arguments
BOWLER_POST, // response method
{0}, // Calling arguments
NULL //Termination
};
RPC_LIST bcsBootloader_rest_c = {BOWLER_CRIT, // Method
"rest", //RPC as string
&bcsBootloaderProcessor_c, //function pointer to a packet parsinf function
{0}, // Calling arguments
BOWLER_POST, // response method
{0}, // Calling arguments
NULL //Termination
};
NAMESPACE_LIST bcsBootloader = {"bcs.bootloader.*;0.3;;", // The string defining the namespace
NULL, // the first element in the RPC list
&bcsBootloaderAsyncEventCallback, // async for this namespace
NULL// no initial elements to the other namesapce field.
};
boolean BootloadernamespcaedAdded = false;
NAMESPACE_LIST * get_bcsBootloaderNamespace() {
if (!BootloadernamespcaedAdded) {
//POST
//Add the RPC structs to the namespace
addRpcToNamespace(&bcsBootloader, & bcsBootloader_blid_g);
addRpcToNamespace(&bcsBootloader, & bcsBootloader__rev_g);
addRpcToNamespace(&bcsBootloader, & bcsBootloader_prog_c);
addRpcToNamespace(&bcsBootloader, & bcsBootloader_erfl_c);
addRpcToNamespace(&bcsBootloader, & bcsBootloader_rest_c);
BootloadernamespcaedAdded = true;
}
return &bcsBootloader; //Return pointer to the struct
}
<file_sep>/Platform/include/arch/pic32/BowlerConfig.h
/*
* BowlerConfig.h
*
* Created on: Jan 11, 2010
* Author: hephaestus
*/
#ifndef BOWLERCONFIG_H_
#define BOWLERCONFIG_H_
#if defined(__PIC32MX__)
#include "arch/pic32/Compiler.h"
#include "arch/pic32/GenericTypeDefs.h"
#endif
#define USE_DYN_RPC
#define ASSERTED 0
#define NOT_ASSERTED 1
#define OUTPUT 0
#define INPUT 1
#include "HardwareProfile.h"
#include "Delay.h"
#include "Tick.h"
#include "LED.h"
#include "UART.h"
#include "FlashStorage.h"
#include "USB/usb_fifo.h"
#include <plib.h>
#include "bootloader/Namespace_bcs_bootloader.h"
#define StartCritical() INTDisableInterrupts();
#define EndCritical() INTEnableSystemMultiVectoredInt();INTEnableInterrupts();
#define WriteUART_COM Write32UART1
#if defined(AIM_ETH)
#define WriteUART_DEBUG Write32UART1
#else
#define WriteUART_DEBUG Write32UART1
#endif
#define USE_UART
#define USE_USB
uint16_t Get_HAL_Byte_Count();
void disableSerialComs(boolean state);
#define Bowler_HAL_Init Pic32_Bowler_HAL_Init
void SetPICUARTFifo(BYTE_FIFO_STORAGE * s);
void SendPacketUSB(uint8_t * packet,uint16_t size);
void Pic32_Bowler_HAL_Init(void);
void FlashSync(void);
void SetFlashData(uint32_t * s,uint32_t size);
void FlashLoad(void);
void setPicIOTristateInput(char port,int pin);
void setPicIOTristateOutput(char port,int pin);
void setPicIOTristate(boolean state,char port,int pin);
void setPicIOPin(boolean state,char port,int pin);
boolean getPicIOPin(char port,int pin);
#define ioPortB(s,p) if(s){PORTBSET=(1<<p);}else{ PORTBCLR=(1<<p);}
#define ioPortC(s,p) if(s){PORTCSET=(1<<p);}else{ PORTCCLR=(1<<p);}
#define ioPortD(s,p) if(s){PORTDSET=(1<<p);}else{ PORTDCLR=(1<<p);}
#define ioPortE(s,p) if(s){PORTESET=(1<<p);}else{ PORTECLR=(1<<p);}
#define ioPortF(s,p) if(s){PORTFSET=(1<<p);}else{ PORTFCLR=(1<<p);}
#define ioPortG(s,p) if(s){PORTGSET=(1<<p);}else{ PORTGCLR=(1<<p);}
#endif /* BOWLERCONFIG_H_ */
<file_sep>/Platform/src/pic32/bootloader/flash.c
/*
* flash.c
*
* Created on: May 30, 2010
* Author: hephaestus
*/
#include "Bowler/Bowler.h"
void writeLine(BowlerPacket * Packet){
//printfDEBUG("Writing Line:");
uint32_t i,offset,numWords;
UINT32_UNION baseAddress,dataWord;
baseAddress.byte.FB=Packet->use.data[1];
baseAddress.byte.TB=Packet->use.data[2];
baseAddress.byte.SB=Packet->use.data[3];
baseAddress.byte.LB=Packet->use.data[4];
numWords = (Packet->use.head.DataLegnth-4-1-4)/4;
//printfDEBUG_UL(baseAddress.Val);
for (i=0;i<numWords;i++){
offset = 4+1+(i*4);
dataWord.byte.FB=Packet->use.data[3 + offset];
dataWord.byte.TB=Packet->use.data[2 + offset];
dataWord.byte.SB=Packet->use.data[1 + offset];
dataWord.byte.LB=Packet->use.data[0 + offset];
writeWordFlash(baseAddress.Val+(i*4),dataWord.Val);
}
}
void writeWordFlash(uint32_t address,uint32_t data){
if (address >= StartAppVectPhysical && (address < EndAppVectPhysical)){
NVMWriteWord((uint32_t*)address, data);
if ((*(int *)(address|0x80000000)) != data){
println_E("FAULT read did not match write on address: ");prHEX32(address,ERROR_PRINT);
eraseFlash();
callBootloaderReset();
}
}else{
println_E("FAULT can not reach address: ");prHEX32(address,ERROR_PRINT);
}
}
void eraseFlash(void){
int temp;
uint32_t address = StartAppVectPhysical;
//uint32_t erAddr;
uint32_t size =EndAppVectPhysical-StartAppVectPhysical;
for( temp = 0; temp < (size/FLASH_PAGE_SIZE); temp++ ){
if (address <(EndAppVectPhysical-FLASH_PAGE_SIZE)){
//printfDEBUG("Erasing page at address:");
//printfDEBUG_UL(address);
NVMErasePage( (uint32_t*) address );
}
address +=FLASH_PAGE_SIZE;
}
}
<file_sep>/Platform/include/arch/AVR/reg_structs.h
/**
* \file reg_structs.h
* \author <NAME>
* \date 26 JAN 2010
*
* This file redefines all of the registers of the ATmega644p as structs
* to allow for easy access to individual bit fields in each register.
*
* The general usage is <register name>bits._<bitfield name>
*/
#ifndef REG_STRUCTS_H_
#define REG_STRUCTS_H_
/**
* Generic 8-bit register
*/
typedef union {
struct {
unsigned _P0:1;
unsigned _P1:1;
unsigned _P2:1;
unsigned _P3:1;
unsigned _P4:1;
unsigned _P5:1;
unsigned _P6:1;
unsigned _P7:1;
};
struct {
unsigned _w:8;
};
} __8bitreg_t;
/**
* DIO
* PIN, DDR, PORT for A,B,C,D
* 8bitreg
*/
/**
* ADC port
* 8bitreg
*/
/**
* SPI port
*/
typedef union {
struct {
unsigned :5;
unsigned _MOSI :1;
unsigned _MISO :1;
unsigned _SCK :1;
};
struct {
unsigned _w :8;
};
} __SPIPORTbits_t;
/**
* TIFR0
*/
typedef union {
struct {
unsigned _TOV0 :1;
unsigned _OCF0A :1;
unsigned _OCF0B :1;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __TIFR0bits_t;
/**
* TIFR1
*/
typedef union {
struct {
unsigned _TOV1 :1;
unsigned _OCF1A :1;
unsigned _OCF1B :1;
unsigned :2;
unsigned _ICF1 :1;
unsigned :2;
};
struct {
unsigned _w:8;
};
} __TIFR1bits_t;
/**
* TIFR2
*/
typedef union {
struct {
unsigned _TOV2 :1;
unsigned _OCF2A :1;
unsigned _OCF2B :1;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __TIFR2bits_t;
/**
* PCIFR
*/
typedef union {
struct {
unsigned _PCIF0 :1;
unsigned _PCIF1 :1;
unsigned _PCIF2 :1;
unsigned _PCIF3 :1;
unsigned :4;
};
struct {
unsigned _w:8;
};
} __PCIFRbits_t;
/**
* EIFR
*/
typedef union {
struct {
unsigned _INTF0 :1;
unsigned _INTF1 :1;
unsigned _INTF2 :1;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __EIFRbits_t;
/**
* EIMSK
*/
typedef union {
struct {
unsigned _INT0 :1;
unsigned _INT1 :1;
unsigned _INT2 :1;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __EIMSKbits_t;
/**
* GPIOR0
*/
typedef union {
struct {
unsigned _b0 :1;
unsigned _b1 :1;
unsigned _b2 :1;
unsigned _b3 :1;
unsigned _b4 :1;
unsigned _b5 :1;
unsigned _b6 :1;
unsigned _b7 :1;
};
struct {
unsigned _w:8;
};
} __GPIOR0bits_t;
/**
* EECR
*/
typedef union {
struct {
unsigned _EERE :1;
unsigned _EEPE :1;
unsigned _EEMPE :1;
unsigned _EERIE :1;
unsigned _EEPM0 :1;
unsigned _EEPM1 :1;
unsigned :2;
};
struct {
unsigned :4;
unsigned _EEPM :2;
unsigned :2;
};
struct {
unsigned _w :8;
};
} __EECRbits_t;
/**
* EEDR
* 8bitreg
*/
/**
* EEAR
*/
typedef union {
struct {
unsigned _low :8;
unsigned _high :8;
};
struct {
unsigned _w :16;
};
}__16bitreg_t;
/**
* EEARL
* 8bitreg
*/
/**
* EEARH
* 8bitreg
*/
/**
* GTCCR
*/
typedef union {
struct {
unsigned _PSRSYNC :1;
unsigned _PSRASY :1;
unsigned :5;
unsigned _TSM :1;
};
struct {
unsigned _w:8;
};
} __GTCCRbits_t;
/**
* TCCR0A
*/
typedef union {
struct {
unsigned _WGM00 :1;
unsigned _WGM01 :1;
unsigned :2;
unsigned _COM0B0 :1;
unsigned _COM0B1 :1;
unsigned _COM0A0 :1;
unsigned _COM0A1 :1;
};
struct {
unsigned _WGM :2;
unsigned :2;
unsigned _COMB :2;
unsigned _COMA :2;
};
struct {
unsigned _w:8;
};
} __TCCR0Abits_t;
/**
* TCCR0B
*/
typedef union {
struct {
unsigned _CS00 :1;
unsigned _CS01 :1;
unsigned _CS02 :1;
unsigned _WGM02 :1;
unsigned :2;
unsigned _FOC0B :1;
unsigned _FOC0A :1;
};
struct {
unsigned _CS :3;
unsigned _WGM :1;
unsigned :2;
unsigned _FOC :2;
};
struct {
unsigned _w:8;
};
} __TCCR0Bbits_t;
/**
* TCNT0
* 8bitreg
*/
/**
* OCR0A
* 8bitreg
*/
/**
* OCR0B
* 8bitreg
*/
/**
* GPIOR1
* 8bitreg
*/
/**
* GPIOR2
* 8bitreg
*/
/**
* SPCR
*/
typedef union {
struct {
unsigned _SPR0 :1;
unsigned _SPR1 :1;
unsigned _CPHA :1;
unsigned _CPOL :1;
unsigned _MSTR :1;
unsigned _DORD :1;
unsigned _SPE :1;
unsigned _SPIE :1;
};
struct {
unsigned _SPR :2;
unsigned :6;
};
struct {
unsigned _w:8;
};
} __SPCRbits_t;
/**
* SPSR
*/
typedef union {
struct {
unsigned _SPI2X :1;
unsigned :5;
unsigned _WCOL :1;
unsigned _SPIF :1;
};
struct {
unsigned _w:8;
};
} __SPSRbits_t;
/**
* SPDR
* 8bitreg
*/
/**
* ACSR
*/
typedef union {
struct {
unsigned _ACIS0 :1;
unsigned _ACIS1 :1;
unsigned _ACIC :1;
unsigned _ACIE :1;
unsigned _ACI :1;
unsigned _ACO :1;
unsigned _ACBG :1;
unsigned _ACD :1;
};
struct {
unsigned _w:8;
};
} __ACSRbits_t;
/**
* MONDR / OCDR
*/
typedef union {
struct {
unsigned _OCDR0 :1;
unsigned _OCDR1 :1;
unsigned _OCDR2 :1;
unsigned _OCDR3 :1;
unsigned _OCDR4 :1;
unsigned _OCDR5 :1;
unsigned _OCDR6 :1;
unsigned _OCDR7 :1;
};
struct {
unsigned :6;
unsigned _IDRD :1;
};
struct {
unsigned _w:8;
};
} __OCDRbits_t;
/**
* SMCR
*/
typedef union {
struct {
unsigned _SE :1;
unsigned _SM0 :1;
unsigned _SM1 :1;
unsigned _SM2 :1;
unsigned :4;
};
struct {
unsigned :1;
unsigned _SM :3;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __SMCRbits_t;
/**
* MCUSR
*/
typedef union {
struct {
unsigned _PORF :1;
unsigned _EXTRF :1;
unsigned _BORF :1;
unsigned _WDRF :1;
unsigned _JTRF :1;
unsigned :3;
};
struct {
unsigned _w:8;
};
} __MCUSRbits_t;
/**
* MCUCR
*/
typedef union {
struct {
unsigned _IVCE :1;
unsigned _IVSEL :1;
unsigned :2;
unsigned _PUD :1;
unsigned _BODSE :1;
unsigned _BODS :1;
unsigned _JTD :1;
};
struct {
unsigned _w:8;
};
} __MCUCRbits_t;
/**
* SPMCSR
*/
typedef union {
struct {
unsigned _SPMEN :1;
unsigned _PGERS :1;
unsigned _PGWRT :1;
unsigned _BLBSET :1;
unsigned _RWWSRE :1;
unsigned _SIGRD :1;
unsigned _RWWSB :1;
unsigned _SPMIE :1;
};
struct {
unsigned _w:8;
};
} __SPMCSRbits_t;
/**
* WDTCSR
*/
typedef union {
struct {
unsigned _WDP0 :1;
unsigned _WDP1 :1;
unsigned _WDP2 :1;
unsigned _WDE :1;
unsigned _WDCE :1;
unsigned _WDP3 :1;
unsigned _WDIE :1;
unsigned _WDIF :1;
};
struct {
unsigned _WDP :3;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __WDTCSRbits_t;
/**
* CLKPR
*/
typedef union {
struct {
unsigned _CLKPS0 :1;
unsigned _CLKPS1 :1;
unsigned _CLKPS2 :1;
unsigned _CLKPS3 :1;
unsigned :3;
unsigned _CLKPCE :1;
};
struct {
unsigned _CLKPS :4;
unsigned :4;
};
struct {
unsigned _w:8;
};
} __CLKPRbits_t;
/**
* PRR
*/
typedef union {
struct {
unsigned _PRADC :1;
unsigned _PRUSART0 :1;
unsigned _PRSPI :1;
unsigned _PRTIM1 :1;
unsigned _PRUSART1 :1;
unsigned _PRTIM0 :1;
unsigned _PRTIM2 :1;
unsigned _PRTWI :1;
};
struct {
unsigned _w:8;
};
} __PRRbits_t;
/**
* OSCCAL
* 8bitreg
*/
/**
* PCICR
*/
typedef union {
struct {
unsigned _PCIE0 :1;
unsigned _PCIE1 :1;
unsigned _PCIE2 :1;
unsigned _PCIE3 :1;
unsigned :4;
};
struct {
unsigned _PCIE :4;
unsigned :4;
};
struct {
unsigned _w:8;
};
} __PCICRbits_t;
/**
* EICRA
*/
typedef union {
struct {
unsigned _ISC00 :1;
unsigned _ISC01 :1;
unsigned _ISC10 :1;
unsigned _ISC11 :1;
unsigned _ISC20 :1;
unsigned _ISC21 :1;
unsigned :2;
};
struct {
unsigned _ISC0 :2;
unsigned _ISC1 :2;
unsigned _ISC2 :2;
unsigned :2;
};
struct {
unsigned _w:8;
};
} __EICRAbits_t;
/**
* PCMSK0
*/
typedef union {
struct {
unsigned _PCINT0:1;
unsigned _PCINT1:1;
unsigned _PCINT2:1;
unsigned _PCINT3:1;
unsigned _PCINT4:1;
unsigned _PCINT5:1;
unsigned _PCINT6:1;
unsigned _PCINT7:1;
};
struct {
unsigned _w:8;
};
} __PCMSK0bits_t;
/**
* PCMSK1
*/
typedef union {
struct {
unsigned _PCINT8:1;
unsigned _PCINT9:1;
unsigned _PCINT10:1;
unsigned _PCINT11:1;
unsigned _PCINT12:1;
unsigned _PCINT13:1;
unsigned _PCINT14:1;
unsigned _PCINT15:1;
};
struct {
unsigned _w:8;
};
} __PCMSK1bits_t;
/**
* PCMSK2
*/
typedef union {
struct {
unsigned _PCINT16:1;
unsigned _PCINT17:1;
unsigned _PCINT18:1;
unsigned _PCINT19:1;
unsigned _PCINT20:1;
unsigned _PCINT21:1;
unsigned _PCINT22:1;
unsigned _PCINT23:1;
};
struct {
unsigned _w:8;
};
} __PCMSK2bits_t;
/**
* TIMSK0
*/
typedef union {
struct {
unsigned _TOIE0 :1;
unsigned _OCIE0A :1;
unsigned _OCIE0B :1;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __TIMSK0bits_t;
/**
* TIMSK1
*/
typedef union {
struct {
unsigned _TOIE1 :1;
unsigned _OCIE1A :1;
unsigned _OCIE1B :1;
unsigned :2;
unsigned _ICIE1 :1;
unsigned :2;
};
struct {
unsigned _w:8;
};
} __TIMSK1bits_t;
/**
* TIMSK2
*/
typedef union {
struct {
unsigned _TOIE2 :1;
unsigned _OCIE2A :1;
unsigned _OCIE2B :1;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __TIMSK2bits_t;
/**
* PCMSK3
*/
typedef union {
struct {
unsigned _PCINT24:1;
unsigned _PCINT25:1;
unsigned _PCINT26:1;
unsigned _PCINT27:1;
unsigned _PCINT28:1;
unsigned _PCINT29:1;
unsigned _PCINT30:1;
unsigned _PCINT31:1;
};
struct {
unsigned _w:8;
};
} __PCMSK3bits_t;
/**
* ADCW
* 16bitreg
*/
/**
* ADCL
* 8bitreg
*/
/**
* ADCH
* 8bitreg
*/
/**
* ADCSRA
*/
typedef union {
struct {
unsigned _ADPS0 :1;
unsigned _ADPS1 :1;
unsigned _ADPS2 :1;
unsigned _ADIE :1;
unsigned _ADIF :1;
unsigned _ADATE :1;
unsigned _ADSC :1;
unsigned _ADEN :1;
};
struct {
unsigned _ADPS :3;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __ADCSRAbits_t;
/**
* ADCSRB
*/
typedef union {
struct {
unsigned _ADTS0 :1;
unsigned _ADTS1 :1;
unsigned _ADTS2 :1;
unsigned :3;
unsigned _ACME :1;
unsigned :1;
};
struct {
unsigned _ADTS :3;
unsigned :5;
};
struct {
unsigned _w:8;
};
} __ADCSRBbits_t;
/**
* ADMUX
*/
typedef union {
struct {
unsigned _MUX0 :1;
unsigned _MUX1 :1;
unsigned _MUX2 :1;
unsigned _MUX3 :1;
unsigned _MUX4 :1;
unsigned _ADLAR :1;
unsigned _REFS0 :1;
unsigned _REFS1 :1;
};
struct {
unsigned _MUX :5;
unsigned :1;
unsigned _REFS :2;
};
struct {
unsigned _w:8;
};
} __ADMUXbits_t;
/**
* DIDR0
*/
typedef union {
struct {
unsigned _ADC0D :1;
unsigned _ADC1D :1;
unsigned _ADC2D :1;
unsigned _ADC3D :1;
unsigned _ADC4D :1;
unsigned _ADC5D :1;
unsigned _ADC6D :1;
unsigned _ADC7D :1;
};
struct {
unsigned _w:8;
};
} __DIDR0bits_t;
/**
* DIDR1
*/
typedef union {
struct {
unsigned _AIN0D :1;
unsigned _AIN1D :1;
unsigned :6;
};
struct {
unsigned _w:8;
};
} __DIDR1bits_t;
/**
* TCCR1A
*/
typedef union {
struct {
unsigned _WGM10 :1;
unsigned _WGM11 :1;
unsigned :2;
unsigned _COM1B0 :1;
unsigned _COM1B1 :1;
unsigned _COM1A0 :1;
unsigned _COM1A1 :1;
};
struct {
unsigned _WGM :2;
unsigned :2;
unsigned _COMB :2;
unsigned _COMA :2;
};
struct {
unsigned _w:8;
};
} __TCCR1Abits_t;
/**
* TCCR1B
*/
typedef union {
struct {
unsigned _CS10 :1;
unsigned _CS11 :1;
unsigned _CS12 :1;
unsigned _WGM12 :1;
unsigned _WGM13 :1;
unsigned :1;
unsigned _ICES1 :1;
unsigned _ICNC1 :1;
};
struct {
unsigned _CS :3;// Clock select 1-5 are valid value
unsigned _WGM :2;
unsigned :3;
};
struct {
unsigned _w:8;
};
} __TCCR1Bbits_t;
/**
* TCCR1C
*/
typedef union {
struct {
unsigned :6;
unsigned _FOC1A :1;
unsigned _FOC1B :1;
};
struct {
unsigned :6;
unsigned _FOC :2;
};
struct {
unsigned _w:8;
};
} __TCCR1Cbits_t;
/**
* TCNT1
* 16bitreg
*/
/**
* TCNT1H
* 8bitreg
*/
/**
* TCNT1L
* 8bitreg
*/
/**
* ICR1
* 16bitreg
*/
/**
* ICR1H
* 8bitreg
*/
/**
* ICR1L8bitreg
*/
/**
* OCR1A
* 16bitreg
*/
/**
* OCR1AH
* 8bitreg
*/
/**
* OCR1AL
* 8bitreg
*/
/**
* OCR1B
* 16bitreg
*/
/**
* OCR1H
* 8bitreg
*/
/**
* OCR1BL
* 8bitreg
*/
/**
* TCCR2A
*/
typedef union {
struct {
unsigned _WGM20 :1;
unsigned _WGM21 :1;
unsigned :2;
unsigned _COM2B0 :1;
unsigned _COM2B1 :1;
unsigned _COM2A0 :1;
unsigned _COM2A1 :1;
};
struct {
unsigned _WGM :2;
unsigned :2;
unsigned _COMB :2;
unsigned _COMA :2;
};
struct {
unsigned _w:8;
};
} __TCCR2Abits_t;
/**
* TCCR2B
*/
typedef union {
struct {
unsigned _CS20 :1;
unsigned _CS21 :1;
unsigned _CS22 :1;
unsigned _WGM22 :1;
unsigned :2;
unsigned _FOC2B :1;
unsigned _FOC2A :1;
};
struct {
unsigned _CS :3;
unsigned _WGM :1;
unsigned :1;
unsigned _FOC :2;
};
struct {
unsigned _w:8;
};
} __TCCR2Bbits_t;
/**
* TCNT2
* 8bitreg
*/
/**
* OCR2A
* 8bitreg
*/
/**
* OCR2B
* 8bitreg
*/
/**
* ASSR
*/
typedef union {
struct {
unsigned _TCR2BUB :1;
unsigned _TCR2AUB :1;
unsigned _OCR2BUB :1;
unsigned _OCR2AUB :1;
unsigned _TCN2UB :1;
unsigned _AS2 :1;
unsigned _EXCLK :1;
unsigned :1;
};
struct {
unsigned _w:8;
};
} __ASSRbits_t;
/**
* TWBR
* 8bitreg
*/
/**
* TWSR
*/
typedef union {
struct {
unsigned _TWPS0 :1;
unsigned _TWPS1 :1;
unsigned :1;
unsigned _TWS3 :1;
unsigned _TWS4 :1;
unsigned _TWS5 :1;
unsigned _TWS6 :1;
unsigned _TWS7 :1;
};
struct {
unsigned _TWPS :2;
unsigned :1;
unsigned _TWS :5;
};
struct {
unsigned _w:8;
};
} __TWSRbits_t;
/**
* TWAR
*/
typedef union {
struct {
unsigned _TWGCE :1;
unsigned _TWA0 :1;
unsigned _TWA1 :1;
unsigned _TWA2 :1;
unsigned _TWA3 :1;
unsigned _TWA4 :1;
unsigned _TWA5 :1;
unsigned _TWA6 :1;
};
struct {
unsigned :1;
unsigned _TWA :7;
};
struct {
unsigned _w:8;
};
} __TWARbits_t;
/**
* TWDR
* 8bitreg
*/
/**
* TWCR
*/
typedef union {
struct {
unsigned _TWIE :1;
unsigned :1;
unsigned _TWEN :1;
unsigned _TWWC :1;
unsigned _TWSTO :1;
unsigned _TWSTA :1;
unsigned _TWEA :1;
unsigned _TWINT :1;
};
struct {
unsigned _w:8;
};
} __TWCRbits_t;
/**
* TWAMR
*/
typedef union {
struct {
unsigned _TWAM0 :1;
unsigned _TWAM1 :1;
unsigned _TWAM2 :1;
unsigned _TWAM3 :1;
unsigned _TWAM4 :1;
unsigned _TWAM5 :1;
unsigned _TWAM6 :1;
unsigned _TWAM7 :1;
};
struct {
unsigned _w:8;
};
} __TWAMRbits_t;
/**
* UCSR0A
*/
typedef union {
struct {
unsigned _MPCM0 :1;
unsigned _U2X0 :1;
unsigned _UPE0 :1;
unsigned _DOR0 :1;
unsigned _FE0 :1;
unsigned _UDRE0 :1;
unsigned _TXC0 :1;
unsigned _RXC0 :1;
};
struct {
unsigned _w:8;
};
} __UCSR0Abits_t;
/**
* UCSR0B
*/
typedef union {
struct {
unsigned _TXB80 :1;
unsigned _RXB80 :1;
unsigned _UCSZ02 :1;
unsigned _TXEN0 :1;
unsigned _RXEN0 :1;
unsigned _UDRIE0 :1;
unsigned _TXCIE0 :1;
unsigned _RXCIE0 :1;
};
struct {
unsigned w:8;
};
} __UCSR0Bbits_t;
/**
* UCSR0C
*/
typedef union {
struct {
unsigned _UCPOL0 :1;
unsigned _UCSZ00 :1;
unsigned _UCSZ01 :1;
unsigned _USBS0 :1;
unsigned _UPM00 :1;
unsigned _UPM01 :1;
unsigned _UMSEL00 :1;
unsigned _UMSEL01 :1;
};
struct {
unsigned :1;
unsigned _UCSZ0 :2;
unsigned :1;
unsigned _UPM0 :2;
unsigned _UMSEL0:2;
};
struct {
unsigned _w:8;
};
} __UCSR0Cbits_t;
/**
* UBRR0
* 16bitreg
*/
/**
* UBRR0H
* 8bitreg
*/
/**
* UBRR0L
* 8bitreg
*/
/**
* UDR0
* 8bitreg
*/
/**
* UCSR1A
*/
typedef union {
struct {
unsigned _MPCM1 :1;
unsigned _U2X1 :1;
unsigned _UPE1 :1;
unsigned _DOR1 :1;
unsigned _FE1 :1;
unsigned _UDRE1 :1;
unsigned _TXC1 :1;
unsigned _RXC1 :1;
};
struct {
unsigned _w:8;
};
} __UCSR1Abits_t;
/**
* UCSR1B
*/
typedef union {
struct {
unsigned _TXB81 :1;
unsigned _RXB81 :1;
unsigned _UCSZ12 :1;
unsigned _TXEN1 :1;
unsigned _RXEN1 :1;
unsigned _UDRIE1 :1;
unsigned _TXCIE1 :1;
unsigned _RXCIE1 :1;
};
struct {
unsigned _w:8;
};
} __UCSR1Bbits_t;
/**
* UCSR1C
*/
typedef union {
struct {
unsigned _UCPOL1 :1;
unsigned _UCSZ10 :1;
unsigned _UCSZ11 :1;
unsigned _USBS1 :1;
unsigned _UPM10 :1;
unsigned _UPM11 :1;
unsigned _UMSEL10 :1;
unsigned _UMSEL11 :1;
};
struct {
unsigned :1;
unsigned _UCSZ1 :2;
unsigned :1;
unsigned _UPM1 :2;
unsigned _UMSEL1:2;
};
struct {
unsigned _w:8;
};
} __UCSR1Cbits_t;
/**
* UBRR1
* 16bitreg
*/
/**
* UBRR1H
* 8bitreg
*/
/**
* UBRR1L
* 8bitreg
*/
/**
* UDR1
* 8bitreg
*/
//#if __AVR_ARCH__ < 100
//extern volatile __8bitreg_t PINAbits __asm__ ("0x00") __attribute__((section("sfr")));
//extern volatile __8bitreg_t ADCPINbits __asm__ ("0x00") __attribute__((section("sfr")));
//extern volatile __8bitreg_t DDRAbits __asm__ ("0x01") __attribute__((section("sfr")));
//extern volatile __8bitreg_t ADCDDRbits __asm__ ("0x01") __attribute__((section("sfr")));
//extern volatile __8bitreg_t PORTAbits __asm__ ("0x02") __attribute__((section("sfr")));
//extern volatile __8bitreg_t ADCPORTbits __asm__ ("0x02") __attribute__((section("sfr")));
//extern volatile __8bitreg_t PINBbits __asm__ ("0x03") __attribute__((section("sfr")));
//extern volatile __8bitreg_t DDRBbits __asm__ ("0x04") __attribute__((section("sfr")));
//extern volatile __SPIPORTbits_t SPIDDRbits __asm__ ("0x04") __attribute__((section("sfr")));
//extern volatile __8bitreg_t PORTBbits __asm__ ("0x05") __attribute__((section("sfr")));
//extern volatile __SPIPORTbits_t SPIPORTbits __asm__ ("0x05") __attribute__((section("sfr")));
//extern volatile __8bitreg_t PINCbits __asm__ ("0x06") __attribute__((section("sfr")));
//extern volatile __8bitreg_t DDRCbits __asm__ ("0x07") __attribute__((section("sfr")));
//extern volatile __8bitreg_t PORTCbits __asm__ ("0x08") __attribute__((section("sfr")));
//extern volatile __8bitreg_t PINDbits __asm__ ("0x09") __attribute__((section("sfr")));
//extern volatile __8bitreg_t DDRDbits __asm__ ("0x0A") __attribute__((section("sfr")));
//extern volatile __8bitreg_t PORTDbits __asm__ ("0x0B") __attribute__((section("sfr")));
//extern volatile __TIFR0bits_t TIFR0bits __asm__ ("0x15") __attribute__((section("sfr")));
//extern volatile __TIFR1bits_t TIFR1bits __asm__ ("0x16") __attribute__((section("sfr")));
//extern volatile __TIFR2bits_t TIFR2bits __asm__ ("0x17") __attribute__((section("sfr")));
//extern volatile __PCIFRbits_t PCIFRbits __asm__ ("0x1B") __attribute__((section("sfr")));
//extern volatile __EIFRbits_t EIFRits __asm__ ("0x1C") __attribute__((section("sfr")));
//extern volatile __EIMSKbits_t EIMSKbits __asm__ ("0x1D") __attribute__((section("sfr")));
//extern volatile __GPIOR0bits_t GPIOR0bits __asm__ ("0x1E") __attribute__((section("sfr")));
//extern volatile __EECRbits_t EECRbits __asm__ ("0x1F") __attribute__((section("sfr")));
//extern volatile __8bitreg_t EEDRbits __asm__ ("0x20") __attribute__((section("sfr")));
//extern volatile __16bitreg_t EEARbits __asm__ ("0x21") __attribute__((section("sfr")));
//extern volatile __8bitreg_t EEARLbits __asm__ ("0x21") __attribute__((section("sfr")));
//extern volatile __8bitreg_t EEARHbits __asm__ ("0x22") __attribute__((section("sfr")));
//extern volatile __GTCCRbits_t GTCCRbits __asm__ ("0x23") __attribute__((section("sfr")));
//extern volatile __TCCR0Abits_t TCCR0Abits __asm__ ("0x24") __attribute__((section("sfr")));
//extern volatile __TCCR0Bbits_t TCCR0Bbits __asm__ ("0x25") __attribute__((section("sfr")));
//extern volatile __8bitreg_t TCNT0bits __asm__ ("0x26") __attribute__((section("sfr")));
//extern volatile __8bitreg_t OCR0Abits __asm__ ("0x27") __attribute__((section("sfr")));
//extern volatile __8bitreg_t OCR0Bbits __asm__ ("0x28") __attribute__((section("sfr")));
//extern volatile __8bitreg_t GPIOR1bits __asm__ ("0x2A") __attribute__((section("sfr")));
//extern volatile __8bitreg_t GPIOR2bits __asm__ ("0x2B") __attribute__((section("sfr")));
//extern volatile __SPCRbits_t SPCRbits __asm__ ("0x2C") __attribute__((section("sfr")));
//extern volatile __SPSRbits_t SPSRbits __asm__ ("0x2D") __attribute__((section("sfr")));
//extern volatile __8bitreg_t SPDRbits __asm__ ("0x2E") __attribute__((section("sfr")));
//extern volatile __ACSRbits_t ACSRbits __asm__ ("0x30") __attribute__((section("sfr")));
//extern volatile __OCDRbits_t OCDRbits __asm__ ("0x31") __attribute__((section("sfr")));
//#define MONDRbits OCDRbits
//#define __MONDRbits_t __OCDRbits_t
//extern volatile __SMCRbits_t SMCRbits __asm__ ("0x33") __attribute__((section("sfr")));
//extern volatile __MCUSRbits_t MCUSRbits __asm__ ("0x34") __attribute__((section("sfr")));
//extern volatile __MCUCRbits_t MCUCRbits __asm__ ("0x35") __attribute__((section("sfr")));
//extern volatile __SPMCSRbits_t SPMCSRbits __asm__ ("0x37") __attribute__((section("sfr")));
//
//#else
extern volatile __8bitreg_t PINAbits __asm__ ("0x20") __attribute__((section("sfr")));
extern volatile __8bitreg_t DDRAbits __asm__ ("0x21") __attribute__((section("sfr")));
extern volatile __8bitreg_t PORTAbits __asm__ ("0x22") __attribute__((section("sfr")));
extern volatile __8bitreg_t PINBbits __asm__ ("0x23") __attribute__((section("sfr")));
extern volatile __8bitreg_t DDRBbits __asm__ ("0x24") __attribute__((section("sfr")));
extern volatile __8bitreg_t PORTBbits __asm__ ("0x25") __attribute__((section("sfr")));
extern volatile __8bitreg_t PINCbits __asm__ ("0x26") __attribute__((section("sfr")));
extern volatile __8bitreg_t DDRCbits __asm__ ("0x27") __attribute__((section("sfr")));
extern volatile __8bitreg_t PORTCbits __asm__ ("0x28") __attribute__((section("sfr")));
extern volatile __8bitreg_t PINDbits __asm__ ("0x29") __attribute__((section("sfr")));
extern volatile __8bitreg_t DDRDbits __asm__ ("0x2A") __attribute__((section("sfr")));
extern volatile __8bitreg_t PORTDbits __asm__ ("0x2B") __attribute__((section("sfr")));
extern volatile __8bitreg_t ADCPINbits __asm__ ("0x20") __attribute__((section("sfr")));
extern volatile __8bitreg_t ADCDDRbits __asm__ ("0x21") __attribute__((section("sfr")));
extern volatile __8bitreg_t ADCPORTbits __asm__ ("0x22") __attribute__((section("sfr")));
extern volatile __SPIPORTbits_t SPIDDRbits __asm__ ("0x24") __attribute__((section("sfr")));
extern volatile __SPIPORTbits_t SPIPORTbits __asm__ ("0x25") __attribute__((section("sfr")));
extern volatile __TIFR0bits_t TIFR0bits __asm__ ("0x35") __attribute__((section("sfr")));
extern volatile __TIFR1bits_t TIFR1bits __asm__ ("0x36") __attribute__((section("sfr")));
extern volatile __TIFR2bits_t TIFR2bits __asm__ ("0x37") __attribute__((section("sfr")));
extern volatile __PCIFRbits_t PCIFRbits __asm__ ("0x3B") __attribute__((section("sfr")));
extern volatile __EIFRbits_t EIFRits __asm__ ("0x3C") __attribute__((section("sfr")));
extern volatile __EIMSKbits_t EIMSKbits __asm__ ("0x3D") __attribute__((section("sfr")));
extern volatile __GPIOR0bits_t GPIOR0bits __asm__ ("0x3E") __attribute__((section("sfr")));
extern volatile __EECRbits_t EECRbits __asm__ ("0x3F") __attribute__((section("sfr")));
extern volatile __8bitreg_t EEDRbits __asm__ ("0x40") __attribute__((section("sfr")));
extern volatile __16bitreg_t EEARbits __asm__ ("0x41") __attribute__((section("sfr")));
extern volatile __8bitreg_t EEARLbits __asm__ ("0x41") __attribute__((section("sfr")));
extern volatile __8bitreg_t EEARHbits __asm__ ("0x42") __attribute__((section("sfr")));
extern volatile __GTCCRbits_t GTCCRbits __asm__ ("0x43") __attribute__((section("sfr")));
extern volatile __TCCR0Abits_t TCCR0Abits __asm__ ("0x44") __attribute__((section("sfr")));
extern volatile __TCCR0Bbits_t TCCR0Bbits __asm__ ("0x45") __attribute__((section("sfr")));
extern volatile __8bitreg_t TCNT0bits __asm__ ("0x46") __attribute__((section("sfr")));
extern volatile __8bitreg_t OCR0Abits __asm__ ("0x47") __attribute__((section("sfr")));
extern volatile __8bitreg_t OCR0Bbits __asm__ ("0x48") __attribute__((section("sfr")));
extern volatile __8bitreg_t GPIOR1bits __asm__ ("0x4A") __attribute__((section("sfr")));
extern volatile __8bitreg_t GPIOR2bits __asm__ ("0x4B") __attribute__((section("sfr")));
extern volatile __SPCRbits_t SPCRbits __asm__ ("0x4C") __attribute__((section("sfr")));
extern volatile __SPSRbits_t SPSRbits __asm__ ("0x4D") __attribute__((section("sfr")));
extern volatile __8bitreg_t SPDRbits __asm__ ("0x4E") __attribute__((section("sfr")));
extern volatile __ACSRbits_t ACSRbits __asm__ ("0x50") __attribute__((section("sfr")));
extern volatile __OCDRbits_t OCDRbits __asm__ ("0x51") __attribute__((section("sfr")));
#define MONDRbits OCDRbits
#define __MONDRbits_t __OCDRbits_t
extern volatile __SMCRbits_t SMCRbits __asm__ ("0x53") __attribute__((section("sfr")));
extern volatile __MCUSRbits_t MCUSRbits __asm__ ("0x54") __attribute__((section("sfr")));
extern volatile __MCUCRbits_t MCUCRbits __asm__ ("0x55") __attribute__((section("sfr")));
extern volatile __SPMCSRbits_t SPMCSRbits __asm__ ("0x57") __attribute__((section("sfr")));
//#endif
extern volatile __WDTCSRbits_t WDTCSRbits __asm__ ("0x60") __attribute__((section("sfr")));
extern volatile __CLKPRbits_t CLKPRbits __asm__ ("0x61") __attribute__((section("sfr")));
extern volatile __PRRbits_t PRRbits __asm__ ("0x64") __attribute__((section("sfr")));
extern volatile __8bitreg_t OSCCALbits __asm__ ("0x66") __attribute__((section("sfr")));
extern volatile __PCICRbits_t PCICRbits __asm__ ("0x68") __attribute__((section("sfr")));
extern volatile __EICRAbits_t EICRAbits __asm__ ("0x69") __attribute__((section("sfr")));
extern volatile __PCMSK0bits_t PCMSK0bits __asm__ ("0x6B") __attribute__((section("sfr")));
extern volatile __PCMSK1bits_t PCMSK1bits __asm__ ("0x6C") __attribute__((section("sfr")));
extern volatile __PCMSK2bits_t PCMSK2bits __asm__ ("0x6D") __attribute__((section("sfr")));
extern volatile __TIMSK0bits_t TIMSK0bits __asm__ ("0x6E") __attribute__((section("sfr")));
extern volatile __TIMSK1bits_t TIMSK1bits __asm__ ("0x6F") __attribute__((section("sfr")));
extern volatile __TIMSK2bits_t TIMSK2bits __asm__ ("0x70") __attribute__((section("sfr")));
extern volatile __PCMSK3bits_t PCMSK3bits __asm__ ("0x73") __attribute__((section("sfr")));
extern volatile __16bitreg_t ADCWbits __asm__ ("0x78") __attribute__((section("sfr")));
extern volatile __8bitreg_t ADCLbits __asm__ ("0x78") __attribute__((section("sfr")));
extern volatile __8bitreg_t ADCHbits __asm__ ("0x79") __attribute__((section("sfr")));
extern volatile __ADCSRAbits_t ADCSRAbits __asm__ ("0x7A") __attribute__((section("sfr")));
extern volatile __ADCSRBbits_t ADCSRBbits __asm__ ("0x7B") __attribute__((section("sfr")));
extern volatile __ADMUXbits_t ADMUXbits __asm__ ("0x7C") __attribute__((section("sfr")));
extern volatile __DIDR0bits_t DIDR0bits __asm__ ("0x7E") __attribute__((section("sfr")));
extern volatile __DIDR1bits_t DIDR1bits __asm__ ("0x7F") __attribute__((section("sfr")));
extern volatile __TCCR1Abits_t TCCR1Abits __asm__ ("0x80") __attribute__((section("sfr")));
extern volatile __TCCR1Bbits_t TCCR1Bbits __asm__ ("0x81") __attribute__((section("sfr")));
extern volatile __TCCR1Cbits_t TCCR1Cbits __asm__ ("0x82") __attribute__((section("sfr")));
extern volatile __16bitreg_t TCNT1bits __asm__ ("0x84") __attribute__((section("sfr")));
extern volatile __8bitreg_t TCNT1Hbits __asm__ ("0x84") __attribute__((section("sfr")));
extern volatile __8bitreg_t TCNT1Lbits __asm__ ("0x85") __attribute__((section("sfr")));
extern volatile __16bitreg_t ICR1bits __asm__ ("0x86") __attribute__((section("sfr")));
extern volatile __8bitreg_t ICR1Hbits __asm__ ("0x86") __attribute__((section("sfr")));
extern volatile __8bitreg_t ICR1Lbits __asm__ ("0x87") __attribute__((section("sfr")));
extern volatile __16bitreg_t OCR1Abits __asm__ ("0x88") __attribute__((section("sfr")));
extern volatile __8bitreg_t OCR1AHbits __asm__ ("0x88") __attribute__((section("sfr")));
extern volatile __8bitreg_t OCR1ALbits __asm__ ("0x89") __attribute__((section("sfr")));
extern volatile __16bitreg_t OCR1Bbits __asm__ ("0x8A") __attribute__((section("sfr")));
extern volatile __8bitreg_t OCR1BHbits __asm__ ("0x8A") __attribute__((section("sfr")));
extern volatile __8bitreg_t OCR1BLbits __asm__ ("0x8B") __attribute__((section("sfr")));
extern volatile __TCCR2Abits_t TCCR2Abits __asm__ ("0xB0") __attribute__((section("sfr")));
extern volatile __TCCR2Bbits_t TCCR2Bbits __asm__ ("0xB1") __attribute__((section("sfr")));
extern volatile __8bitreg_t TCNT2bits __asm__ ("0xB2") __attribute__((section("sfr")));
extern volatile __8bitreg_t OCR2Abits __asm__ ("0xB3") __attribute__((section("sfr")));
extern volatile __8bitreg_t OCR2Bbits __asm__ ("0xB4") __attribute__((section("sfr")));
extern volatile __ASSRbits_t ASSRbits __asm__ ("0xB6") __attribute__((section("sfr")));
extern volatile __8bitreg_t TWBRbits __asm__ ("0xB8") __attribute__((section("sfr")));
extern volatile __TWSRbits_t TWSRbits __asm__ ("0xB9") __attribute__((section("sfr")));
extern volatile __TWARbits_t TWARbits __asm__ ("0xBA") __attribute__((section("sfr")));
extern volatile __8bitreg_t TWDRbits __asm__ ("0xBB") __attribute__((section("sfr")));
extern volatile __TWCRbits_t TWCRbits __asm__ ("0xBC") __attribute__((section("sfr")));
extern volatile __TWAMRbits_t TWAMRbits __asm__ ("0xBD") __attribute__((section("sfr")));
extern volatile __UCSR0Abits_t UCSR0Abits __asm__ ("0xC0") __attribute__((section("sfr")));
extern volatile __UCSR0Bbits_t UCSR0Bbits __asm__ ("0xC1") __attribute__((section("sfr")));
extern volatile __UCSR0Cbits_t UCSR0Cbits __asm__ ("0xC2") __attribute__((section("sfr")));
extern volatile __16bitreg_t UBRR0bits __asm__ ("0xC4") __attribute__((section("sfr")));
extern volatile __8bitreg_t UBRR0Lbits __asm__ ("0xC4") __attribute__((section("sfr")));
extern volatile __8bitreg_t UBRR0Hbits __asm__ ("0xC5") __attribute__((section("sfr")));
extern volatile __8bitreg_t UDR0bits __asm__ ("0xC6") __attribute__((section("sfr")));
extern volatile __UCSR1Abits_t UCSR1Abits __asm__ ("0xC8") __attribute__((section("sfr")));
extern volatile __UCSR1Bbits_t UCSR1Bbits __asm__ ("0xC9") __attribute__((section("sfr")));
extern volatile __UCSR1Cbits_t UCSR1Cbits __asm__ ("0xCA") __attribute__((section("sfr")));
extern volatile __16bitreg_t UBRR1bits __asm__ ("0xCC") __attribute__((section("sfr")));
extern volatile __8bitreg_t UBRR1Hbits __asm__ ("0xCC") __attribute__((section("sfr")));
extern volatile __8bitreg_t UBRR1Lbits __asm__ ("0xCD") __attribute__((section("sfr")));
extern volatile __8bitreg_t UDR1bits __asm__ ("0xCE") __attribute__((section("sfr")));
#endif /*REG_STRUCTS_H_*/
<file_sep>/BowlerStack/src/PID/PidHysteresis.c
/*
* PidHysteresis.c
*
* Created on: Feb 14, 2014
* Author: hephaestus
*/
#include "Bowler/Bowler.h"
void incrementHistoresis(int group) {
getPidGroupDataTable(group)->config.upperHistoresis += 1;
//calcCenter( group);
}
void decrementHistoresis(int group) {
getPidGroupDataTable(group)->config.lowerHistoresis -= 1;
}
void calcCenter(int group) {
int diff = (getPidGroupDataTable(group)->config.upperHistoresis + getPidGroupDataTable(group)->config.lowerHistoresis) / 2;
getPidGroupDataTable(group)->config.stop = diff;
}
void checkCalibration(int group) {
if (getPidGroupDataTable(group)->calibration.calibrated != true) {
getPidGroupDataTable(group)->config.upperHistoresis = 0;
getPidGroupDataTable(group)->config.lowerHistoresis = 0;
getPidGroupDataTable(group)->config.stop = 0;
getPidGroupDataTable(group)->calibration.calibrated = true;
}
}
int getUpperPidHistoresis(int group) {
checkCalibration(group);
return getPidGroupDataTable(group)->config.upperHistoresis;
}
int getLowerPidHistoresis(int group) {
checkCalibration(group);
return getPidGroupDataTable(group)->config.lowerHistoresis;
}
int getPidStop(int group) {
checkCalibration(group);
return getPidGroupDataTable(group)->config.stop;
}
boolean processRunAutoCal(BowlerPacket * Packet) {
int group = Packet->use.data[0];
runPidHysterisisCalibration(group);
READY(Packet, 0, 0);
return true;
}
void runPidHysterisisCalibration(int group) {
if (!getPidGroupDataTable(group)->config.Enabled) {
println_E("Axis disabled for calibration #");
p_int_E(group);
getPidGroupDataTable(group)->config.Enabled = true;
}
getPidGroupDataTable(group)->config.lowerHistoresis = 0;
getPidGroupDataTable(group)->config.upperHistoresis = 0;
getPidGroupDataTable(group)->config.stop = 0;
// println_I("\tReset PID");
pidReset(group, 0); // Zero encoder reading
// println_I("\tDisable PID Output");
SetPIDEnabled(group, true);
SetPIDCalibrateionState(group, CALIBRARTION_hysteresis);
getPidGroupDataTable(group)->calibration.state = forward;
// println_I("\tSetting slow move");
setOutput(group, -1.0f);
getPidGroupDataTable(group)->timer.setPoint = 2000;
getPidGroupDataTable(group)->timer.MsTime = getMs();
}
CAL_STATE pidHysterisis(int group) {
if (RunEvery(&getPidGroupDataTable(group)->timer) > 0) {
Print_Level l = getPrintLevel();
//setPrintLevelInfoPrint();
float boundVal = 150.0;
float extr = GetPIDPosition(group);
if (bound(0, extr, boundVal, boundVal)) {// check to see if the encoder has moved
//we have not moved
// println_I("NOT moved ");p_fl_I(extr);
if (getPidGroupDataTable(group)->calibration.state == forward) {
incrementHistoresis(group);
} else if (getPidGroupDataTable(group)->calibration.state == backward) {
decrementHistoresis(group);
}
int historesisBound = 25;
if (getPidGroupDataTable(group)->config.lowerHistoresis < (-historesisBound) &&
getPidGroupDataTable(group)->calibration.state == backward) {
println_E("Backward Motor seems damaged, more then counts of historesis #");
p_int_I(group);
getPidGroupDataTable(group)->calibration.state = forward;
}
if (getPidGroupDataTable(group)->config.upperHistoresis > (historesisBound) &&
getPidGroupDataTable(group)->calibration.state == forward) {
println_E("Forward Motor seems damaged, more then counts of historesis #");
p_int_I(group);
getPidGroupDataTable(group)->calibration.state = done;
}
} else {
pidReset(group, 0);
setOutput(group, 0);
println_E("Moved ");
p_fl_E(extr);
if (getPidGroupDataTable(group)->calibration.state == forward) {
println_I("Backward Calibrated for link# ");
p_int_I(group);
getPidGroupDataTable(group)->calibration.state = backward;
} else {
println_I("Calibration done for link# ");
p_int_I(group);
getPidGroupDataTable(group)->calibration.state = done;
float offset = .9;
getPidGroupDataTable(group)->config.lowerHistoresis *= offset;
getPidGroupDataTable(group)->config.upperHistoresis *= offset;
calcCenter(group);
}
}
if (getPidGroupDataTable(group)->calibration.state == forward) {
setOutput(group, 1.0f);
} else if (getPidGroupDataTable(group)->calibration.state == backward) {
setOutput(group, -1.0f);
}
setPrintLevel(l);
}
if (getPidGroupDataTable(group)->calibration.state == done)
SetPIDCalibrateionState(group, CALIBRARTION_DONE);
return getPidGroupDataTable(group)->calibration.state;
}
void startHomingLink(int group, PidCalibrationType type, float homedValue) {
float speed = 20.0;
if (type == CALIBRARTION_home_up)
speed *= 1.0;
else if (type == CALIBRARTION_home_down)
speed *= -1.0;
else {
println_E("Invalid homing type");
return;
}
getPidGroupDataTable(group)->config.tipsScale = 1;
SetPIDCalibrateionState(group, type);
setOutput(group, speed);
getPidGroupDataTable(group)->timer.MsTime = getMs();
getPidGroupDataTable(group)->timer.setPoint = 1000;
getPidGroupDataTable(group)->homing.homingStallBound = 20;
getPidGroupDataTable(group)->homing.previousValue = GetPIDPosition(group);
getPidGroupDataTable(group)->homing.lastTime = getMs();
getPidGroupDataTable(group)->homing.homedValue = homedValue;
SetPIDEnabled(group,true);
}
void checkLinkHomingStatus(int group) {
if (!(GetPIDCalibrateionState(group) == CALIBRARTION_home_down ||
GetPIDCalibrateionState(group) == CALIBRARTION_home_up ||
GetPIDCalibrateionState(group) == CALIBRARTION_home_velocity
)
) {
return; //Calibration is not running
}
float current = GetPIDPosition(group);
float currentTime = getMs();
if (RunEvery(&getPidGroupDataTable(group)->timer) > 0) {
//println_W("Check Homing ");
if (GetPIDCalibrateionState(group) != CALIBRARTION_home_velocity) {
float boundVal = getPidGroupDataTable(group)->homing.homingStallBound;
if (bound(getPidGroupDataTable(group)->homing.previousValue,
current,
boundVal,
boundVal
)
) {
pidReset(group, getPidGroupDataTable(group)->homing.homedValue);
//after reset the current value will have changed
current = GetPIDPosition(group);
getPidGroupDataTable(group)->config.tipsScale = 1;
println_W("Homing Velocity for group ");
p_int_W(group);
print_W(", Resetting position to: ");
p_fl_W(getPidGroupDataTable(group)->homing.homedValue);
print_W(" current ");
p_fl_W(current);
float speed = -20.0;
if (GetPIDCalibrateionState(group) == CALIBRARTION_home_up)
speed *= 1.0;
else if (GetPIDCalibrateionState(group) == CALIBRARTION_home_down)
speed *= -1.0;
else {
println_E("Invalid homing type");
return;
}
Print_Level l = getPrintLevel();
//setPrintLevelInfoPrint();
setOutput(group, speed);
setPrintLevel(l);
getPidGroupDataTable(group)->timer.MsTime = getMs();
getPidGroupDataTable(group)->timer.setPoint = 2000;
SetPIDCalibrateionState(group, CALIBRARTION_home_velocity);
getPidGroupDataTable(group)->homing.lastTime = currentTime;
}
} else {
current = GetPIDPosition(group);
float posDiff = current - getPidGroupDataTable(group)->homing.previousValue; //ticks
float timeDiff = (currentTime - getPidGroupDataTable(group)->homing.lastTime) / 1000.0; //
float tps = (posDiff / timeDiff);
getPidGroupDataTable(group)->config.tipsScale = 20 / tps;
println_E("New scale factor: ");
p_fl_E(getPidGroupDataTable(group)->config.tipsScale);
print_E(" speed ");
p_fl_E(tps);
print_E(" on ");
p_int_E(group);
print_E(" Position difference ");
p_fl_E(posDiff);
print_E(" time difference ");
p_fl_E(timeDiff);
OnPidConfigure(group);
SetPIDCalibrateionState(group, CALIBRARTION_DONE);
}
getPidGroupDataTable(group)->homing.previousValue = current;
}
}
|
782634866e6d43e4010da6b2945c8a201e63f1a6
|
[
"Markdown",
"Makefile",
"Text",
"C",
"Shell"
] | 72 |
Makefile
|
NeuronRobotics/c-bowler
|
facfca978f2c1c8677e823bd35fd18cab0d81a03
|
e6edce8d0a4477843bc1deb93836aef6317ae32a
|
refs/heads/master
|
<file_sep>$(document).ready(function(){
$('#otherApplicationTable').DataTable({
processing: true,
serverSide: true,
pagingType: 'simple',
pageLength: 10,
searching: false,
lengthChange: false,
ajax: '/admin/all_banks',
});
});
<file_sep><?php
namespace App\Repository;
use DB;
use Auth;
class Loans{
public function getApplications($loan_id, $bank_id, $status, $sort){
$loans = DB::table('applications')
->join('offers', 'applications.offer_id', '=', 'offers.id')
->join('banks', 'banks.id','=','offers.bank_id')
->join('classifications', 'classifications.id', '=', 'offers.classification_id')
->join('loans', 'classifications.loan_id', '=', 'loans.id')
->join('users', 'users.id', '=', 'applications.user_id')
->whereRaw('banks.id = ?',[$bank_id])
->whereRaw('loans.slug = ?',[$loan_id]);
if($status == null){
$loans->where('applications.status');
}else{
$loans->whereRaw('applications.status = ?',[$status]);
}
$loans->select('applications.created_at','users.id', DB::raw('CONCAT(users.firstname," ",users.middlename," ",users.lastname) as fullname'),'classifications.classification','applications.amount','applications.term','applications.borrower_type as type', DB::raw('IF (applications.status IS NULL, "Unassigned", applications.status) as status'))
->orderBy($sort['key'], $sort['value'])
->get();
return $loans;
}
public function getBorrowerApplications($borrower, $bank){
$applications = DB::table('users')
->join('applications', 'users.id', '=', 'applications.user_id')
->join('offers', 'applications.offer_id', '=', 'offers.id')
->join('banks', 'banks.id','=','offers.bank_id')
->join('classifications', 'classifications.id', '=', 'offers.classification_id')
->join('loans', 'classifications.loan_id', '=', 'loans.id')
->select(
'applications.created_at',
DB::raw('IF (applications.status IS NULL, "Unassigned", applications.status) as status'),
'loans.type',
'classifications.classification',
'applications.amount',
'applications.term'
)
->whereRaw('users.id = ?',[$borrower])
->whereRaw('banks.id = ?',[$bank])
->get();
return $applications;
}
}<file_sep>$(document).ready(function(){
$('#checkAddress').click(function(e){
if($(this).is(':checked')){
$('#txtStreetPermanent').val($('#txtStreet').val());
$('#txtMunicipalPermanent').val($('#txtMunicipal').val());
$('#txtProvincePermanent').val($('#txtProvince').val());
$('#txtStayPermanent').val($('#txtStay').val());
$('#selOwnershipPermanent').val($('#selOwnership').val());
}else{
$('#txtStreetPermanent').val('');
$('#txtMunicipalPermanent').val('');
$('#txtProvincePermanent').val('');
$('#txtStayPermanent').val('');
$('#selOwnershipPermanent').val('');
}
});
$('#personal-form').validate({
submitHandler:function(form){
$.ajax({
url: $(form).attr('action'),
type: 'post',
data: $(form).serialize(),
dataType: 'json',
success: function(res){
console.log(res);
// ajaxSuccessResponse(res).then(function(value){
// location.reload();
// });
},
error: function(xhr){
console.log(xhr.responseText);
//ajaxErrorDisplay(xhr.responseText);
}
});
}
});
$('#individual-income-form').validate({
submitHandler:function(form){
//console.log($(form).serialize());
$.ajax({
url: $(form).attr('action'),
type: 'post',
data: $(form).serialize(),
dataType: 'json',
success: function(res){
console.log(res);
// ajaxSuccessResponse(res).then(function(value){
// location.reload();
// });
},
error: function(xhr){
console.log(xhr.responseText);
//ajaxErrorDisplay(xhr.responseText);
}
});
}
})
$('#individual-attachment-form').validate({
submitHandler:function(form){
let data = new FormData(form);
data.append('borrower_type', 0);
$.ajax({
url: '/attachments',
type: 'post',
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function(res){
ajaxSuccessResponse(res).then(function(value){
location.reload();
});
},
error: function(xhr){
console.log(xhr.responseText);
}
})
}
});
$('#individual-spouse-form').validate({
submitHandler: function(form){
$.ajax({
url: '/my-profile/spouse',
type: 'post',
dataType: 'json',
data: $(form).serialize(),
success:function(res){
console.log(res);
},
error: function(xhr){
ajaxErrorDisplay(xhr.responseText);
}
});
}
})
});<file_sep><?php
namespace App\Http\Controllers\Creditor;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use DB;
class BorrowerController extends Controller
{
public function getBorrower($borrower, $type){
$details = DB::table('users')
->join('borrowers', 'users.id', '=', 'borrowers.user_id')
->join('applications', 'users.id', '=', 'applications.user_id')
->join('offers', 'applications.offer_id', '=', 'offers.id')
->select(
'users.*'
/* 'applications.*',
'borrowers.*',
'offers.*' */)
->whereRaw('users.id = ?', [$borrower])
->whereRaw('applications.borrower_type = ?', [$type])
->get();
return response()->json($details);
return view('creditor.details.borrower_details', ['details' => $details]);
}
public function getEntity(User $entity){
return $entity;
}
}
|
e3cf1c5ce4530f07240dff6126248c75ec60e110
|
[
"JavaScript",
"PHP"
] | 4 |
JavaScript
|
sonnyhermo/bridged
|
b6e3217a995cfffff496fdf3c9858dc5d389a96d
|
394524ce3982119bb19d29537321852b471c19cc
|
refs/heads/master
|
<file_sep>var express = require('express');
var router = express.Router();
var dna={};
var Prism = require('prismjs');
var aa={};
router.get('/', function(req, res, next){
res.render('index', { dna : dna, aa : aa })
});
router.post('/send', function (req, res, next) {
var data = req.body.data;
var spawn = require('child_process').spawn,
py = spawn('python', ['./api/writeDna.py']),
dataString = '';
py.stdout.on('data', function(data){
dataString += data.toString();
console.log((dataString.replace("'",'"')), " dataString");
});
py.stdout.on('end', function(){
dna = JSON.parse(dataString.replace(/'/g,'"'));
res.redirect('/');
});
py.stdin.write(JSON.stringify(data));
py.stdin.end();
});
router.post('/aminoAcidPrecentage', function(req,res,next){
var spawn = require('child_process').spawn,
py = spawn('python', ['./api/aminoAcid.py']),
data = [req.body.data],
dataString = '';
py.stdout.on('data', function(data){
dataString += data.toString();
});
py.stdout.on('end', function(){
aa = JSON.parse(dataString.replace(/'/g,'"'));
//console.log(typeof(dna));
res.redirect('/');
});
py.stdin.write(JSON.stringify(data));
py.stdin.end();
});
module.exports = router;
<file_sep>
class matchers:
@staticmethod
def dnaMatch(argument = str):
switcher = {
'a': 't',
't': 'a',
"c": 'g',
'g': 'c'
}
return switcher.get(argument)
@staticmethod
def rnaMatch(argument = str):
switcher = {
"t" : "a",
"a" : "u",
"c" : "g",
"g" : "c",
}
return switcher.get(argument)
@staticmethod
def aminoMatch(argument = str):
switcher = {
"uuu":"phenylalanine", "uuc":"phenylalanine","uua":"leucine","uug":"leucine",
"ucu":"serine","ucc":"serine","uca":"serine","ucg":"serine",
"uau":"tyrosine","uac":"tyrosine","uaa":"stop","uag":"stop",
"ugu":"cysteine", "ugc":"cysteine", "uga":"stop","ugg":"tryptophan",
"cuu":"leucine","cuc":"leucine","cua":"leucine","cug":"leucine",
"ccu":"proline","ccc":"proline","cca":"proline","ccg":"proline",
"cau":"histidine","cac":"histidine","caa":"glutamine","cag":"glutamine",
"cgu":"arginine","cgc":"arginine","cga":"arginine","cgg":"arginine",
"auu":"isoleucine","auc":"isoleucine","aua":"isoleucine","aug":"methionine",
"acu":"threonine","acc":"threonine","aca":"threonine","acg":"threonine",
"aau":"asparagine","aac":"asparagine","aaa":"lysine","aag":"lysine",
"agu":"serine","agc":"serine","aga":"arginine","agg":"arginine",
"guu":"valine","guc":"valine","gua":"valine","gug":"valine",
"gcu":"alanine","gcc":"alanine","gca":"alanine","gcg":"alanine",
"gau":"aspartate","gac":"aspartate","gaa":"glutamate","gag":"glutamate",
"ggu":"glycine","ggc":"glycine","gga":"glycine","ggg":"glycine",
}
return switcher.get(argument)
<file_sep>
import sys, json, numpy as np
test = ["a", "t", "c", "g"]
from seqMatchers import matchers as Matchers
def writeDna(dna = str):
seq =[]
aminoAcid = []
for i in range(1, len(dna)-1):
if dna[i] == test[0] or dna[i]==test[1] or dna[i]==test[2] or dna[i]==test[3]:
x = ""
codingLine = dna[i]
template = Matchers.dnaMatch(codingLine)
rna = Matchers.rnaMatch(template)
seq.append({ "location": i, "coding" : codingLine, "template": template, "rna": rna })
else:
print "error"
print seq
return seq
#Read data from stdin
def read_in():
lines = sys.stdin.readlines()
dna = writeDna(lines[0])
#Since our input would only be having one line, parse our JSON data from that
return json.loads(dna)
def main():
#get our data as an array from read_in()
lines = read_in()
print lines
#create a numpy array
np_lines = np.array(lines)
#use numpys sum method to find sum of all elements in the array
lines_sum = np.sum(np_lines)
#return the sum to the output stream
print lines_sum
#start process
if __name__ == '__main__':
main()<file_sep>
import sys, json, numpy as np
test = ["a", "t", "c", "g"]
from seqMatchers import matchers as Matchers
def aminoAcidPrecentage(mrna = str):
aminoAcid = []
aminoAcidPrecent = []
seq = list(mrna[1:])
## every 3 mrna creates the amino acid we need##
for i in range(0,len(seq)-4,3):
###mrna = str(seq[i])+ str(seq[i+1]["rna"])+ str(seq[i+2]["rna"])
rna = str(seq[i+1]) + str(seq[i+2]) + str(seq[i+3])
# mrna return the right amino acid
amino = Matchers.aminoMatch(rna)
aminoAcid.append(amino)
np_amino = np.array(aminoAcid)
unique_elements, counts_elements = np.unique(np_amino, return_counts=True)
index = 0
## calculate precentage of the each amino in the dna##
for i in counts_elements:
precentage = float(i)/(len(np_amino))*100
aminoAcidPrecent.append({ "amino_name" : str(unique_elements[index]), "precentage" : precentage })
index = index + 1
print aminoAcidPrecent
return aminoAcidPrecent
#Read data from stdin
def read_in():
lines = sys.stdin.readlines()
aa = aminoAcidPrecentage(lines[0])
#Since our input would only be having one line, parse our JSON data from that
return json.loads(aa)
def main():
#get our data as an array from read_in()
lines = read_in()
print lines
#create a numpy array
np_lines = np.array(lines)
#use numpys sum method to find sum of all elements in the array
lines_sum = np.sum(np_lines)
#return the sum to the output stream
print lines_sum
#start process
if __name__ == '__main__':
main()
|
7f77ecb71778d9a8216d79ebb1fcf4a8998caf19
|
[
"JavaScript",
"Python"
] | 4 |
JavaScript
|
gilmarom/dna-sequance
|
992e95e87c83ebcf05a0a7669a17fc46defbf0af
|
8ce446f632ceb17d7c9fd992a22850f4f3db42f9
|
refs/heads/main
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CheckPosition : MonoBehaviour
{
public float xRange = 49;
public float z1Range = 42;
public float z2Range = 54;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.position.x < -xRange)
{
transform.position = new Vector3(-xRange, transform.position.y, transform.position.z);
}
if (transform.position.x > xRange)
{
transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
}
if (transform.position.z < -z2Range)
{
transform.position = new Vector3(transform.position.x, transform.position.y, -z2Range);
}
if (transform.position.z > z1Range)
{
transform.position = new Vector3(transform.position.x, transform.position.y, z1Range);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovementController : MonoBehaviour
{
private float mSpeed = 5.0f;
private Vector3 mVelocity;
private Vector3 mRotation;
public string v = "vertical";
public string h = "horizontal";
public Animator animator;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
mVelocity = Vector3.zero;
animator.SetFloat(v, 0);
animator.SetFloat(h, 0);
if (Input.GetKey(KeyCode.W))
{
mVelocity.z = 1.0f;
} else if (Input.GetKey(KeyCode.S))
{
mVelocity.z = -1.0f;
}
if (Input.GetKey(KeyCode.D))
{
mVelocity.x = 1.0f;
}
else if (Input.GetKey(KeyCode.A))
{
mSpeed = 5.0f;
mVelocity.x = -1.0f;
}
if ((Input.GetKey(KeyCode.W)) || (Input.GetKey(KeyCode.S)) || (Input.GetKey(KeyCode.D)) || (Input.GetKey(KeyCode.A)))
{
animator.SetFloat(v, 1);
}
if ((Input.GetKey(KeyCode.LeftShift)) && ((Input.GetKey(KeyCode.W)) || (Input.GetKey(KeyCode.S)) || (Input.GetKey(KeyCode.D)) || (Input.GetKey(KeyCode.A))))
{
animator.SetFloat(h, 1);
}
transform.Translate(transform.position.x, 0, transform.position.z);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAnimation : MonoBehaviour
{
private Animator animator;
public GameObject sparkle;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
sparkle.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("magic");
sparkle.SetActive(true);
StartCoroutine(stopSparkles());
}
if (Input.GetKey(KeyCode.W))
{
transform.eulerAngles = new Vector3(0, 0, 0);
} else if (Input.GetKey(KeyCode.S))
{
transform.eulerAngles = new Vector3(0, 180, 0);
}
if (Input.GetKey(KeyCode.D))
{
transform.eulerAngles = new Vector3(0, 90, 0);
}
else if (Input.GetKey(KeyCode.A))
{
transform.eulerAngles = new Vector3(0, -90, 0);
}
}
IEnumerator stopSparkles()
{
yield return new WaitForSeconds(2.4f);
sparkle.SetActive(false);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DetectCollision : MonoBehaviour
{
int coins;
public GameObject Counter;
// Start is called before the first frame update
void Start()
{
coins = 0;
}
// Update is called once per frame
void Update()
{
Counter.GetComponent<UnityEngine.UI.Text>().text = "SCORE: "+coins.ToString();
}
void OnTriggerStay(Collider other)
{
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(destroyObject());
}
}
IEnumerator destroyObject()
{
yield return new WaitForSeconds(2.4f);
Destroy(gameObject);
}
}
|
f6097ba01c0f8c2b8d882ad7333947332f87e8ac
|
[
"C#"
] | 4 |
C#
|
Butonsusumom/FinalProject
|
7311cfec4292ff9ebe9435dc406986f6dfb3bd97
|
366c95f414cfb15365fb4c810e16453f274803af
|
refs/heads/master
|
<file_sep>require_relative "php_shared"
describe "A PHP 5.5 application with a composer.json", :requires_php_on_stack => "5.5" do
include_examples "A PHP application with a composer.json", "5.5"
end
<file_sep>require_relative "php_shared"
describe "A PHP 7.4 application with a composer.json", :requires_php_on_stack => "7.4" do
include_examples "A PHP application with a composer.json", "7.4"
context "with an index.php that allows for different execution times" do
['apache2', 'nginx'].each do |server|
context "running the #{server} web server" do
let(:app) {
new_app_with_stack_and_platrepo('test/fixtures/sigterm',
before_deploy: -> { system("composer require --quiet --ignore-platform-reqs php '7.4.*'") or raise "Failed to require PHP version" }
)
}
# FIXME: move to php_shared.rb once all PHPs are rebuilt with that tracing capability
it "logs slowness after configured time and sees a trace" do
app.deploy do |app|
# first, launch in the background wrapped in a 10 second timeout
# then sleep three seconds to allow boot
# curl the sleep() script with a timeout
# ensure slowlog info and trace is there
# wait for timeout process
cmd = "timeout 10 heroku-php-apache2 -F fpm.request_slowlog_timeout.conf & sleep 3; curl \"localhost:$PORT/index.php?wait=5\"; wait"
output = app.run(cmd)
expect(output).to include("executing too slow")
expect(output).to include("sleep() /app/index.php:5")
end
end
it "logs slowness after about 3 seconds and terminates the process after about 30 seconds" do
app.deploy do |app|
# first, launch in the background wrapped in a 45 second timeout
# then sleep three seconds to allow boot
# curl the sleep() script with a very long timeout
# ensure slowlog and terminate output is there
# wait for timeout process
cmd = "timeout 45 heroku-php-apache2 & sleep 3; curl \"localhost:$PORT/index.php?wait=35\"; wait"
output = app.run(cmd)
expect(output).to match(/executing too slow/)
expect(output).to match(/execution timed out/)
end
end
end
end
end
end
<file_sep>require_relative "php_shared"
describe "A PHP 7.1 application with a composer.json", :requires_php_on_stack => "7.1" do
include_examples "A PHP application with a composer.json", "7.1"
end
<file_sep>require_relative "php_shared"
describe "A PHP 7.3 application with a composer.json", :requires_php_on_stack => "7.3" do
include_examples "A PHP application with a composer.json", "7.3"
end
<file_sep>require_relative "php_shared"
describe "A PHP 5.6 application with a composer.json", :requires_php_on_stack => "5.6" do
include_examples "A PHP application with a composer.json", "5.6"
end
<file_sep>require_relative "php_shared"
describe "A PHP 7.2 application with a composer.json", :requires_php_on_stack => "7.2" do
include_examples "A PHP application with a composer.json", "7.2"
end
<file_sep>require_relative "php_shared"
describe "A PHP 7.0 application with a composer.json", :requires_php_on_stack => "7.0" do
include_examples "A PHP application with a composer.json", "7.0"
end
|
58441df55654446ded687fe148e45ba7027594ce
|
[
"Ruby"
] | 7 |
Ruby
|
intercom/heroku-buildpack-php
|
85561920834e7ed40f7d2b9f8627254aeb5aca69
|
7582099c7f63b572053fd58a5efd89cdbf76a381
|
refs/heads/master
|
<repo_name>Minisai/AirTraffic<file_sep>/app/models/departure.rb
class Departure < ActiveRecord::Base
after_create :schedule_departure
private
def schedule_departure
DepartJob.perform_later(self)
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
root to: 'departures#index'
resources :departures, only: [:create, :index]
end
<file_sep>/spec/factories/departures.rb
FactoryGirl.define do
factory :departure do
departed_at "2015-07-04 02:47:02"
name "MyString"
end
end
<file_sep>/README.md
Air Traffic
================
App was generated by Rails Composer
How to run:
1) Run rails server:
rails s
2) Run redis:
redis-server
3) Run private-pub:
rackup private_pub.ru -s thin -E production
4) Run resque:
rake resque:work QUEUE='*'
<file_sep>/app/assets/javascripts/departure.js
$(function() {
$('#add-departure').click(function () {
$.post("departures", function(data) {
var elementHtml = '<tr data-id="' + data['id'] + '"><td>Flight ' + data['id'] + '</td><td>Scheduled</td></tr>'
var firstElement = $('#departures').find('> tbody > tr:first');
if(firstElement.length > 0) {
firstElement.before(elementHtml);
}
else {
$('#departures').find('> tbody').html(elementHtml);
}
});
});
PrivatePub.subscribe("/departures", function(data, channel) {
$('#departures').find('tr[data-id="'+data['id']+'"]').html('<td>Flight '+data['id']+'</td><td>'+data['departed_at']+'</td>');
});
});
<file_sep>/app/controllers/departures_controller.rb
class DeparturesController < ApplicationController
def index
@departures = Departure.order(id: :desc)
end
def create
@departure = Departure.create
render json: @departure
end
end
<file_sep>/app/jobs/depart_job.rb
class DepartJob < ActiveJob::Base
queue_as :serial_work
def perform(departure)
sleep(rand(10..15))
departure.touch(:departed_at)
PrivatePub.publish_to "/departures", {id: departure.id, departed_at: departure.departed_at.to_formatted_s(:rfc822)}
end
end
|
f71e14af003a064ddf710886e84a10e3f0de4139
|
[
"Markdown",
"JavaScript",
"Ruby"
] | 7 |
Ruby
|
Minisai/AirTraffic
|
c035329b85b65c4c0c9e9b6ac732c3c25d786892
|
3aa0c2b986f5c88178615349b467380078d0a951
|
refs/heads/master
|
<repo_name>YurchevskyRoman/Chat<file_sep>/app/src/main/java/com/romanyu/chat/authUtil/DateUtil.kt
package com.romanyu.chat.authUtil
import java.text.SimpleDateFormat
import java.util.*
val FULL_DATE_PATTERN = "yyyy.MM.dd G HH:mm:ss"
val TIME_DATE_PATTERN = "HH:mm"
fun getDateString(date: Date, pattern: String) : String{
val dateFormat = SimpleDateFormat(pattern, Locale.ENGLISH)
val dateString = dateFormat.format(date) as String
return dateString
}
fun getDateFromString(dateString: String, pattern: String) : Date{
val dateFormat = SimpleDateFormat(pattern, Locale.ENGLISH)
val date = dateFormat.parse(dateString) as Date
return date
}<file_sep>/app/src/main/java/com/romanyu/chat/SingleChatActivity.kt
package com.romanyu.chat
import android.Manifest
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.bumptech.glide.Glide
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.romanyu.chat.UserUtil.ChatInfoBlock
import com.romanyu.chat.UserUtil.Message
import com.romanyu.chat.UserUtil.User
import com.romanyu.chat.adapters.MessagesAdapter
import com.romanyu.chat.authUtil.FULL_DATE_PATTERN
import com.romanyu.chat.authUtil.getDateString
import kotlinx.android.synthetic.main.activity_single_chat.*
import java.util.*
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.database.Cursor
import android.net.Uri
import android.widget.Toast
import com.romanyu.chat.gallery.ImageData
import android.provider.MediaStore
import android.util.Log
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.webkit.MimeTypeMap
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.UploadTask
import com.romanyu.chat.gallery.ImagesAdapter
import java.io.File
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class SingleChatActivity : AppCompatActivity(), TextWatcher, View.OnClickListener,
MessagesAdapter.ICheckableMessages, ImagesAdapter.IShowableSendButton {
companion object {
val COMPANION_USER_ID = "COMPANION_USER_ID"
val PERMISSION_READ_EXTERNAL_STORAGE = 0
var lastDeleteMessageId: Int? = null
}
var companion: User? = null
var currentUser: User? = null
var chatKey: String? = null
var companionId: String? = null
lateinit var databaseReference: DatabaseReference
//Lists
val messagesList: MutableList<Message> = ArrayList<Message>()
val checkedMessagesList: MutableList<Message> = ArrayList<Message>()
lateinit var imagesList: MutableList<ImageData>
val checkedOrNotMessagesList: MutableList<Boolean> = ArrayList<Boolean>()
val valuesEventsListenersList: MutableList<ValueEventListener> = ArrayList<ValueEventListener>()
val referencesOnValuesEventsListenersList: MutableList<DatabaseReference> = ArrayList<DatabaseReference>()
val menuItemsList: MutableList<MenuItem> = ArrayList<MenuItem>()
val userProfilePhotos: HashMap<String, Any> = HashMap()
lateinit var messagesAdapter: MessagesAdapter
var messagesManipulationSettingsIsVisible: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_chat)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
message_text.requestFocus()
val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
linearLayoutManager.stackFromEnd = true
messages_recycler.layoutManager = linearLayoutManager
databaseReference = FirebaseDatabase.getInstance().reference
companionId = intent.extras.getString(COMPANION_USER_ID)
message_text.addTextChangedListener(this)
send_button.setOnClickListener(this)
val layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
gallery.layoutManager = layoutManager
attach_photo_button.setOnClickListener(this)
gallery_hide_button.setOnClickListener(this)
gallery_block.setOnClickListener(this)
gallery_send_button.setOnClickListener(this)
}
override fun onStart() {
super.onStart()
val mCompanionId = companionId
if (mCompanionId != null) {
readDatas(mCompanionId)
}
}
override fun onStop() {
stopValueEventListener()
super.onStop()
}
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s?.length ?: 0 > 0) {
attach_photo_button.visibility = View.GONE
attach_file_button.visibility = View.GONE
send_button.visibility = View.VISIBLE
} else {
attach_file_button.visibility = View.VISIBLE
attach_photo_button.visibility = View.VISIBLE
send_button.visibility = View.GONE
}
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.send_button -> {
sendTextMessage()
}
R.id.attach_photo_button -> {
onClickAttachPhotoButton()
}
R.id.gallery_hide_button -> {
hideGallery()
}
R.id.gallery_block -> {
hideGallery()
}
R.id.gallery_send_button -> {
sendImageMessage()
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.messages_manipulation_menu, menu)
val closeMenuItem = menu?.findItem(R.id.close_item)
addMenuItem(closeMenuItem)
val replyMenuItem = menu?.findItem(R.id.reply_item)
addMenuItem(replyMenuItem)
val forwardMenuItem = menu?.findItem(R.id.forward_item)
addMenuItem(forwardMenuItem)
val deleteMenuItem = menu?.findItem(R.id.delete_item)
addMenuItem(deleteMenuItem)
hideMenu()
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.close_item -> {
closeMessagesMenuItemHandler()
return true
}
R.id.reply_item -> {
replyMessages()
return true
}
R.id.forward_item -> {
return true
}
R.id.delete_item -> {
deleteMessagesMenuItemHandler()
return true
}
else -> {
return super.onOptionsItemSelected(item)
}
}
}
fun isOwnMessage(message: Message): Boolean {
return message.senderUId.equals(currentUser?.userId)
}
fun setTitleToolbar(title: String) {
supportActionBar?.title = title
}
fun addMenuItem(menuItem: MenuItem?) {
if (menuItem != null) {
menuItemsList.add(menuItem)
}
}
fun hideMenu() {
menuItemsList.forEach {
it.setVisible(false)
}
}
fun showMenu() {
menuItemsList.forEach {
it.setVisible(true)
}
}
fun sendTextMessage() {
val text = message_text.text.toString()
message_text.setText("")
packUpMessageAndSend(text = text)
}
fun packUpMessageAndSend(
text: String = "", imageUrl: String = "", fileUrl: String = "",
senderUId: String = currentUser?.userId ?: "", recipientUId: String = companion?.userId ?: ""
) {
if (companion != null && currentUser != null) {
val date = getDateString(Date(), FULL_DATE_PATTERN)
val message = Message(
senderUId = senderUId,
recipientUId = recipientUId,
text = text,
imageUrl = imageUrl,
fileUrl = fileUrl,
date = date
)
sendMessage(message)
}
}
fun sendMessage(message: Message) {
if (chatKey != null) {
addMessage(message)
} else {
createChat(message)
}
}
fun deleteMessagesMenuItemHandler() {
val key = chatKey
if (key != null) {
val reference = FirebaseDatabase.getInstance().reference.child("SinglesChats").child(key).child("Messages")
var decrement = 0
checkedMessagesList.forEach {
if (isOwnMessage(it)) {
if (!it.imageUrl.equals("")) {
deletePhotoFromStorageByUrl(it.imageUrl)
}
reference.child(it.messageKey).removeValue()
if (!it.isRead) {
decrement++
}
} else {
reference.child(it.messageKey).child("isShowOnlyForSender").setValue(true)
}
}
if (decrement > 0) {
decrementUnreadMessages(decrement)
}
}
hideMessagesManipulationSettings()
}
fun deletePhotoFromStorageByUrl(photoUrl: String) {
val mStorageReference = FirebaseStorage.getInstance().getReferenceFromUrl(photoUrl)
mStorageReference.delete()
}
fun closeMessagesMenuItemHandler() {
hideMessagesManipulationSettings()
checkedMessagesList.clear()
resetCheckedOrNotMessagesList()
notifyDataSetChanged()
}
fun addMessage(message: Message) {
val mUserId = currentUser?.userId as String
val mCompanionId = companionId as String
val mChatKey = chatKey as String
val reference = databaseReference.child("SinglesChats").child(mChatKey).child("Messages").push()
val messageKey = reference.key
message.messageKey = messageKey ?: ""
incrementUnreadMessages()
reference.setValue(message.toMap())
val usersId: Array<String> = arrayOf(mUserId, mCompanionId)
setSameLastMessageForAll(usersId, message)
}
fun replyMessages() {
checkedMessagesList.forEach {
packUpMessageAndSend(
text = it.text,
imageUrl = it.imageUrl,
fileUrl = it.fileUrl,
recipientUId = it.recipientUId
)
}
}
fun setChatProperties(chatKey: String, usersId: Array<String>, allMessages: Array<Message>) {
val messages = getLastMessageForAll(usersId, allMessages)
setLastMessageForAll(usersId, messages)
resetUnreadMessagesAmountForCurrentUser()
}
fun setSameLastMessageForAll(usersId: Array<String>, message: Message) {
for (id in usersId) {
var mCompanionId: String;
if (id.equals(message.recipientUId)) {
mCompanionId = message.senderUId
} else {
mCompanionId = message.recipientUId
}
setLastMessage(id, mCompanionId, message)
}
}
fun setLastMessageForAll(usersId: Array<String>, messages: Array<Message>) {
setLastMessage(usersId[0], usersId[1], messages[0])
setLastMessage(usersId[1], usersId[0], messages[1])
}
fun setLastMessage(currentUserId: String, companionId: String, message: Message) {
databaseReference.child("Users").child(currentUserId).child("ChatInfoBlocks")
.child(companionId).child("lastMessage").setValue(message.toMap())
}
fun getLastMessageForAll(usersId: Array<String>, messages: Array<Message>): Array<Message> {
val lastMessages = Array<Message>(usersId.size, { Message(isRead = true) })
val states = Array<Boolean>(usersId.size, { false })
val upperMessageIndex = messages.size - 1
for (messageIndex in upperMessageIndex downTo 0) {
for (userIdIndex in 0 until usersId.size) {
if (!states[userIdIndex] && isMessageOwnedByUser(usersId[userIdIndex], messages[messageIndex])) {
lastMessages[userIdIndex] = messages[messageIndex]
states[userIdIndex] = true
}
}
if (isLastMessagesToPack(states)) {
break
}
}
return lastMessages
}
fun isLastMessagesToPack(states: Array<Boolean>): Boolean {
states.forEach {
if (it == false) {
return false
}
}
return true
}
fun isMessageDontOwnedByUser(userId: String, message: Message): Boolean {
val isSender = message.senderUId.equals(userId)
return !isSender && message.isShowOnlyForSender
}
fun isMessageOwnedByUser(userId: String, message: Message): Boolean {
return !isMessageDontOwnedByUser(userId, message)
}
fun incrementUnreadMessages(i: Int = 1) {
val mCompanionId = companionId as String
val mCurrentUserId = currentUser?.userId as String
databaseReference.child("Users").child(mCompanionId).child("ChatInfoBlocks")
.child(mCurrentUserId).child("unReadMessagesAmount")
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var amount = dataSnapshot.getValue(Int::class.java) as Int
amount += i
setUnreadMessagesAmount(mCompanionId, mCurrentUserId, amount)
}
override fun onCancelled(databaseError: DatabaseError) {
}
});
}
fun decrementUnreadMessages(i: Int = 1) {
val mCompanionId = companionId as String
val mCurrentUserId = currentUser?.userId as String
databaseReference.child("Users").child(mCompanionId).child("ChatInfoBlocks")
.child(mCurrentUserId).child("unReadMessagesAmount")
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var amount = dataSnapshot.getValue(Int::class.java) as Int
amount -= i
setUnreadMessagesAmount(mCompanionId, mCurrentUserId, amount)
}
override fun onCancelled(databaseError: DatabaseError) {
}
});
}
fun setUnreadMessagesAmount(currentUserId: String, companionId: String, amount: Int) {
databaseReference.child("Users").child(currentUserId).child("ChatInfoBlocks")
.child(companionId).child("unReadMessagesAmount").setValue(amount)
}
fun createChatInfoBlockForParticipants(chatKey: String, currentUser: User, companion: User) {
val currentUserChatInfoBlock = ChatInfoBlock(
companionProfilePhotoUrl = companion.imageUrl,
currentUserProfilePhotoUrl = currentUser.imageUrl,
companionUserName = companion.username,
chatKey = chatKey,
companionId = companion.userId
)
val companionChatInfoBlock = ChatInfoBlock(
companionProfilePhotoUrl = currentUser.imageUrl,
currentUserProfilePhotoUrl = companion.imageUrl,
companionUserName = currentUser.username,
chatKey = chatKey,
companionId = currentUser.userId
)
createChatInfoBlockForUser(currentUserChatInfoBlock, currentUser.userId, companion.userId)
createChatInfoBlockForUser(companionChatInfoBlock, companion.userId, currentUser.userId)
}
fun createChatInfoBlockForUser(userChatInfoBlock: ChatInfoBlock, currentUserId: String, companionId: String) {
databaseReference.child("Users").child(currentUserId).child("ChatInfoBlocks").child(companionId)
.setValue(userChatInfoBlock.toMap())
}
fun createChat(message: Message) {
val reference = databaseReference.child("SinglesChats").push()
chatKey = reference.key
val participantsReference = reference.child("Participants")
val currentUserId = currentUser?.userId as String
val companionId = companion?.userId as String
participantsReference.child("participantA").setValue(currentUserId)
participantsReference.child("participantB").setValue(companionId)
databaseReference.child("Users").child(currentUserId).child("SinglesChats").push().child("chatKey")
.setValue(chatKey)
databaseReference.child("Users").child(companionId).child("SinglesChats").push().child("chatKey")
.setValue(chatKey)
val mChatKey = chatKey as String
val mCurrentUser = currentUser as User
val mCompanion = companion as User
createChatInfoBlockForParticipants(mChatKey, mCurrentUser, mCompanion)
addMessage(message)
}
fun readDatas(companionId: String) {
readCurrentUserData(companionId)
}
fun readChatKey() {
val currentUserId = currentUser?.userId
if (currentUserId != null) {
val reference = databaseReference.child("Users").child(currentUserId).child("SinglesChats")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
dataSnapshot.children.forEach {
val key = it.child("chatKey").getValue(String::class.java)
if (key != null) {
val mReference = databaseReference.child("SinglesChats").child(key).child("Participants")
val mValueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val participantAUId =
dataSnapshot.child("participantA").getValue(String::class.java)
val participantBUId =
dataSnapshot.child("participantB").getValue(String::class.java)
if ((participantAUId == companion?.userId && participantBUId == currentUser?.userId)
|| (participantBUId == companion?.userId && participantAUId == currentUser?.userId)
) {
chatKey = key
readMessages()
return
}
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
mReference.addValueEventListener(mValueEventListener)
addValueEventListener(mReference, mValueEventListener)
}
}
}
override fun onCancelled(dataSnapshot: DatabaseError) {
}
}
reference.addValueEventListener(valueEventListener)
addValueEventListener(reference, valueEventListener)
}
}
fun readCurrentUserData(companionId: String) {
val currentUserId = FirebaseAuth.getInstance().currentUser?.uid
if (currentUserId != null) {
val reference = databaseReference.child("Users").child(currentUserId).child("UserInfo")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
currentUser = dataSnapshot.getValue(User::class.java)
readCompanionData(companionId)
}
override fun onCancelled(dataSnapshot: DatabaseError) {
}
}
reference.addValueEventListener(valueEventListener)
addValueEventListener(reference, valueEventListener)
}
}
fun readCompanionData(companionId: String) {
val reference = databaseReference.child("Users").child(companionId).child("UserInfo")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
companion = dataSnapshot.getValue(User::class.java)
username.text = companion?.username
email.text = companion?.email
Glide.with(this@SingleChatActivity).load(companion?.imageUrl)
.placeholder(R.drawable.placeholder_avatar)
.into(profile_photo)
readChatKey()
}
override fun onCancelled(dataSnapshot: DatabaseError) {
}
}
reference.addValueEventListener(valueEventListener)
addValueEventListener(reference, valueEventListener)
}
fun readMessages() {
val mChatKey = chatKey as String
val mCompanionId = companion?.userId as String
val mCurrentUserId = currentUser?.userId as String
val reference = databaseReference.child("SinglesChats").child(mChatKey).child("Messages")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val allMessages = ArrayList<Message>()
messagesList.clear()
checkedMessagesList.clear()
checkedOrNotMessagesList.clear()
userProfilePhotos.clear()
dataSnapshot.children.forEach {
val message = it.getValue(Message::class.java) as Message
allMessages.add(message)
if (isMessageShow(message)) {
val senderUId = message.senderUId
if (!userProfilePhotos.containsKey(senderUId)) {
userProfilePhotos.put(senderUId, "")
}
if (message.senderUId == mCompanionId && !message.isRead) {
setAsReadMessage(message)
}
messagesList.add(message)
checkedOrNotMessagesList.add(false)
}
}
val usersId = arrayOf(mCurrentUserId, mCompanionId)
setChatProperties(mChatKey, usersId, allMessages.toTypedArray())
readSenderProfilePhotoUrls()
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
reference.addValueEventListener(valueEventListener)
addValueEventListener(reference, valueEventListener)
}
fun readSenderProfilePhotoUrls() {
if(userProfilePhotos.isEmpty()){
empty_content_warning.visibility = View.VISIBLE
messages_progress_bar.visibility = View.GONE
return
}
userProfilePhotos.forEach {
getSenderProfilePhotoUrl(it.key)
}
}
fun getSenderProfilePhotoUrl(userId: String) {
databaseReference.child("Users").child(userId).child("UserInfo").child("imageUrl")
.addListenerForSingleValueEvent(
object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val imageUrl = dataSnapshot.getValue(String::class.java) as String
userProfilePhotos.set(userId, imageUrl)
if (isSenderProfilePhotoUrlPackUp()) {
notifyDataSetChanged()
}
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
)
}
fun isSenderProfilePhotoUrlPackUp(): Boolean {
val values = userProfilePhotos.values
values.forEach {
if (it.equals("")) {
return false
}
}
return true
}
fun setAsReadMessage(message: Message) {
val key = chatKey
if (key != null) {
databaseReference.child("SinglesChats").child(key).child("Messages")
.child(message.messageKey)
.child("isRead").setValue(true)
}
}
fun resetUnreadMessagesAmountForCurrentUser() {
val mCurrentUserId = currentUser?.userId as String
val mCompanionId = companionId as String
setUnreadMessagesAmount(mCurrentUserId, mCompanionId, 0)
}
fun isMesssageDontShow(message: Message): Boolean {
return !isOwnMessage(message) && message.isShowOnlyForSender
}
fun isMessageShow(message: Message): Boolean {
return !isMesssageDontShow(message)
}
fun notifyDataSetChanged() {
messages_progress_bar.visibility = View.GONE
empty_content_warning.visibility = View.GONE
messagesAdapter =
MessagesAdapter(this, messagesList, checkedMessagesList, checkedOrNotMessagesList, userProfilePhotos)
messages_recycler.adapter = messagesAdapter
}
fun addValueEventListener(reference: DatabaseReference, valueEventListener: ValueEventListener) {
referencesOnValuesEventsListenersList.add(reference)
valuesEventsListenersList.add(valueEventListener)
}
fun stopValueEventListener() {
for (index in 0 until referencesOnValuesEventsListenersList.size) {
referencesOnValuesEventsListenersList[index].removeEventListener(valuesEventsListenersList[index])
}
referencesOnValuesEventsListenersList.clear()
valuesEventsListenersList.clear()
}
fun resetCheckedOrNotMessagesList() {
for (index in 0 until checkedOrNotMessagesList.size) {
checkedOrNotMessagesList[index] = false
}
}
override fun onCheckMessage() {
if (checkedMessagesList.isNotEmpty()) {
if (!messagesManipulationSettingsIsVisible) {
showMessagesManipulationSettings()
}
setTitleToolbar(checkedMessagesList.size.toString())
} else {
if (messagesManipulationSettingsIsVisible) {
hideMessagesManipulationSettings()
}
}
}
fun showMessagesManipulationSettings() {
messagesManipulationSettingsIsVisible = true
showMenu()
companion_header.visibility = View.GONE
}
fun hideMessagesManipulationSettings() {
messagesManipulationSettingsIsVisible = false
hideMenu()
companion_header.visibility = View.VISIBLE
}
///////////////////////////////////////////////////////////////////////////////////////
fun checkPermissionForGetImages() {
if (isPermissionAccess(Manifest.permission.READ_EXTERNAL_STORAGE)) {
showImagesList();
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
PERMISSION_READ_EXTERNAL_STORAGE
);
}
}
fun isPermissionAccess(permissions: String): Boolean {
return ContextCompat.checkSelfPermission(this, permissions) == PackageManager.PERMISSION_GRANTED
}
private fun showImagesList() {
imagesList = getAllImagesFromDevice()
val imagesAdapter = ImagesAdapter(this, imagesList)
gallery.setAdapter(imagesAdapter)
showGallery()
}
private fun getAllImagesFromDevice(): MutableList<ImageData> {
val imagesList = ArrayList<ImageData>()
val uri: Uri
val cursor: Cursor?
val column_index: Int
var path: String? = null
val sortOrder: String
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(MediaStore.MediaColumns.DATA)
sortOrder = MediaStore.Images.ImageColumns.DATE_ADDED + " DESC"
val permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
1
)
}
cursor = this.contentResolver.query(uri, projection, null, null, sortOrder)
try {
if (null != cursor) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
while (cursor.moveToNext()) {
path = cursor.getString(column_index)
val imageData = ImageData(path)
imagesList.add(imageData)
}
cursor.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
return imagesList
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSION_READ_EXTERNAL_STORAGE -> {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
showImagesList()
} else {
Toast.makeText(this, "This app do not have access to storage!!!", Toast.LENGTH_LONG).show()
}
}
}
}
fun onClickAttachPhotoButton() {
checkPermissionForGetImages()
}
fun showGallery() {
gallery_block.visibility = View.VISIBLE
val showBottomSheetAnimation = AnimationUtils.loadAnimation(
this, R.anim.gallery_show
)
val appearGalleryBlockAnimation = AnimationUtils.loadAnimation(
this, R.anim.gallery_block_appear
)
gallery_block.startAnimation(appearGalleryBlockAnimation)
bottom_sheet.startAnimation(showBottomSheetAnimation)
}
fun hideGallery() {
val hideBottomSheetAnimation = AnimationUtils.loadAnimation(
this, R.anim.gallery_hide
)
val fadeGalleryBlockAnimation = AnimationUtils.loadAnimation(
this, R.anim.gallery_block_fade
)
fadeGalleryBlockAnimation.setAnimationListener(
object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
gallery_block.visibility = View.GONE
hideButton()
}
}
)
gallery_block.startAnimation(fadeGalleryBlockAnimation)
bottom_sheet.startAnimation(hideBottomSheetAnimation)
}
fun sendImageMessage() {
hideGallery()
imagesList.forEach {
if (it.isCheck) {
val imageUri = Uri.fromFile(File(it.imagePath))
if (imageUri != null) {
uploadAndSendImage(imageUri)
}
}
}
}
fun getFileExtension(uri: Uri): String {
val uriParts = uri.toString().split('.')
val fileExtension = uriParts[uriParts.size - 1]
Log.d("ryu", fileExtension.toString())
return fileExtension
}
fun uploadAndSendImage(imageUri: Uri?) {
val mImageUri = imageUri
if (mImageUri != null) {
val fileName = System.currentTimeMillis().toString() + "." + getFileExtension(mImageUri)
val fileReference = FirebaseStorage.getInstance().reference.child("messageImages").child(fileName)
val mUploadTask = fileReference.putFile(mImageUri)
mUploadTask.addOnSuccessListener(
object : OnSuccessListener<UploadTask.TaskSnapshot> {
override fun onSuccess(taskSnapshot: UploadTask.TaskSnapshot?) {
if (taskSnapshot?.metadata != null) {
if (taskSnapshot.metadata?.reference != null) {
val result = taskSnapshot.storage.downloadUrl
result.addOnSuccessListener(
object : OnSuccessListener<Uri> {
override fun onSuccess(uri: Uri?) {
val downloadUrl = uri.toString()
packUpMessageAndSend(imageUrl = downloadUrl)
}
});
}
}
}
}
)
}
}
override fun showButton() {
gallery_send_button.visibility = View.VISIBLE
gallery_hide_button.visibility = View.GONE
}
override fun hideButton() {
gallery_send_button.visibility = View.GONE
gallery_hide_button.visibility = View.VISIBLE
ImageData.resetNumber()
}
}
<file_sep>/app/src/main/java/com/romanyu/chat/ImageActivity.kt
package com.romanyu.chat
import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.android.synthetic.main.activity_image.*
class ImageActivity : AppCompatActivity() {
companion object {
val IMAGE_URL = "IMAGE_URL"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image)
toolbar.setPadding(0, getStatusBarHeight(), 0, 0)
setSupportActionBar(toolbar)
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
val imageUrl = intent.extras.getString(IMAGE_URL)
loadingImage(imageUrl)
}
fun loadingImage(imageUrl: String) {
Glide.with(this)
.load(imageUrl)
.into(image_container)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
finish()
}
}
return true
}
fun getStatusBarHeight() : Int{
val height: Int
val heightId = resources.getIdentifier(
"status_bar_height",
"dimen",
"android"
)
height = resources.getDimensionPixelSize(heightId)
return height
}
}
<file_sep>/app/src/main/java/com/romanyu/chat/MainActivity.kt
package com.romanyu.chat
import android.app.Activity
import android.content.ContentResolver
import android.content.Intent
import android.content.res.ColorStateList
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.webkit.MimeTypeMap
import android.widget.Button
import android.widget.Toast
import com.bumptech.glide.Glide
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.google.firebase.storage.*
import com.romanyu.chat.UserUtil.ChatInfoBlock
import com.romanyu.chat.UserUtil.User
import com.romanyu.chat.adapters.ChatsAdapter
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.nav_header.view.*
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
lateinit var headerView: View
var searchMenuItem: MenuItem? = null
var closeMenuItem: MenuItem? = null
var user: User? = null
lateinit var databaseReference: DatabaseReference
val chatsList: MutableList<ChatInfoBlock> = ArrayList<ChatInfoBlock>()
val valuesEventsListenersList: MutableList<ValueEventListener> = java.util.ArrayList<ValueEventListener>()
val referencesOnValuesEventsListenersList: MutableList<DatabaseReference> = java.util.ArrayList<DatabaseReference>()
lateinit var chatsAdapter: ChatsAdapter
companion object {
val IMAGE_REQUEST = 0
}
lateinit var storageReference: StorageReference
var imageUri : Uri? = null
var uploadTask : UploadTask? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
databaseReference = FirebaseDatabase.getInstance().reference
storageReference = FirebaseStorage.getInstance().reference
setSupportActionBar(toolbar)
val toogle: ActionBarDrawerToggle = ActionBarDrawerToggle(
this,
drawer,
toolbar,
R.string.nav_open_drawer,
R.string.nav_close_drawer
)
drawer.addDrawerListener(toogle)
toogle.syncState()
nav_view.setNavigationItemSelectedListener(this)
headerView = LayoutInflater.from(this).inflate(R.layout.nav_header, null)
headerView.camera_button.setOnClickListener(this)
nav_view.addHeaderView(headerView)
chatsAdapter = ChatsAdapter(this, chatsList)
val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
chats_recycler.adapter = chatsAdapter
chats_recycler.layoutManager = linearLayoutManager
}
override fun onStart() {
super.onStart()
readDatas()
}
override fun onStop() {
stopValueEventListener()
super.onStop()
}
override fun onClick(v: View?) {
when(v?.id){
R.id.camera_button -> {
openImage()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val mUploadTask = uploadTask
if(requestCode == IMAGE_REQUEST && resultCode == Activity.RESULT_OK
&& data != null && data.data != null){
imageUri = data.data
if(mUploadTask != null && mUploadTask.isInProgress){
Toast.makeText(this, "Upload in progress", Toast.LENGTH_LONG).show()
}else{
uploadImage()
}
}
}
fun openImage(){
val intent = Intent()
intent.setType("image/*")
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(intent, IMAGE_REQUEST)
}
fun getFileExtension(uri: Uri) : String{
val contentResolver = this.contentResolver
val mimeTypeMap = MimeTypeMap.getSingleton()
return mimeTypeMap.getExtensionFromMimeType(contentResolver?.getType(uri)) as String
}
fun uploadImage(){
val mImageUri = imageUri
if(mImageUri != null){
val fileName = System.currentTimeMillis().toString() + "." + getFileExtension(mImageUri)
val fileReference = storageReference.child("avatarPhoto").child(fileName)
uploadTask = fileReference.putFile(mImageUri)
val mUploadTask = uploadTask
mUploadTask?.addOnSuccessListener(
object : OnSuccessListener<UploadTask.TaskSnapshot>{
override fun onSuccess(taskSnapshot: UploadTask.TaskSnapshot?) {
if (taskSnapshot?.metadata != null) {
if (taskSnapshot.metadata?.reference != null) {
val result = taskSnapshot.storage.downloadUrl
result.addOnSuccessListener(
object : OnSuccessListener<Uri> {
override fun onSuccess(uri: Uri?) {
val downloadUrl = uri.toString()
val mUser = user as User
deletePhotoFromStorageByUrl(mUser.imageUrl)
val map : HashMap<String, Any> = HashMap()
map.put("imageUrl",downloadUrl)
val reference = databaseReference.child("Users").child(mUser.userId)
.child("UserInfo")
reference.updateChildren(map)
rewritePhotoUrl(downloadUrl)
}
});
}
}
}
}
)
}
}
fun deletePhotoFromStorageByUrl(photoUrl: String){
val mStorageReference = FirebaseStorage.getInstance().getReferenceFromUrl(photoUrl)
mStorageReference.delete()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.search_menu, menu)
searchMenuItem = menu?.findItem(R.id.search_item)
searchMenuItem?.setVisible(true)
closeMenuItem = menu?.findItem(R.id.close_item)
closeMenuItem?.setVisible(false)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.search_item -> {
search_text.visibility = View.VISIBLE
searchMenuItem?.setVisible(false)
closeMenuItem?.setVisible(true)
search_text.requestFocus()
return true
}
R.id.close_item -> {
search_text.setText("")
return true
}
else -> {
return super.onOptionsItemSelected(item)
}
}
}
override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
when (menuItem.itemId) {
R.id.create_single_chat -> {
val intent = Intent(this, SearchUserActivity::class.java)
startActivity(intent)
}
R.id.sign_out ->{
FirebaseAuth.getInstance().signOut()
val intent = Intent(this, SignInActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
}
return true
}
override fun onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
fun readDatas() {
readUserInfo()
}
fun readUserInfo() {
val currentUserId = FirebaseAuth.getInstance().currentUser?.uid as String
val reference = databaseReference.child("Users").child(currentUserId).child("UserInfo")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
user = dataSnapshot.getValue(User::class.java)
headerView.username.text = user?.username
headerView.email.text = user?.email
Glide.with(this@MainActivity)
.load(user?.imageUrl)
.placeholder(R.drawable.placeholder_avatar)
.into(headerView.profile_photo)
headerView.loading_block.visibility = View.GONE
headerView.user_info_block.visibility = View.VISIBLE
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
reference.addValueEventListener(valueEventListener)
addValueEventListener(reference, valueEventListener)
readChats(currentUserId)
}
fun readChats(currentUserId: String) {
val reference = databaseReference.child("Users").child(currentUserId).child("ChatInfoBlocks")
val valueEventListener = object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot) {
chatsList.clear()
dataSnapshot.children.forEach {
val chatInfoBlock = it.getValue(ChatInfoBlock::class.java) as ChatInfoBlock
chatsList.add(chatInfoBlock)
}
notifyDataSetChanged()
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
reference.addValueEventListener(valueEventListener)
addValueEventListener(reference, valueEventListener)
}
fun addValueEventListener(reference: DatabaseReference, valueEventListener: ValueEventListener) {
referencesOnValuesEventsListenersList.add(reference)
valuesEventsListenersList.add(valueEventListener)
}
fun stopValueEventListener() {
for (index in 0 until referencesOnValuesEventsListenersList.size) {
referencesOnValuesEventsListenersList[index].removeEventListener(valuesEventsListenersList[index])
}
referencesOnValuesEventsListenersList.clear()
valuesEventsListenersList.clear()
}
fun notifyDataSetChanged() {
if(chatsList.isEmpty()){
empty_content_warning.visibility = View.VISIBLE
}else{
empty_content_warning.visibility = View.GONE
}
chats_progress_bar.visibility = View.GONE
chatsAdapter = ChatsAdapter(this, chatsList)
chats_recycler.adapter = chatsAdapter
}
fun rewritePhotoUrl(photoUrl: String){
val currentUserId = user?.userId as String
val companionsIdList = ArrayList<String>()
chatsList.forEach {
companionsIdList.add(it.companionId)
}
rewriteAllPhotoUrlInChatInfoBlocks(photoUrl, currentUserId, companionsIdList)
}
fun rewriteAllPhotoUrlInChatInfoBlocks(photoUrl: String, userId: String, companionsIdList: ArrayList<String>){
companionsIdList.forEach {
rewritePhotoUrlForChat(photoUrl, userId, it)
}
}
fun rewritePhotoUrlForChat(photoUrl: String, userId: String, companionId: String){
val mapForCurrentUser : HashMap<String, Any> = HashMap()
mapForCurrentUser.put("currentUserProfilePhotoUrl",photoUrl)
databaseReference.child("Users").child(userId).child("ChatInfoBlocks")
.child(companionId).updateChildren(mapForCurrentUser)
val mapForCompanion : HashMap<String, Any> = HashMap()
mapForCompanion.put("companionProfilePhotoUrl",photoUrl)
databaseReference.child("Users").child(companionId).child("ChatInfoBlocks")
.child(userId).updateChildren(mapForCompanion)
}
}
<file_sep>/app/src/main/java/com/romanyu/chat/SignInActivity.kt
package com.romanyu.chat
import android.content.Context
import com.romanyu.chat.authUtil.*
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TextInputLayout
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentManager
import android.support.v7.widget.Toolbar
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.FirebaseApp
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.FirebaseDatabase
import com.romanyu.chat.dialog.VerifyEmailDialog
import kotlinx.android.synthetic.main.activity_sign_in.*
class SignInActivity : AppCompatActivity(), View.OnClickListener,TextWatcher {
val IS_ERROR_TEXT_VIEW_VISIBLE:String = "IS_ERROR_TEXT_VIEW_VISIBLE"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
val user:FirebaseUser? = FirebaseAuth.getInstance().currentUser
if(user != null){
if(isEmailVerify()){
signInCompleted(this)
}else{
FirebaseDatabase.getInstance().reference.child("Users").child(user.uid).child("UserInfo").removeValue()
user.delete()
}
}
val toolbar:Toolbar? = findViewById(R.id.toolbar) as? Toolbar
setSupportActionBar(toolbar)
sign_in_button.setOnClickListener(this)
sign_up_button.setOnClickListener(this)
forgot_password_button.setOnClickListener(this)
email_edit_text.addTextChangedListener(this)
password_edit_text.addTextChangedListener(this)
}
override fun onStart() {
super.onStart()
error_text.visibility = View.GONE
progress_bar.visibility = View.GONE
}
override fun onSaveInstanceState(outState: Bundle?) {
val isErrorTextViewVisisble = error_text.visibility == View.VISIBLE
outState?.putBoolean(IS_ERROR_TEXT_VIEW_VISIBLE,isErrorTextViewVisisble)
super.onSaveInstanceState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
if(savedInstanceState != null) {
val isErrorTextViewVisible = savedInstanceState.getBoolean(IS_ERROR_TEXT_VIEW_VISIBLE)
if(isErrorTextViewVisible){
error_text.visibility = View.VISIBLE
}
}
}
override fun onClick(v: View?) {
when(v?.id){
R.id.sign_in_button ->{
signInButtonListener()
}
R.id.sign_up_button ->{
val intent = Intent(this,SignUpActivity::class.java)
startActivity(intent)
}
R.id.forgot_password_button ->{
val intent = Intent(this,ResetPasswordActivity::class.java)
startActivity(intent)
}
}
}
private fun signInButtonListener(){
val email = email_edit_text.text.toString()
val password = password_edit_text.text.toString()
val isValidEmail = isValidEmail(email)
val isValidPassword = isValidPassword(password)
if(isValidEmail && isValidPassword){
email_input.error = null
password_input.error = null
signInWithEmailAndPassword(email,password)
}else{
if(!isValidEmail){
email_input.error = resources.getString(R.string.invalid_email)
}else{
email_input.error = null
}
if(!isValidPassword){
password_input.error = resources.getString(R.string.invalid_password)
}else{
password_input.error = null
}
}
}
private fun signInWithEmailAndPassword(email:String,password:String) {
progress_bar.visibility = View.VISIBLE
val mAuth = FirebaseAuth.getInstance()
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener{
task -> if(task.isSuccessful){
progress_bar.visibility = View.GONE
signInCompleted(this)
}else{
progress_bar.visibility = View.GONE
error_text.visibility = View.VISIBLE
}
}
}
override fun afterTextChanged(s: Editable?) {
sign_in_button.isEnabled = email_edit_text.text.toString().isNotEmpty() && password_edit_text.text.toString().isNotEmpty()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
}
<file_sep>/app/src/main/java/com/romanyu/chat/UserUtil/User.kt
package com.romanyu.chat.UserUtil
import com.google.firebase.database.Exclude
import com.google.firebase.database.IgnoreExtraProperties
@IgnoreExtraProperties
data class User(
val username:String = "",
val email:String = "",
val imageUrl:String = "https://firebasestorage.googleapis.com/v0/b/chat-73ee2.appspot.com/o/placeholder_avatar.jpg?alt=media&token=<PASSWORD>",
val userId:String = ""
) {
@Exclude
fun toMap(): Map<String, Any> {
return mapOf(
"username" to username,
"email" to email,
"imageUrl" to imageUrl,
"userId" to userId
)
}
}<file_sep>/app/src/main/java/com/romanyu/chat/adapters/UsersAdapter.kt
package com.romanyu.chat.adapters
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.firebase.auth.FirebaseAuth
import com.romanyu.chat.R
import com.romanyu.chat.SingleChatActivity
import com.romanyu.chat.UserUtil.User
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.synthetic.main.profile_item.view.*
class UsersAdapter(
val context: Context,
val usersList: MutableList<User>
) : RecyclerView.Adapter<UsersAdapter.ViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.profile_item, viewGroup, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return usersList.size
}
override fun onBindViewHolder(viewHolder: ViewHolder, index: Int) {
val user = usersList[index]
if(index == usersList.size - 1){
viewHolder.bottomOutline.visibility = View.GONE
}else{
viewHolder.bottomOutline.visibility = View.VISIBLE
}
viewHolder.usernameTextView.text = user.username
viewHolder.emailTextView.text = user.email
Glide.with(context).load(user.imageUrl).placeholder(R.drawable.placeholder_avatar)
.into(viewHolder.profileImageView)
viewHolder.itemView.setOnClickListener {
val intent = Intent(context,SingleChatActivity::class.java)
val bundle = Bundle()
bundle.putString(SingleChatActivity.COMPANION_USER_ID,user.userId)
intent.putExtras(bundle)
context.startActivity(intent)
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val profileImageView: CircleImageView
val usernameTextView: TextView
val emailTextView: TextView
val bottomOutline: View
init {
profileImageView = view.profile_photo
usernameTextView = view.username
emailTextView = view.email
bottomOutline = view.bottom_outline
}
}
}<file_sep>/app/src/main/java/com/romanyu/chat/UserUtil/ChatInfoBlock.kt
package com.romanyu.chat.UserUtil
import com.google.firebase.database.Exclude
import com.google.firebase.database.IgnoreExtraProperties
@IgnoreExtraProperties
data class ChatInfoBlock(
var companionProfilePhotoUrl:String = "",
var currentUserProfilePhotoUrl:String = "",
var companionUserName:String = "",
var lastMessage:Message = Message(),
var unReadMessagesAmount:Int = 0,
var chatKey:String = "",
var companionId: String = ""
) {
@Exclude
fun toMap() : Map<String, Any>{
return mapOf(
"companionProfilePhotoUrl" to companionProfilePhotoUrl,
"currentUserProfilePhotoUrl" to currentUserProfilePhotoUrl,
"companionUserName" to companionUserName,
"lastMessage" to lastMessage,
"unReadMessagesAmount" to unReadMessagesAmount,
"chatKey" to chatKey,
"companionId" to companionId
)
}
}<file_sep>/app/src/main/java/com/romanyu/chat/dialog/VerifyEmailDialog.kt
package com.romanyu.chat.dialog
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.auth.FirebaseAuth
import com.romanyu.chat.R
import com.romanyu.chat.authUtil.isEmailVerify
import kotlinx.android.synthetic.main.activity_sign_in.*
class VerifyEmailDialog : DialogFragment(), View.OnClickListener {
interface OnVerifyAndCancelListener {
fun onCancel()
fun onVerify()
}
private var verifyAndCancelListener: OnVerifyAndCancelListener? = null
private var errorTextView: TextView? = null
override fun onAttach(context: Context?) {
super.onAttach(context)
verifyAndCancelListener = context as OnVerifyAndCancelListener
}
override fun onStart() {
super.onStart()
progress_bar.visibility = View.GONE
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.verify_email_dialog, null)
errorTextView = view.findViewById(R.id.verify_error_text)
view.findViewById<Button>(R.id.verify_button).setOnClickListener(this)
view.findViewById<Button>(R.id.cancel_button).setOnClickListener(this)
dialog.window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.setCanceledOnTouchOutside(false)
return view
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.verify_button -> {
reloadAndVerifyEmail()
}
R.id.cancel_button -> {
verifyAndCancelListener?.onCancel()
}
}
}
fun reloadAndVerifyEmail() {
progress_bar.visibility = View.VISIBLE
val mUser = FirebaseAuth.getInstance().currentUser
mUser?.reload()?.addOnSuccessListener(
object : OnSuccessListener<Void> {
override fun onSuccess(mVoid: Void?) {
progress_bar.visibility = View.GONE
if (isEmailVerify()) {
verifyAndCancelListener?.onVerify()
} else {
errorTextView?.visibility = View.VISIBLE
}
}
}
)
}
}<file_sep>/app/src/main/java/com/romanyu/chat/dialog/ResetPasswordDialog.kt
package com.romanyu.chat.dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.romanyu.chat.R
class ResetPasswordDialog : DialogFragment(), View.OnClickListener {
interface OnOkListener{
fun onOk()
}
private lateinit var onOkListener: OnOkListener
override fun onAttach(context: Context?) {
super.onAttach(context)
onOkListener = context as OnOkListener
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.reset_password_dialog,null)
view.findViewById<Button>(R.id.ok_button).setOnClickListener(this)
dialog.window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.setCanceledOnTouchOutside(false)
return view
}
override fun onClick(v: View?) {
onOkListener.onOk()
dialog.dismiss()
}
}<file_sep>/app/src/main/java/com/romanyu/chat/adapters/MessagesAdapter.kt
package com.romanyu.chat.adapters
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.firebase.auth.FirebaseAuth
import com.romanyu.chat.ImageActivity
import com.romanyu.chat.R
import com.romanyu.chat.SingleChatActivity
import com.romanyu.chat.UserUtil.Message
import com.romanyu.chat.authUtil.FULL_DATE_PATTERN
import com.romanyu.chat.authUtil.TIME_DATE_PATTERN
import com.romanyu.chat.authUtil.getDateFromString
import com.romanyu.chat.authUtil.getDateString
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.synthetic.main.own_message_layout.view.*
class MessagesAdapter(
val context: Context,
val messagesList: MutableList<Message>,
val checkedMessagesList: MutableList<Message>,
val checkedOrNotMessagesList: MutableList<Boolean>,
val userProfilePhotos: HashMap<String, Any>
) : RecyclerView.Adapter<MessagesAdapter.ViewHolder>() {
val currentUserId: String
val checkableMessages: ICheckableMessages
val deleteMessagesPositions = ArrayList<Int>()
init {
currentUserId = FirebaseAuth.getInstance().currentUser?.uid as String
checkableMessages = context as ICheckableMessages
userProfilePhotos.forEach {
Log.d("ryu", "key - " + it.key + " value - " + it.value)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(viewType, viewGroup, false)
return ViewHolder(view, viewType)
}
override fun getItemCount(): Int {
return messagesList.size
}
override fun onBindViewHolder(viewHolder: ViewHolder, index: Int) {
val message = messagesList[index]
if(!message.imageUrl.equals("")){
viewHolder.setMessageImage(message.imageUrl)
}else if(!message.text.equals("")){
viewHolder.setMessageText(message.text)
}else{
}
val date = getDateStringForView(message.date)
viewHolder.dateTextView.text = date
val photoUrl = userProfilePhotos[message.senderUId]
Glide.with(context).load(photoUrl)
.placeholder(R.drawable.placeholder_avatar)
.into(viewHolder.profilePhotoView)
if (isOwnMessage(index) && !message.isRead) {
viewHolder.indicator?.visibility = View.VISIBLE
} else {
viewHolder.indicator?.visibility = View.GONE
}
if (checkedOrNotMessagesList[index]) {
setAsCheckMessage(viewHolder, index)
} else {
setAsUnCheckMessage(viewHolder, index)
}
}
fun getDateStringForView(dateString: String): String {
return getDateString(getDateFromString(dateString, FULL_DATE_PATTERN), TIME_DATE_PATTERN)
}
fun setAsCheckMessage(viewHolder: ViewHolder, index: Int) {
checkedOrNotMessagesList[index] = true
viewHolder.itemView.setBackgroundColor(context.resources.getColor(R.color.checked_message_background))
}
fun setAsUnCheckMessage(viewHolder: ViewHolder, index: Int) {
checkedOrNotMessagesList[index] = false
viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT)
}
fun onCheckMessage(viewHolder: ViewHolder, index: Int) {
if (checkedOrNotMessagesList[index]) {
setAsUnCheckMessage(viewHolder, index)
checkedMessagesList.remove(messagesList[index])
} else {
setAsCheckMessage(viewHolder, index)
checkedMessagesList.add(messagesList[index])
}
checkableMessages.onCheckMessage()
}
fun isOwnMessage(index: Int): Boolean {
return messagesList[index].senderUId == currentUserId
}
override fun getItemViewType(position: Int): Int {
if (isOwnMessage(position)) {
return R.layout.own_message_layout
} else {
return R.layout.companion_message_layout
}
}
inner class ViewHolder(view: View, viewType: Int) : RecyclerView.ViewHolder(view), View.OnClickListener,
View.OnLongClickListener {
val messageTextView: TextView
val dateTextView: TextView
val indicator: View?
val profilePhotoView: CircleImageView
val messageImageView: ImageView
init {
messageTextView = view.message_text
profilePhotoView = view.profile_photo
messageImageView = view.message_image
dateTextView = view.findViewById(R.id.date_text) as TextView
if (viewType == R.layout.own_message_layout) {
indicator = view.indicator
} else {
indicator = null
}
this.itemView.setOnClickListener(this)
this.itemView.setOnLongClickListener(this)
}
override fun onClick(v: View?) {
val message = messagesList[adapterPosition]
if (checkedMessagesList.isNotEmpty()) {
onCheckMessage(this, adapterPosition)
}else if(!message.imageUrl.equals("")){
showImage(message.imageUrl)
}
}
fun showImage(imageUrl: String){
val intent = Intent(context,ImageActivity::class.java)
intent.putExtra(ImageActivity.IMAGE_URL, imageUrl)
context.startActivity(intent)
}
override fun onLongClick(v: View?): Boolean {
onCheckMessage(this, adapterPosition)
return true
}
fun setMessageImage(url: String) {
messageTextView.visibility = View.GONE
messageImageView.visibility = View.VISIBLE
Glide.with(context).load(url)
.into(messageImageView)
}
fun setMessageText(text: String) {
messageImageView.visibility = View.GONE
messageTextView.visibility = View.VISIBLE
messageTextView.text = text
}
}
interface ICheckableMessages {
fun onCheckMessage()
}
}<file_sep>/app/src/main/java/com/romanyu/chat/adapters/ChatsAdapter.kt
package com.romanyu.chat.adapters
import android.content.Context
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.bumptech.glide.Glide
import com.romanyu.chat.R
import com.romanyu.chat.SingleChatActivity
import com.romanyu.chat.UserUtil.ChatInfoBlock
import com.romanyu.chat.authUtil.FULL_DATE_PATTERN
import com.romanyu.chat.authUtil.TIME_DATE_PATTERN
import com.romanyu.chat.authUtil.getDateFromString
import com.romanyu.chat.authUtil.getDateString
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.synthetic.main.chat_item.view.*
class ChatsAdapter(context: Context,chatsList: MutableList<ChatInfoBlock>) : RecyclerView.Adapter<ChatsAdapter.ChatView>() {
val chatsList : MutableList<ChatInfoBlock>
val context: Context
init {
this.context = context
this.chatsList = chatsList
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ChatView {
val view = LayoutInflater.from(context).inflate(R.layout.chat_item, viewGroup, false)
return ChatView(view)
}
override fun getItemCount(): Int {
return chatsList.size
}
override fun onBindViewHolder(chatView: ChatView, position: Int) {
val chatInfoBlock = chatsList[position]
var chatLastText = ""
if(!chatInfoBlock.lastMessage.text.equals("")){
chatLastText = chatInfoBlock.lastMessage.text
}else if(!chatInfoBlock.lastMessage.imageUrl.equals("")){
chatLastText = "Photo"
}else if(!chatInfoBlock.lastMessage.fileUrl.equals("")){
chatLastText = "File"
}else{
chatLastText = "You dont have messages history"
}
chatView.chatLastMessageView.text = chatLastText
chatView.companionUsernameView.text = chatInfoBlock.companionUserName
var timeText = ""
if(!chatInfoBlock.lastMessage.date.equals("")){
timeText = getDateStringForView(chatInfoBlock.lastMessage.date)
}
chatView.messageTimeView.text = timeText
if(chatInfoBlock.unReadMessagesAmount > 0){
chatView.howUnReadMessagesView.visibility = View.VISIBLE
chatView.howUnReadMessagesView.text = chatInfoBlock.unReadMessagesAmount.toString()
}else{
chatView.howUnReadMessagesView.visibility = View.GONE
}
Glide.with(context).load(chatInfoBlock.companionProfilePhotoUrl).placeholder(R.drawable.placeholder_avatar)
.into(chatView.companionProfilePhotoView)
if(chatInfoBlock.companionId.equals(chatInfoBlock.lastMessage.senderUId)){
chatView.currentUserProfilePhotoView.visibility = View.GONE
chatView.indicatorView.visibility = View.GONE
}else{
chatView.currentUserProfilePhotoView.visibility = View.VISIBLE
Glide.with(context).load(chatInfoBlock.currentUserProfilePhotoUrl).placeholder(R.drawable.placeholder_avatar)
.into(chatView.currentUserProfilePhotoView)
if(chatInfoBlock.lastMessage.isRead){
chatView.indicatorView.visibility = View.GONE
}else{
chatView.indicatorView.visibility = View.VISIBLE
}
}
chatView.itemView.setOnClickListener {
goIntoChat(chatsList[position].companionId)
}
var bottomOutlineVisibility: Int
if(position == chatsList.size - 1){
bottomOutlineVisibility = View.GONE
}else{
bottomOutlineVisibility = View.VISIBLE
}
chatView.bottomOutline.visibility = bottomOutlineVisibility
}
fun goIntoChat(companionId : String){
val intent = Intent(context, SingleChatActivity::class.java)
intent.putExtra(SingleChatActivity.COMPANION_USER_ID, companionId)
context.startActivity(intent)
}
fun getDateStringForView(dateString: String) : String{
return getDateString(getDateFromString(dateString, FULL_DATE_PATTERN), TIME_DATE_PATTERN)
}
class ChatView(view: View) : RecyclerView.ViewHolder(view){
val companionProfilePhotoView : CircleImageView;
val companionUsernameView : TextView;
val currentUserProfilePhotoView : CircleImageView;
val chatLastMessageView : TextView;
val messageTimeView : TextView
val howUnReadMessagesView : TextView;
val indicatorView: View
val bottomOutline: View
init {
companionProfilePhotoView = view.companion_profile_photo
companionUsernameView = view.companion_username
currentUserProfilePhotoView = view.current_user_profile_photo
chatLastMessageView = view.chat_last_message
messageTimeView = view.message_time
howUnReadMessagesView = view.how_message
indicatorView = view.indicator
bottomOutline = view.bottom_outline
}
}
}<file_sep>/app/src/main/java/com/romanyu/chat/SearchUserActivity.kt
package com.romanyu.chat
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.romanyu.chat.UserUtil.User
import com.romanyu.chat.adapters.UsersAdapter
import kotlinx.android.synthetic.main.activity_search_user.*
class SearchUserActivity : AppCompatActivity() {
var searchMenuItem: MenuItem? = null
var closeMenuItem: MenuItem? = null
lateinit var usersAdapter: UsersAdapter
val usersList: MutableList<User> = ArrayList<User>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search_user)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
usersAdapter = UsersAdapter(this, usersList)
val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
users_recycler.adapter = usersAdapter
users_recycler.layoutManager = linearLayoutManager
readUsersData()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.search_menu, menu)
searchMenuItem = menu?.findItem(R.id.search_item)
searchMenuItem?.setVisible(true)
closeMenuItem = menu?.findItem(R.id.close_item)
closeMenuItem?.setVisible(false)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
if (search_text.visibility == View.VISIBLE) {
search_text.visibility = View.GONE
closeMenuItem?.setVisible(false)
searchMenuItem?.setVisible(true)
return true
} else {
return super.onOptionsItemSelected(item)
}
}
R.id.search_item -> {
search_text.visibility = View.VISIBLE
searchMenuItem?.setVisible(false)
closeMenuItem?.setVisible(true)
search_text.requestFocus()
return true
}
R.id.close_item -> {
search_text.setText("")
return true
}
else -> {
return super.onOptionsItemSelected(item)
}
}
}
fun readUsersData() {
FirebaseDatabase.getInstance().reference.child("Users").addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
usersList.clear()
val currentUser = FirebaseAuth.getInstance().currentUser
dataSnapshot.children.forEach {
val user = it.child("UserInfo").getValue(User::class.java)
if (user != null && user.userId != currentUser?.uid) {
usersList.add(user)
}
}
usersAdapter.notifyDataSetChanged()
users_progress_bar.visibility = View.GONE
if(usersList.isEmpty()){
empty_content_warning.visibility = View.VISIBLE
}else{
empty_content_warning.visibility = View.GONE
}
}
override fun onCancelled(databaseError: DatabaseError) {
}
})
}
}
<file_sep>/app/src/main/java/com/romanyu/chat/UserUtil/Message.kt
package com.romanyu.chat.UserUtil
import com.google.firebase.database.Exclude
import com.google.firebase.database.IgnoreExtraProperties
@IgnoreExtraProperties
data class Message(
var messageKey:String = "",
val senderUId:String = "",
val recipientUId:String = "",
val imageUrl:String = "",
val fileUrl:String = "",
val text:String = "",
val date:String = "",
@field:JvmField
val isRead:Boolean = false,
@field:JvmField
val isShowOnlyForSender: Boolean = false
) {
@Exclude
fun toMap(): Map<String, Any> {
return mapOf(
"messageKey" to messageKey,
"senderUId" to senderUId,
"recipientUId" to recipientUId,
"imageUrl" to imageUrl,
"fileUrl" to fileUrl,
"text" to text,
"isRead" to isRead,
"isShowOnlyForSender" to isShowOnlyForSender,
"date" to date
)
}
}<file_sep>/app/src/main/java/com/romanyu/chat/SignUpActivity.kt
package com.romanyu.chat
import android.app.ActionBar
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TextInputLayout
import android.support.v4.app.DialogFragment
import android.support.v7.widget.Toolbar
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.romanyu.chat.UserUtil.User
import com.romanyu.chat.authUtil.*
import com.romanyu.chat.dialog.VerifyEmailDialog
import kotlinx.android.synthetic.main.activity_sign_up.*
class SignUpActivity : AppCompatActivity(), View.OnClickListener, TextWatcher,
VerifyEmailDialog.OnVerifyAndCancelListener {
val IS_ERROR_TEXT_VIEW_VISIBLE: String = "IS_ERROR_TEXT_VIEW_VISIBLE"
val IS_VERIFY_EMAIL_DIALOG_ERROR_TEXTVIEW_VISIBLE: String = "IS_VERIFY_EMAIL_DIALOG_ERROR_TEXTVIEW_VISIBLE"
var verifyEmailDialog: VerifyEmailDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_up)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
sign_up_button.setOnClickListener(this)
sign_in_button.setOnClickListener(this)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
username_edit_text.addTextChangedListener(this)
email_edit_text.addTextChangedListener(this)
password_edit_text.addTextChangedListener(this)
}
override fun onSaveInstanceState(outState: Bundle?) {
val isErrorTextViewVisisble = error_text.visibility == View.VISIBLE
outState?.putBoolean(IS_ERROR_TEXT_VIEW_VISIBLE, isErrorTextViewVisisble)
super.onSaveInstanceState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
if (savedInstanceState != null) {
val isErrorTextViewVisible = savedInstanceState.getBoolean(IS_ERROR_TEXT_VIEW_VISIBLE)
if (isErrorTextViewVisible) {
error_text.visibility = View.VISIBLE
}
}
}
override fun onStart() {
super.onStart()
error_text.visibility = View.GONE
progress_bar.visibility = View.GONE
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.sign_up_button -> {
signUpButtonListener()
}
R.id.sign_in_button -> {
signInButtonListener()
}
}
}
private fun signInButtonListener() {
val intent = Intent(this, SignInActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
}
private fun signUpButtonListener() {
val username = username_edit_text.text.toString().toLowerCase()
val email = email_edit_text.text.toString()
val password = password_edit_text.text.toString()
val isValidUsername = isValidUsername(username)
val isValidEmail = isValidEmail(email)
val isValidPassword = isValidPassword(password)
if (isValidEmail && isValidPassword && isValidUsername) {
progress_bar.visibility = View.VISIBLE
username_input.error = null
email_input.error = null
password_input.error = null
signUpWithEmailAndPassword(username, email, password)
} else {
if (!isValidUsername) {
username_input.error = resources.getString(R.string.invalid_username)
} else {
username_input.error = null
}
if (!isValidEmail) {
email_input.error = resources.getString(R.string.invalid_email)
} else {
email_input.error = null
}
if (!isValidPassword) {
password_input.error = resources.getString(R.string.invalid_password)
} else {
password_input.error = null
}
}
}
fun signUpWithEmailAndPassword(username: String, email: String, password: String) {
val mAuth = FirebaseAuth.getInstance()
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task ->
if (task.isSuccessful) {
progress_bar.visibility = View.GONE
val user = User(
username = username,
email = email,
userId = FirebaseAuth.getInstance().currentUser?.uid ?: ""
)
FirebaseDatabase.getInstance().reference.child("Users").child(user.userId).child("UserInfo").setValue(user.toMap())
verifyEmailDialog = VerifyEmailDialog()
sendEmailVerification()
} else {
progress_bar.visibility = View.GONE
error_text.visibility = View.VISIBLE
}
}
}
fun sendEmailVerification() {
val mUser = FirebaseAuth.getInstance().currentUser
mUser?.sendEmailVerification()?.addOnCompleteListener { task ->
if (task.isSuccessful) {
verifyEmailDialog?.show(supportFragmentManager, "VerifyEmail")
} else {
Toast.makeText(this, "Verification not sent...", Toast.LENGTH_LONG).show()
}
}
}
override fun afterTextChanged(s: Editable?) {
sign_up_button.isEnabled = username_edit_text.text.toString().isNotEmpty() &&
email_edit_text.text.toString().isNotEmpty() &&
password_edit_text.text.toString().isNotEmpty()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun onCancel() {
verifyEmailDialog?.dismiss()
val mUser = FirebaseAuth.getInstance().currentUser
if (mUser != null) {
FirebaseDatabase.getInstance().reference.child("Users").child(mUser.uid).child("UserInfo").removeValue()
mUser.delete()
}
signInButtonListener()
}
override fun onVerify() {
verifyEmailDialog?.dismiss()
signInCompleted(this)
}
}
<file_sep>/app/src/main/java/com/romanyu/chat/ResetPasswordActivity.kt
package com.romanyu.chat
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TextInputLayout
import android.support.v4.app.DialogFragment
import android.support.v7.app.ActionBar
import android.support.v7.widget.Toolbar
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.romanyu.chat.authUtil.isValidEmail
import com.romanyu.chat.dialog.ResetPasswordDialog
import kotlinx.android.synthetic.main.activity_reset_password.*
class ResetPasswordActivity : AppCompatActivity(), View.OnClickListener, TextWatcher, ResetPasswordDialog.OnOkListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_reset_password)
val toolbar:Toolbar? = findViewById(R.id.toolbar) as? Toolbar
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
reset_button.setOnClickListener(this)
sign_up_button.setOnClickListener(this)
email_edit_text.addTextChangedListener(this)
}
override fun onClick(v: View?) {
when(v?.id){
R.id.reset_button ->{
resetButtonListener()
}
R.id.sign_up_button ->{
val intent = Intent(this,SignUpActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
}
}
}
private fun resetButtonListener(){
val email = email_edit_text.text.toString()
val isValidEmail = isValidEmail(email)
if(isValidEmail){
email_input.error = null
resetPassword(email)
}else{
email_input.error = resources.getString(R.string.invalid_email)
}
}
private fun resetPassword(email:String){
FirebaseAuth.getInstance().sendPasswordResetEmail(email).addOnCompleteListener {
task -> if(task.isSuccessful){
val resetPasswordDialog:DialogFragment = ResetPasswordDialog()
resetPasswordDialog.show(supportFragmentManager,"ResetPassword")
}else{
Toast.makeText(this,"Message not sent in your mail, try again...",Toast.LENGTH_LONG).show()
}
}
}
override fun onOk() {
val intent = Intent(this,SignInActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
}
override fun afterTextChanged(s: Editable?) {
reset_button.isEnabled = email_edit_text.text.toString().isNotEmpty()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
}
<file_sep>/app/src/main/java/com/romanyu/chat/authUtil/AuthUtil.kt
package com.romanyu.chat.authUtil
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentManager
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.romanyu.chat.MainActivity
import com.romanyu.chat.dialog.VerifyEmailDialog
import java.util.regex.Pattern
val emailRegex:String = "(\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,6})"
fun isValidEmail(email:String):Boolean{
var isValid = true
if(!Pattern.matches(emailRegex,email)){
isValid = false
}
return isValid
}
fun isValidPassword(password:String):Boolean{
var isValid = true
if(password.length<8 || password.length>32 || !checkPasswordByLetter(password) ){
isValid = false
}
return isValid
}
fun isValidUsername(username:String):Boolean{
var isValid = true
if(username.length<3 || username.length>32 || !checkUsernameByLetter(username)){
isValid = false
}
return isValid
}
fun checkPasswordByLetter(password:String):Boolean{
val passwordLetters:CharArray = password.toCharArray()
var isValid = true
for (letter in passwordLetters){
isValid = when(letter){
in 'A'..'Z',in 'a'..'z',in '0'..'9','_','.' -> true
else -> false
}
if(!isValid){
break
}
}
return isValid
}
fun checkUsernameByLetter(username:String):Boolean{
val usernameLetters:CharArray = username.toCharArray()
var isValid = true
for(letter in usernameLetters){
isValid = when(letter){
in 'A'..'Z',in 'a'..'z',in '0'..'9','_' -> true
else -> false
}
if(!isValid){
break
}
}
return isValid
}
//Autorisation function
fun signInCompleted(activity: Activity){
val intent = Intent(activity, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
activity.startActivity(intent)
}
fun isEmailVerify():Boolean{
val mUser = FirebaseAuth.getInstance().currentUser
return mUser?.isEmailVerified ?: false
}<file_sep>/app/src/main/java/com/romanyu/chat/gallery/ImageData.java
package com.romanyu.chat.gallery;
public class ImageData {
private static int currentNumber = 1;
private String imagePath;
private boolean isCheck;
private int checkNumber;
public ImageData(String imagePath){
this.imagePath = imagePath;
this.isCheck = false;
}
public static void resetNumber(){
currentNumber = 1;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean check) {
if(isCheck == check){return;}
if(check) {
checkNumber = currentNumber;
currentNumber++;
}else{
currentNumber--;
}
isCheck = check;
}
public int getCheckNumber() {
return checkNumber;
}
public void setCheckNumber(int checkNumber) {
this.checkNumber = checkNumber;
}
}
|
71f5dec674d9960a0cb2ab2c05e683a2c22e6781
|
[
"Java",
"Kotlin"
] | 18 |
Kotlin
|
YurchevskyRoman/Chat
|
9499186562e600d6bade13611df123c8803db854
|
767144f8587ab058217df07ddd8fba50bf023abe
|
refs/heads/master
|
<file_sep>function selectImg(id) {
var e = window.document.getElementById('selectResult');
if (e) {
e.setAttribute('value',id);
}
}
(function () {
function HelloWorldDialog(editor) {
var category = [
[ 'label1', 'value1' ],
[ 'label2', 'value2' ],
[ 'label3', 'value3' ],
[ 'label4', 'value4' ],
[ 'label5', 'value5' ]
];
return {
title: '来源于图片库',
minWidth: 600,
minHeight: 400,
buttons: [{
type: 'button',
id: 'someButtonID',
label: '自定义Button',
onClick: function () {
//alert('Custom Button');
}
},
CKEDITOR.dialog.okButton,
CKEDITOR.dialog.cancelButton
],
contents:
[
{
id: 'info',
label: '名字',
title: '名字',
elements:
[
{
id: 'selectResult',
type: 'html',
label: '选定图片',
html: '<div><input type="hidden" id="selectResult" /></div>',
required: true,
validate: CKEDITOR.dialog.validate.notEmpty('内容不能为空'),
commit: function () {
/*var text = '<img src="'+this.getValue()+'"/>';
var element = new CKEDITOR.dom.element('img', editor.document);
element.setText(text);
editor.insertElement(element);
*/
var doc = this.getElement().getDocument();
var element = doc.getById('selectResult');
var id = element.getAttribute('value');
CKEDITOR.ajax.load('http://localhost:8080/user/imageList.do', function( data ) {
if(data){
data = JSON.parse(data);
var imageElement = editor.document.createElement( 'img' );
imageElement.setAttribute( 'alt', 'sss流量' );
imageElement.setAttribute( 'src', data[id] );
editor.insertElement( imageElement );
}
});
}
},
{
id: 'category',
type: 'select',
items: category,
label: '分类',
onChange: function() {
alert(this.getValue());
},
setup: function( type, element ) {
alert('setup');
},
commit: function( type, element ) {
}
},
{
id: 'mainContent',
type: 'html',
html: '<div id="myDiv"></div>',
label: '内容',
setup: function( type, element ) {
alert('setup');
},
onLoad: function (me, element) {
},
commit: function( type, element ) {
}
}
]
}
],
onLoad: function () {
var document = this.getElement().getDocument();
var doc = CKEDITOR.dom.document;
var element = document.getById('myDiv');
if (element) {
// 从后台请求数据
CKEDITOR.ajax.load('http://localhost:8080/user/imageList.do', function( data ) {
var _html = '<div><p>';
if(data){
data = JSON.parse(data);
for (var i = 0; i < data.length; i++){
_html += '<img onclick="selectImg('+i+')" style="width: 250px;" src="'+data[i]+'" />';
}
}
_html +='<img src="http://localhost:8080/user/image.do">';
_html += '</p></div>';
element.setHtml(_html);
});
}
},
onShow: function () {
//alert('onShow');
},
onHide: function () {
//alert('onHide');
},
onOk: function () {
this.commitContent();
},
onCancel: function () {
//alert('onCancel');
},
resizable: CKEDITOR.DIALOG_RESIZE_HEIGHT
};
}
CKEDITOR.dialog.add('helloworld', function (editor) {
return HelloWorldDialog(editor);
});
})();
|
560007cd32556ee7dae8daea1a535757539ea8ac
|
[
"JavaScript"
] | 1 |
JavaScript
|
fengzhimengna/CKEditor-plugin
|
697a0bf64411f3bf2e6a5a410165a392df49ca37
|
83b2684a6838facab8aa40469d36b8343a876e99
|
refs/heads/main
|
<repo_name>fangyuman/reactg<file_sep>/precache-manifest.4691a0bac5dbe2db304f912888493e4d.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "862cb83a06aa814dbac4027444db62d9",
"url": "./index.html"
},
{
"revision": "fc0723ce646e27ebb98a",
"url": "./static/css/2.3786585f.chunk.css"
},
{
"revision": "24e9513bf275303f4820",
"url": "./static/css/main.92a3ebff.chunk.css"
},
{
"revision": "fc0723ce646e27ebb98a",
"url": "./static/js/2.7bcb7e46.chunk.js"
},
{
"revision": "4d47ffde3dc69784e8e23fd910817ef8",
"url": "./static/js/2.7bcb7e46.chunk.js.LICENSE.txt"
},
{
"revision": "24<KEY>03f4820",
"url": "./static/js/main.a51bfb74.chunk.js"
},
{
"revision": "705f434324a29d64b932",
"url": "./static/js/runtime-main.075efe5b.js"
},
{
"revision": "f24fadf5ca4424ca89bf2d9df4d8d657",
"url": "./static/media/pic.f24fadf5.png"
}
]);
|
4f808134f006e47e0c9f78074d4c7b9103c73e62
|
[
"JavaScript"
] | 1 |
JavaScript
|
fangyuman/reactg
|
34e082f84fdd5d35816c2ed8eabde670f8985a5f
|
706b3667731893baff848092b0cd929a942c97e9
|
refs/heads/master
|
<repo_name>agyonov/NgInitGA<file_sep>/src/app/services/google-analitics.service.ts
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, DOCUMENT } from '@angular/common';
import { environment } from 'src/environments/environment';
// Typescript extention of Window interface
declare global {
interface Window { ga: any; }
}
@Injectable({
providedIn: 'root'
})
export class GoogleAnaliticsService {
// The source for the load
private googleAnaliticsScript = {
loaded: false,
url: 'https://www.google-analytics.com/analytics.js'
};
constructor(@Inject(PLATFORM_ID) private platformId: Object,
@Inject(DOCUMENT) private dom: Document) {
}
// Send page view event to Google Analytics
public send(pageUrl: string): void {
// Send
window.ga('set', 'page', pageUrl);
window.ga('send', 'pageview');
}
// Send event tracking event to Google Analytics
public event(eventCategory: string, eventAction: string): void {
// Send
window.ga('send', 'event', eventCategory, eventAction);
}
// Init the GA infrastructure
public loadScript(): void {
// Check already loaded
if (!this.googleAnaliticsScript.loaded) {
// Check if we are at browser
if (isPlatformBrowser(this.platformId)) {
// Create new scipt element
const scriptElm: HTMLScriptElement = this.dom.createElement('script');
scriptElm.src = this.googleAnaliticsScript.url;
scriptElm.type = 'text/javascript';
scriptElm.async = true;
scriptElm.onload = () => {
// Prevent from load second time
this.googleAnaliticsScript.loaded = true;
};
// Define GA object
window.ga = window.ga || function () { (window.ga.q = window.ga.q || []).push(arguments); };
window.ga.l = +new Date;
// Set some Google Analytics stuff
window.ga('create', environment.propertyID, 'auto');
// Add to document
this.dom.body.appendChild(scriptElm);
}
}
}
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
propertyID: 'UA-YYYYY-Y' // Production environment should be placed here
};
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GoogleAnaliticsService } from './services/google-analitics.service';
import { SecondPageComponent } from './second-page/second-page.component';
import { HomeComponent } from './home/home.component';
// Factory provider for Angular. Provides function to be executed on Angular application startup
export const GoogleAnaliticsServiceFactory = (gas: GoogleAnaliticsService) => {
return () => {
// download
gas.loadScript();
};
};
@NgModule({
declarations: [
AppComponent,
SecondPageComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [
// Provides function to be executed on Angular application startup
{
provide: APP_INITIALIZER,
useFactory: GoogleAnaliticsServiceFactory,
deps: [GoogleAnaliticsService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/second-page/second-page.component.ts
import { Component, OnInit } from '@angular/core';
import { GoogleAnaliticsService } from '../services/google-analitics.service';
@Component({
selector: 'app-second-page',
templateUrl: './second-page.component.html',
styleUrls: ['./second-page.component.scss']
})
export class SecondPageComponent implements OnInit {
constructor(private gas: GoogleAnaliticsService) { }
ngOnInit() {
// Set that the user was here
this.gas.send('page-2');
}
}
<file_sep>/README.md
# NgInit
A small example project to discuss possible initialization of an angular application and using this inizialization for bootstraping third party js libraries for example - Google Analytics.
<file_sep>/src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { GoogleAnaliticsService } from './services/google-analitics.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'NgInit';
constructor(private gas: GoogleAnaliticsService) {
}
ngOnInit(): void {
}
// Button click event handler
clEvent(): void {
// Send event to google analytics
this.gas.event('softPage', 'Just an Event');
}
}
|
21e64357d0889fd7b52345d2444b79694a442118
|
[
"Markdown",
"TypeScript"
] | 6 |
TypeScript
|
agyonov/NgInitGA
|
a7bbe40ba5f336385668263df2d2cfbe6eb59f9e
|
6b3f8bf34a6df1478c27ac3cc95952b4b7264b3e
|
refs/heads/master
|
<file_sep>#!/bin/sh
#===================================#
# #
# A Simple Cacti Installer #
# #
# by <NAME> #
# <EMAIL> #
# #
# Jan. 12, 2015 #
#===================================#
# common variables assignment
#------------------------------
#. common
# configuration files
#-----------------------
ftp=
cvs=
# environment variables
#-----------------------
# repository
repo=$ftp
# run-time stamp
timestamp=`date +%Y%m%d-%H%M%S`
#echo "repository=$repo"
#echo "time=$timestamp"
# global variables
#-----------------------
#prog=${0##*/}
prog=$(basename $0)
#relativepath=${0%/*}
relativepath=$(dirname $0)
workingpath=$(pwd)
#
# system absolute path to this prog
#
if [ "${relativepath}x" = "x" ]; then
if [ `echo $0 | grep '/'` ]; then
#for example: /prog
path="/"
else
#for example: prog
path=`which $prog | sed "s/\/$prog//g"`
fi
elif [ ${relativepath:0:1} = '/' ]; then
#for example: /path/to/prog
path=$relativepath
else
#for example: current_path/to/prog
cd $workingpath/$relativepath/
path=$(pwd)
cd $workingpath
fi
#echo $path
#
# cacti's home directory
#
#for cacti installed using rpm
cacti_home="/usr/share/cacti"
#for cacti installed with tarball
#cacti_home="/var/www/html"
#
# cacti version
#
version=$1
[ $version ] || version="0.8.8c"
#echo $version
#
# path/to/cacti source code(tarball/src.rpm), binary package(rpm)
# and other config files(.spec/patch etc)
#
cacti_path="${path}/cacti"
mkdir -p $cacti_path
#
# path/to/rrdtool source code(tarball/src.rpm), binary package(rpm)
# and other config files(.spec/patch etc)
#
rrdtool_path="${path}/rrdtool"
mkdir -p $rrdtool_path
#
# path/to/the plugins source code(tarball)
# and other config files(patch/sql etc)
#
plugins_path="${path}/plugins"
mkdir -p $plugins_path
#
# path/to/the templates(tarball)
#
templates_path="${path}/templates"
mkdir -p $templates_path
#
# cacti uses mysql to store configuration
#
#=================================
# DB | OWNER | PASSWORD |
#---------------------------------
# mysql | root | cerNet2 |
#=================================
# cacti | cactiuser| cactisecret |
#---------------------------------
# syslog| cactiuser| cactisecret |
#=================================
mysqlroot="cerNet2"
cactidb="cacti"
cactidbown="cactiuser"
mysqlcacti="cactisecret"
# functions
#-----------------------
pause()
{
echo -en "continue?(Y/n): "
local key=""
read key
case $key in
'y')
;;
'Y')
;;
'')
;;
*)
exit 1
;;
esac
echo
}
#
# show services needed to run under run level 3
#
chkservice()
{
chkconfig --list | egrep -e "3\:on"
}
#
# clean up all temporary files including *.src.rpm *.rpm *.tgz *.zip
#
function cheanup()
{
rm -f $templates_path/*.tgz
rm -f $templates_path/*.zip
rm -f $plugins_path/*.tgz
rm -f $plugins_path/*.zip
rm -f $rrdtool_path/*.rpm
rm -f $rrdtool_path/*.tar.gz
rm -f $cacti_path/*.rpm
rm -f $cacti_path/*.tar.gz
rm -f $cacti_path/*.ttf
rm -f $cacti_path/*.php
}
#
# add extra yum repositories for centos
#
function add_yum_repo()
{
rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -Uvh http://dl.atrpms.net/el6.6-x86_64/atrpms/stable/atrpms-repo-6-7.el6.x86_64.rpm
rpm -Uvh http://apt.sw.be/redhat/el6/en/x86_64/rpmforge/RPMS/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
rpm -Uvh http://mirror.its.dal.ca/ius/stable/CentOS/6/x86_64/ius-release-1.0-13.ius.centos6.noarch.rpm
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
yum install -y system-config-firewall ntsysv setuptool vim ntp
}
#
# upate rrdtool to 1.4.7
#
function update_rrdtool()
{
cd $rrdtool_path
#rrdver="1.4.7"
rrdver="1.5.2"
if [ -f rrdtool-${rrdver}-2.el6.cacti.x86_64.rpm -a -f perl-rrdtool-${rrdver}-2.el6.cacti.x86_64.rpm ] ; then
echo
echo
echo "--------------------------------------------------------------"
echo "rrdtool and perl-rrdtool rpms found locally, install them now."
pause
yum localinstall -y rrdtool-${rrdver}-2.el6.cacti.x86_64.rpm perl-rrdtool-${rrdver}-2.el6.cacti.x86_64.rpm
elif [ -f rrdtool-${rrdver}-2.el6.cacti.src.rpm ] ; then
echo
echo
echo "--------------------------------------------------------"
echo "rrdtool source rpm found locally, build binary rpms now."
pause
yum groupinstall -y "development tools"
[ -d ~/rpmbuild ] && rm -fr ~/rpmbuild
rpmbuild --rebuild --define '__rel 2' rrdtool-${rrdver}-2.el6.cacti.src.rpm
elif [ -f rrdtool.spec ] ; then
echo
echo
echo "-------------------------------------------------------------"
echo "rrdtool.spec found locally, download source tarball to build."
pause
which wget > /dev/null 2>&1 || yum install wget -y
#[ ! -f rrdtool-${rrdver}.tar.gz ] && wget http://oss.oetiker.ch/rrdtool/pub/rrdtool-${rrdver}.tar.gz
[ -f rrdtool-${rrdver}.tar.gz ] || wget http://oss.oetiker.ch/rrdtool/pub/rrdtool-${rrdver}.tar.gz
yum groupinstall -y "development tools"
yum install -y ruby-devel tcl-devel tk-devel xulrunner-devel perl-devel ruby openssl-devel python-devel lua-devel
[ -d ~/rpmbuild ] && rm -fr ~/rpmbuild
mkdir -p ~/rpmbuild
mkdir -p ~/rpmbuild/SPEC
mkdir -p ~/rpmbuild/SOURCES
install -m 644 rrdtool-${rrdver}.tar.gz ~/rpmbuild/SOURCES
install -m 755 rrdcached.init ~/rpmbuild/SOURCES
install -m 644 rrdcached.sysconfig ~/rpmbuild/SOURCES
install -m 644 rrdtool-cacti.patch ~/rpmbuild/SOURCES
install -m 644 rrdtool.spec ~/rpmbuild/SPEC
rpmbuild -ba ~/rpmbuild/SPEC/rrdtool.spec --define '__rel 2'
install -m 644 ~/rpmbuild/SRPMS/rrdtool-${rrdver}-2.el6.cacti.src.rpm ./
else
echo
echo
echo "--------------------------------------"
echo "No rrdtool spec found, nothing to do."
pause
return 1
fi
#install -m 644 ~/rpmbuild/RPMS/x86_64/rrdtool-${rrdver}-2.el6.cacti.x86_64.rpm ./
#install -m 644 ~/rpmbuild/RPMS/x86_64/perl-rrdtool-${rrdver}-2.el6.cacti.x86_64.rpm ./
install -m 644 ~/rpmbuild/RPMS/x86_64/*.rpm ./
yum localinstall -y rrdtool-${rrdver}-2.el6.cacti.x86_64.rpm perl-rrdtool-${rrdver}-2.el6.cacti.x86_64.rpm
[ -d ~/rpmbuild ] && rm -fr ~/rpmbuild
cd $path
}
#
# add TrueType MS YaHei support
#
function add_msyh()
{
cd ${cacti_path}
font=msyh.ttf
if [ ! -f $font ] ; then
echo
echo
echo "--------------------------------------"
echo "No msyh.ttf found, try to download it."
pause
which wget > /dev/null 2>&1 || yum install wget -y
wget https://github.com/chenqing/ng-mini/blob/master/font/msyh.ttf?raw=true -O $font
fi
if [ -f $font ] ; then
echo
echo
echo "---------------------------"
echo "msyh.ttf found, install it."
pause
font_path=/usr/share/fonts/TrueType/
install -d -m 755 $font_path
install -m 755 -o root -g root $font $font_path
fc-cache -f -v
fc-list| grep Microsoft
else
echo
echo
echo "------------------------------------"
echo "Fail to download and install $font ."
pause
fi
cd $path
# Console > Paths > RRDTool Default Font > /usr/share/fonts/TrueType/msyh.ttf
# add chinese support to cacti_escapeshellarg()
sed -i '/^function\ title_trim/i\\setlocale(LC_CTYPE,"zh_CN.UTF-8");' ${cacti_home}/lib/functions.php
}
#
# install LAMP(Linux Apache2 MySQL PHP phpMyAdmin)
#
function install_lamp()
{
# add yum repositories, especially epel
add_yum_repo
# install apache, mysql, php and phpmyadmin
yum install --disablerepo=ius,remi -y httpd mysql-server php phpMyAdmin
# set time zone for php
#ZONE="Asia/Shanghai"
cat /etc/sysconfig/clock|sed 's/"//g' > /tmp/zone
echo "export ZONE" >> /tmp/zone
echo 'sed -i s,";date.timezone =","date.timezone = $ZONE", /etc/php.ini' >> /tmp/zone
. /tmp/zone
rm -f /tmp/zone
# set RAM capacity for php
#sed 's/^memory_limit = 128M/memory_limit = 512M/' /etc/php.ini
# secure MySQL
service mysqld restart
#=================================
# DB | OWNER | PASSWORD |
#---------------------------------
# mysql | root | cerNet2 |
#=================================
#mysqladmin --u root password '<PASSWORD>'
#sed -i 's/symbolic-links=0/symbolic-links=0\nbind-address=127.0.0.1/' /etc/my.cnf
mysql -e "DELETE FROM mysql.user WHERE User='';"
mysql -e "DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';"
mysql -e "DROP DATABASE test;"
mysql -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';"
mysql -e "UPDATE mysql.user SET Password=PASSWORD('$<PASSWORD>') WHERE User='root';"
mysql -e "FLUSH PRIVILEGES;"
# set ACL(s) for phpMyAdmin
sed -i '/172.16.58.3/d' /etc/httpd/conf.d/phpMyAdmin.conf
sed -i '/Allow from ::1/i\\ Allow from 172.16.58.3/26' /etc/httpd/conf.d/phpMyAdmin.conf
# start apache to access http://localhost/phpmyadmin
service httpd restart
#chkconfig --level 3 httpd on
}
#
# install cacti
#
function install_cacti()
{
cd ${cacti_path}
which wget > /dev/null 2>&1 || yum install wget -y
# download source code
[ ! -f cacti-${version}.tar.gz ] && \
wget http://www.cacti.net/downloads/cacti-${version}.tar.gz -O cacti-${version}.tar.gz
# extract the distribution tarball.
if [ -f cacti-${version}.tar.gz ] ; then
tar xfpz cacti-${version}.tar.gz -C /tmp > /dev/null 2>&1
chown root:root -R /tmp/cacti-${version}
mv /tmp/cacti-${version}/* ${cacti_home}
rm -fr /tmp/cacti-${version}
sed -i 's/\/cacti\//\//g' ${cacti_home}/config.php
chown apache:apache -R ${cacti_home}/plugins
fi
cd $path
}
#
# install spine
#
function install_spine()
{
cd ${cacti_path}
which wget > /dev/null 2>&1 || yum install wget -y
# download source code
[ ! -f cacti-spine-${version}.tar.gz ] && \
wget http://www.cacti.net/downloads/spine/cacti-spine-${version}.tar.gz -O cacti-${version}.tar.gz
# build
if [ -f cacti-spine-${version}.tar.gz ] ; then
tar xfpz cacti-spine-${version}.tar.gz -C /tmp > /dev/null 2>&1
cd /tmp/cacti-spine-${version}
yum install -y gcc gcc-c++ libtool net-snmp-devel openssl-devel mysql mysql-devel unzip
aclocal
libtoolize --force
autoheader
autoconf
automake
./configure
make && make install
cp /usr/local/spine/etc/spine.conf.dist /usr/local/spine/etc/spine.conf
fi
cd $path
}
#
# rebuild cacti and spine
#
function rebuild_cacti_spine()
{
# dependencies for building cacti and spine
for pkg in mysql-devel net-snmp-devel openssl-devel net-snmp-utils; do
[ `rpm -qa $pkg|wc -l` -eq 0 ] && yum install -y $pkg
done
# download source code and make rpms
cd ${cacti_path}
if [ -f cacti-${version}-1.rhel6_6.noarch.rpm -a -f cacti-spine-${version}-1.rhel6_6.x86_64.rpm ] ; then
echo
echo
echo "----------------------------------------------------"
echo "cacti and spine rpms found. NO need to rebuild them."
pause
return 0
elif [ -f cacti-${version}-1.rhel6_6.src.rpm -a -f cacti-spine-${version}-1.rhel6_6.src.rpm ] ; then
echo
echo
echo "---------------------------------------------------------"
echo "cacti and spine source rpms found, build binary rpms now."
pause
yum groupinstall -y "development tools"
[ -d ~/rpmbuild ] && rm -fr ~/rpmbuild
rpmbuild --rebuild --define '__rel 1' cacti-${version}-1.rhel6_6.src.rpm
rpmbuild --rebuild --define '__rel 1' cacti-spine-${version}-1.rhel6_6.src.rpm
elif [ -f cacti.spec -a -f cacti-spine.spec ] ; then
echo
echo
echo "-----------------------------------------------------------------------------"
echo "cacti and spine spec files found, download source tarball and build them now."
pause
which wget > /dev/null 2>&1 || yum install wget -y
[ ! -f cacti-${version}.tar.gz ] && \
wget http://www.cacti.net/downloads/cacti-${version}.tar.gz -O cacti-${version}.tar.gz
[ ! -f cacti-spine-${version}.tar.gz ] && \
wget http://www.cacti.net/downloads/spine/cacti-spine-${version}.tar.gz -O cacti-spine-${version}.tar.gz
yum groupinstall -y "development tools"
[ -d ~/rpmbuild ] && rm -fr ~/rpmbuild
mkdir -p ~/rpmbuild
mkdir -p ~/rpmbuild/SPEC
mkdir -p ~/rpmbuild/SOURCES
install -m 644 cacti-${version}.tar.gz ~/rpmbuild/SOURCES
install -m 644 cacti.spec ~/rpmbuild/SPEC
install -m 644 cacti-spine-${version}.tar.gz ~/rpmbuild/SOURCES
install -m 644 cacti-spine.spec ~/rpmbuild/SPEC
sed -i s/'^Version:.*$'/'Version: '$version/ ~/rpmbuild/SPEC/cacti.spec
sed -i s/'^Version:.*$'/'Version: '$version/ ~/rpmbuild/SPEC/cacti-spine.spec
rpmbuild -ba ~/rpmbuild/SPEC/cacti.spec --define '__rel 1'
rpmbuild -ba ~/rpmbuild/SPEC/cacti-spine.spec --define '__rel 1'
install -m 644 ~/rpmbuild/SRPMS/cacti-${version}-1.rhel6_6.src.rpm ./
install -m 644 ~/rpmbuild/SRPMS/cacti-spine-${version}-1.rhel6_6.src.rpm ./
else
echo
echo
echo "---------------------------------------------------"
echo "No cacti and/or spine spec(s) found, nothing to do."
pause
return 1
fi
install -m 644 ~/rpmbuild/RPMS/noarch/cacti-${version}-1.rhel6_6.noarch.rpm ./
install -m 644 ~/rpmbuild/RPMS/x86_64/cacti-spine-${version}-1.rhel6_6.x86_64.rpm ./
[ -d ~/rpmbuild ] && rm -fr ~/rpmbuild
cd $path
}
#
# install cacti and spine using rpm
#
function rpm_cacti_spine()
{
cd ${cacti_path}
if [ -f cacti-${version}-1.rhel6_6.noarch.rpm -a -f cacti-spine-${version}-1.rhel6_6.x86_64.rpm ] ; then
yum localinstall -y --disablerepo=rpmforge \
cacti-${version}-1.rhel6_6.noarch.rpm cacti-spine-${version}-1.rhel6_6.x86_64.rpm
else
echo
echo
echo "-----------------------------------"
echo "No cacti and/or spine rpm(s) found."
pause
return 1
fi
cd $path
# edit spine.conf and specify the database type, name, host, user and password
sed -i s/'^DB_Pass[[:blank:]]\+cactiuser$'/'DB_Pass\t'$mysqlcacti/ /etc/spine.conf
#"Settings" ->"Paths" ->"Spine Poller File Path" ->"/usr/bin/spine"
#"Settings" ->"Poller" ->"Poller Type"
}
#
# configure cacti
#
function config_cacti()
{
# create and setup MySQL databases for Cacti and Syslog, then import the tables
#=================================
# DB | OWNER | PASSWORD |
#---------------------------------
# cacti | cactiuser| cactisecret |
#---------------------------------
# syslog| cactiuser| cactisecret |
#=================================
#
#mysqladmin --user=root --password=$<PASSWORD> create cacti
mysql --user=root --password=$mysql<PASSWORD> -e 'CREATE DATABASE `cacti` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;'
mysql --user=root --password=$mysql<PASSWORD> -e 'CREATE DATABASE `syslog` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;'
# create MySQL username and password for cacti/syslog database
mysql --user=root --password=$<PASSWORD> -e "GRANT ALL ON cacti.* TO cactiuser@localhost IDENTIFIED BY '$mysqlcacti';"
mysql --user=root --password=$mysql<PASSWORD> -e "GRANT ALL ON syslog.* TO cactiuser@localhost IDENTIFIED BY '$mysqlcacti';"
mysql --user=root --password=$<PASSWORD> -e "FLUSH PRIVILEGES;"
# import the default cacti database
mysql --user=root --password=$<PASSWORD> cacti < /usr/share/doc/cacti-${version}/cacti.sql
#mysql --user=root --password=$<PASSWORD> cacti < /var/www/html/cacti-changes.sql #initial config value
mysql --user=root --password=$<PASSWORD> syslog < $cacti_home/plugins/syslog/syslog-partitions.sql
mysql --user=root --password=$mysql<PASSWORD> cacti < $cacti_home/plugins/syslog/syslog-plugin-setup.sql
# edit the Cacti config file (either include/config.php or db.php) and specify the database password
if [ -f /etc/cacti/db.php ] ; then
cacti_config="/etc/cacti/db.php"
else
cacti_config="${cacti_home}/include/config.php"
fi
sed -i s/'password = "<PASSWORD>user'/'password = "'$mysqlcacti/ ${cacti_config}
#sed -i '/^\/\/$url_path = "\/cacti\/"/a\\$url_path = "/";' ${cacti_config}
# set RSyslog to log to MySQL
echo "
\$ModLoad ommysql
\$template cacti_syslog,\"INSERT INTO syslog_incoming(facility, priority, date, time, host, message) values (%syslogfacility%, %syslogprior
ity%, '%timereported:::date-mysql%', '%timereported:::date-mysql%', '%HOSTNAME%', '%msg%')\", SQL
*.* >127.0.0.1,syslog,cactiuser,$mysqlcacti;cacti_syslog" >> /etc/rsyslog.conf
sed -i 's/#$ModLoad imudp.so/$ModLoad imudp.so/' /etc/rsyslog.conf
sed -i 's/#$UDPServerRun 514/$UDPServerRun 514/' /etc/rsyslog.conf
sed -i 's/#$ModLoad imtcp.so/$ModLoad imtcp.so/' /etc/rsyslog.conf
sed -i 's/#$InputTCPServerRun 514/$InputTCPServerRun 514/' /etc/rsyslog.conf
# modify the Cacti config files with proper passwords
sed -i s/"syslogdb_password = '<PASSWORD>'"/"syslogdb_password = '"<PASSWORD>"'"/ $cacti_home/plugins/syslog/config.php
sed -i 's/use_cacti_db = true/use_cacti_db = false/' $cacti_home/plugins/syslog/config.php
# disable IPv6 until Cacti at least supports it
echo "install ipv6 /bin/true
blacklist ipv6" > /etc/modprobe.d/blacklist-ipv6.conf
# stop some unneeded services
for service in lvm2-monitor netconsole netfs rdisc restorecond ip6tables auditd blk-availability haldaemon mdmonitor postfix udev-post kdump
do
service $service stop
chkconfig --level 3 $service off
done
# start the services we do want
# for service in cacti_rrdsvc flow-capture httpd mysqld ntpd snmpd webmin
for service in cacti_rrdsvc httpd mysqld ntpd snmpd rsyslog network crond sshd iptables messagebus
do
service $service start
chkconfig --level 3 $service on
done
chkservice
# set MySQL to start before the syslog daemon, since we log to MySQL
mv /etc/rc.d/rc3.d/S64mysqld /etc/rc.d/rc3.d/S11mysqld
mv /etc/rc.d/rc0.d/K36mysqld /etc/rc.d/rc0.d/K89mysqld
mv /etc/rc.d/rc1.d/K36mysqld /etc/rc.d/rc1.d/K89mysqld
mv /etc/rc.d/rc6.d/K36mysqld /etc/rc.d/rc6.d/K89mysqld
mysql --user=root --password=$<PASSWORD> cacti < $cacti_home/plugins/boost/boost_sql_memory.sql
#mysql --user=root --password=$mysql<PASSWORD> cacti < $cacti_home/plugins/autom8/changes.sql
mysql --user=root --password=$<PASSWORD> cacti < $cacti_home/plugins/flowview/flowview.sql
#mysql --user=root --password=$<PASSWORD> cacti < $cacti_home/plugins/weathermap/weathermap.sql
# set web ACL(s) for cacti
sed -i '/172.16.58.3/d' /etc/httpd/conf.d/phpMyAdmin.conf
sed -i '/^[[:blank:]]\+Allow from localhost/i\\ \t\tAllow from 172.16.58.3/26' /etc/httpd/conf.d/cacti.conf
service httpd reload
}
#
# install plugins
#
function install_plugins()
{
which wget > /dev/null 2>&1 || yum install wget -y
which unzip > /dev/null 2>&1 || yum install unzip -y
which svn > /dev/null 2>&1 || yum install subversion -y
cd ${plugins_path}
# 1. plugins packaged in tarball
for url in http://docs.cacti.net/_media/plugin:settings-v0.71-1.tgz \
http://docs.cacti.net/_media/plugin:clog-v1.7-1.tgz \
http://docs.cacti.net/_media/plugin:cycle-v2.3-1.tgz \
http://docs.cacti.net/_media/plugin:errorimage-v0.2-1.tgz \
http://docs.cacti.net/_media/plugin:aggregate-v0.75.tgz \
http://docs.cacti.net/_media/plugin:spikekill-v1.3-2.tgz \
http://docs.cacti.net/_media/plugin:docs-v0.4-1.tgz \
http://docs.cacti.net/_media/plugin:monitor-v1.3-1.tgz \
http://docs.cacti.net/_media/plugin:thold-v0.5.0.tgz \
http://docs.cacti.net/_media/plugin:discovery-v1.5-1.tgz \
http://docs.cacti.net/_media/plugin:hmib-v1.4-2.tgz \
http://docs.cacti.net/_media/plugin:nectar-v0.35a.tgz \
http://docs.cacti.net/_media/plugin:dsstats-v1.4-1.tgz \
http://docs.cacti.net/_media/plugin:autom8-v0.35.tgz \
http://docs.cacti.net/_media/plugin:mactrack-v2.9-1.tgz \
http://docs.cacti.net/_media/plugin:realtime-v0.5-2.tgz \
http://docs.cacti.net/_media/plugin:rrdclean-v0.41.tgz \
http://docs.cacti.net/_media/plugin:boost-v5.1-1.tgz \
http://docs.cacti.net/_media/plugin:ugroup-v0.2-2.tgz \
http://docs.cacti.net/_media/plugin:slowlog-v1.3-1.tgz \
http://docs.cacti.net/_media/plugin:flowview-v1.1-1.tgz \
http://docs.cacti.net/_media/plugin:ntop-v0.2-1.tgz \
http://docs.cacti.net/_media/plugin:domains-v0.1-1.tgz \
http://docs.cacti.net/_media/plugin:remote_v01.tar.gz \
http://docs.cacti.net/_media/plugin:routerconfigs-v0.3-1.tgz \
http://docs.cacti.net/_media/plugin:mikrotik_v1.0.tar.gz \
http://docs.cacti.net/_media/plugin:syslog-v1.22-2.tgz \
http://sourceforge.net/projects/gibtmirdas/files/npc-2.0.4.tar.gz \
http://sourceforge.net/projects/murlin/files/mURLin-0.2.4.tar.gz \
http://runningoffatthemouth.com/unifiedtrees-latest.tgz \
https://github.com/Super-Visions/cacti-plugin-acceptance/archive/acceptance-v1.1.1.tar.gz
do
name=${url##*/}
name=${name##*:}
name=${name%%-*}
name=${name%%_*}
[ ! -f $name.tgz ] && wget $url -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
done
name=reportit
[ ! -f $name.tgz ] && wget http://sourceforge.net/projects/cacti-reportit/files/latest/download -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
name=dashboard
if [ ! -f $name.tgz ]; then
wget http://docs.cacti.net/_media/userplugin:dashboardv_v1.2.tar -O $name.tar
gzip $name.tar
mv $name.tar.gz $name.tgz
fi
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
name=mobile
[ ! -f $name.tgz ] && wget http://docs.cacti.net/_media/plugin:mobile-latest.tgz -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
mv ${cacti_home}/plugins/$name-0.1 ${cacti_home}/plugins/$name
name=loginmod
[ ! -f $name.tgz ] && wget http://docs.cacti.net/_media/plugin:loginmod-latest.tgz -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
mv ${cacti_home}/plugins/$name-1.0 ${cacti_home}/plugins/$name
# 2. plugins packaged with zip
for url in http://thingy.com/haj/cacti/superlinks-0.8.zip \
http://thingy.com/haj/cacti/titlechanger-0.1.zip \
http://thingy.com/haj/cacti/quicktree-0.2.zip \
http://gilles.boulon.free.fr/manage/manage-0.6.2.zip \
http://docs.cacti.net/_media/userplugin:timeshift-0.1.1.zip \
http://docs.cacti.net/_media/userplugin:predict_1.0.0.zip
do
name=${url##*/}
name=${name##*:}
name=${name%%-*}
name=${name%%_*}
[ ! -f $name.zip ] && wget $url -O $name.zip
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
unzip -q $name.zip -d ${cacti_home}/plugins
done
name=weathermap
[ ! -f $name.zip ] && wget http://network-weathermap.com/files/php-weathermap-0.97c.zip -O $name.zip
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
unzip -q $name.zip -d ${cacti_home}/plugins
# 3. plugins downloaded from web forum
name=cdnd
[ ! -f $name.tgz ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=29886' -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
name=intropage
[ ! -f $name.tgz ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=29498&sid=f873048221497fa62591429927732777' -O ${name}.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
cd ${cacti_home}/plugins/$name; patch -p1 < ${plugins_path}/$name.patch; cd ${plugins_path}
name=watermark
#wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=16973' -O $name.zip
[ ! -f $name.tgz ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=28440' -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
name=jqueryskin
[ ! -f $name.tgz ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=28439' -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
#name=dashboard
#[ ! -f $name.zip ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=28707&sid=95d7f8394f753230ab16d7a474f58b11' -O ${name}.zip
#[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
#unzip -q $name.zip -d ${cacti_home}/plugins
# 4. plugins check out from svn/cvs/github
name=maint
if [ ! -f $name.tgz ] ; then
svn co svn://svn.cacti.net/cacti_plugins/maint/trunk
if [ -d trunk ] ; then
mv trunk $name
tar cfpz $name.tgz $name
rm -fr $name
fi
fi
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
# plugins need to be patched and/or configured
# weathermap
# bug fix: wrong version no
sed -i 's/97b/97c/' ${cacti_home}/plugins/weathermap/setup.php
# enable editing
sed -i 's/^$ENABLED=false;/$ENABLED=true;/' ${cacti_home}/plugins/weathermap/editor.php
# split() oboleted
sed -i 's/$parts = split/$parts = explode/' ${cacti_home}/plugins/weathermap/editor.php
# keep generated htmls and images
output=${cacti_home}/plugins/weathermap/output
#chown -R cacti:apache ${output}
#chmod g+w ${output}/ ${output}/*
# easy and simple but secure way to configure SELinux to allow the Apache/httpd to
# write at the Weathemaps configs folder without disable it
chcon -R -t httpd_cache_t ${cacti_home}/plugins/weathermap/configs
# superlinks
# configure SELinux to allow superlinks accessible
chcon -R -t httpd_cache_t ${cacti_home}/plugins/superlinks/
# thold
# bug fix: some graphs invisible
sed -i 's/explode('"'"'"'"'"'/explode("'"'"'"/g' ${cacti_home}/plugins/thold/setup.php
# monitor
# for mointor to show thold breach legend
sed -i '/^if (in_array(/a\\if (true) {' ${cacti_home}/plugins/monitor/monitor.php
sed -i 's/^if (in_array(/\/\/if (in_array(/' ${cacti_home}/plugins/monitor/monitor.php
sed -i '/^$thold = (in_array(/a\\$thold = true;' ${cacti_home}/plugins/monitor/monitor.php
#sed -i '$i\$plugins[]='"'"'thold'"'"';' ${cacti_home}/include/config.php
# realtime
# cache image generated on-the-fly
install -d -m 755 ${cacti_home}/plugins/realtime/cache
#Console > Settings > Misc > Cache Directory ${cacti_home}/plugins/realtime/cache
# autom8
mv ${cacti_home}/plugins/trunk ${cacti_home}/plugins/autom8
# acceptance
mv ${cacti_home}/plugins/cacti-plugin-acceptance-acceptance-v1.1.1 ${cacti_home}/plugins/acceptance
# syslog
install -m 644 syslog-partitions.sql $cacti_home/plugins/syslog
install -m 644 syslog-plugin-setup.sql $cacti_home/plugins/syslog
# quicktree
cd ${cacti_home}/plugins/quicktree; patch -p1 < ${plugins_path}/quicktree.patch; cd ${plugins_path}
# manage
cd ${cacti_home}/plugins/manage/sql; patch -p0 < ${plugins_path}/9-uninstall.sql.patch ; cd ${plugins_path}
# boost
install -d -m 755 ${cacti_home}/plugins/boost/cache
chmod -R 755 ${cacti_home}/plugins/boost/cache
install -m 755 ${cacti_home}/plugins/boost/cacti_rrdsvc /etc/rc.d/init.d
chkconfig --add cacti_rrdsvc
# extra directory making and permisson setting
chown apache:apache -R ${cacti_home}/plugins
chown apache:apache -R ${cacti_home}/scripts
chmod 755 ${cacti_home}/scripts
chown apache:apache -R ${cacti_home}/resource
chmod 755 ${cacti_home}/resource
chmod 755 ${cacti_home}/resource/script_queries
chmod 755 ${cacti_home}/resource/script_server
chmod 755 ${cacti_home}/resource/snmp_queries
#rrdclean
install -d -m 755 ${cacti_home}/rra/backup
chown cacti:root ${cacti_home}/rra/backup
install -d -m 755 ${cacti_home}/rra/archive
chown cacti:root ${cacti_home}/rra/archive
chkservice
cd $path
}
# shell program
#-----------------------
if [ `id -u` -ne 0 ] ; then
echo -e "\nrun this program with root privilege.\n"
exit 1
fi
tmp="/tmp"
#cd $tmp
while true; do
PS3="Your choice: "
echo
echo "What would you like to do?"
echo -e "---------------------------------------------------------"
select opt in "Update rrdtool to 1.4.7 along with patch" \
"Install LAMP(Linux Apache MySQL PHP phpMyAdmin)" \
"Build cacti and spine rpms" \
"Install cacti and spine using rpm" \
"Add Chinese font support to cacti (TrueType MS YaHei)" \
"Install plugins for cacti" \
"Configure cacti" \
"Install cacti with tarball" \
"Install spine with tarball" \
"Clean up." \
"Quit."; do
case $opt in
"Quit.")
echo -e "\nExiting.\n"
exit 0
;;
"Clean up.")
cheanup
;;
"Update rrdtool to 1.4.7 along with patch")
update_rrdtool
;;
"Install LAMP(Linux Apache MySQL PHP phpMyAdmin)")
install_lamp
;;
"Build cacti and spine rpms")
rebuild_cacti_spine
;;
"Install cacti and spine using rpm")
rpm_cacti_spine
;;
"Add Chinese font support to cacti (TrueType MS YaHei)")
add_msyh
;;
"Install plugins for cacti")
install_plugins
;;
"Configure cacti")
config_cacti
;;
"Install cacti with tarball")
#install_cacti
;;
"Install spine with tarball")
#install_spine
;;
esac
break
done #select
done #while ;;
<file_sep>#!/bin/sh
# http://www.right.com.cn/forum/thread-146171-1-1.html
# get source of openwrt (trunk)
# Chaos Calmer r45580 (May.16, 2015)
#git clone git://git.openwrt.org/openwrt.git
#git clone git://git.openwrt.org/14.07/openwrt.git
#git clone https://github.com/openwrt-mirror/openwrt.git
# go into working dir
cd openwrt
while true ; do
# fix url of luci repo
#echo "src-git shadowsocks-libev https://github.com/shadowsocks/shadowsocks-libev.git" >> feeds.conf.default
./scripts/feeds update -a
./scripts/feeds install -a
# build 16M firmware
#$(eval $(call SingleProfile,TPLINK,64kraw,TLWR841NV7,tl-wr841nd-v7,TL-WR841N-v7,ttyS0,115200,0x08410007,1,4M))
sed -i '/tl-wr841nd-v7/{s/4M))$/16M))/;}' target/linux/ar71xx/image/Makefile
# config firmware
make defconfig
make prereq
make menuconfig
exit 0
# build firmware
make clean
make V=99
exit 0
#build tools and toolchain
make prereq
make tools/install
make toolchain/install
exit 0
done #while
# build package shadowsocks-libev
pushd package
[ -d shadowsocks-libev ] && rm -fr shadowsocks-libev
git clone https://github.com/shadowsocks/shadowsocks-libev.git
popd
sed -i 's/{local/{server,local/' package/shadowsocks-libev/openwrt/Makefile
#sed -i 's/ss-local/ss-server/;s/-b 0.0.0.0//' package/shadowsocks-libev/openwrt/files/shadowsocks.init
make V=99 package/shadowsocks-libev/openwrt/compile
#
# build options
#
#base system->dnsmasq-full
#kernel modules->netfilter extensions->kmod-ipt-filter ipopt u32
#luci->luci
#luci->protocols->luci-proto-ipv6
#network->iptables-> ->iptables-mod-filter ipopt u32
#network->web servers->uhttpd
#network->iperf ipset ppp-mod-pptp
<file_sep>
DROP TABLE `manage_host`;
/*DROP TABLE `manage_method`;*/
DROP TABLE `manage_alerts`;
DROP TABLE `manage_tcp`;
/*DROP TABLE `manage_device_type`;*/
DROP TABLE `manage_templates`;
DROP TABLE `manage_groups`;
DROP TABLE `manage_services`;
DROP TABLE `manage_process`;
DROP TABLE `manage_poller_output`;
DROP TABLE `manage_sites`;
/*DROP TABLE `manage_host_services`;*/
DROP TABLE `manage_admin_link`;
DROP TABLE `manage_uptime_method`;
ALTER TABLE `host` DROP `manage`;
DELETE FROM `settings` WHERE `name` like 'manage\_%';
/*DELETE FROM `plugin_update_info` WHERE `plugin` = 'manage';*/
<file_sep>#!/bin/sh
# get source of openwrt (attitude adjustment 12.09)
git clone git://git.openwrt.org/12.09/openwrt.git
#git clone https://github.com/tominescu/attitude_adjustment.git
# go into working dir
cd openwrt
# fix url of luci repo
sed -i 's/src-svn xwrt/#src-svn xwrt/' feeds.conf.default
sed -i 's/src-svn luci/#src-svn luci/' feeds.conf.default
echo "src-git luci https://github.com/openwrt/luci.git;luci-0.12" >> feeds.conf.default
./scripts/feeds update -a
./scripts/feeds install -a
# find souce files including word '703N' or '703n'
grep -i 703n ./* -r -l
# make a copy for wr720n
cp -pa ./target/linux/ar71xx/files/arch/mips/ath79/mach-tl-wr703n.c ./target/linux/ar71xx/files/arch/mips/ath79/mach-tl-wr720n.c
# substitute for 703
sed -i "s/0x07030101/0x7200103/g" `grep -i 0x07030101 ./* -r -l`
sed -i "s/070300/072001/g" `grep -i '"070300"' ./* -r -l`
sed -i "s/wr703n-v1/wr720n-v3/g" `grep -i wr703n-v1 ./* -r -l`
sed -i "s/WR703N_V1/WR720N_V3/g" `grep -i WR703N_V1 ./* -r -l`
sed -i "s/wr703nv1/wr720nv3/g" `grep -i wr703nv1 ./* -r -l`
A1="WR703N v1"
B1="WR720N v3"
sed -i "s/$A1/$B1/g" `grep -i "$A1" ./* -r -l`
A2="TP-LINK TL-WR703N v1"
B2="TP-LINK TL-WR720N v3"
sed -i "s/$A2/$B2/g" `grep -i "$A2" ./* -r -l`
sed -i "s/WR703/WR720/g" `grep -i WR703 ./* -r -l`
sed -i "s/wr703/wr720/g" `grep -i wr703 ./* -r -l`
#
install -m 755 -t ./target/linux/ar71xx/base-files/etc/uci-defaults/ ../network
install -m 644 -t ./target/linux/ar71xx/files/arch/mips/ath79/ ../mach-tl-wr720n.c
install -m 644 -t ./package/mac80211/files/lib/wifi/ ../mac80211.sh
#
sed -i 's/0x7200103,1,4Mlzma))$/0x7200103,1,16Mlzma))/' target/linux/ar71xx/image/Makefile
sed -i '/HWID_TL_WR720N_V3,$/{n;n;s/4M/16M/;}' tools/firmware-utils/src/mktplinkfw.c
exit
# config kernel
make defconfig
make prereq
make menuconfig
exit
# build
make clean
make V=99
# build package
#make package/greenlet/compile V=99
#make package/gevent/compile V=99
# http://www.right.com.cn/forum/thread-160345-1-1.html
# FreeRouterV2 for 14.07
# opkg install dnsmasq-full ip ipset iptables-mod-filter iptables-mod-ipopt iptables-mod-u32 ppp-mod-pptp
#base system->dnsmasq-full
#network->routing and redirection->ip
#network->ipset
#network->firewall->iptables->iptables-mod-filter/ipopt/u32
#network->ppp-mod-pptp
#LuCI->luci(protocols->luci-proto-ppp)
<file_sep>#!/usr/bin/perl
use strict;
#my $i = 12648448;
#my $i = 16580608;
#my $i = 16646144;
my $i = 9842688;
open(FH,'>','16M_FF.bin');
binmode(FH);
my $xff =pack("H*","FF");
while($i>0)
{
print FH $xff;
$i--;
}
close FH;
<file_sep>rpmbuild -ba mailman.spec --define "__rel 1"
<file_sep>#!/bin/sh
#
# enable jffs and mount
#mkdir -p /opt
#mount -o bind /jffs/opt /opt
# install entware
cd /jffs
wget -O - http://entware.wl500g.info/binaries/mipselsf/installer/entware_install.sh | sh
# install essentials
opkg update
opkg install vim-full diffutils patch
# install git
opkg install openssh-client openssh-client-utils openssh-keygen
opkg install git
eval $(ssh-agent -s)
cp -pa ../../git/id_rsa /jffs
ln -s ~/.ssh/id_rsa /jffs/id_rsa
ssh-add ~/.ssh/id_rsa
# install
<file_sep>-- phpMyAdmin SQL Dump
-- version 3.4.8
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Dec 20, 2011 at 04:50 PM
-- Server version: 5.1.52
-- PHP Version: 5.3.3
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `syslog`
--
-- --------------------------------------------------------
--
-- Table structure for table `syslog`
--
CREATE TABLE IF NOT EXISTS `syslog` (
`facility_id` int(10) DEFAULT NULL,
`priority_id` int(10) DEFAULT NULL,
`host_id` int(10) DEFAULT NULL,
`logtime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`message` text NOT NULL,
`seq` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
KEY `seq` (`seq`),
KEY `logtime` (`logtime`),
KEY `host_id` (`host_id`),
KEY `priority_id` (`priority_id`),
KEY `facility_id` (`facility_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
/*!50100 PARTITION BY RANGE (TO_DAYS(logtime))
(PARTITION d20110920 VALUES LESS THAN (734766) ENGINE = MyISAM,
PARTITION dMaxValue VALUES LESS THAN MAXVALUE ENGINE = MyISAM) */;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_alert`
--
CREATE TABLE IF NOT EXISTS `syslog_alert` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '',
`severity` int(10) unsigned NOT NULL DEFAULT '0',
`method` int(10) unsigned NOT NULL DEFAULT '0',
`num` int(10) unsigned NOT NULL DEFAULT '1',
`type` varchar(16) NOT NULL DEFAULT '',
`enabled` char(2) DEFAULT 'on',
`repeat_alert` int(10) unsigned NOT NULL DEFAULT '0',
`open_ticket` char(2) DEFAULT '',
`message` varchar(128) NOT NULL DEFAULT '',
`user` varchar(32) NOT NULL DEFAULT '',
`date` int(16) NOT NULL DEFAULT '0',
`email` varchar(255) DEFAULT NULL,
`command` varchar(255) DEFAULT NULL,
`notes` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_facilities`
--
CREATE TABLE IF NOT EXISTS `syslog_facilities` (
`facility_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`facility` varchar(10) NOT NULL,
`last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`facility`),
KEY `facility_id` (`facility_id`),
KEY `last_updates` (`last_updated`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_hosts`
--
CREATE TABLE IF NOT EXISTS `syslog_hosts` (
`host_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`host` varchar(128) NOT NULL,
`last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`host`),
KEY `host_id` (`host_id`),
KEY `last_updated` (`last_updated`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Contains all hosts currently in the syslog table';
-- --------------------------------------------------------
--
-- Table structure for table `syslog_host_facilities`
--
CREATE TABLE IF NOT EXISTS `syslog_host_facilities` (
`host_id` int(10) unsigned NOT NULL,
`facility_id` int(10) unsigned NOT NULL,
`last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`host_id`,`facility_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_incoming`
--
CREATE TABLE IF NOT EXISTS `syslog_incoming` (
`facility` varchar(10) DEFAULT NULL,
`priority` varchar(10) DEFAULT NULL,
`date` date DEFAULT NULL,
`time` time DEFAULT NULL,
`host` varchar(128) DEFAULT NULL,
`message` varchar(1024) NOT NULL DEFAULT '',
`seq` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`status` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`seq`),
KEY `status` (`status`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_logs`
--
CREATE TABLE IF NOT EXISTS `syslog_logs` (
`alert_id` int(10) unsigned NOT NULL DEFAULT '0',
`logseq` bigint(20) unsigned NOT NULL,
`logtime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`logmsg` varchar(1024) DEFAULT NULL,
`host` varchar(32) DEFAULT NULL,
`facility` varchar(10) DEFAULT NULL,
`priority` varchar(10) DEFAULT NULL,
`count` int(10) unsigned NOT NULL DEFAULT '0',
`html` blob,
`seq` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`seq`),
KEY `logseq` (`logseq`),
KEY `alert_id` (`alert_id`),
KEY `host` (`host`),
KEY `seq` (`seq`),
KEY `logtime` (`logtime`),
KEY `priority` (`priority`),
KEY `facility` (`facility`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_priorities`
--
CREATE TABLE IF NOT EXISTS `syslog_priorities` (
`priority_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`priority` varchar(10) NOT NULL,
`last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`priority`),
KEY `priority_id` (`priority_id`),
KEY `last_updated` (`last_updated`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_remove`
--
CREATE TABLE IF NOT EXISTS `syslog_remove` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '',
`type` varchar(16) NOT NULL DEFAULT '',
`enabled` char(2) DEFAULT 'on',
`method` char(5) DEFAULT 'del',
`message` varchar(128) NOT NULL DEFAULT '',
`user` varchar(32) NOT NULL DEFAULT '',
`date` int(16) NOT NULL DEFAULT '0',
`notes` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_removed`
--
CREATE TABLE IF NOT EXISTS `syslog_removed` (
`facility_id` int(10) DEFAULT NULL,
`priority_id` int(10) DEFAULT NULL,
`host_id` int(10) DEFAULT NULL,
`logtime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`message` text NOT NULL,
`seq` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
KEY `seq` (`seq`),
KEY `logtime` (`logtime`),
KEY `host_id` (`host_id`),
KEY `priority_id` (`priority_id`),
KEY `facility_id` (`facility_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
/*!50100 PARTITION BY RANGE (TO_DAYS(logtime))
(PARTITION d20110920 VALUES LESS THAN (734766) ENGINE = MyISAM,
PARTITION dMaxValue VALUES LESS THAN MAXVALUE ENGINE = MyISAM) */;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_reports`
--
CREATE TABLE IF NOT EXISTS `syslog_reports` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '',
`type` varchar(16) NOT NULL DEFAULT '',
`enabled` char(2) DEFAULT 'on',
`timespan` int(16) NOT NULL DEFAULT '0',
`timepart` char(5) NOT NULL DEFAULT '00:00',
`lastsent` int(16) NOT NULL DEFAULT '0',
`body` varchar(1024) DEFAULT NULL,
`message` varchar(128) DEFAULT NULL,
`user` varchar(32) NOT NULL DEFAULT '',
`date` int(16) NOT NULL DEFAULT '0',
`email` varchar(255) DEFAULT NULL,
`notes` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `syslog_statistics`
--
CREATE TABLE IF NOT EXISTS `syslog_statistics` (
`host_id` int(10) unsigned NOT NULL,
`facility_id` int(10) unsigned NOT NULL,
`priority_id` int(10) unsigned NOT NULL,
`insert_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`records` int(10) unsigned NOT NULL,
PRIMARY KEY (`host_id`,`facility_id`,`priority_id`,`insert_time`),
KEY `host_id` (`host_id`),
KEY `facility_id` (`facility_id`),
KEY `priority_id` (`priority_id`),
KEY `insert_time` (`insert_time`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Maintains High Level Statistics';
<file_sep>#!/bin/sh
#
#http://www.linksysinfo.org/index.php?threads/entware-arm-is-ready-for-tomato-by-shibby.70917
#
# enable jffs and mount
#mkdir -p /opt
#mount -o bind /jffs/opt /opt
# install entware
cd /jffs
wget http://qnapware.zyxmon.org/binaries-armv7/installer/entware_install_arm.sh
chmod 755 entware_install_arm.sh
./entware_install_arm.sh
# install essentials
opkg update
opkg install vim-full diffutils patch
# install git
opkg install openssh-client openssh-client-utils openssh-keygen
opkg install git
eval $(ssh-agent -s)
cp -pa ../../git/id_rsa /jffs
ln -s ~/.ssh/id_rsa /jffs/id_rsa
ssh-add ~/.ssh/id_rsa
# install
<file_sep>#!/bin/sh
LOGFILE='/tmp/vpn.log'
echo "Log: VPN Disconnect! @$(date +'%T@%Y-%m-%d')" >>$LOGFILE
echo "Log: Remove IP rules for table 'vpn'! @$(date +'%T@%Y-%m-%d')" >>$LOGFILE
ip rule del table vpn
<file_sep>#!/bin/sh
git=/root/soft/piggyhome
#Format is "Address 1: 192.168.3.11 n058152223191.netvigator.com"
#record_ip=`nslookup piggyhome.tunel.edu.cn| grep netvigator|awk '{print $3 }'`
record_ip=`/bin/cat $git/ip`
#
#Format is " inet 192.168.3.11/24 brd 192.168.3.11 scope global eth0.2"
current_ip=`ip addr show eth0.2|grep global |awk '{print $2}'|awk -F'/' '{print $1}'`
if [ "$record_ip"x != "$current_ip"x ]; then
echo $current_ip > $git/ip
cd $git
/usr/bin/git commit -m "`date`" . > /dev/null 2>&1
/usr/bin/git push origin master > /dev/null 2>&1
fi
<file_sep>#!/bin/sh
# get source of openwrt (trunk)
# Chaos Calmer r45427 (Apr. 14, 2015)
#git clone git://git.openwrt.org/openwrt.git
#git clone git://git.openwrt.org/14.07/openwrt.git
# go into working dir
cd openwrt
while false ; do
# fix url of luci repo
#echo "src-git shadowsocks-libev https://github.com/shadowsocks/shadowsocks-libev.git" >> feeds.conf.default
./scripts/feeds update -a
./scripts/feeds install -a
# build 128M firmware
# http://www.right.com.cn/forum/thread-161640-3-1.html
# change
#wndr4300_mtdlayout=mtdparts=ar934x-nfc:256k(u-boot)ro,256k(u-boot-env)ro,256k(caldata),512k(pot),2048k(language),512k(config),3072k(traffic_meter),2048k(kernel),23552k(ubi),25600k@0x6c0000(firmware),256k(caldata_backup),-(reserved)
# to
#wndr4300_mtdlayout=mtdparts=ar934x-nfc:256k(u-boot)ro,256k(u-boot-env)ro,256k(caldata),512k(pot),2048k(language),512k(config),3072k(traffic_meter),2048k(kernel),121856k(ubi),123904k@0x6c0000(firmware),256k(caldata_backup),-(reserved)
sed -i '/^wndr4300_mtdlayout/{s/23552k/121856k/;s/25600k/123904k/;}' target/linux/ar71xx/image/Makefile
# config firmware
make defconfig
make prereq
make menuconfig
exit 0
# build firmware
make clean
make V=99
exit 0
#build tools and toolchain
make prereq
make tools/install
make toolchain/install
exit 0
done #while
# build package shadowsocks-libev
#pushd package
#[ -d shadowsocks-libev ] && rm -fr shadowsocks-libev
#git clone https://github.com/shadowsocks/shadowsocks-libev.git
#popd
sed -i 's/{local/{server,local/' package/shadowsocks-libev/openwrt/Makefile
sed -i 's/ss-local/ss-server/;s/-b 0.0.0.0//' package/shadowsocks-libev/openwrt/files/shadowsocks.init
make V=99 package/shadowsocks-libev/openwrt/compile
#
# build options
#
#subtarget(generic devices with nand flash)
#target profile(netgear wndr3700v4/wndr4300)
#base system->block-mount dnsmasq-full
#development->diffutils patch
#kernel modules->fiesystems-> kmod-fs-ext4 hfs jfs msdos nfs vfat
#kernel modules->native language support->kmod-nfs-utf8
#kernel modules->netfilter extensions->kmod-ipt-filter ipopt u32
#kernel modules->usb support->kmod-usb-ohci usb-storage usb-uhci
#luci->luci luci-ssl
#luci->modules->translations->english chinese
#luci->applications->luci-app-commands ddns multiwan mwan3 qos samba
#luci->protocols->luci-proto-ipv6
#network->file transfer->aria2 curl vsftpd wget
#network->iptables-> ->iptables-mod-filter ipopt u32
#network->ssh->openssh-client-utils openssh-moduli openssh-server openssh-sftp-client openssh-sftp-server
#network->time synchronization->ntp-utils ntpclient ntpdate
#network->vpn->ipsec-tools openvpn-openssl
#network->version control systems->git
#network->web servers->uhttpd
#network->iperf ipset iputils-ping iputils-ping6 iputils-tracepath iputils-tracepath6 iputils-traceroute6 mtr ppp-mod-pptp snmp-utils snmpd tcpdump xinetd
#utilities->compression->unrar unzip zip
#utilities->editors->vim-full vim-help
#utilities->filesystem->e2freefrag e2fsprogs
#utilities->database->mysql-server
#utilities->disc->fdisk findfs hdparm lvm2 partx-utils
#utilities->bash dmesg file grep ldd less lm-sensors lm-sensors-detect mount-utils tar tmux whereis
<file_sep>#!/bin/sh
opkg update
opkg install libstdcpp
[ -f /etc/init.d/adbyby ] && /etc/init.d/adbyby stop
[ ! -f ./openwrt.tar.gz ] && wget http://info.adbyby.com/download/openwrt.tar.gz
tar -zvxf openwrt.tar.gz
[ -d /usr/share/adbyby ] && rm -fr /usr/share/adbyby
mv bin /usr/share/adbyby
cd /usr/share/adbyby
cat << EOF > /usr/share/adbyby/show-state
ps | grep "/usr/share/adbyby/adbyby" | grep -v grep
EOF
cat << EOF > /usr/share/adbyby/start-adbyby
/usr/share/adbyby/adbyby &> /tmp/log/adbyby.log &
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8118
EOF
cat << EOF > /usr/share/adbyby/stop-adbyby
ps | grep "/usr/share/adbyby/adbyby" | grep -v 'grep' | awk '{print \$1}' | xargs kill -9
iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8118
EOF
chmod 755 /usr/share/adbyby/show-state
chmod 755 /usr/share/adbyby/stop-adbyby
chmod 755 /usr/share/adbyby/start-adbyby
[ -f /etc/init.d/adbyby ] && rm -f /etc/init.d/adbyby
cat << EOF > /etc/init.d/adbyby
#!/bin/sh /etc/rc.common
START=80
start() {
echo "starting adbyby..."
/usr/share/adbyby/start-adbyby
}
stop() {
echo "stopping adbyby..."
/usr/share/adbyby/stop-adbyby
}
restart() {
stop
sleep 1
start
}
EOF
chmod 755 /etc/init.d/adbyby
cd /etc/rc.d
[ -s S80adbyby ] && rm -f S80adbyby
ln -s /etc/init.d/adbyby S80adbyby
/etc/init.d/adbyby start
cat << EOF >
* */2 * * * isfound=\$(ps | grep "/usr/share/adbyby/adbyby" | grep -v "grep"); if [ -z "$isfound" ]; then echo "$(date): restart adbyby...">>/tmp/log/adbyby.log && /etc/init.d/adbyby restart; fi
EOF
<file_sep>#!/bin/sh
set -x
LOGFILE='/tmp/vpn.log'
echo "Log: VPN Connected! @$(date +'%T@%Y-%m-%d')" >>$LOGFILE
VPN_DEV=$(ifconfig | grep "pptp" | sed -e "s#^\([^ ]*\) .*#\1#g")
echo "Log: Add DNS servers to VPN route! @$(date +'%T@%Y-%m-%d')" >>$LOGFILE
route add -host 8.8.8.8 dev $VPN_DEV
echo "Log: Add VPN device for table 'vpn'! @$(date +'%T@%Y-%m-%d')" >>$LOGFILE
ip route add default dev $VPN_DEV table vpn
echo "Log: Add IP marked by firewall to table 'vpn'! @$(date +'%T@%Y-%m-%d')" >>$LOGFILE
ip rule add fwmark 1 priority 1984 table vpn
/etc/init.d/dnsmasq restart
<file_sep>#!/bin/sh
pwd=`pwd`
#[ -f CentOS-6.5-x86_64-bin-DVD1to2.torrent ] && rm -f CentOS-6.5-x86_64-bin-DVD1to2.torrent
#wget http://centos.ustc.edu.cn/centos/6/isos/x86_64/CentOS-6.5-x86_64-bin-DVD1to2.torrent
#yum install ctorrent cdw
#[ -f CentOS-6.5-x86_64-bin-DVD1to2.torrent ] && ctorrent CentOS-6.5-x86_64-bin-DVD1to2.torrent
#[ -f CentOS-6.5-x86_64-bin-DVD1to2.torrent ] && rm -f CentOS-6.5-x86_64-bin-DVD1to2.torrent
mkdir -p /mnt/iso
mount -t iso9660 -o loop CentOS-6.5-x86_64-bin-DVD1to2/CentOS-6.5-x86_64-bin-DVD1.iso /mnt/iso
cp -r /mnt/iso /tmp
umount /mnt/iso
# 把附件中的 ks.cfg 放到 ~/iso 下;用附件中的 isolinux.cfg 替换 ~/iso/isolinux/isolinux.cfg
cp -f ks.cfg /tmp/iso
cp -f isolinux.cfg /tmp/iso/isolinux/isolinux.cfg
# Put custom RPMs into /tmp/iso/myrpms
#cp -rf myrpms /tmp/iso/
# 使用 mkisofs 创建新的 iso 文件
cd /tmp/iso
[ -f $pwd/mycentos.iso ] && rm -f $pwd/mycentos.iso
mkisofs -o $pwd/mycentos.iso -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -J -R -V 'My CentOS' .
cd $pwd
rm -rf /tmp/iso
<file_sep>INSERT INTO `plugin_config` VALUES (1, 'syslog', 'Syslog Monitoring', 1, 'The Cacti Group', 'http://cacti.net', '1.22');
INSERT INTO `plugin_hooks` VALUES (3, 'syslog', 'graph_buttons', 'setup.php', 'syslog_graph_buttons', 1);
INSERT INTO `plugin_hooks` VALUES (4, 'syslog', 'poller_bottom', 'setup.php', 'syslog_poller_bottom', 1);
INSERT INTO `plugin_hooks` VALUES (5, 'syslog', 'top_graph_refresh', 'setup.php', 'syslog_top_graph_refresh', 1);
INSERT INTO `plugin_hooks` VALUES (6, 'syslog', 'top_header_tabs', 'setup.php', 'syslog_show_tab', 1);
INSERT INTO `plugin_hooks` VALUES (7, 'syslog', 'config_settings', 'setup.php', 'syslog_config_settings', 1);
INSERT INTO `plugin_hooks` VALUES (8, 'syslog', 'top_graph_header_tabs', 'setup.php', 'syslog_show_tab', 1);
INSERT INTO `plugin_hooks` VALUES (9, 'syslog', 'draw_navigation_text', 'setup.php', 'syslog_draw_navigation_text', 1);
INSERT INTO `plugin_hooks` VALUES (10, 'syslog', 'config_arrays', 'setup.php', 'syslog_config_arrays', 1);
INSERT INTO `plugin_hooks` VALUES (11, 'syslog', 'config_insert', 'setup.php', 'syslog_config_insert', 1);
INSERT INTO `plugin_realms` VALUES (2, 'syslog', 'syslog.php', 'Plugin -> Syslog User');
INSERT INTO `plugin_realms` VALUES (3, 'syslog', 'syslog_alerts.php,syslog_removal.php,syslog_reports.php', 'Plugin -> Syslog Administration');
INSERT INTO `user_auth_realm` VALUES (102, 1);
INSERT INTO `user_auth_realm` VALUES (103, 1);<file_sep>#!/bin/sh
# openwrt release name
name=chaos_calmer
# openwrt release number
ver=15.05.1
# openwrt factory rom
rom=openwrt-$ver-ar71xx-generic-tl-wr841n-v9-squashfs-factory
#count length of pad: 16M - uboot(128K) - art(64K) - openwrt_factory(4M-257*512=3932160)...
#NEED_PAD_LEN=$((0x1000000-0x020000-0x010000-0x3c0000))
#count length of pad: 16M - uboot(128K) - art(64K) - openwrt_factory(16M-1024*512=16252928)...
NEED_PAD_LEN=$((0x1000000-0x020000-0x010000-0xf80000))
#generate a file used as pad
dd if=/dev/zero bs=1 count=$NEED_PAD_LEN| tr "\000" "\377" > pad.bin
#download openwrt rom
if [ ! -f ${rom}.bin ] ; then
curl -O https://downloads.openwrt.org/$name/$ver/ar71xx/generic/${rom}.bin
fi
#make 16M rom
cat u-boot-qca953x.bin ${rom}.bin pad.bin art-qca9533.bin > ${rom}_16M.bin
#remove pad
[ -f pad.bin ] && rm -f pad.bin
<file_sep>#!/bin/sh
yum install git -y
yum groupinstall development -y
yum install ncurses-devel ncurses-libs zlib-static openssl-devel -y
# http://www.right.com.cn/forum/thread-146171-1-1.html
# https://wiki.openwrt.org/doc/howto/build
# get source of openwrt (trunk)
# Chaos Calmer r45580 (May.3, 2016)
git clone git://git.openwrt.org/openwrt.git
#git clone git://git.openwrt.org/15.05.1/openwrt.git
#git clone https://github.com/openwrt-mirror/openwrt.git
# go into working dir
cd openwrt
while true ; do
# fix url of luci repo
#echo "src-git shadowsocks-libev https://github.com/shadowsocks/shadowsocks-libev.git" >> feeds.conf.default
./scripts/feeds update -a
./scripts/feeds install -a
# prepare to build 16M firmware
#841n v9 == 800n v2
#define Device/tl-wr841-v9
# $(Device/tplink-16mlzma)
sed -i '/^define\ Device\/tl-wr841-v9/{n;s/4mlzma)$/16mlzma)/;}' target/linux/ar71xx/image/Makefile
# 841n v7
#define Device/tl-wr841-v7
# $(Device/tplink-16mlzma)
#sed -i '/^define\ Device\/tl-wr841-v7/{n;s/4mlzma)$/16mlzma)/;}' target/linux/ar71xx/image/Makefile
#$(eval $(call SingleProfile,TPLINK,64kraw,TLWR841NV7,tl-wr841nd-v7,TL-WR841N-v7,ttyS0,115200,0x08410007,1,4M))
#sed -i '/tl-wr841nd-v7/{s/4M))$/16M))/;}' target/linux/ar71xx/image/Makefile
# config firmware
# method 1: set target and modify set of packages
if [ ! -f ../defconfig ] ; then
make defconfig
make prereq
make menuconfig
./scripts/diffconfig.sh > ../defconfig
fi
# method 2: using config diff instead of menuconfig
if [ -f ../defconfig ] ; then
cp -pa ../defconfig .config # write changes to .config
#cat ../defconfig >> .config # append changes to bottom of .config
make defconfig # expand to full config
fi
# build firmware
export FORCE_UNSAFE_CONFIGURE=1 #allow root to build firmware
make clean
make V=99
exit 0
# build tools and toolchain
make prereq
make tools/install
make toolchain/install
exit 0
done #while
# build package shadowsocks-libev
pushd package
[ -d shadowsocks-libev ] && rm -fr shadowsocks-libev
git clone https://github.com/shadowsocks/shadowsocks-libev.git
popd
sed -i 's/{local/{server,local/' package/shadowsocks-libev/openwrt/Makefile
#sed -i 's/ss-local/ss-server/;s/-b 0.0.0.0//' package/shadowsocks-libev/openwrt/files/shadowsocks.init
make V=99 package/shadowsocks-libev/openwrt/compile
#
# image configuration
#
# set target
# target system->atheros ar7xxxx/ar9xxx
# subtrget->generic
# profile->tp-link tl-wr841n/nd
# modify set of packages
# optional
#base system->busybox->networking utilities->ip
#kernel modules->netfilter extensions->kmod-ipt-filter ipopt u32
# mandatory
#base system->dnsmasq-full
#luci->collection->luci
#luci->protocols->luci-proto-ipv6
#network->iptables->iptables-mod-filter ipopt u32
#network->web servers->uhttpd
#network->iperf ipset ppp-mod-pptp
#network->vpn->pptpd
#network->ssh->openssh-client openssh-client-utils
#network->version control->git
#network->file transfer->curl wget
<file_sep>#!/bin/sh
omd="omd-1.20.rhel6.x86_64.rpm"
#wget http://files.omdistro.org/releases/centos_rhel/${omd}
yum -y localinstall --disablerepo=ius,remi --enablerepo=epel ${omd}
#service omd restart
#service httpd restart
#omd create ipacc
#su - ipacc
#omd start
#username/passwd:omdadmin/admin
#omd stop
#omd config ipacc
<file_sep>#!/bin/sh
# get source of openwrt (trunk)
# chaor Calmer r45369
git clone git://git.openwrt.org/openwrt.git
# go into working dir
cd openwrt
while false; do
# fix url of luci repo
#sed -i 's/src-svn xwrt/#src-svn xwrt/' feeds.conf.default
#sed -i 's/src-svn luci/#src-svn luci/' feeds.conf.default
#echo "src-git luci https://github.com/openwrt/luci.git;luci-0.12" >> feeds.conf.default
./scripts/feeds update -a
./scripts/feeds install -a
# build 16M firmware
sed -i 's/0x07200103,1,4Mlzma))$/0x07200103,1,16Mlzma))/' target/linux/ar71xx/image/Makefile
sed -i '/HWID_TL_WR720N_V3,$/{n;n;s/4M/16M/;}' tools/firmware-utils/src/mktplinkfw.c
# build package shadowsocks-libev
pushd package
[ -d shadowsocks-libev ] && rm -fr shadowsocks-libev
git clone https://github.com/shadowsocks/shadowsocks-libev.git
popd
sed -i 's/{local/{server,local/' package/shadowsocks-libev/openwrt/Makefile
sed -i 's/ss-local/ss-server/;s/-b 0.0.0.0//' package/shadowsocks-libev/openwrt/files/shadowsocks.init
# config firmware
make defconfig
make prereq
make menuconfig
exit 0
# build firmware
make clean
make V=99
exit 0
done #while
# build package shadowsocks-libev
pushd package
[ -d shadowsocks-libev ] && rm -fr shadowsocks-libev
git clone https://github.com/shadowsocks/shadowsocks-libev.git
popd
sed -i 's/{local/{server,local/' package/shadowsocks-libev/openwrt/Makefile
sed -i 's/ss-local/ss-server/;s/-b 0.0.0.0//' package/shadowsocks-libev/openwrt/files/shadowsocks.init
make V=99 package/shadowsocks-libev/openwrt/compile
exit 0
# http://www.right.com.cn/forum/thread-160345-1-1.html
# FreeRouterV2
# opkg install dnsmasq-full ip ipset iptables-mod-filter iptables-mod-ipopt iptables-mod-u32 ppp-mod-pptp
#base system->dnsmasq-full
#network->routing and redirection->ip
#network->ipset
#network->firewall->iptables->iptables-mod-filter/ipopt/u32
#network->ppp-mod-pptp
#LuCI->luci(protocols->luci-proto-ppp)
<file_sep>#!/bin/sh
# common variables assignment
#-----------------------
#. common
# configuration files
#-----------------------
ftp="ftp://172.16.58.3"
cvs=":pserver:[email protected]:2401/public/cvsroot"
# additional repositories
#http://ftp.riken.jp/Linux/fedora/epel/
epelver_x86="5-4"
epelver="6-8"
#http://dl.iuscommunity.org/pub/ius/stable/CentOS
iusver="1.0-13"
#http://apt.sw.be/redhat/el6/en/i386/
rpmforgever="0.5.3-1"
#http://dl.atrpms.net/el6-i386/atrpms/stable/
atrpmsver_x86="5-7"
atrpmsver="6-7"
#http://dl.atrpms.net/el6-i386/atrpms/stable/
remi=""
#http://rpms.famillecollet.com/enterprise/
# environment variables
#-----------------------
# repository
repo=$ftp
# run-time stamp
timestamp=`date +%Y%m%d-%H%M%S`
#echo "repository=$repo"
#echo "time=$timestamp"
# global variables
#-----------------------
#prog=${0##*/}
prog=$(basename $0)
#relativepath=${0%/*}
relativepath=$(dirname $0)
workingpath=$(pwd)
#path is the system absolute path to prog.
if [ "${relativepath}x" = "x" ]; then
if [ `echo $0 | grep '/'` ]; then
#for example: /prog
path="/"
else
#for example: prog
path=`which $prog | sed "s/\/$prog//g"`
fi
elif [ ${relativepath:0:1} = '/' ]; then
#for example: /path/to/prog
path=$relativepath
else
#for example: current_path/to/prog
cd $workingpath/$relativepath/
path=$(pwd)
cd $workingpath
fi
#echo $path
# functions
#-----------------------
pause() {
echo -en "continue?(Y/n): "
local key=""
read key
case $key in
'y')
;;
'Y')
;;
'')
;;
*)
exit 1
;;
esac
echo
}
test_cmd() {
if [ ! `which $1 2>/dev/null` ] ; then
echo -ne "Error! Command "$1" needed by this program not found. Exit.\n"
exit 1
fi
}
chkservice(){
chkconfig --list | egrep -e "3\:on"
}
#########
# list updated RPMS
#########
install_rpmul_script() {
local file="rpmul_el${rel}_${arch}.sh"
if [ $rel -eq 5 ] ; then
if [ $arch = "i386" ] ; then
cat << EOF > $file
#!/bin/sh
#echo $(basename $0)
sed '/^$/d;/packages$/d;/^warning/d;/^FINI/d;s/^Installing\ //g;s/^[0-9]\+\://g;s/\.i[36]86$//g;s/\.noarch$//g' /root/install.log|sort > /tmp/foo
rpm -qa | sort > /tmp/bar
diff -y /tmp/foo /tmp/bar | egrep -e [\|\>]
rm -f /tmp/foo /tmp/bar
EOF
elif [ $arch = "x86_64" ] ; then
cat << EOF > $file
#!/bin/sh
#echo $(basename $0)
sed '/^$/d;/packages$/d;/^warning/d;/\.i[36]86$/d;s/^Installing\ //g;s/^[0-9]\+\://g;s/\.x86\_64$//g;s/\.noarch$//g' /root/install.log|sort > /tmp/foo
rpm -qa | sort > /tmp/bar
diff -y /tmp/foo /tmp/bar | egrep -e [\|\>]
rm -f /tmp/foo /tmp/bar
EOF
else
echo "$arch invalid for el$rel."
exit 1
fi
elif [ $rel -eq 6 ] ; then
if [ $arch = "i386" ] ; then
cat << EOF > $file
#!/bin/sh
#echo $(basename $0)
sed '/^$/d;/packages$/d;/^warning/d;s/^Installing\ //g;s/^[0-9]\+\://g;s/\.i[36]86$//g;s/\.noarch$//g' /root/install.log|sort > /tmp/foo
rpm -qa |sed 's/\.i[36]86$//g;s/\.noarch$//g' |sort > /tmp/bar
diff -y /tmp/foo /tmp/bar | egrep -e [\|\>]
rm -f /tmp/foo /tmp/bar
EOF
elif [ $arch = "x86_64" ] ; then
cat << EOF > $file
#!/bin/sh
#echo $(basename $0)
#sed '/^$/d;/packages$/d;/^warning/d;/\.i[36]86$/d;s/^Installing\ //g;s/^[0-9]\+\://g;s/\.x86\_64$//g;s/\.noarch$//g' /root/install.log|sort > /tmp/foo
sed '/^$/d;/packages$/d;/^warning/d;/\.i[36]86$/d;s/^Installing\ //g;s/^[0-9]\+\://g' /root/install.log|sort > /tmp/foo
rpm -qa | sort > /tmp/bar
diff -y /tmp/foo /tmp/bar | egrep -e [\|\>]
rm -f /tmp/foo /tmp/bar
EOF
else
echo "$arch invalid for el$rel."
exit 1
fi
fi
echo
echo "A shell program named $file will be put under $HOME."
echo -e "---------------------------------------------------------"
pause
[ -f $file ] && (chmod 755 $file ;mv -f $file ~)
ls -l ~/$file
}
#########
# NTP
#########
install_ntp() {
echo
echo "Start NTP server."
echo -e "---------------------------------------------------------"
pause
yum install -y ntp
chkconfig --level 3 ntpd on
service ntpd stop
ntpdate 0.pool.ntp.org
service ntpd start
}
#########
# SNMP
#########
install_snmp() {
echo
echo "Start SNMP server."
echo -e "---------------------------------------------------------"
pause
yum install -y net-snmp net-snmp-utils net-snmp-libs lm_sensors
sed -i -e 's/^com2sec.*public$/&\n&a/' /etc/snmp/snmpd.conf
sed -i -e 's/^com2sec.*public$/#&/' /etc/snmp/snmpd.conf
sed -i -e 's/publica$/fit1-211/g' /etc/snmp/snmpd.conf
sed -i -e 's/^view.*25\.1\.1$/&\n&a/' /etc/snmp/snmpd.conf
sed -i -e 's/\.2\.1\.25\.1\.1a$//g' /etc/snmp/snmpd.conf
sensors-detect
sensors
chkconfig --level 3 snmpd on
service snmpd restart
}
#############
# MSMTP MUTT
#############
install_msmtp_mutt() {
echo
echo " SMTP & Mutt."
echo -e "---------------------------------------------------------"
pause
yum install -y msmtp mutt
cat << EOF > /etc/msmtprc
# Example for a user configuration file
# Set default values for all following accounts.
defaults
#tls on
#tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile ~/.msmtp.log
# A freemail service
account ipacc
host 192.168.127.12
#from <EMAIL>
from <EMAIL>
auth plain
user ipacc
password <PASSWORD>
# A second mail address at the same freemail service
#account freemail2 : freemail
#from <EMAIL>
# The SMTP server of the provider.
#account sybase
#host 192.168.127.12
#from <EMAIL>
#auth on
#user sybase
#password <PASSWORD>
# Set a default account
account default : ipacc
EOF
cat << EOF > /etc/Muttrc.local
set sendmail="/usr/bin/msmtp"
set from=<EMAIL>
#set strict_mime=no
#set assumed_charset="big5:gb2312:utf-8"
set rfc2047_parameters=yes
set move=no
set indent_str="> "
set charset="UTF-8"
set sort=date-received
set pager_index_lines=5
set locale="zh_TW.UTF-8"
EOF
}
#############
# RPM update
#############
rpm_update() {
echo
echo " Update system."
echo -e "---------------------------------------------------------"
pause
# crontabs yum
yum clean all
yum update
}
#############
# RPMs for a base linux system
#############
install_sys_base() {
echo
echo " Install some RPMs necessary."
echo -e "---------------------------------------------------------"
pause
yum install -y mlocate man vim ctags tmux tree vsftpd cvs chkconfig yum-utils wget
yum install -y openssh-clients openssh-server
yum install -y setuptool ntsysv authconfig system-config-network-tui system-config-date system-config-language
[ $rel -eq 5 ] && yum install -y system-config-securitylevel-tui
if [ $rel -eq 6 ] ; then
yum install -y system-config-firewall
chkconfig messagebus on
service messagebus start
fi
[ $rel -eq 5 ] && yum install -y vim-plugin-taglist
}
#############
# RPMs for development environment
#############
config_devel() {
echo
echo " Install RPMs necessary for a development environment."
echo -e "---------------------------------------------------------"
yum install -y gcc make automake autoconf libtool rpm-build
yum groupinstall -y "Development tools"
if [ $rel = 5 ] ; then
yum install -y kernel-headers
uname -r | grep PAE > /dev/null
if [ $? -eq 1 ] ; then #error means 'no PAE'
yum install -y kernel-devel
else
yum install -y kernel-PAE-devel
fi
fi
}
#############
# SELINUX
#############
config_selinux() {
sed -i 's/^SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
}
#############
# YUM additional repositories
#############
config_yum_add_repo() {
# epel
if [ $rel -le 5 ]; then
#el3-5
rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel/${rel}/${arch}/epel-release-${epelver_x86}.noarch.rpm
else
#el6
rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel/${rel}/${arch}/epel-release-${epelver}.noarch.rpm
fi
# ius
rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/CentOS/${rel}/${arch}/ius-release-${iusver}.ius.centos${rel}.noarch.rpm
# rpmforge
if [ $arch = "i386" ]; then
if [ $rel -le 5 ]; then
#el3-5
rpm -Uhv http://apt.sw.be/redhat/el${rel}/en/${arch}/rpmforge/RPMS/rpmforge-release-${rpmforgever}.el${rel}.rf.${arch}.rpm
else
#el6
rpm -Uhv http://apt.sw.be/redhat/el${rel}/en/${arch}/rpmforge/RPMS/rpmforge-release-${rpmforgever}.el${rel}.rf.i686.rpm
fi
else
#x86_64
rpm -Uhv http://apt.sw.be/redhat/el${rel}/en/${arch}/rpmforge/RPMS/rpmforge-release-${rpmforgever}.el${rel}.rf.${arch}.rpm
fi #i386
# atrpms
if [ $arch = "i386" ]; then
if [ $rel -le 5 ]; then
#el3-5
rpm -Uhv http://dl.atrpms.net/el${rel}-${arch}/atrpms/stable/atrpms-repo-${atrpmsver_x86}.el${rel}.${arch}.rpm
else
#el6
rpm -Uhv http://dl.atrpms.net/el${rel}-${arch}/atrpms/stable/atrpms-repo-${atrpmsver}.el${rel}.i686.rpm
fi
else
#x86_64
if [ $rel -le 5 ]; then
#el3-5
rpm -Uhv http://dl.atrpms.net/el${rel}-${arch}/atrpms/stable/atrpms-repo-${atrpmsver_x86}.el${rel}.${arch}.rpm
else
#el6
rpm -Uhv http://dl.atrpms.net/el${rel}-${arch}/atrpms/stable/atrpms-repo-${atrpmsver}.el${rel}.${arch}.rpm
fi
fi
#remi
if [ $rel -le 7 -a $rel -ge 4 ]; then
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-${rel}.rpm
fi
###########################
#
###########################
if [ $arch = 'x86_64' ] ; then
echo
echo -e "As for x86_64 system, all of the installed RPMs for i[36]86 should be removed,"
echo -e "and any RPMs for i[36]86 should not be installed."
echo -e "---------------------------------------------------------"
pause
yum remove *.i?86
grep 'exclude=\*.i?86' /etc/yum.conf > /dev/null
[ $? -eq 1 ] && sed -ie '/^plugins/a\exclude=*.i?86' /etc/yum.conf
fi
# CentOS 5.x 32bit
#rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel/5/i386/epel-release-5-4.noarch.rpm
#rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/CentOS/5/x86_64/ius-release-1.0-13.ius.centos5.noarch.rpm
# CentOS 6.x 32bit
#rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel/6/i386/epel-release-6-8.noarch.rpm
#rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/CentOS/6/i386/ius-release-1.0-13.ius.centos6.noarch.rpm
#rpm -Uvh http://apt.sw.be/redhat/el6/en/i386/rpmforge/RPMS/rpmforge-release-0.5.3-1.el6.rf.i686.rpm
# CentOS 6.x 64bit
#rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
#rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/CentOS/6/x86_64/ius-release-1.0-13.ius.centos6.noarch.rpm
#rpm -Uvh http://apt.sw.be/redhat/el6/en/x86_64/rpmforge/RPMS/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
}
# shell program
#-----------------------
if [ `id -u` -ne 0 ] ; then
echo -e "\nMust be root to run this program.\n"
exit 1
fi
tmp="/tmp"
cd $tmp
# release version and architecture
#-----------------------
#yum -y install redhat-lsb
#test_cmd lsb_release
rel=`[ -f /etc/redhat-release ] && sed 's/^.*release\ //g' /etc/redhat-release| awk '{print $1}'`
#rel=`lsb_release -r |awk '{print $NF}'`
arch=`uname -i`
#arch=`uname -p`
echo
echo "Your system is Redhat Linux/CentOS release $rel for $arch by default."
echo -e "---------------------------------------------------------"
pause
PS3="Your choice: "
echo
echo "What release your Redhat Linux/CentOS system is?"
echo -e "---------------------------------------------------------"
select opt in "CentOS 5.x i386" \
"CentOS 5.x x86_64" \
"CentOS 6.x i386" \
"CentOS 6.x x86_64" \
"Default."; do
case $opt in
"Default.")
#echo -e "\nExiting.\n"
#exit 1
rel=${rel%%.*}
;;
"CentOS 5.x i386" )
rel=5;arch=i386
;;
"CentOS 5.x x86_64" )
rel=5;arch=x86_64
;;
"CentOS 6.x i386" )
rel=6;arch=i386
;;
"CentOS 6.x x86_64" )
rel=6;arch=x86_64
;;
esac
break
done #select
while true; do
PS3="Your choice: "
echo
echo "What would you like to do?"
echo -e "---------------------------------------------------------"
select opt in "Set the environment variables." \
"Install a script(rpmul_xxx) which is able to list updated RPMs." \
"Install necessary RPMs for the following installations." \
"Set up this system to use additional reporsitories via yum." \
"Update OS to the latest version(yum update)." \
"Start NTP service." \
"Set up SNMP service." \
"Set up a SMTP client(msmtp/mutt)." \
"Disable SELinux." \
"Show the services being up under run level 3." \
"Configure system services." \
"Configure system by setuptool." \
"Install RPMs for development environment." \
"Clean up." \
"Quit."; do
case $opt in
"Quit.")
echo -e "\nExiting.\n"
exit 0
;;
"Clean up.")
;;
"Set the environment variables.")
export LANG=en_US.UTF-8
if [ -z "$CVSROOT" ] ; then
export CVSROOT=$cvs
cvs login
else
cvs logout
cvs login
fi
echo "... done."
;;
"Install a script(rpmul_xxx) which is able to list updated RPMs.")
install_rpmul_script
;;
"Install necessary RPMs for the following installations." )
install_sys_base
;;
"Set up this system to use additional reporsitories via yum.")
config_yum_add_repo
;;
"Update OS to the latest version(yum update)." )
rpm_update
;;
"Start NTP service." )
install_ntp
;;
"Set up SNMP service." )
install_snmp
;;
"Set up an SMTP client(msmtp/mutt)." )
install_msmtp_mutt
;;
"Disable SELinux." )
config_selinux
;;
"Show the services being up under run level 3.")
chkservice
;;
"Configure system services.")
ntsysv
telinit 1;telinit 3
clear
chkservice
;;
"Configure system by setuptool.")
setup
clear
;;
"Install RPMs for development environment.")
config_devel
;;
esac
break
done #select
done #while
<file_sep>#!/bin/sh
# intro page: http://www.right.com.cn/FORUM/forum.php?mod=viewthread&tid=135454
# downloading package: http://robots.shuyz.com/openwrt/general/luci-app-pptpd/luci-app-pptpd.ipk
opkg update
opkg install ppp-mod-pptp pptpd
wget http://robots.shuyz.com/openwrt/general/luci-app-pptpd/luci-app-pptpd.ipk
opkg install luci-app-pptpd.ipk
exit 0
# Services -> VPN Server
# General Settings :
#Enable VPN Server -> check
#Server IP -> leave blank
#Client IP -> 192.168.135.20-30 (dont collide with DHCP)
#DNS IP address -> 8.8.8.8
#Enable MPPE -> check
#Enable NAT -> check
#Enable remote server -> check
# Users Manager :
# username /password /ip (blank) -> add & check
cat << EOF > /etc/config/pptpd
config service 'pptpd'
option remoteip '192.168.135.20-30'
option mppe '1'
option internet '1'
option nat '1'
option enabled '0'
list dns '8.8.8.8'
list dns '8.8.4.4'
config login
option username 'guest'
option password '<PASSWORD>..'
option ipaddress '*'
option enabled '1'
EOF
<file_sep>#!/bin/sh
#
#echo "alias ll='ls -l --color'" >> ~/.bashrc
#echo "alias ls='ls --color'" >> ~/.bashrc
# for lsusb
apt-get install usbutils
# for
apt-get install vim git file
# for wireless config
apt-get install wireless-tools wpasupplicant wireless-firmware-osmc
# for building vnc server
apt-get install build-essential rbp-userland-dev-osmc libvncserver-dev libconfig++-dev unzip
vnc=dispmanx_vnc
[ -d ${vnc} ] && rm -fr $vnc
git clone https://github.com/patrikolausson/dispmanx_vnc.git
[ ! -d ${vnc} ] && exit 0
cd $vnc
make
[ ! -f ${vnc}server ] && exit 0
install -m 755 ${vnc}server /usr/bin/
cd ..
install -m 644 ${vnc}server.conf /etc/
install -m 644 ${vnc}server.service /etc/systemd/system/
systemctl restart ${vnc}server.service
systemctl enable ${vnc}server.service
systemctl daemon-reload
# Addon scripts, plugins, and skins for XBMC Media Center. Special for chinese laguage.
#git clone https://github.com/taxigps/xbmc-addons-chinese.git
<file_sep>#!/bin/sh
#
# uwsgi This shell script takes care of starting and stopping
# uwsgi daemon.
#
# chkconfig: - 80 20
# description: uwsgi
#
# Source function library.
. /etc/rc.d/init.d/functions
uwsgi="/usr/bin/uwsgi"
prog=$(basename $uwsgi)
PORT=9090
PROCESSES=4
USER=nginx
LOG=/var/log/uwsgi.log
lockfile=/var/lock/subsys/uwsgi
start() {
[ -x $uwsgi ] || exit 5
echo -n $"Starting $prog: "
daemon $uwsgi --uid $USER -s ":$PORT" -M -p $PROCESSES -d $LOG
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
stop
start
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart)
$1
;;
status|status_q)
rh_$1
;;
*)
echo $"Usage: $0 {start|stop|status}"
exit 2
esac
<file_sep>#!/bin/sh
yum install -y --disablerepo=ius,remi --enablerepo=epel docker-io
#useradd stg
#passwd stg
#vim /etc/sudoers
# stg ALL=(ALL) ALL
#su - stg
#$ git clone https://github.com/rohit01/docker_shinken.git
#$ cd docker_shinken/shinken_thruk_graphite
#$ sudo docker run -d -v "$(pwd)/custom_configs:/etc/shinken/custom_configs" -p 80:80 rohit01/shinken_thruk_graphite
#
<file_sep>#!/bin/sh
# get source of openwrt (break barrier 14.07)
#git clone git://git.openwrt.org/14.07/openwrt.git
# go into working dir
cd openwrt
# fix url of luci repo
#sed -i 's/src-svn xwrt/#src-svn xwrt/' feeds.conf.default
#sed -i 's/src-svn luci/#src-svn luci/' feeds.conf.default
#echo "src-git luci https://github.com/openwrt/luci.git;luci-0.12" >> feeds.conf.default
./scripts/feeds update -a
./scripts/feeds install -a
# build 16M firmware
sed -i 's/0x07200103,1,4Mlzma))$/0x07200103,1,16Mlzma))/' target/linux/ar71xx/image/Makefile
sed -i '/HWID_TL_WR720N_V3,$/{n;n;s/4M/16M/;}' tools/firmware-utils/src/mktplinkfw.c
# config firmware
make defconfig
make prereq
make menuconfig
exit
# build firmware
make clean
make V=99
# build package
#make package/greenlet/compile V=99
#make package/gevent/compile V=99
# http://www.right.com.cn/forum/thread-160345-1-1.html
# FreeRouterV2
# opkg install dnsmasq-full ip ipset iptables-mod-filter iptables-mod-ipopt iptables-mod-u32 ppp-mod-pptp
#base system->dnsmasq-full
#network->routing and redirection->ip
#network->ipset
#network->firewall->iptables->iptables-mod-filter/ipopt/u32
#network->ppp-mod-pptp
#LuCI->luci(protocols->luci-proto-ppp)
<file_sep>#!/bin/sh
# homepage: http://www.lifetyper.com/
# source code: https://github.com/lifetyper/FreeRouter_V2
# 0. install supporting packages.
opkg update
# git
opkg install openssh-client openssh-client-utils git
# kernel mod
opkg install ip ipset iptables-mod-ipopt iptables-mod-filter iptables-mod-u32
opkg list_installed | grep dnsmasq-full > /dev/null || /etc/init.d/dnsmasq stop && opkg remove dnsmasq && opkg install dnsmasq-full && /etc/init.d/dnsmasq start
# PPTP client: https://wiki.openwrt.org/doc/howto/vpn.client.pptp
opkg install ppp-mod-pptp kmod-nf-nathelper-extra
opkg install luci-proto-ppp
# 1. create a vpn interface.
# name: vpn #(hard-coded)
# protocol: PPtP
# vpn server: 192.168.127.12
# chap name:
# chap password:
# 2. advanced settings for this vpn interface.
# uncheck USE DEFAULT GATEWAY
# check BRING UP ON BOOT
#cat << EOF >> /etc/config/network
#config interface 'vpn'
# option proto 'pptp'
# option server '172.16.58.3'
# option username 'guest'
# option password '<PASSWORD>..'
# option defaultroute '0'
# option auto '1'
#EOF
# 3. firewall settings.
# assign firewall-zone to WAN
#sed -i "s/option network 'wan wan6'/option network 'wan wan6 vpn'/" /etc/config/firewall
# 4. install freerouter v2
chown root:root -R etc
cp -pa etc/dnsmasq.conf /etc
cp -pa etc/firewall.user /etc
[ ! -d /etc/iproute2 ] && mkdir /etc/iproute2
cp -pa etc/iproute2/rt_tables /etc/iproute2
[ ! -d /etc/ppp ] && mkdir /etc/ppp
[ ! -d /etc/ppp/ip-down.d ] && mkdir /etc/ppp/ip-down.d
cp etc/ppp/ip-down.d/vpndown.sh /etc/ppp/ip-down.d
[ ! -d /etc/ppp/ip-up.d ] && mkdir /etc/ppp/ip-up.d
cp -pa etc/ppp/ip-up.d/vpnup.sh /etc/ppp/ip-up.d
[ ! -d /etc/dnsmasq.d ] && mkdir /etc/dnsmasq.d
cp -pa etc/dnsmasq.d/gfw.conf /etc/dnsmasq.d
cp -pa etc/dnsmasq.d/option.conf /etc/dnsmasq.d
cp -pa etc/dnsmasq.d/server.conf /etc/dnsmasq.d
<file_sep>#!/bin/sh
mysqlpass="<PASSWORD>"
#yum install mysql-server mysql phpmyadmin httpd --disablerepo=ius
#vi /etc/httpd/conf.d/phpMyAdmin.conf
# Allow from 192.168.3.11
# Allow from 172.16.17.32
#vi /usr/share/phpmyadmin/config.inc.php
#$cfg['Servers'][$i]['auth_type'] = 'http';
#service mysqld restart
#chkconfig --level 3 mysqld on
#service httpd restart
#chkconfig --level 3 httpd on
#mysqladmin -u root -p password '<PASSWORD>'
#mysql_secure_installation
sed -i 's/^SELINUX=enforcing$/SELINUX=disabled/g' /etc/selinux/config
cat << EOF > /tmp/temp.sql
CREATE USER 'glpi'@'%' IDENTIFIED BY 'glpisecret';
GRANT USAGE ON *.* TO 'glpi'@'%' IDENTIFIED BY 'glpisecret';
CREATE DATABASE IF NOT EXISTS \`glpi\` ;
GRANT ALL PRIVILEGES ON \`glpi\`.* TO 'glpi'@'%';
FLUSH PRIVILEGES;
exit
EOF
mysql -uroot -p$mysqlpass < /tmp/temp.sql
yum install --enablerepo=remi --disablerepo=ius glpi
service httpd reload
<file_sep>"""
MoinMoin - Parser for Markdown
Syntax:
To use in a code block:
{{{{#!text_markdown
<add markdown text here>
}}}}
To use for an entire page:
#format text_markdown
<add markdown text here>
@copyright: 2009 by <NAME> (JasonFruit at g mail dot com)
@license: GNU GPL, see http://www.gnu.org/licenses/gpl for details
"""
from markdown import markdown
Dependencies = ['user']
class Parser:
"""
A thin wrapper around a Python implementation
(http://www.freewisdom.org/projects/python-markdown/) of John
Gruber's Markdown (http://daringfireball.net/projects/markdown/)
to make it suitable for use with MoinMoin.
"""
def __init__(self, raw, request, **kw):
self.raw = raw
self.request = request
def format(self, formatter):
output_html = markdown(self.raw)
try:
self.request.write(formatter.rawHTML(output_html))
except:
self.request.write(formatter.escapedText(output_html))
<file_sep>#!/bin/sh
#===================================#
# #
# A Simple Cactiez Patch #
# #
# by <NAME> #
# <EMAIL> #
# #
# Jan. 12, 2015 #
#===================================#
# common variables assignment
#------------------------------
#. common
# configuration files
#-----------------------
ftp=
cvs=
# environment variables
#-----------------------
# repository
repo=$ftp
# run-time stamp
timestamp=`date +%Y%m%d-%H%M%S`
#echo "repository=$repo"
#echo "time=$timestamp"
# global variables
#-----------------------
#prog=${0##*/}
prog=$(basename $0)
#relativepath=${0%/*}
relativepath=$(dirname $0)
workingpath=$(pwd)
#
# system absolute path to this prog
#
if [ "${relativepath}x" = "x" ]; then
if [ `echo $0 | grep '/'` ]; then
#for example: /prog
path="/"
else
#for example: prog
path=`which $prog | sed "s/\/$prog//g"`
fi
elif [ ${relativepath:0:1} = '/' ]; then
#for example: /path/to/prog
path=$relativepath
else
#for example: current_path/to/prog
cd $workingpath/$relativepath/
path=$(pwd)
cd $workingpath
fi
#echo $path
#
# cactiez's home directory
#
cacti_home="/var/www/html"
#
# cactiez version
#
version="0.8.8b"
#
# path/to/cacti source code(tarball/src.rpm), binary package(rpm)
# and other config files(.spec/patch etc)
#
cacti_path="${path}/cacti"
mkdir -p $cacti_path
#
# path/to/rrdtool source code(tarball/src.rpm), binary package(rpm)
# and other config files(.spec/patch etc)
#
rrdtool_path="${path}/rrdtool"
mkdir -p $rrdtool_path
#
# path/to/the plugins source code(tarball)
# and other config files(patch/sql etc)
#
plugins_path="${path}/plugins"
mkdir -p $plugins_path
#
# path/to/the templates(tarball)
#
templates_path="${path}/templates"
mkdir -p $templates_path
#
# cactiez uses mysql to store configuration
#
#=================================
# DB | OWNER | PASSWORD |
#---------------------------------
# mysql | root | ~root/mysqlpass.txt|
#=================================
# cacti | cactiuser| ~root/mysqlpass.txt|
#---------------------------------
# syslog| cactiuser| |
#=================================
passfile=~root/mysqlpass.txt
[ ! -f $passfile ] && exit 1
mysqlroot=`grep root $passfile | awk '{print $NF}'`
cactidb="cacti"
cactidbown="cactiuser"
mysqlcacti=`grep cactiuser $passfile | awk '{print $NF}'`
echo $mysqlroot
echo $mysqlcacti
# functions
#-----------------------
pause()
{
echo -en "continue?(Y/n): "
local key=""
read key
case $key in
'y')
;;
'Y')
;;
'')
;;
*)
exit 1
;;
esac
echo
}
#
# show services needed to run under run level 3
#
chkservice()
{
chkconfig --list | egrep -e "3\:on"
}
#
# clean up all temporary files including *.src.rpm *.rpm *.tgz *.zip
#
function cheanup()
{
rm -f $templates_path/*.tgz
rm -f $templates_path/*.zip
rm -f $plugins_path/*.tgz
rm -f $plugins_path/*.zip
rm -f $rrdtool_path/*.rpm
rm -f $rrdtool_path/*.tar.gz
rm -f $cacti_path/*.rpm
rm -f $cacti_path/*.tar.gz
rm -f $cacti_path/*.ttf
rm -f $cacti_path/*.php
}
#
# add extra yum repositories for centos
#
function add_yum_repo()
{
[ -f /etc/yum.repo.d/cactiez.repo ] && mv /etc/yum.repo.d/cactiez.repo{,.orig}
rpm -Uvh http://ftp.riken.jp/Linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -Uvh http://dl.atrpms.net/el6.6-x86_64/atrpms/stable/atrpms-repo-6-7.el6.x86_64.rpm
rpm -Uvh http://apt.sw.be/redhat/el6/en/x86_64/rpmforge/RPMS/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
rpm -Uvh http://mirror.its.dal.ca/ius/stable/CentOS/6/x86_64/ius-release-1.0-13.ius.centos6.noarch.rpm
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
}
#
# update centos
#
function update_centos()
{
yum update -y
yum install -y system-config-firewall ntsysv setuptool vim ntp cvs
yum install -y --disablerepo=ius,remi phpMyAdmin
sed -i '/172.16.31.10/d' /etc/httpd/conf.d/phpMyAdmin.conf
sed -i '/Allow from ::1/i\\ Allow from 172.16.31.10/26' /etc/httpd/conf.d/phpMyAdmin.conf
service httpd restart
}
#
# upgrade rrd
#
function install_rrdtool()
{
cd $rrdtool_path
rrdver="1.4.7"
if [ -f rrdtool-${rrdver}-2.el6.cactic.x86_64.rpm -a -f perl-rrdtool-${rrdver}-2.el6.cactic.x86_64.rpm ] ; then
echo
echo
echo "--------------------------------------------------------------"
echo "rrdtool and perl-rrdtool rpms found locally, install them now."
pause
yum localinstall -y rrdtool-${rrdver}-2.el6.cactic.x86_64.rpm perl-rrdtool-${rrdver}-2.el6.cactic.x86_64.rpm
else
echo
echo
echo "------------------------------------------------------------------"
echo "no rrdtool and perl-rrdtool rpms found locally, download them now."
which wget > /dev/null 2>&1 || yum install wget -y
wget http://pkgs.repoforge.org/rrdtool/perl-rrdtool-1.4.7-1.el6.rfx.x86_64.rpm
wget http://pkgs.repoforge.org/rrdtool/rrdtool-1.4.7-1.el6.rfx.x86_64.rpm
yum localinstall -y perl-rrdtool-1.4.7-1.el6.rfx.x86_64.rpm rrdtool-1.4.7-1.el6.rfx.x86_64.rpm
#rm -f perl-rrdtool-1.4.7-1.el6.rfx.x86_64.rpm rrdtool-1.4.7-1.el6.rfx.x86_64.rpm
fi
cd $path
}
#
# add TrueType MS YaHei support
#
function add_msyh()
{
cd ${cacti_path}
font=msyh.ttf
if [ ! -f $font ] ; then
echo
echo
echo "--------------------------------------"
echo "No msyh.ttf found, try to download it."
pause
which wget > /dev/null 2>&1 || yum install wget -y
wget https://github.com/chenqing/ng-mini/blob/master/font/msyh.ttf?raw=true -O $font
fi
if [ -f $font ] ; then
echo
echo
echo "---------------------------"
echo "msyh.ttf found, install it."
pause
font_path=/usr/share/fonts/TrueType/
install -d -m 755 $font_path
install -m 755 -o root -g root $font $font_path
fc-cache -f -v
fc-list| grep Microsoft
else
echo
echo
echo "------------------------------------"
echo "Fail to download and install $font ."
pause
fi
cd $path
# Console > Paths > RRDTool Default Font > /usr/share/fonts/TrueType/msyh.ttf
# add chinese support to cacti_escapeshellarg()
sed -i '/^function\ title_trim/i\\setlocale(LC_CTYPE,"zh_CN.UTF-8");' ${cacti_home}/lib/functions.php
}
#
# upgrade cactiez
#
function upgrade_cacitez()
{
cd ${path}/cactiez
# http://mirror.cactiusers.org/RPMS/CentOS/x86_64/
yum install -y cactiez-0.8.8b-1.x86_64.rpm
yum install -y cactiez-spine-0.8.8b-1.x86_64.rpm
yum install -y cactiez-plugin-monitor-1.3-2.x86_64.rpm
yum install -y cactiez-plugin-templates-0.1-1.x86_64.rpm
yum install -y cactiez-0.7-fixes-1-1.x86_64.rpm
# for cactiez-plugin-templates-0.1-1.x86_64.rpm
chown apache:apache ${cacti_home}/resource/*
chown apache:apache ${cacti_home}/scripts/
# for some thumbnail invisible
[ -f rrd.php ] || wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://svn.cacti.net/viewvc/cacti/branches/0.8.8/lib/rrd.php?revision=7418&pathrev=7418' -O rrd.php
#mv rrd.php\?revision\=7418 rrd.php
if [ -f ${cacti_home}/lib/rrd.php -a -f rrd.php ] ; then
mv ${cacti_home}/lib/rrd.php{,.orig}
#install -m 644 -o apache -g apache rrd.php ${cacti_home}/lib/
install -m 644 rrd.php ${cacti_home}/lib/
service httpd restart
fi
cd $path
}
#
# install extra plugins
#
function install_extra_plugins()
{
which wget > /dev/null 2>&1 || yum install wget -y
which unzip > /dev/null 2>&1 || yum install unzip -y
which svn > /dev/null 2>&1 || yum install subversion -y
cd ${plugins_path}
#echo $plugins_path
# 1. plugins packaged in tarball
for url in http://docs.cacti.net/_media/plugin:clog-v1.7-1.tgz \
http://docs.cacti.net/_media/plugin:cycle-v2.3-1.tgz \
http://docs.cacti.net/_media/plugin:spikekill-v1.3-2.tgz \
http://docs.cacti.net/_media/plugin:docs-v0.4-1.tgz \
http://docs.cacti.net/_media/plugin:rrdclean-v0.41.tgz \
http://docs.cacti.net/_media/plugin:ugroup-v0.2-2.tgz \
http://docs.cacti.net/_media/plugin:slowlog-v1.3-1.tgz \
http://docs.cacti.net/_media/plugin:ntop-v0.2-1.tgz \
http://docs.cacti.net/_media/plugin:domains-v0.1-1.tgz \
http://docs.cacti.net/_media/plugin:remote_v01.tar.gz \
http://docs.cacti.net/_media/plugin:routerconfigs-v0.3-1.tgz \
http://docs.cacti.net/_media/plugin:mikrotik_v1.0.tar.gz \
http://sourceforge.net/projects/gibtmirdas/files/npc-2.0.4.tar.gz \
http://sourceforge.net/projects/murlin/files/mURLin-0.2.4.tar.gz \
http://runningoffatthemouth.com/unifiedtrees-latest.tgz \
https://github.com/Super-Visions/cacti-plugin-acceptance/archive/acceptance-v1.1.1.tar.gz
do
name=${url##*/}
name=${name##*:}
name=${name%%-*}
name=${name%%_*}
[ ! -f $name.tgz ] && wget $url -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
done
name=reportit
[ ! -f $name.tgz ] && wget http://sourceforge.net/projects/cacti-reportit/files/latest/download -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
name=dashboard
if [ ! -f $name.tgz ]; then
wget http://docs.cacti.net/_media/userplugin:dashboardv_v1.2.tar -O $name.tar
gzip $name.tar
mv $name.tar.gz $name.tgz
fi
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
#only for cactiez
cd ${cacti_home}/plugins/$name ; patch -p1 < ${plugins_path}/$name.patch; cd ${plugins_path}
name=mobile
[ ! -f $name.tgz ] && wget http://docs.cacti.net/_media/plugin:mobile-latest.tgz -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
mv ${cacti_home}/plugins/$name-0.1 ${cacti_home}/plugins/$name
name=loginmod
[ ! -f $name.tgz ] && wget http://docs.cacti.net/_media/plugin:loginmod-latest.tgz -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
mv ${cacti_home}/plugins/$name-1.0 ${cacti_home}/plugins/$name
# 2. plugins packaged with zip
for url in http://thingy.com/haj/cacti/superlinks-0.8.zip \
http://thingy.com/haj/cacti/titlechanger-0.1.zip \
http://thingy.com/haj/cacti/quicktree-0.2.zip \
http://gilles.boulon.free.fr/manage/manage-0.6.2.zip \
http://docs.cacti.net/_media/userplugin:timeshift-0.1.1.zip \
http://docs.cacti.net/_media/userplugin:predict_1.0.0.zip
do
name=${url##*/}
name=${name##*:}
name=${name%%-*}
name=${name%%_*}
[ ! -f $name.zip ] && wget $url -O $name.zip
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
unzip -q $name.zip -d ${cacti_home}/plugins
done
name=weathermap
cd ${cacti_home}
#/usr/bin/php ${cacti_home}/plugins.php --disable jqueryskin
#/usr/bin/php ${cacti_home}/plugins.php --disable --uninstall weathermap
cd ${plugins_path}
[ ! -f $name.zip ] && wget http://network-weathermap.com/files/php-weathermap-0.97c.zip -O $name.zip
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
unzip -q $name.zip -d ${cacti_home}/plugins
#chown apache:apache -R ${cacti_home}/plugins/$name/
cd ${cacti_home}
#/usr/bin/php ${cacti_home}/plugins.php --install weathermap
#/usr/bin/php ${cacti_home}/plugins.php --enable jqueryskin
cd ${plugins_path}
name=history
[ ! -f $name.zip ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=21996&sid=531358d24e8f5532f97a0a0c7e27e707' -O ${name}.zip
if [ -d ${cacti_home}/plugins/weathermap ] ; then
unzip -q $name.zip -d ${cacti_home}/plugins/weathermap
install -d -m 755 ${cacti_home}/plugins/weathermap/out/history
fi
#chown apache:apache -R ${cacti_home}/plugins/$name/
# 3. plugins downloaded from web forum
name=cdnd
[ ! -f $name.tgz ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=29886' -O $name.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
name=intropage
[ ! -f $name.tgz ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=29498&sid=f873048221497fa62591429927732777' -O ${name}.tgz
[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
tar xfpz $name.tgz -C ${cacti_home}/plugins
cd ${cacti_home}/plugins/$name; patch -p1 < ${plugins_path}/$name.patch; cd ${plugins_path}
#name=dashboard
#[ ! -f $name.zip ] && wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=28707&sid=95d7f8394f753230ab16d7a474f58b11' -O ${name}.zip
#[ -d ${cacti_home}/plugins/$name ] && rm -fr ${cacti_home}/plugins/$name
#unzip -q $name.zip -d ${cacti_home}/plugins
#chown apache:apache -R ${cacti_home}/plugins/$name/
# plugins need to be patched and/or configured
chown apache:apache -R ${cacti_home}/plugins
chown apache:apache -R ${cacti_home}/scripts
chown apache:apache -R ${cacti_home}/resource
chown apache:apache -R ${cacti_home}/log
# weathermap
cd ${cacti_home}
# bug fix: wrong version no
sed -i 's/97b/97c/' ${cacti_home}/plugins/weathermap/setup.php
# enable editing
sed -i 's/^$ENABLED=false;/$ENABLED=true;/' ${cacti_home}/plugins/weathermap/editor.php
# split() oboleted
sed -i 's/$parts = split/$parts = explode/' ${cacti_home}/plugins/weathermap/editor.php
# keep generated htmls and images
output=${cacti_home}/plugins/weathermap/output
#chown -R cacti:apache ${output}
#chmod g+w ${output}/ ${output}/*
# easy and simple but secure way to configure SELinux to allow the Apache/httpd to
# write at the Weathemaps configs folder without disable it
chcon -R -t httpd_cache_t ${cacti_home}/plugins/weathermap/configs
# superlinks
# configure SELinux to allow superlinks accessible
chcon -R -t httpd_cache_t ${cacti_home}/plugins/superlinks/
# acceptance
mv ${cacti_home}/plugins/cacti-plugin-acceptance-acceptance-v1.1.1 ${cacti_home}/plugins/acceptance
# quicktree
cd ${cacti_home}/plugins/quicktree; patch -p1 < ${plugins_path}/quicktree.patch; cd ${plugins_path}
# manage
cd ${cacti_home}/plugins/manage/sql; patch -p0 < ${plugins_path}/9-uninstall.sql.patch ; cd ${plugins_path}
# thold
# for graph invisible after cactiez upgraded to 0.8.8b
# bug fix: some graphs invisible
sed -i 's/explode('"'"'"'"'"'/explode("'"'"'"/g' ${cacti_home}/plugins/thold/setup.php
# monitor
# for mointor to show thold breach legend
sed -i '/^if (in_array(/a\\if (true) {' ${cacti_home}/plugins/monitor/monitor.php
sed -i 's/^if (in_array(/\/\/if (in_array(/' ${cacti_home}/plugins/monitor/monitor.php
sed -i '/^$thold = (in_array(/a\\$thold = true;' ${cacti_home}/plugins/monitor/monitor.php
#sed -i '$i\$plugins[]='"'"'thold'"'"';' ${cacti_home}/include/config.php
#rrdclean
install -d -m 755 ${cacti_home}/rra/backup
#chown cacti:root ${cacti_home}/rra/backup
install -d -m 755 ${cacti_home}/rra/archive
#chown cacti:root ${cacti_home}/rra/archive
service httpd restart
cd $path
}
function config_cacti()
{
echo "How to install and configure cactiez 7.0"
echo "----------------------------------------"
echo
echo "use cactiez 7.0 iso to complete a cactiez installation"
echo "sed -i s/^#PermitRootLogin/PermitRootLogin/ /etc/ssh/sshd_config"
echo "setup->firewall->add snmp/udp"
echo "sed -i s/public$/fit1-211/ /etc/snmp/snmpd.conf"
echo "service snmpd restart"
echo "point browser to http://localhost/ and configure"
echo "install but do not activate the optional plugins"
echo "install all templates"
echo "Device->Community "
echo
echo
echo "mv /etc/yum.repos.d/cactiez.repo{,.orig}"
echo "yum install -y vim cvs"
echo "export CVSROOT=:pserver:<EMAIL>/public/cvsroot"
echo "cvs login"
echo "cvs co conf/cacti"
echo "run install.cactiez.sh"
echo "update centos"
echo "reboot"
echo "more ~/mysqlpass.txt to get mysql password"
echo "http://localhost/phpmyadmin"
echo "update rrdtool,update cactiez,add chinese,install extra plugins"
}
#
#
#
function install_templates()
{
which wget > /dev/null 2>&1 || yum install wget -y
which unzip > /dev/null 2>&1 || yum install unzip -y
cd $templates_path
# 1. templates packaged in tarball
name=memory
[ -f $name.tgz ] || wget http://www.eric-a-hall.com/software/cacti-netsnmp-memory/cacti-netsnmp-memory.0.7.tar.gz -O $name.tgz
p=cacti-netsnmp-memory
[ -d $p ] && rm -fr $p
tar xfpz $name.tgz
install -m 755 -o apache -g apache $p/scripts/ss_netsnmp_memory.php $cacti_home/scripts/
name=lmsensors
[ -f $name.tgz ] || wget http://www.eric-a-hall.com/software/cacti-netsnmp-lmsensors/cacti-netsnmp-lmsensors.0.9.tar.gz -O $name.tgz
p=cacti-netsnmp-lmsensors
[ -d $p ] && rm -fr $p
tar xfpz $name.tgz
install -m 644 -o apache -g apache $p/resource/0.8.7/netsnmp_lmsensors_* $cacti_home/resource/script_server/
install -m 755 -o apache -g apache $p/scripts/ss_netsnmp_lmsensors.php $cacti_home/scripts/
name=diskio
[ -f $name.tgz ] || wget http://docs.cacti.net/_media/usertemplate:data:host_mib:diskio087d.tar.gz -O $name.tgz
p=$name
[ -d $p ] && rm -fr $p
install -d -m 755 $p
tar xfpz $name.tgz -C $p
#install -m 644 -o apache -g apache $p/disk_io.xml $cacti_home/resource/snmp_queries/
# 3. plugins downloaded from web forum
name=esxi5
[ -f $name.tgz ] || wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=29171' -O $name.tgz
p=cacte_esxi_template
[ -d $p ] && rm -fr $p
tar xfpz $name.tgz
#bug fix: typo
sed -i 's/<text>host_description|/<text>|host_description|/' $p/cacti_host_template_esxi_5_x.xml
sed -i 's/<title>ESXi/<title>|host_description| - ESXi/' $p/cacti_host_template_esxi_5_x.xml
install -m 644 -o apache -g apache $p/resource/snmp_queries/esxi_* $cacti_home/resource/snmp_queries/
install -m 755 -o apache -g apache $p/scripts/ss_esxi_vhosts.php $cacti_home/scripts/
name=multicpu_2_4_8
[ -f $name.zip ] || wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=27303&sid=81c6ed88b6cfea0ace816f8c02424bcb' -O $name.zip
p=multi.2.4.8.cpu
unzip -q $name.zip
name=multicpu_12_16_20
[ -f $name.zip ] || wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=29798' -O $name.zip
p="Multithreaded CPU-12-16-20"
unzip -q $name.zip
name=multicpu_24
[ -f $name.tgz ] || wget -U 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' 'http://forums.cacti.net/download/file.php?id=26034' -O $name.tgz
tar xfpz $name.tgz
#name=advanced_ping
cd $path
}
# shell program
#-----------------------
if [ `id -u` -ne 0 ] ; then
echo -e "\nrun this program with root privilege.\n"
exit 1
fi
tmp="/tmp"
#cd $tmp
while true; do
PS3="Your choice: "
echo
echo "What would you like to do?"
echo -e "---------------------------------------------------------"
select opt in "Update CentOS" \
"Update rrdtool to 1.4.7 along with patch" \
"Upgrade cactiez" \
"Add Chinese font support to cacti (TrueType MS YaHei)" \
"Install extra plugins for cactiez" \
"Install templates for cactiez" \
"Configure cacti" \
"Clean up." \
"Quit."; do
case $opt in
"Quit.")
echo -e "\nExiting.\n"
exit 0
;;
"Clean up.")
cheanup
;;
"Update CentOS")
add_yum_repo
update_centos
;;
"Update rrdtool to 1.4.7 along with patch")
install_rrdtool
;;
"Upgrade cactiez")
upgrade_cacitez
;;
"Add Chinese font support to cacti (TrueType MS YaHei)")
add_msyh
;;
"Install extra plugins for cactiez")
install_extra_plugins
;;
"Install templates for cactiez")
install_templates
;;
"Configure cacti")
config_cacti
;;
esac
break
done #select
done #while ;;
|
802f8ac9bbafee3c2e1bb0d876eba736f049bbe1
|
[
"SQL",
"Python",
"Shell"
] | 30 |
Shell
|
zhanghui2008/conf
|
30ed1bd67a408bb7a62fdbb6a6526f88690c230c
|
31db1c3fb2cfea28cec5fee27607b8cfedd94aa5
|
refs/heads/master
|
<file_sep><?php
$usuario = "root";
$password = "";
$servidor = "localhost";
$basededatos = "practica2";
// creación de la conexión a la base de datos con mysql_connect()
$conexion = mysqli_connect( $servidor, $usuario, "" ) or die ("No se ha podido conectar al servidor de Base de datos");
// Selección del a base de datos a utilizar
$db = mysqli_select_db( $conexion, $basededatos ) or die ( "Upps! Pues va a ser que no se ha podido conectar a la base de datos" );
// establecer y realizar consulta. guardamos en variable.
$consulta = "SELECT juguetes.nombre_juguetes, juguetes.precio_juguetes FROM ninos JOIN reparto ON reparto.ninos_reparto = ninos.id_ninos JOIN juguetes ON juguetes.id_juguetes = reparto.juguetes_reparto WHERE juguetes.reyes_juguetes = 1";
$resultado = mysqli_query( $conexion, $consulta ) or die ( "Algo ha ido mal en la consulta a la base de datos");
$consulta1 = "SELECT juguetes.nombre_juguetes, juguetes.precio_juguetes FROM ninos JOIN reparto ON reparto.ninos_reparto = ninos.id_ninos JOIN juguetes ON juguetes.id_juguetes = reparto.juguetes_reparto WHERE juguetes.reyes_juguetes = 2";
$resultado1 = mysqli_query( $conexion, $consulta1 ) or die ( "Algo ha ido mal en la consulta a la base de datos");
$consulta2 = "SELECT juguetes.nombre_juguetes, juguetes.precio_juguetes FROM ninos JOIN reparto ON reparto.ninos_reparto = ninos.id_ninos JOIN juguetes ON juguetes.id_juguetes = reparto.juguetes_reparto WHERE juguetes.reyes_juguetes = 3";
$resultado2 = mysqli_query( $conexion, $consulta2 ) or die ( "Algo ha ido mal en la consulta a la base de datos");
$total = 0;
$total1 = 0;
$total2 = 0;
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo de menú desplegable</title>
<meta charset=utf-8" />
</head>
<body>
<table width="70%" border="1px" align="center">
<tr align="center">
<td>Nombre regalo</td><td>Precio de regalo</td>
</tr>
<?php
while ($columna = mysqli_fetch_array( $resultado )){
?>
<tr>
<td><?php echo $columna['nombre_juguetes'] ?></td><td><?php echo $columna['precio_juguetes'] ?></td>
<?php $total = $total + $columna['precio_juguetes'] ?>
</tr>
<?php
}
?>
<tfoot>
<tr>
<tr><td>TOTAL FACTURA DE GASPAR:</td><td><?php echo $total; ?></td></tr>
</tr>
</tfoot>
</table>
<p></p>
<p></p>
<table width="70%" border="1px" align="center">
<tr align="center">
<td>Nombre regalo</td><td>Precio de regalo</td>
</tr>
<?php
while ($columna = mysqli_fetch_array( $resultado1 )){
?>
<tr>
<td><?php echo $columna['nombre_juguetes'] ?></td><td><?php echo $columna['precio_juguetes'] ?></td>
<?php $total1 = $total1 + $columna['precio_juguetes'] ?>
</tr>
<?php
}
?>
<tfoot>
<tr>
<tr><td>TOTAL FACTURA DE MELCHOR:</td><td><?php echo $total1; ?></td></tr>
</tr>
</tfoot>
</table>
<p></p>
<p></p>
<table width="70%" border="1px" align="center">
<tr align="center">
<td>Nombre regalo</td><td>Precio de regalo</td>
</tr>
<?php
while ($columna = mysqli_fetch_array( $resultado2 )){
?>
<tr>
<td><?php echo $columna['nombre_juguetes'] ?></td><td><?php echo $columna['precio_juguetes'] ?></td>
<?php $total2 = $total2 + $columna['precio_juguetes'] ?>
</tr>
<?php
}
?>
<tfoot>
<tr>
<tr><td>TOTAL FACTURA DE BALTASAR:</td><td><?php echo $total2; ?></td></tr>
</tr>
</tfoot>
</table>
</option>
</body>
</html>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1:3306
-- Tiempo de generación: 23-02-2020 a las 12:14:24
-- Versión del servidor: 10.4.10-MariaDB
-- Versión de PHP: 7.3.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `practica2`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `juguetes`
--
DROP TABLE IF EXISTS `juguetes`;
CREATE TABLE IF NOT EXISTS `juguetes` (
`id_juguetes` int(11) NOT NULL AUTO_INCREMENT,
`nombre_juguetes` varchar(50) COLLATE utf8_spanish_ci NOT NULL,
`precio_juguetes` decimal(5,2) NOT NULL,
`reyes_juguetes` int(11) NOT NULL,
PRIMARY KEY (`id_juguetes`),
KEY `reyes` (`reyes_juguetes`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `juguetes`
--
INSERT INTO `juguetes` (`id_juguetes`, `nombre_juguetes`, `precio_juguetes`, `reyes_juguetes`) VALUES
(1, 'Aula de ciencia: Rob', '159.95', 1),
(2, 'Carbón', '0.00', 1),
(3, 'Cochecito Classic', '99.95', 1),
(4, 'Consola PS4 1 TB', '349.90', 1),
(5, '<NAME> ', '64.99', 2),
(6, '<NAME>', '150.00', 2),
(7, 'trucos con luz', '32.95', 2),
(8, 'Meccano Excavadora c', '30.99', 2),
(9, '<NAME>as', '29.95', 2),
(10, 'P<NAME>', '34.00', 3),
(11, 'Pequeordenador', '22.95', 3),
(12, 'Robot Coji', '69.95', 3),
(13, 'Telescopio astronómi', '72.00', 3),
(14, 'Twister', '17.95', 3);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `ninos`
--
DROP TABLE IF EXISTS `ninos`;
CREATE TABLE IF NOT EXISTS `ninos` (
`id_ninos` int(11) NOT NULL AUTO_INCREMENT,
`nombre_ninos` varchar(20) COLLATE utf8_spanish_ci NOT NULL,
`apellidos_ninos` varchar(20) COLLATE utf8_spanish_ci NOT NULL,
`fechadenacimiento_ninos` date NOT NULL,
`bueno_ninos` varchar(2) COLLATE utf8_spanish_ci NOT NULL,
PRIMARY KEY (`id_ninos`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `ninos`
--
INSERT INTO `ninos` (`id_ninos`, `nombre_ninos`, `apellidos_ninos`, `fechadenacimiento_ninos`, `bueno_ninos`) VALUES
(1, 'Alberto', 'Alcántara', '1994-10-13', 'No'),
(2, 'Beatriz', 'Bueno', '1982-04-18', 'Sí'),
(3, 'Carlos', 'Crepo', '1998-12-01', 'Sí'),
(4, 'Diana', 'Domínguez', '1987-09-02', 'No'),
(5, 'Emilio', 'Enamorado', '1986-08-12', 'Sí'),
(6, 'Francisca', 'Fernández', '1990-07-28', 'Sí');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `reparto`
--
DROP TABLE IF EXISTS `reparto`;
CREATE TABLE IF NOT EXISTS `reparto` (
`id_reparto` int(11) NOT NULL AUTO_INCREMENT,
`ninos_reparto` int(11) NOT NULL,
`juguetes_reparto` int(11) NOT NULL,
PRIMARY KEY (`id_reparto`),
KEY `ninos_ninos` (`ninos_reparto`),
KEY `juguetes_ninos` (`juguetes_reparto`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `reparto`
--
INSERT INTO `reparto` (`id_reparto`, `ninos_reparto`, `juguetes_reparto`) VALUES
(1, 1, 2),
(2, 2, 2),
(3, 3, 3),
(4, 3, 4),
(5, 4, 2),
(6, 5, 6),
(7, 5, 7),
(8, 6, 8);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `reyes`
--
DROP TABLE IF EXISTS `reyes`;
CREATE TABLE IF NOT EXISTS `reyes` (
`id_reyes` int(11) NOT NULL AUTO_INCREMENT,
`nombre_reyes` varchar(20) COLLATE utf8_spanish_ci NOT NULL,
PRIMARY KEY (`id_reyes`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `reyes`
--
INSERT INTO `reyes` (`id_reyes`, `nombre_reyes`) VALUES
(1, 'Gaspa'),
(2, 'Melchor'),
(3, 'Baltasar');
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `juguetes`
--
ALTER TABLE `juguetes`
ADD CONSTRAINT `juguetes_ibfk_1` FOREIGN KEY (`reyes_juguetes`) REFERENCES `reyes` (`id_reyes`);
--
-- Filtros para la tabla `reparto`
--
ALTER TABLE `reparto`
ADD CONSTRAINT `reparto_ibfk_1` FOREIGN KEY (`ninos_reparto`) REFERENCES `ninos` (`id_ninos`),
ADD CONSTRAINT `reparto_ibfk_2` FOREIGN KEY (`juguetes_reparto`) REFERENCES `juguetes` (`id_juguetes`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
260bf997851c05194c9f9035536db7575772078d
|
[
"SQL",
"PHP"
] | 2 |
PHP
|
marobri79/practica2Dwec
|
bc4a06083935ee06ad35eac357ca6aa35527d7e6
|
7bb308a4792f15b61ff89a586d0c4dd6ff9a4dc5
|
refs/heads/master
|
<repo_name>kfjhdoghfkdvhf/server<file_sep>/app.js
/* File app.js se thuc hien cac chuc nang nhu binh thuong, khong co van de gi :) */
'use strict';
global.express = require('express');
var app = express();
var services = require(root_path + '/server/services/router');
app.use(function(request, respone, next){
console.log("co nguoi dang nhap vao dia chi: " + request.url);
next()
});
app.use('/services', services);
app.listen(8080);
console.log("app dang chay o cong 8080")
<file_sep>/services/router.js
/* service router*/
var router = express.Router();
var authentication = require(root_path+'/server/services/authentication');
router.get('/authentication', authentication);
module.exports = router;
|
0ebc72d444e898662c218d9050e903941679e4e8
|
[
"JavaScript"
] | 2 |
JavaScript
|
kfjhdoghfkdvhf/server
|
5b78a70fbfbe4d59933a25366c069d1c284086e9
|
15f51a360c8c3868e5a259653f5c2551e1e45f3e
|
refs/heads/master
|
<file_sep>import firebase from "firebase";
export const state = () => ({
comments: []
})
export const mutations = {
setComments(state, comments) {
state.comments = comments
}
}
export const actions = {
async firebaseFetchComments({commit}, noteId) {
try {
const comments = (await firebase.database().ref(`/notes/${noteId}/comments`).once('value')).val() || {}
const commentsModified = Object.keys(comments).map(key => ({...comments[key], id: key}))
commit('setComments', commentsModified)
return commentsModified
} catch (e) {}
},
async localStorageFetchComments({commit}, noteId) {
try {
const comments = await JSON.parse(window.localStorage.getItem('comments')) || []
const noteComments = comments.filter(el => el.noteId === noteId)
commit('setComments', noteComments)
return comments
} catch (e) {}
},
async firebaseCreateComment({commit}, {...args}) {
try {
await firebase.database().ref(`/notes/${args.noteId}/comments`).push({...args})
return args
} catch (e) {}
},
async localStorageCreateComment({commit, state}, {...args}) {
try {
const comments = [...state.comments]
comments.push(args)
await window.localStorage.setItem('comments', JSON.stringify(comments))
commit('setComments', comments)
} catch (e) {}
},
}
export const getters = {
comments: s => s.comments
}
<file_sep>import {LOCAL_STORAGE} from "../helpers/constants";
export const state = () => ({
storage: LOCAL_STORAGE
})
export const mutations = {
setStorage(state, storage) {
state.storage = storage
}
}
export const actions = {
async updateStorage({commit}, value) {
commit('setStorage', value)
},
}
export const getters = {
storage: s => s.storage
}
|
769c25f79a04e668f90d232ab75d6a062f01614f
|
[
"JavaScript"
] | 2 |
JavaScript
|
voskrekasenko/my-notes
|
17286df9d533a156279058106bef44967ffdf7c8
|
17c918b52e6fba3414a0aad5827bd503744acc29
|
refs/heads/master
|
<repo_name>epigen/Artemether_scRNA<file_sep>/src/16_02_M_DiffGenes_NoInsulin_FindMore.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "16_M_02_DiffGenes/"
dir.create(dirout(out))
list.files(dirout("15_Counts/"))
meta <- loadMMeta2()
meta[,celltype := celltype2]
table(meta$celltype)
pbmc <- loadMData2()
marker.genes <- c("Ins1", "Ins2", "Gcg", "Sst", "Ppy")
# Diff expression of marker genes -----------------------------------------
outTreat <- paste0(out, "VsDMSO_negbinom_onlyIns/")
seurat.genes.use <- marker.genes
seurat.thresh.use <- 0.1
source("src/12_DiffGenes_SCRIPT.R", echo=TRUE)
(load(dirout(outTreat, "AllRes.RData")))
# ggplot(res[!grepl("^\\d", V1)], aes(x=V3, y=V1, color=V3, size=pmin(5, -log10(V2)))) + geom_point() + facet_grid(V1 ~ V2.1) +
# theme_bw(12) + scale_color_gradient2(low="blue", high="red") + xRot()
# ggsave(dirout(out, "VsDMSO_negbinom_onlyIns.pdf"), width=15, height=8)
rm(list=c("seurat.genes.use", "seurat.thresh.use", "outTreat"))
# Diff expression without marker genes -----------------------------------------
pbmcOrig <- pbmc
gg <- row.names(pbmcOrig@data)
rawDat <- [email protected][gg[!gg %in% marker.genes], [email protected]]
str(rawDat)
pbmc <- CreateSeuratObject(raw.data = rawDat, min.cells = 3, min.genes = -Inf, scale.factor=SCALE.FACTOR, project = "X")
pbmc <- NormalizeData(object = pbmc, normalization.method = "LogNormalize", scale.factor = SCALE.FACTOR)
rm(list=c("pbmcOrig"))
outTreat <- paste0(out, "VsDMSO_negbinom_noIns/")
seurat.thresh.use <- 0.1
source("src/12_DiffGenes_SCRIPT.R", echo=TRUE)
# list.files(dirout(outTreat))
#
# x <- loadMMeta2()
# hits <- fread(dirout(outTreat, "3_Agg_Genes.tsv"))
# tar <- hits[V2.1=="A10" & V3.1 == "Alpha" & direction == "up"]$V1
#
# cells = x[celltype2 == "Alpha" & treatment %in% c("DMSO", "A10")]
# cells = cells[sample(1:nrow(cells), 600)][order(replicate, treatment)]$rn
# dat = pbmc@data[tar, cells]
# dat = dat / apply(dat, 1, max)
# pheatmap(dat, cluster_cols=F,
# annotation_col=data.frame(row.names=x$rn, replicate=x$replicate, treatment=x$treatment),
# color=colorRampPalette(c("black", "yellow"))(50))
#
# x2 = x[rn %in% cells]
# x2 <- cbind(x2, data.table(as.matrix(t(dat[,x2$rn]))))
# x2 = melt(x2, id.vars=c("replicate", "treatment"),measure.vars=tar)
# ggplot(x2, aes(x=replicate, fill=treatment,y=value)) + geom_violin() +
# facet_grid(. ~ variable)
# ggsave(dirout(outTreat, "Diff_Expr_example.pdf"), width=15, height=5)
<file_sep>/src/30_03_ClusteringExperiments_raw_subcluster.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
data.raw <- Read10X(paste0(getOption("PROCESSED.PROJECT"), "results_pipeline/cellranger_count/","Human1_2","/outs/raw_gene_bc_matrices_mex/GRCh38/"))
out <- "30_03_ClusteringExperiments_raw_subcluster/"
dir.create(dirout(out))
# SUBCLUSTER --------------------------------------------------------------
meta <- loadHMeta2()
meta <- meta[!sample %in% c("hIslets_I_pla2g16", "hIslets_II_Aold")]
cellsToKeep.list <- with(meta, split(rn, factor(paste(treatment, replicate, sep="_"))))
str(cellsToKeep.list)
# Create one base seurat object -------------------------------------------
pbmcOLD <- CreateSeuratObject(raw.data = data.raw[, meta$rn], min.cells = 3, min.genes = MIN.GENES, scale.factor=SCALE.FACTOR, project = "X")
xnam <- names(cellsToKeep.list)[1]
for(xnam in names(cellsToKeep.list)){
# do this for each
outS <- paste0(out, xnam, "/")
cellsToKeep <- cellsToKeep.list[[xnam]]
cluster.precision <- c()
pbmc <- pbmcOLD
source("src/FUNC_Seurat_subcluster.R",echo=TRUE)
ggplot(data.table(pbmc@[email protected]), aes(x=tSNE_1, y=tSNE_2)) + geom_point(alpha=0.1)
ggsave(dirout(outS, "TSNE.jpg"), w=4,h=4)
}
<file_sep>/src/DropSeq/13_2_MarkerPlot_noGABA.R
require("project.init")
require(Seurat)
require(dplyr)
require(Matrix)
require(methods)
require(gridExtra)
require(glmnet)
require(ROCR)
project.init2("artemether")
out <- "13_2_CellTypes_noGABA/"
dir.create(dirout(out))
load(file=dirout("10_Seurat/", "DropSeq/","DropSeq.RData"))
(load(dirout("12_2_INS_GLC_noGABA/Artemether_groups.RData")))
table(pDat$res.0.5)
pDat[,Celltype := "NA"]
pDat[res.0.5 == 2, Celltype := "Endothelial"]
pDat[res.0.5 %in% c(3), Celltype := "Ductal"]
pDat[res.0.5 %in% c(4), Celltype := "Acinar"]
pDat[res.0.5 == 5, Celltype := "Unclear1"]
pDat[res.0.5 == 6 & tSNE_1 < 0, Celltype := "Tcell"]
pDat[res.0.5 == 6 & tSNE_1 > 0, Celltype := "Dendrites"]
pDat[res.0.5 == 7, Celltype := "Unclear2"]
pDat[group == "GCG+", Celltype := "GCG+"]
pDat[group == "INS+", Celltype := "INS+"]
pDat[group == "INS+ GCG+", Celltype := "INS+ GCG+"]
pDat[Celltype == "NA", Celltype := NA]
table(pDat$Celltype)
write.table(pDat, file=dirout(out, "MetaData.tsv"), sep="\t", quote=F, row.names=F)
# T-SNE
cl.x <- "Celltype"
labelCoordinates <- pDat[,.(tSNE_1=median(tSNE_1), tSNE_2=median(tSNE_2)),by=cl.x]
ggplot(pDat, aes_string(x="tSNE_1",y="tSNE_2", color=cl.x)) + geom_point(alpha=0.5) + # ggtitle(sample.x) +
geom_label(data=labelCoordinates, aes_string(x="tSNE_1", y="tSNE_2", label=cl.x), color="black", alpha=0.5)
ggsave(dirout(out, "Cluster_tSNE_", cl.x, ".pdf"), width=7, height=7)
# Percentages
xx <- pDat[,.N, by=c("Celltype", "sample")]
xx[, sum := sum(N), by="sample"]
xx[,Percentage := N/sum * 100]
ggplot(xx, aes(x=Celltype, fill=sample, y=Percentage)) + geom_bar(position="dodge", stat="identity") +
theme_bw(24) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "Celltype_Percentages.pdf"), height=7, width=7)
pDat <- pDat[!is.na(Celltype)]# & !Celltype %in% c("Dendrites", "Unclear2", "Tcell")]
# Plot unbiased markers
markers <- c("CD3D", "ARX","CRYBA2", "DLK1","GCG","IAPP","INS","KRT8", "KRT19", "LOXL4", "MAFA", "NPTX2", "PRSS1", "RBP4","REG1A","SPARC", "SPP1","TM4SF4","TPSAB1","TTR")
# markers <- c(fread("metadata/PancreasMarkers.tsv")$Human_GeneName,
# fread("metadata/CellMarkers.csv")$GeneSymbol)
pList <- list()
for(mm in unique(markers)){
x <- data.table(pDat,Expression=pbmc@data[mm, pDat$cell])
pList[[mm]] <- ggplot(x, aes(x=tSNE_1, y=tSNE_2, color=Expression)) +
geom_point(alpha=0.5) + ggtitle(mm) + theme_bw(12) + guides(color=F) +
scale_color_gradient(low="lightgrey", high="blue")
}
plt <- grid.arrange(grobs=pList, ncol=4)
ggsave(dirout(out, "Marker_Tsne.jpg"),width=16, height=20, plot=plt)
ggsave(dirout(out, "Marker_Tsne.pdf"),width=16, height=20, plot=plt)
inPath <- dirout("10_Seurat/", "DropSeq/", "Cluster_res.0.5/")
for(f in list.files(inPath, pattern="_version2.tsv")){
markers <- c(markers, fread(paste0(inPath, f))[V4 > 0.1]$V3)
}
markers <- unique(markers[markers %in% row.names(pbmc@data)])
meanMar <- foreach(cl = unique(pDat$Celltype)) %do% {
apply(pbmc@data[markers,pDat[Celltype == cl]$cell], 1, mean)
}
names(meanMar) <- unique(pDat$Celltype)
meanMar <- do.call(cbind, meanMar)
pdf(dirout(out, "MarkerMatrix.pdf"), height=15, width=7, onefile=F)
pheatmap(meanMar[,colnames(meanMar) != "NA"], scale="row")
dev.off()
# DELTA MARKERS
xx <- pDat[is.na(Celltype) | grepl("\\+", Celltype)]
xx[is.na(Celltype),Celltype := "NA"]
pdf(dirout(out, "DeltaMarkers.pdf"), height=5, width=10, onefile=F)
pheatmap(pbmc@data[c("RBP4", "SST", "PCSK1", "HHEX", "INS", "GCG", "TTR", "IAPP","MAFA","DLK1"), xx[order(Celltype)]$cell],
border_color=NA,cluster_rows=F,cluster_cols=F, show_colnames=F,color=colorRampPalette(c("black", "yellow"))(50),
annotation_col = data.frame(Celltype = xx$Celltype, row.names=xx$cell))
dev.off()
for(g in c("RBP4", "SST", "INS")){
xx[[g]] <- pbmc@data[g, xx$cell]
}
ggplot(xx, aes(x=RBP4, y=SST,color=Celltype, shape=sample, size=nGene)) + geom_point(alpha=0.8) + theme_bw(24)
ggsave(dirout(out, "DeltaMarkers_SST_RBP4.pdf"), height=7, width=7)
ggplot(xx, aes(x=INS, y=SST,color=Celltype, shape=sample, size=nGene)) + geom_point(alpha=0.8) + theme_bw(24)
ggsave(dirout(out, "DeltaMarkers_SST_INS.pdf"), height=7, width=7)
ggplot(xx, aes(x=GCG, y=SST,color=Celltype, shape=sample, size=nGene)) + geom_point(alpha=0.8) + theme_bw(24)
ggsave(dirout(out, "DeltaMarkers_SST_GCG.pdf"), height=7, width=7)
ggplot(xx, aes(x=SST)) + geom_density() + theme_bw(24)
ggsave(dirout(out, "DeltaMarkers_SST.pdf"), height=7, width=7)
# Multinomial model -------------------------------------------------------
predMeta <- pDat[sample == "DMSO" & !is.na(Celltype) & Celltype != "INS+ GCG+"]
predMeta <- predMeta[Celltype %in% predMeta[,.N, by="Celltype"][N > 20]$Celltype]
table(predMeta$Celltype)
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$cell]))
set.seed(5001)
glmFit <- glmnet(y=factor(predMeta$Celltype), x=dat,family="multinomial",alpha=1,lambda=0.05)
str(coef(glmFit))
save(glmFit, file=dirout(out, "ModelFit.RData"))
treat <- "DMSO"
for(treat in unique(pDat$sample)){
message(treat)
predMeta <- pDat[sample == treat & Celltype %in% names(coef(glmFit))]
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$cell]))
predMeta$class <- predict(glmFit, dat, type="class")
jac <- matrix(NA, length(unique(predMeta$class)), length(unique(predMeta$Celltype)))
row.names(jac) <- unique(predMeta$class)
colnames(jac) <- unique(predMeta$Celltype)
for(cl1 in unique(predMeta$class)){ for(cl2 in unique(predMeta$Celltype)){
x1 <- predMeta[class == cl1]$cell
x2 <- predMeta[Celltype == cl2]$cell
jac[cl1, cl2] <- length(intersect(x1, x2))/length(union(x1,x2))
}}
pdf(dirout(out, "Prediction_Accuracy_", treat,".pdf"), width=5, height=4.5, onefile=F)
pheatmap(jac[sort(row.names(jac)), sort(colnames(jac))],main= paste(treat, "\nAccuracy = ", round(sum(predMeta$Celltype == predMeta$class)/nrow(predMeta),3)),
color=colorRampPalette(c("lightgrey", "blue"))(50), cluster_rows=F, cluster_cols=F)
dev.off()
}
cf <- do.call(cbind, lapply(coef(glmFit), function(m) as.matrix(m)))
colnames(cf) <- names(coef(glmFit))
pdf(dirout(out, "Prediction_Coefficient.pdf"), width=7, height=10, onefile=F)
pheatmap(as.matrix(cf[apply(cf, 1, sum) != 0 & row.names(cf) != "",]), color=colorRampPalette(c("lightgrey", "blue"))(50))
dev.off()
treat <- "Artemether"
for(treat in unique(pDat$sample)){
predMeta <- pDat[sample == treat & !is.na(Celltype)]
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$cell]))
resp <- predict(glmFit, dat, type="response")[,,1]
rowAnnot <- data.frame(predMeta[,"Celltype", with=F], row.names=predMeta$cell)
pdf(dirout(out, "Prediction_",treat,"_Probabilities.pdf"), width=7, height=12, onefile=F)
pheatmap(resp[order(predMeta$Celltype),], annotation_row=rowAnnot, cluster_rows=F, show_rownames=F,
color=colorRampPalette(c("lightgrey", "blue"))(50))
dev.off()
stopifnot(all(predMeta$cell == row.names(resp)))
predMeta$Beta_Probability <- resp[,"INS+"]
predMeta$Alpha_Probability <- resp[,"GCG+"]
pList <- lapply(unique(predMeta$Celltype), function(gg){
ggplot(predMeta, aes(x=Beta_Probability, y=Alpha_Probability)) +
geom_point(alpha=0.7, color="lightgrey") +
geom_point(data=predMeta[Celltype == gg], alpha=0.7, color="black") +
xlab("Beta cell class probability") + ylab("Alpha cell class probability") + ggtitle(gg)
})
names(pList) <- unique(predMeta$Celltype)
plt <- gridExtra::grid.arrange(grobs=pList[c("INS+", "GCG+", "INS+ GCG+", "Endothelial")], ncol=4)
ggsave(dirout(out, "Prediction_",treat,"Probabilities.pdf"), width=16, height=4, plot=plt)
plt <- gridExtra::grid.arrange(grobs=pList, ncol=3)
ggsave(dirout(out, "Prediction_",treat,"Probabilities_All.pdf"), width=13, height=13, plot=plt)
}<file_sep>/src/20_01_AlphaCellSignature.R
# This script does the same as 20_01 but just slightly different
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "20_01_AlphaCells/"
dir.create(dirout(out))
metaH <- loadHMeta2()
metaM <- loadMMeta2()
pbmcM <- loadMData2()
pbmcH <- loadHData2()
# Identify Cell type markers ----------------------------------------------------------------
markers.file <- dirout(out, "Markers.RData")
if(!file.exists(markers.file)){
require(doMC); registerDoMC(cores=2)
org <- "mouse"
for(org in c("human", "mouse")){
pbmc <- pbmcM
meta <- metaM
if(org == "human"){
pbmc <- pbmcH
meta <- metaH
}
meta <- meta[treatment == "DMSO"]
meta <- meta[rn %in% unique(do.call(c, lapply(split(meta$rn, factor(paste(meta$replicate, meta$celltype2))), function(x) sample(x, 200, replace=T))))]
table(meta$celltype2)
pbmc <- SubsetData(pbmc, cells.use=meta$rn)
meta <- meta[match(row.names(<EMAIL>), meta$rn)]
stopifnot(all(meta$rn == row.names(pbmc<EMAIL>)))
pbmc@ident <- factor(meta$celltype2)
names(pbmc@ident) <- [email protected]
(celltypes <- unique(as.character(pbmc@ident)))
cells <- "Alpha"
foreach(cells = c("Alpha", "Beta")) %dopar% {
if(!file.exists(dirout(out, cells, "_", org, ".tsv"))){
cluster.markers <- FindMarkers(pbmc,
thresh.use=0.7,
test.use="roc",
ident.1 = cells,
ident.2 = celltypes[celltypes != cells])
write.table(cluster.markers, dirout(out, cells, "_", org, ".tsv"), sep="\t", quote=F, row.names=TRUE)
}
}
}
markers <- do.call(rbind, lapply(list.files(dirout(out), pattern="\\.tsv"), function(x) data.table(fread(dirout(out, x)), name=x)))
markers[, name := gsub(".tsv", "", name)]
markers <- cbind(markers, do.call(rbind, strsplit(markers$name, "_")))
colnames(markers) <- make.unique(colnames(markers))
save(markers, file=markers.file)
} else {
load(markers.file)
}
# Calculate marker based scores ----------------------------------------------------------------
scores.file <- dirout(out, "Scores.RData")
if(!file.exists(scores.file)){
org <- "mouse"
for(org in c("mouse", "human")){
pbmc <- pbmcM
meta <- metaM
if(org == "human"){
pbmc <- pbmcH
meta <- metaH
}
mark <- markers[V2 == org & myAUC > 0.75]
ct <- "Alpha"
for(ct in unique(mark$V1.1)){
x <- as.matrix(pbmc@data[mark[V1.1 == ct]$V1,meta$rn])
x <- x - rowMin(x)
x <- x / rowMax(x)
meta[[paste0(ct, "_score")]] <- colMeans(x)
h <- sapply(split(meta$rn, factor(with(meta, paste(celltype2, treatment, replicate, sep="_")))),function(rns) rowMeans(x[,rns, drop=F]))
pdf(dirout(out, "GeneAverages_", org, "_", ct, ".pdf"), width=25, height=8, onefile=F)
pheatmap(h, cluster_cols=F)
dev.off()
}
if(org == "mouse") metaM <- meta
if(org == "human") metaH <- meta
}
save(metaH, metaM, file=scores.file)
} else { load(scores.file)}
# Plot scores ----------------------------------------------------------------
for(org in c("mouse", "human")){
meta <- if(org == "human") metaH else metaM
meta$treatment <- factor(meta$treatment, levels = c("DMSO", unique(meta[treatment != "DMSO"]$treatment)))
for(score in c("Beta_score", "Alpha_score")){
for(treat in unique(meta$treatment)){
ggplot(meta[treatment %in% c(treat, "DMSO") & celltype2 %in% c("Alpha", "Beta")], aes_string(x=score, color="treatment")) + theme_bw(12) +
stat_ecdf() + facet_grid(replicate ~ celltype2)+ scale_color_manual(values=c("black", "red"))
ggsave(dirout(out, "Density_", org, "_", treat, "_", score, ".pdf"), width=8, height=12)
}
ggplot(meta[celltype2 %in% c("Alpha", "Beta")], aes_string(y=score, x="treatment")) + theme_bw(12) +
geom_violin() + facet_grid(replicate ~ celltype2)
ggsave(dirout(out, "Violin_", org, "_", "_", score, ".pdf"), width=8, height=12)
}
}<file_sep>/src/36_01_INSposALphaCells.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
require(Rtsne)
project.init2("artemether")
out <- "36_01_AlphaInsHighVsLow/"
dir.create(dirout(out))
metaH <- loadHMeta2()
metaM <- loadMMeta2()
pbmcH <- loadHData2()
pbmcM <- loadMData2()
metaH <- assignGenesMeta(c("INS", "GCG"), metaH, pbmcH)
metaM <- assignGenesMeta(c("Ins2", "Gcg"), metaM, pbmcM)
metaM[,INS := Ins2]
ct <- "Alpha"
orgx <- "human"
# GET DIFF GENES ----------------------------------------------------------
cluster.markers <- list()
for(orgx in c("mouse", "human")){
metaX <- metaH
pbmc <- pbmcH
if(orgx == "mouse"){
metaX <- metaM
pbmc <- pbmcM
}
metaX <- metaX[celltype2 == "Alpha"]
metaX$group <- c("INShigh", "INSlow")[(metaX$INS == 0) + 1]
pbmc <- SubsetData(pbmc, cells.use=metaX$rn)
[email protected][["cluster"]] <- metaX[match(row.names([email protected]), metaX$rn)]$group
pbmc@ident <- factor([email protected][["cluster"]])
names(pbmc@ident) <- [email protected] # it needs those names apparently
cluster.markers[[orgx]] <- FindMarkers(pbmc, test.use="negbinom",ident.1 = "INShigh", ident.2 = "INSlow")
write.table(cluster.markers[[orgx]], dirout(out, orgx, "Markers.tsv"), sep="\t", quote=F, row.names=TRUE)
}
<file_sep>/src/20_02_AlphaCellSignature2.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
inDir <- "20_01_AlphaCells/"
out <- "20_02_Signatures/"
dir.create(dirout(out))
metaH <- loadHMeta2()
metaM <- loadMMeta2()
pbmcM <- loadMData2()
pbmcH <- loadHData2()
load(dirout(inDir, "Markers.RData"))
# Calculate marker based scores ----------------------------------------------------------------
scores.file <- dirout(out, "Scores.RData")
if(!file.exists(scores.file)){
org <- "mouse"
for(org in c("mouse", "human")){
pbmc <- pbmcM
meta <- metaM
if(org == "human"){
pbmc <- pbmcH
meta <- metaH
}
mark <- markers[V2 == org & myAUC > 0.75]
ct <- "Alpha"
for(ct in unique(mark$V1.1)){
x <- as.matrix(pbmc@data[mark[V1.1 == ct]$V1,meta$rn])
dr <- sapply(split(meta$rn, factor(meta$celltype2)),function(rns) rowMeans(x[,rns, drop=F]))
dr <- dr[,-which(colnames(dr) == ct)] - dr[,ct]
x <- x[names(which(
apply(dr < -log(2), 1, sum) >= ncol(dr) * 1 &
apply(dr < 0, 1, sum) == ncol(dr)
)),,drop=F]
x <- x - rowMin(x)
x <- x / rowMax(x)
meta[[paste0(ct, "_score")]] <- colMeans(x)
h <- sapply(split(meta$rn, factor(with(meta, paste(celltype2, treatment, replicate, sep="_")))),function(rns) rowMeans(x[,rns, drop=F]))
pdf(dirout(out, "GeneAverages_", org, "_", ct, ".pdf"), width=25, height=8, onefile=F)
pheatmap(h, cluster_cols=F)
dev.off()
}
if(org == "mouse") metaM <- meta
if(org == "human") metaH <- meta
}
save(metaH, metaM, file=scores.file)
} else { load(scores.file)}
# Plot scores ----------------------------------------------------------------
org <- "human"
score <- "Alpha_score"
for(org in c("mouse", "human")){
meta <- if(org == "human") metaH else metaM
meta$treatment <- factor(meta$treatment, levels = c("DMSO", sort(unique(meta[treatment != "DMSO"]$treatment))))
for(score in c("Beta_score", "Alpha_score")){
# for(treat in unique(meta$treatment)){
# ggplot(meta[treatment %in% c(treat, "DMSO") & celltype2 %in% c("Alpha", "Beta")], aes_string(x=score, color="treatment")) + theme_bw(12) +
# stat_ecdf() + facet_grid(replicate ~ celltype2)+ scale_color_manual(values=c("black", "red"))
# ggsave(dirout(out, "Density_", org, "_", treat, "_", score, ".pdf"), width=8, height=12)
# }
# meta[celltype2 %in% c("Alpha", "Beta")][,score := mean(get(score)), by=c("treatment", "replicate", "celltype2")]
# ggplot(meta[celltype2 %in% c("Alpha", "Beta")], aes_string(y=score, x="treatment")) + theme_bw(12) +
# geom_violin(draw_quantiles=c(0.25, 0.5, 0.75)) + facet_grid(replicate ~ celltype2)
# ggsave(dirout(out, "Violin_", org, "_", "_", score, ".pdf"), width=8, height=12)
#
ggplot(meta[celltype == "Endocrine" & celltype2 %in% c("Alpha", "Beta")], aes_string(y=score, x="treatment")) + theme_bw(12) +
geom_violin(draw_quantiles=c(0.25, 0.5, 0.75)) + facet_grid(replicate ~ celltype2)
ggsave(dirout(out, "ViolinEndocrine_", org, "_", "_", score, ".pdf"), width=8, height=12)
}
# ggplot(meta[celltype2 %in% c("Alpha", "Beta", "Gamma", "Delta") & treatment %in% c("DMSO", "A10")],
# aes(x=Alpha_score, y=Beta_score, color=treatment)) + stat_ellipse() + facet_grid(replicate ~ .)
# ggsave(dirout(out, "Ellipses_", org, ".pdf"), width=4, height=8)
#
# ggplot(meta[celltype2 %in% c("Alpha", "Beta", "Gamma", "Delta") & treatment %in% c("DMSO", "A10")],
# aes(x=Alpha_score, y=Beta_score,color=treatment)) + geom_point(alpha=0.1) + facet_grid(replicate ~ .) +
# scale_color_manual(values=c("blue", "red"))
# ggsave(dirout(out, "Points_", org, ".pdf"), width=4, height=8)
#
# ggplot(meta[celltype2 %in% c("Alpha", "Beta", "Gamma", "Delta") & treatment %in% c("DMSO", "A10")],
# aes(x=Alpha_score, y=Beta_score)) + geom_hex() + facet_grid(replicate ~ treatment) +
# scale_color_manual(values=c("blue", "red"))
# ggsave(dirout(out, "Hex_", org, ".pdf"), width=8, height=8)
}
<file_sep>/src/21_01_CellCorrelation.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "21_01_CellCorrelation/"
dir.create(dirout(out))
metaH <- loadHMeta2()
metaM <- loadMMeta2()
metaH3 <- loadH3Meta2()
(load(dirout("20_01_AlphaCells/", "Markers.RData")))
markers <- markers[power > 0.5]
write.tsv(markers, dirout(out, "Markers.tsv"))
xx <- "Markers"
for(xx in c("Markers")){
outX <- paste0(out, xx, "/")
dir.create(dirout(outX))
org <- "human3"
for(org in c("human", "mouse", "human3")){
org.file <- dirout(outX, org, ".RData")
if(!file.exists(org.file)){
pbmc <- NULL
meta <- NULL
if(org == "mouse"){
pbmc <- loadMData2()
meta <- metaM
}
if(org == "human"){
pbmc <- loadHData2()
meta <- metaH
}
if(org == "human3"){
pbmc <- loadH3Data2()
meta <- metaH3
}
stopifnot(!is.null(pbmc) & !is.null(meta))
genes <- row.names(pbmc@data)
if(xx == "Markers") genes <- markers[V2 == gsub("\\d+$", "", org)]$V1
meta <- meta[celltype %in% c("Alpha", "Beta", "Delta", "Gamma", "Endocrine")]
meta2 <- data.table()
for(rep in unique(meta$replicate)){
metaR <- meta[replicate == rep]
beta.mean <- Matrix::rowMeans(pbmc@data[genes, metaR[treatment == "DMSO" & celltype == "Beta"]$rn])
alpha.mean <- Matrix::rowMeans(pbmc@data[genes, metaR[treatment == "DMSO" & celltype == "Alpha"]$rn])
metaR$betaCor <- cor(as.matrix(pbmc@data[genes, metaR$rn]), beta.mean, method="spearman")
metaR$alphaCor <- cor(as.matrix(pbmc@data[genes, metaR$rn]), alpha.mean, method="spearman")
meta2 <- rbind(meta2, metaR)
}
save(meta2, genes, file=org.file)
} else {
load(org.file)
}
meta2[,corDiff := betaCor - alphaCor]
write.tsv(meta2, dirout(outX, "MetaData_", org, ".tsv"))
treatments <- as.character(unique(meta2$treatment))
treatments <- treatments[treatments != "DMSO"]
meta2$treatment <- factor(meta2$treatment, levels=c("DMSO", treatments))
treat <- "A10"
nrR <- length(unique(meta2$replicate))
for(treat in treatments){
# Density plots
for(cc in c("betaCor", "alphaCor")){
(p <- ggplot(meta2[treatment %in% c("DMSO", treat)], aes_string(x=cc, color="treatment")) +
theme_bw(12) + geom_density() + scale_color_manual(values=c("black", "red")))
ggsave(dirout(outX, paste(org, treat, cc, sep="_"),"comb.pdf"), width=5, height=4)
(p + facet_grid(. ~ replicate))
ggsave(dirout(outX, paste(org, treat, cc, sep="_"), ".pdf"), width=5*nrR, height=4)
}
(p <- ggplot(meta2[treatment %in% c("DMSO", treat)], aes_string(x="corDiff", color="treatment")) +
theme_bw(12) + geom_density() + scale_color_manual(values=c("black", "red")))
ggsave(dirout(outX, paste(org, treat, sep="_"),"_diff_comb.pdf"), width=5, height=4)
(p + facet_grid(. ~ replicate))
ggsave(dirout(outX, paste(org, treat, sep="_"), "_diff.pdf"), width=5*nrR, height=4)
(p <- ggplot(meta2[treatment %in% c("DMSO", treat)], aes(x=alphaCor, y=betaCor, color=treatment)) + geom_point(alpha=0.05) +
scale_color_manual(values=c("black", "red")))
ggsave(dirout(outX, paste(org, treat, sep="_"), "_points.jpg"), width=5, height=4)
(p + facet_grid(. ~ replicate))
ggsave(dirout(outX, paste(org, treat, sep="_"), "_points_repl.jpg"), width=5*nrR, height=4)
}
for(cc in c("betaCor", "alphaCor")){
ggplot(meta2, aes_string(x="treatment", y=cc)) + geom_violin(draw_quantiles=c(0.25, 0.5, 0.75)) +
facet_grid(. ~ replicate) + theme_bw(12) + xRot()
ggsave(dirout(outX, paste(org, "violin", cc, sep="_"), ".pdf"), width=5*nrR, height=4)
}
}
}<file_sep>/src/05_PrepSpikeIns_Clean.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "05_SpikeIns_Clean/"
dir.create(dirout(out))
path <- paste0(getOption("PROCESSED.PROJECT"),'results_pipeline/cellranger_count/MF179')
# LOAD DATA INTO SEURAT OBJECT --------------------------------------------
scDat.file <- dirout(out, "scData.RData")
if(!file.exists(scDat.file)){
datH <- Read10X(paste0(path, '_hmG/outs/raw_gene_bc_matrices/hg19/'))
datM <- Read10X(paste0(path, '_hmG/outs/raw_gene_bc_matrices/mm10/'))
str(datH); str(datM)
stopifnot(all(sort(colnames(datH)) == sort(colnames(datM))))
pbmc.data <- rbind(datH, datM)
# Apply UMI threshold
cell.umis <- Matrix::colSums(pbmc.data)
pbmc.data <- pbmc.data[,cell.umis >= MIN.UMIS]
cell.genes <- Matrix::colSums(pbmc.data != 0)
pbmc.data <- pbmc.data[,cell.genes >= MIN.GENES]
# Set up Seurat Object
pbmc <- CreateSeuratObject(raw.data = pbmc.data, min.cells = 3, min.genes = MIN.GENES, scale.factor=SCALE.FACTOR, project = "MH")
#pbmc@data@x <- log(((exp(pbmc@data@x) - 1) / 100) + 1)
save(pbmc, file=scDat.file)
} else {
load(scDat.file)
}
# IDENTIFY ORGANISM -------------------------------------------------------
str(pbmc@data)
org.idx <- substr(row.names(pbmc@data), 0,4) == "hg19"
org.reads.H <- Matrix::colSums([email protected][org.idx, colnames(pbmc@data)])
org.reads.M <- Matrix::colSums([email protected][!org.idx, colnames(pbmc@data)])
pDat <- data.table(rh = org.reads.H, rm = org.reads.M, barcode=colnames(pbmc@data))
pDat$nGene <- Matrix::colSums([email protected][, colnames(pbmc@data)] != 0)
pDat[,org := "NA"]
pDat[,ratio := log2(rh/rm)]
pDat[ratio > 2, org := "human"]
pDat[ratio < -2, org := "mouse"]
ggplot(pDat, aes(x=rh, y=rm, color=org, size=nGene)) + geom_point(alpha=0.3) + geom_abline()+
scale_y_log10() + scale_x_log10() + xlab("Human reads") + ylab("Mouse reads")
ggsave(dirout(out, "IdentifyOrganism.pdf"), height=5, width=6)
# EXPORT ANNOTATION AS FILE -----------------------------------------------
pDat <- pDat[org != "NA"]
write.tsv(pDat[,c("barcode", "org", "ratio")], file=dirout(out, "CrossSpecies_Alignment.tsv"))
# SIGNATURE OF SPIKE INS IN cross alignment --------------------------------------------------
human.sig <- data.table(gene=row.names(pbmc@data)[org.idx],
value=Matrix::rowMeans(pbmc@data[org.idx, pDat[org == "human"]$barcode]))
write.tsv(human.sig, dirout(out, "Human_hmG_signature.tsv"))
mouse.sig <- data.table(gene=row.names(pbmc@data)[!org.idx],
value=Matrix::rowMeans(pbmc@data[!org.idx, pDat[org == "mouse"]$barcode]))
write.tsv(mouse.sig, dirout(out, "Mouse_hmG_signature.tsv"))
# EXPORT SPIKE IN DATA ALIGNED TO TWO ORGANISMS ----------------------------------------
org.to.export <- "human"
for(org.to.export in c("mouse", "human")){
export.file <- dirout(out, "SpikeData_", org.to.export, ".RData")
if(file.exists(export.file)) next
dat <- Read10X(paste0(path, "_", org.to.export, '/outs/raw_gene_bc_matrices/', ifelse(org.to.export == "mouse", "mm10", "GRCh38") ,"/"))
dat.spike <- dat[, colnames(dat) %in% pDat$barcode]
str(dat.spike)
cell.umis <- Matrix::colSums(dat.spike)
dat.spike <- dat.spike[,cell.umis >= MIN.UMIS]
cell.genes <- Matrix::colSums(dat.spike != 0)
dat.spike <- dat.spike[,cell.genes >= MIN.GENES]
tpm.dat <- t(t(dat.spike) * SCALE.FACTOR/Matrix::colSums(dat.spike))
dat.log.spike <- toLogTPM(tpm.dat)
metaDat <- data.table(barcode=colnames(tpm.dat), nUMI=Matrix::colSums(dat.spike), nGene=Matrix::colSums(dat.spike != 0))
metaDat <- merge(metaDat, pDat[,c("org", "barcode"), with=F], by="barcode")
write.tsv(metaDat[order(org)], dirout(out, "SpikeMeta_", org.to.export, ".tsv"))
save(dat.log.spike, file=export.file)
}<file_sep>/README.md
# Artemether_scRNA
Single cell RNA-seq analysis of pancreatic islets with drug treatment. This is the code used to analyze this dataset.
# Structure
Scripts to analyze all data are in src/, see the readme file in this directory for more details.
Additional data (i.e. list of marker genes, etc) are in the folder metadata/.
# System requirements
The code provided requires the setting of two environmental variables $CODEBASE (where the code is) and $PROCESSED (where the data is and analysis results will be stored). For example:
```
export CODEBASE="$HOME/code/"
export PROCESSED="$HOME/projects/"
```
Genome alignments are based on CellRanger (version 2.1.0).
Statistical analysis is based on R (version 3.4.0), using the following packages:
- SoupX (version 0.1.1)
- Seurat (version 2.0.1)
- cowplot (version 0.8.0)
- Rtsne (version 0.13)
- ROCR (version 1.0-7)
- gplots (version 3.0.1.1)
- rhdf5 (version 2.20.0)
- pryr (version 0.1.4)
- project.init (version 0.0.1)
- pheatmap (version 1.0.12)
- glmnet (version 2.0-18)
- enrichR (version 1.0)
- dplyr (version 0.7.2)
- doMC (version 1.3.4)
- iterators (version 1.0.12)
- foreach (version 1.4.3)
- data.table (version 1.12.2)
- cellrangerRkit (version 2.0.0)
- Rmisc (version 1.5)
- plyr (version 1.8.4)
- lattice (version 0.20-38)
- ggplot2 (version 3.1.1)
- RColorBrewer (version 1.1-2)
- Matrix (version 1.2-17)
<file_sep>/src/Fig4and5_plotting.R
require(ggplot2)
require(data.table)
library(dplyr)
require(project.init)
project.init2("artemether")
#########
color_all<- c("#4D4D4E","#1CBCC2", "#4FB763", "#904198")
color_FOX<- c("#4D4D4E","#1CBCC2")
fig4_human<- as.data.frame(fread(dirout("FIG_03_DiffEXPR/", "MetaData_Export_human.tsv")))
fig4_mouse<- as.data.frame(fread(dirout("FIG_03_DiffEXPR/", "MetaData_Export_mouse.tsv")))
#FIGURE 4a- Violin plot for beta cells, human INS and mouse Ins1 and Ins2 with FoxOi
fig4a_human_beta <- fig4_human %>%
filter(celltype2 == "Beta" & treatment%in%c("FoxOi", "DMSO"))
fig4a_mouse_beta <- fig4_mouse %>%
filter(celltype2 == "Beta" & treatment%in%c("FoxOi", "DMSO"))
ggplot(fig4a_human_beta,aes(x=replicate, y=INS, color=treatment, fill=treatment)) + geom_violin()+
scale_color_manual(values = color_FOX) + scale_fill_manual(values = color_FOX)+ theme_bw() +ylim(8,14)+
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")+
labs(y = "Log10 INS") + labs(x = "Replicate")
ggplot(fig4a_mouse_beta,aes(x=replicate, y=Ins1, color=treatment, fill=treatment)) + geom_violin()+
scale_color_manual(values = color_FOX) + scale_fill_manual(values = color_FOX)+ theme_bw() +ylim(8,14)+
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")+
labs(y = "Log10 INS") + labs(x = "Replicate")
ggplot(fig4a_mouse_beta,aes(x=replicate, y=Ins2, color=treatment, fill=treatment)) + geom_violin()+
scale_color_manual(values = color_FOX) + scale_fill_manual(values = color_FOX)+ theme_bw() +ylim(8,14)+
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")+
labs(y = "Log10 INS") + labs(x = "Replicate")
#FIGURE 4C- bubble heatmap for key genes in alpha and beta cell identity
library(gridExtra)
grid_arrange_shared_legend <- function(...) {
plots <- list(...)
g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
grid.arrange(
do.call(arrangeGrob, lapply(plots, function(x)
x + theme(legend.position="none"))),
legend,
ncol = 1,
heights = grid::unit.c(unit(1, "npc") - lheight, lheight))
}
fig4c<- as.data.frame(fread(dirout("FIG_03_DiffEXPR/", "DiffGenes_byReplicate_AlphaBetaOnly.tsv")))
genesbetafoxo <- c("NEUROD1","INS/Ins2", "Ins1", "ISL1", "NKX6-1", "NKX2-2", "FOXA2",
"MAFA", "FOXO3", "FOXO1", "LY96", "CRYBA2", "C2CD4A", "PPP1CC", "PDX1",
"STX4", "YWHAB", "RHOQ", "PAX6", "INSR", "IGF2")
genesalphafoxo <- c("GCG","ARX", "INS/Ins2", "Ins1", "GC", "NEUROD1", "TTR", "PAX6",
"PCSK2", "MAFB", "TM4SF4", "DDIT3", "ID1", "NPTX2")
fig4c_alpha <- fig4c %>%
filter(celltype == "Alpha" & treatment =="FoxOi"& human%in%genesalphafoxo)
fig4c_beta <- fig4c %>%
filter(celltype == "Alpha" & treatment =="FoxOi"& human%in%genesbetafoxo)
fig4c_alpha<-ggplot(fig4c_alpha, aes(x=replicate, y=human, color=logFC, size=pmin(10, -log10(qval)))) +
geom_point() + facet_grid(~org , scales="free", space="free") +
scale_color_gradient2(name="logFC", high="indianred", low="navyblue") +
theme_bw(16) +
scale_size_continuous(name=expression(-log[10](qval))) +
ylab("") + facet_grid(~org)
fig4c_beta<-ggplot(fig4c_beta, aes(x=replicate, y=human, color=logFC, size=pmin(10, -log10(qval)))) +
geom_point() + facet_grid(~org , scales="free", space="free") +
scale_color_gradient2(name="logFC", high="indianred", low="navyblue") +
theme_bw(16) +
scale_size_continuous(name=expression(-log[10](qval))) +
ylab("") + facet_grid(~org)
grid_arrange_shared_legend (fig4c_beta, fig4c_alpha, nrow=2)
#FIGURE 5A - Fraction of alpha cells that express insulin. Use same files as fig4, but filter for alpha cells:
color_5a<- c("#904198", "#4D4D4E","#1CBCC2")
#Filter treatments and samples
fig5a_human <- fig4_human %>%
filter(celltype2 == "Alpha" & treatment%in%c("FoxOi", "DMSO", "Artemether"))
fig5a_mouse <- fig4_mouse %>%
filter(celltype2 == "Alpha" & treatment%in%c("FoxOi", "DMSO", "Artemether"))
#plot distribution
fig5a_human<-ggplot(fig5a_human, aes(x=INS, color=treatment))+ stat_ecdf()
fig5a_mouse_Ins1<-ggplot(fig5a_mouse, aes(x=Ins1, color=treatment))+
stat_ecdf()
fig5a_mouse_Ins2<-ggplot(fig5a_mouse, aes(x=Ins2, color=treatment))+
stat_ecdf()
#inverse plot
fig5a_human + geom_line(aes(y = 1 - ..y..), stat='ecdf', size=1.2) + ylim(0,.17)+labs(x = "Log INS") + xlim(0,15) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5a) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
fig5a_mouse_Ins1 + geom_line(aes(y = 1 - ..y..), stat='ecdf', size=1.2) + ylim(0,.17)+labs(x = "Log Ins1") + xlim(0,15) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5a) + theme_bw() +
theme(text = element_text(size=19), axis.text.x = element_text(size= 16),axis.text.y = element_text(size= 16))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
fig5a_mouse_Ins2 + geom_line(aes(y = 1 - ..y..), stat='ecdf', size=1.2) + ylim(0,.17)+labs(x = "Log Ins2") + xlim(0,15) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5a) + theme_bw() +
theme(text = element_text(size=19), axis.text.x = element_text(size= 16),axis.text.y = element_text(size= 16))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
#FIGure 5C -Bubble heatmap for key genes in alpha Ins+ cells vs alpha Ins- cells.
human_markers<-as.data.frame(fread(dirout("36_01_AlphaInsHighVsLow/", "humanMarkers.tsv")))
mouse_markers<-as.data.frame(fread(dirout("36_01_AlphaInsHighVsLow/", "mouseMarkers.tsv")))
#homology file to convert gene mouse names into human
hom<-as.data.frame(fread(dirout("FIG_03_DiffEXPR/", "Homology_unique.tsv")))
#merge homology file with mouse markers, to get human names
mouse_homology<-merge(hom, mouse_markers, by="gene_mouse")
mouse_names <- names(mouse_homology) %in% c("gene_mouse")
mouse_human_names<- mouse_homology[!mouse_names]
#add human and mouse markers, to have them in the same plot
mouse_human_markers<-rbind(human_markers, mouse_human_names)
#alpha and beta marker genes
genesalphains<- c("GCG", "IAPP", "DLK1","PAX4","NGN3", "ABCC8","PDX1", "MAFA", "NKX6-1", "NKX2-2", "ARX", "TTR", "IGF1R", "SLC2A2", "FOXO1")
fig5c <- mouse_human_markers %>%
filter(gene_human%in%genesalphains)
ggplot(fig5c, aes(x=group, y=gene_human, color=logFC, size=pmin(9, -log10(p_val)))) +
geom_point() + facet_grid(~org , scales="free", space="free") +
scale_color_gradient2(name="logFC", high="indianred", low="navyblue") +
theme_bw(16) +
scale_size_continuous(name=expression(-log[10](p_val))) +
ylab("")
#FIGURE 5D, same data as figure 4A and 5A, but for beta
color_5d<- c("#904198", "#4D4D4E","#1CBCC2")
fig5d_hbeta <- fig4_human %>%
filter(celltype == "Beta" & treatment%in%c("FoxOi", "DMSO", "Artemether"))
fig5d_mbeta <- fig4_mouse %>%
filter(celltype == "Beta" & treatment%in%c("FoxOi", "DMSO", "Artemether"))
ggplot(fig5d_hbeta, aes(x=INS, color=treatment))+ stat_ecdf(size=1.2)+
labs(x = "Log INS") + xlim(5.5,13.5) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5d) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
ggplot(fig5d_mbeta, aes(x=Ins1, color=treatment))+ stat_ecdf(size=1.2)+
labs(x = "Log Ins1") + xlim(5.5,13.5) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5d) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
ggplot(fig5d_mbeta, aes(x=Ins2, color=treatment))+ stat_ecdf(size=1.2)+
labs(x = "Log Ins2") + xlim(5.5,13.5) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5d) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
#inverse plots outside of R
#FIGURE 5E- Bubble plot for expression of key beta cell genes and markers of de-differentiaiton in mouse and human beta cells, Sam data as figure 4c.
genesbetahuman <- c("GCG","UCN3", "HN1", "IMPDH2", "HES1", "NEUROD1","INS/Ins2", "ISL1", "NKX6-1", "NKX2-2", "FOXO3", "PDX1", "FOXO1", "SCG5", "IGF1R", "ABCC8", "GCGR", "TTR", "PCSK2", "MAFB", "INSR", "VAMP2", "CRYBA2", "CDCD4A", "PPP1CC", "YWHAB", "SLC2A2", "RFX6", "SPP1", "PTEN", "PTPN1")
pDat5e_fox <- fig4c %>%
filter(human%in%genesbetahuman &celltype == "Beta"& treatment%in%c("FoxOi") & org%in%c("mouse", "human"))
pDat5e_art <- fig4c %>%
filter(human%in%genesbetahuman &celltype == "Beta"& treatment%in%c("A10") & org%in%c("mouse", "human"))
pDat5e <- hierarch.ordering(pDat5e, "celltype", "group","logFC")
fig5efoxo<-ggplot(pDat5e_art, aes(x=replicate, y=human, color=logFC, size=pmin(10, -log10(qval)))) +
geom_point() + facet_grid(~org , scales="free", space="free") +
scale_color_gradient2(name="logFC", high="indianred", low="navyblue") +
theme_bw(16) +
scale_size_continuous(name=expression(-log[10](qval))) +
ylab("") + xlab("A10") +facet_grid(~org)+theme(legend.position="left", legend.box = "vertical")
fig5eart<-ggplot(pDat5e_fox, aes(x=replicate, y=human, color=logFC, size=pmin(10, -log10(qval)))) +
geom_point() + facet_grid(~org , scales="free", space="free") +
scale_color_gradient2(name="logFC", high="indianred", low="navyblue") +
theme_bw(16) +
scale_size_continuous(name=expression(-log[10](qval))) +
ylab("") + facet_grid(~org)+theme(legend.position="left", legend.box = "vertical")
grid_arrange_shared_legend (fig5eart, fig5efoxo)
#FIGURES S7a- insulin expression in alpha cells, separated by replicates
#same as figure 5a, but facet_grid by replicate to show different replicates
fig5a_human + geom_line(aes(y = 1 - ..y..), stat='ecdf', size=1.2) + ylim(0,.17)+labs(x = "Log Ins2") + xlim(0,15) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5a) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")+
facet_grid(~replicate)
fig5a_mouse_Ins1 + geom_line(aes(y = 1 - ..y..), stat='ecdf', size=1.2) + ylim(0,.17)+labs(x = "Log Ins2") + xlim(0,15) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5a) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")+
facet_grid(~replicate)
fig5a_mouse_Ins2 + geom_line(aes(y = 1 - ..y..), stat='ecdf', size=1.2) + ylim(0,.17)+labs(x = "Log Ins2") + xlim(0,15) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_5a) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")+
facet_grid(~replicate)
#FIGURE S8- Insulin expression in alpha and beta cells in human donor 3
color_supp <- c("#904198","#4D4D4E")
fig_supp8_h3<- as.data.frame(fread(dirout("FIG_03_DiffEXPR/", "MetaData_Export_human3.tsv")))
#filter treatments and samples
figsupp8_h3_alpha_72 <- fig_supp8_h3 %>%
filter(celltype2 == "Alpha" & time=="72" & treatment%in%c("FoxOi", "DMSO", "Artemether"))
figsupp8_h3_beta_72 <- fig_supp8_h3 %>%
filter(celltype2 == "Beta" & time=="72" & treatment%in%c("FoxOi", "DMSO", "Artemether"))
figsupp8_h3_alpha_36 <- fig_supp8_h3 %>%
filter(celltype2 == "Alpha" & time=="36" & treatment%in%c("FoxOi", "DMSO", "Artemether"))
figsupp8_h3_beta_36 <- fig_supp8_h3 %>%
filter(celltype2 == "Beta" & time=="36" & treatment%in%c("FoxOi", "DMSO", "Artemether"))
#plot distributions and inverse plot
figsupp8_h3_alpha_72<-ggplot(figsupp8_h3_alpha_72, aes(x=INS, color=treatment))+
stat_ecdf()
figsupp8_h3_alpha_72 + geom_line(aes(y = 1 - ..y..), stat='ecdf', size=1.2) + ylim(0,.17)+labs(x = "Log INS") + xlim(0,15) +
theme(text = element_text(size=25), axis.text.x = element_text(size= 20),axis.text.y = element_text(size= 20))+
theme(strip.text.y = element_blank())+ facet_grid(~replicate)+
scale_color_manual(values = color_supp) + theme_bw() +
theme(text = element_text(size=19), axis.text.x = element_text(size= 16),axis.text.y = element_text(size= 16))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
figsupp8_h3_alpha_36<-ggplot(figsupp8_h3_alpha_36, aes(x=INS, color=treatment))+
stat_ecdf()
figsupp8_h3_alpha_36 + geom_line(aes(y = 1 - ..y..), stat='ecdf', size=1.2) + ylim(0,.17)+labs(x = "Log INS") + xlim(0,15) +
theme(text = element_text(size=25), axis.text.x = element_text(size= 20),axis.text.y = element_text(size= 20))+
theme(strip.text.y = element_blank())+ facet_grid(~replicate)+
scale_color_manual(values = color_supp) + theme_bw() +
theme(text = element_text(size=19), axis.text.x = element_text(size= 16),axis.text.y = element_text(size= 16))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
#BETA CELLS
ggplot(figsupp8_h3_beta_36, aes(x=INS, color=treatment))+ stat_ecdf(size=1.2)+
labs(x = "Log Ins1") + xlim(5.5,13.5) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_supp) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
ggplot(figsupp8_h3_beta_72, aes(x=INS, color=treatment))+ stat_ecdf(size=1.2)+
labs(x = "Log Ins1") + xlim(5.5,13.5) +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(strip.text.y = element_blank())+
scale_color_manual(values = color_supp) + theme_bw() +
theme(text = element_text(size=27), axis.text.x = element_text(size= 22),axis.text.y = element_text(size= 22))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position="none")
#invert outside of R
<file_sep>/src/EXT_04_OrganismMixtureExperiments.sh
cd $PROCESSED/artemether/analysis/EXT_04_SpeciesMixtures/
wget http://cf.10xgenomics.com/samples/cell-exp/3.0.0/hgmm_1k_v3/hgmm_1k_v3_filtered_feature_bc_matrix.tar.gz
wget http://cf.10xgenomics.com/samples/cell-exp/3.0.0/hgmm_1k_v2/hgmm_1k_v2_filtered_feature_bc_matrix.tar.gz
wget http://cf.10xgenomics.com/samples/cell-exp/3.0.0/hgmm_5k_v3/hgmm_5k_v3_filtered_feature_bc_matrix.tar.gz
wget http://cf.10xgenomics.com/samples/cell-exp/3.0.0/hgmm_10k_v3/hgmm_10k_v3_filtered_feature_bc_matrix.tar.gz
tar -xvzf hgmm_1k_v3_filtered_feature_bc_matrix.tar.gz
mv filtered_feature_bc_matrix hgmm_1k_v3_filtered_feature_bc_matrix
cd hgmm_1k_v3_filtered_feature_bc_matrix
gunzip barcodes.tsv.gz
gunzip features.tsv.gz
gunzip matrix.mtx.gz
mv features.tsv genes.tsv
cd ..
tar -xvzf hgmm_1k_v2_filtered_feature_bc_matrix.tar.gz
mv filtered_feature_bc_matrix hgmm_1k_v2_filtered_feature_bc_matrix
cd hgmm_1k_v2_filtered_feature_bc_matrix
gunzip barcodes.tsv.gz
gunzip features.tsv.gz
gunzip matrix.mtx.gz
mv features.tsv genes.tsv
cd ..
tar -xvzf hgmm_5k_v3_filtered_feature_bc_matrix.tar.gz
mv filtered_feature_bc_matrix hgmm_5k_v3_filtered_feature_bc_matrix
cd hgmm_5k_v3_filtered_feature_bc_matrix
gunzip barcodes.tsv.gz
gunzip features.tsv.gz
gunzip matrix.mtx.gz
mv features.tsv genes.tsv
cd ..
tar -xvzf hgmm_10k_v3_filtered_feature_bc_matrix.tar.gz
mv filtered_feature_bc_matrix hgmm_10k_v3_filtered_feature_bc_matrix
cd hgmm_10k_v3_filtered_feature_bc_matrix
gunzip barcodes.tsv.gz
gunzip features.tsv.gz
gunzip matrix.mtx.gz
mv features.tsv genes.tsv
cd ..<file_sep>/src/DropSeq/15_FirstTestRun.R
require("project.init")
require(Seurat)
require(dplyr)
require(Matrix)
require(methods)
project.init2("artemether")
sample.x <- "IsletTestRun"
data.path <- paste0(Sys.getenv("PROCESSED"), "10x_datasets/results_pipeline/cellranger_count/Islets_10x_test/outs/raw_gene_bc_matrices/GRCh38/")
outS <- "15_TestRun/"
dir.create(dirout(outS))
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Seurat_preprocess.R"),echo=TRUE)
# extra.genes.to.plot <- unique(fread("metadata//PancreasMarkers.tsv")$Human_GeneName)
# x <- fread("metadata//PancreasMarkers.tsv")
# x[Mouse_GeneName == "", Mouse_GeneName := paste0(substr(Human_GeneName,0,1), tolower(substr(Human_GeneName,2,100)))]
# write.table(x, "metadata//PancreasMarkers.tsv", sep="\t", quote=F, row.names=F)
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Enrichr.R"))
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Seurat2.R"),echo=TRUE)
<file_sep>/src/16_02_H_DiffGenes_NoInsulin_FindMore.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "16_H_02_DiffGenes/"
dir.create(dirout(out))
list.files(dirout("15_Counts/"))
meta <- loadHMeta2()
meta[,celltype := celltype2]
table(meta$celltype)
pbmc <- loadHData2()
marker.genes <- c("INS", "GCG", "SST", "PPY")
# Diff expression of marker genes -----------------------------------------
outTreat <- paste0(out, "VsDMSO_negbinom_onlyIns/")
seurat.genes.use <- marker.genes
seurat.thresh.use <- 0.1
source("src/12_DiffGenes_SCRIPT.R", echo=TRUE)
(load(dirout(outTreat, "AllRes.RData")))
# ggplot(res[!grepl("^\\d", V1)], aes(x=V3.1, y=V1.1, color=V3, size=pmin(5, -log10(V2)))) + geom_point() + facet_grid(V1 ~ V2.1) +
# theme_bw(12) + scale_color_gradient2(low="blue", high="red") + xRot()
# ggsave(dirout(out, "VsDMSO_negbinom_onlyIns.pdf"), width=15, height=8)
rm(list=c("seurat.genes.use", "seurat.thresh.use", "outTreat"))
# Diff expression without marker genes -----------------------------------------
pbmcOrig <- pbmc
gg <- row.names(pbmcOrig@data)
rawDat <- [email protected][gg[!gg %in% marker.genes], [email protected]]
str(rawDat)
pbmc <- CreateSeuratObject(raw.data = rawDat, min.cells = 3, min.genes = -Inf, scale.factor=SCALE.FACTOR, project = "X")
pbmc <- NormalizeData(object = pbmc, normalization.method = "LogNormalize", scale.factor = SCALE.FACTOR)
#
# dmso <- log(mean(toTPM(pbmc@data["AC004556.1", meta[treatment == "DMSO" & replicate == "I" & celltype == "Beta"]$rn, drop=F]))+1)
# foxo <- log(mean(toTPM(pbmc@data["AC004556.1", meta[treatment == "FoxO" & replicate == "I" & celltype == "Beta"]$rn, drop=F]))+1)
# a10 <- log(mean(toTPM(pbmc@data["AC004556.1", meta[treatment == "A10" & replicate == "I" & celltype == "Beta"]$rn, drop=F]))+1)
# foxo-dmso
# a10-dmso
rm(list=c("pbmcOrig"))
outTreat <- paste0(out, "VsDMSO_negbinom_noIns/")
seurat.thresh.use <- 0.1
source("src/12_DiffGenes_SCRIPT.R", echo=TRUE)
<file_sep>/src/10_SCRIPT_01_Seurat.R
if(!exists("data.path")) stop("MISSING data.path")
if(!exists("outS")) stop("MISSING outS")
if(!exists("sample.labels")) stop("MISSING sample.labels")
stopifnot(file.exists(data.path))
dir.create(dirout(outS))
(load(data.path))
pbmc.data <- corr.export
if(!exists("seurat.mito.cutoff")) seurat.mito.cutoff <- 0.2
if(!exists("seurat.max.genes")) seurat.max.genes <- Inf
if(!exists("cluster.precision")) cluster.precision <- 0.5
# Apply UMI threshold
cell.umis <- Matrix::colSums(pbmc.data)
if(!is.null(MIN.UMIS)){
pbmc.data <- pbmc.data[,cell.umis >= MIN.UMIS]
}
cell.genes <- Matrix::colSums(pbmc.data != 0)
if(!is.null(MIN.GENES)){
pbmc.data <- pbmc.data[,cell.genes >= MIN.GENES]
}
# Set up Seurat Object
pbmc <- CreateSeuratObject(raw.data = pbmc.data, min.cells = 3, min.genes = MIN.GENES, scale.factor=SCALE.FACTOR, project = "X")
# Add labels for aggregated datasets
[email protected][["sample"]] <- sample.labels$library_id[as.numeric(gsub("^[A-Z]+\\-(\\d+)$", "\\1", colnames(pbmc@data)))]
# Mitochondrial genes
mito.genes <- grep(pattern = "^MT-", x = rownames(x = pbmc@data), value = TRUE, ignore.case=TRUE)
percent.mito <- Matrix::colSums([email protected][mito.genes, ])/Matrix::colSums([email protected])
pbmc <- AddMetaData(object = pbmc, metadata = percent.mito, col.name = "percent.mito")
ggplot([email protected], aes(y=percent.mito, x=nUMI)) + geom_point(alpha=0.3) +
geom_hline(yintercept=seurat.mito.cutoff) +
ggtitle(paste(nrow(<EMAIL>), "cells"))
ggsave(dirout(outS, "QC_MitoPlot.pdf"))
# Number of genes (many genes probably duplets) ---------------------------
ggplot(<EMAIL>, aes(x=nUMI, y=nGene)) + geom_point(alpha=0.3) +
geom_hline(yintercept=seurat.max.genes) + ggtitle(paste(nrow(<EMAIL>), "cells"))
ggsave(dirout(outS, "QC_GenePlot.pdf"))
# Filter genes
VlnPlot(object = pbmc, features.plot = c("nGene", "nUMI", "percent.mito"), nCol = 3)
ggsave(dirout(outS, "QC_Summary.pdf"), height=7, width=7)
pbmc <- FilterCells(object = pbmc, subset.names = c("nGene", "percent.mito"),low.thresholds = c(MIN.GENES, -Inf), high.thresholds = c(seurat.max.genes, seurat.mito.cutoff))
VlnPlot(object = pbmc, features.plot = c("nGene", "nUMI", "percent.mito"), nCol = 3)
ggsave(dirout(outS, "QC_Summary2.pdf"), height=7, width=7)
# Normalize and Scale
pbmc <- NormalizeData(object = pbmc, normalization.method = "LogNormalize", scale.factor = SCALE.FACTOR)
pbmc <- ScaleData(object = pbmc, vars.to.regress = c("nUMI", "percent.mito"))
# Variable genes
pbmc <- FindVariableGenes(object = pbmc, mean.function = ExpMean, dispersion.function = LogVMR, x.low.cutoff = 0.0125, x.high.cutoff = 3, y.cutoff = 0.5)
#ggsave(dirout(outS, "QC_VariableGenes.pdf"))
# Dimensionality reduction
pbmc <- RunPCA(pbmc, pc.genes = [email protected], do.print = TRUE, pcs.print = 5, genes.print = 5)
pdf(dirout(outS, "QC_PCs.pdf"), height=20, width=20); PCHeatmap(object = pbmc, pc.use = 1:20, cells.use = 500, do.balanced = TRUE, label.columns = FALSE, use.full = FALSE); dev.off()
ggplot(data.table(StandDev=pbmc@dr$pca@sdev, PC=1:20), aes(x=PC, y=StandDev)) + geom_point(); ggsave(dirout(outS, "QC_PC_SD.pdf"), height=7, width=7)
pbmc <- RunTSNE(pbmc, dims.use = 1:10, do.fast = T)
# Clustering
for(x in cluster.precision){
pbmc <- FindClusters(pbmc, reduction.type="pca", dims.use = 1:10, resolution = x, print.output = 0, save.SNN = T)
pbmc <- StashIdent(pbmc, save.name = paste0("ClusterNames_", x))
}
# WRITE META DATA AND TSNE ------------------------------------------------
write.table(
merge(data.table([email protected], keep.rownames=T), data.table(pbmc@[email protected], keep.rownames=T), by="rn"),
file=dirout(outS, "MetaData_tSNE.tsv"), sep="\t", quote=F, row.names=F)
save(pbmc, file=dirout(outS, "SeuratObject",".RData"))
<file_sep>/src/17_02_06_GenePlots_ByGroup_q0.1_noGABAII.R
require("project.init")
project.init2("artemether")
source("src/FUNC_Enrichr.R")
# min 2 replicates
out <- "17_02_06_Gene_plots_q0.1_ByGroup/"
dir.create(dirout(out))
res.file <- dirout(out, "Diff_Genes.tsv")
if(!file.exists(res.file)){
# Load data
(load(dirout("16_H_02_DiffGenes/VsDMSO_negbinom_noIns/AllRes.RData")))
resH <- res
(load(dirout("16_M_02_DiffGenes/VsDMSO_negbinom_noIns/AllRes.RData")))
resM <- res
resH <- resH[V1.1 != "II" | V2 != "GABA"]
resH <- resH[V2 != "pla2g16"]
resH[,qval := p.adjust(p_val, method="BH")]
resM[,qval := p.adjust(p_val, method="BH")]
# Combine results
resH[,org:="human"]
resM[,org:="mouse"]
resX <- rbind(resH, resM)
write.tsv(resX, dirout(out, "AllResults.tsv"))
res.agg <- resX[qval < 0.1]
res.agg <- res.agg[, count := .N, by=c("V1", "V2", "V3", "direction", "org")]
res.agg <- res.agg[, logFC := mean(avg_diff), by=c("V1", "V2", "V3", "direction", "org")]
res.agg[,totalCnt := length(unique(V1.1)), by=c("V2", "org")]
res.agg[,.(totalCnt = length(unique(V1.1))), by=c("V2", "org")]
res.agg <- res.agg[count >= totalCnt]
res <- res.agg[, .(count = .N, logFC = mean(avg_diff)), by=c("V1", "V2", "V3", "direction", "org")]
table(res$count, paste(res$V2, res$org))
write.tsv(res, res.file)
} else {
res <- fread(res.file)
}
# Plot numbers
ggplot(res, aes(x=V3, fill=direction)) + geom_bar(position="dodge") + theme_bw(12) +
facet_grid(org ~ V2) + theme(axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5))
ggsave(dirout(out, "Numbers.pdf"), width=20, height=10)
# MAP TO HOMOLOGS ---------------------------------------------------------
source("src/FUNCTIONS_Synonyms_etc.R")
# homologs.file <- dirout(out, "Homologs.tsv")
# if(!file.exists(homologs.file)){
# source("src/FUNCTIONS_Synonyms_etc.R")
# resHomologs <- res
# resHomologs <- merge(resHomologs, homol, by.x="V1", by.y="mouse", all.x=T)
# resHomologs <- merge(resHomologs, homol, by.x="V1", by.y="human", all.x=T)
# resHomologs[org == "human", human := V1]
# resHomologs[org == "mouse", mouse := V1]
# write.tsv(resHomologs, file=homologs.file)
# } else {
# resHomologs <- fread(homologs.file)
# }
# resHomologs <- resHomologs[!is.na(human) & !is.na(mouse)]
# resHomologs[,id := paste(V2, V3, org, direction)]
# x <- resHomologs[((V2 == "FoxO" & direction == "down") |
# (V2 == "A10" & org == "human") |
# (V2 == "A10" & org == "mouse" & direction == "down")) & V3 == "Beta"]
# gplots::venn(split(x$human, factor(x$id)))
# # Enrichments
# ll2 <- with(res, split(V1, factor(paste(V2, V3, direction, org, sep="_"))))
# enr <- enrichGeneList.oddsRatio.list(ll2, enrichrDBs=ENRICHR.DBS)
# enrichr.plot.many(enrichRes=enr, out=dirout(out), label="Enrichr_")
# enr <- fread(dirout(out, "Enrichr_.tsv"))
#
# # ENRICHR OVERLAPS --------------------------------------------------------
# enr <- cbind(enr, do.call(rbind, strsplit(enr$grp, "_")))
# enr2 <- enr[V1 %in% c("A10", "FoxO") & V2 %in% c("Alpha", "Beta") & hitLength > 2]
# enrichr.plot.many(enrichRes=enr2, out=dirout(out), label="EnrFocus_")
# enr2 <- enr[V1 %in% c("A10") & V2 %in% c("Alpha", "Beta") & V3 == "up" & hitLength > 2]
# enrichr.plot.many(enrichRes=enr2, out=dirout(out), label="EnrFocus2_")
#
#
#
# # MOUSE VS HUMAN ----------------------------------------------------------
# enrX <- enr[database %in% c("ENCODE_and_ChEA_Consensus_TFs_from_ChIP-X", "TRANSFAC_and_JASPAR_PWMs")]
# enrB <- enrX[V3 == "up" & V1 == "A10" & V2 == "Beta"]
# enrB <- enrB[category %in% enrB[,.N,by="category"][N == 1]$category]
# enrA <- enrX[V3 == "up" & V1 == "A10" & V2 == "Alpha"]
# enrA <- enrA[category %in% enrA[,.N,by="category"][N == 1]$category]
# enrC <- rbind(enrA, enrB)
# enrCC <- enr[V3 == "up" & V1 == "A10" & V2 %in% c("Beta", "Alpha") & category %in% enrC$category]
# enrCC <- hierarch.ordering(dt=enrCC,toOrder="category",orderBy="grp",value.var="oddsRatio")
# ggplot(enrCC, aes(x=category, y=V4, color=oddsRatio, size=pmin(5, -log10(qval)))) +
# geom_point() +
# geom_point(data=enrCC[qval < 0.05], color="black", size=1) +
# theme_bw(12) +
# theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
# facet_grid(V2 ~ database, space="free_x", scales="free_x") +
# scale_color_gradient(low= "grey", high="red")
# ggsave(dirout(out,"MvsH.pdf"), width=14, height=4)
#
# write.tsv(enrCC, dirout(out, "MvsH.tsv"))
# Gene HITS overlaps - JACCARD AND MDS ------------------------------------------------------
source("src/FUNCTIONS_Synonyms_etc.R")
hits <- copy(res)
hits[,grp := paste(V2, V3, direction, org, sep="_")]
hits[org == "human",gene := V1]
hits[org == "mouse"]$gene <- homol[match(hits[org == "mouse"]$V1, homol$mouse)]$human
write.tsv(hits, dirout(out, "Hits_Mapped.tsv"))
hits <- hits[!is.na(gene)]
x <- toMT(dt=hits,row="gene", col="grp", val="logFC")
x[is.na(x)] <- 0
write.table(x, dirout(out, "Hits_Overlaps.tsv"), sep="\t", row.names=TRUE, quote=FALSE)
ll <- split(hits$gene, factor(hits$grp))
cleanDev()
pdf(dirout(out, "Hits_Jaccard.pdf"), height=15, width=15,onefile=F)
pheatmap(jaccard(ll),cluster_rows=T, cluster_cols=T,color=colorRampPalette(c("grey", "blue"))(50))
dev.off()
#
# xx <- list(human=hits[org=="human"], mouse=hits[org=="mouse"], comb=hits)
# for(nam in names(xx)){
# hitsX <- xx[[nam]]
# MDS.scale=cmdscale(as.dist(1-jaccard(split(hitsX$gene, factor(hitsX$grp)))), eig = TRUE, k = 2)
# MDS = data.table(sample_name =rownames(MDS.scale$points), MDS1 = MDS.scale$points[,1], MDS2 = MDS.scale$points[, 2])
# MDS <- cbind(MDS, do.call(rbind, strsplit(MDS$sample_name, "_")))
# hitsX <- xx[[nam]]
# MDS.scale=cmdscale(as.dist(1-jaccard(split(hitsX$gene, factor(hitsX$grp)))), eig = TRUE, k = 2)
# MDS = data.table(sample_name =rownames(MDS.scale$points), MDS1 = MDS.scale$points[,1], MDS2 = MDS.scale$points[, 2])
# MDS <- cbind(MDS, do.call(rbind, strsplit(MDS$sample_name, "_")))
# ggplot(MDS, aes(x=MDS1, y=MDS2)) +
# geom_point(aes(color=V1), alpha=0.5) +
# geom_text(aes(label=V2,color=V1), data=MDS[V2 %in% c("Alpha", "Beta")]) +
# theme_bw(12) + facet_grid(V3 ~ V4) +
# scale_color_manual(values=COLORS.TREATMENTS)
# ggsave(dirout(out, "Hits_MDS_",nam,".pdf"), width=length(unique(MDS$V4)) * 4 + 1, height=9)
# }
# Correlation in logfold changes ------------------------------------------
hm.col <- colorRampPalette(c("lightgrey", "khaki", "darkorchid4"))(51)
orgx <- "human"
for(orgx in c("human", "mouse")){
resX <- fread(dirout(out, "AllResults.tsv"))
resX[,id := gsub("I+_", "", file)]
resX.H <- resX[V3 %in% c("Alpha", "Beta")][org == orgx][,.(logFC = mean(avg_diff)), by=c("V1", "id")]
resX.H.MT <- toMT(resX.H, row="V1", col="id", val="logFC")
#ggplot(data.table(resX.H.MT), aes(x=A10_Beta, y=FoxO_Beta)) + geom_point()
corMT <- cor(resX.H.MT, use="pairwise.complete.obs", method="spearman")
diag(corMT) <- NA
cleanDev()
pdf(dirout(out, "HM_Similarity_",orgx,".pdf"), width=6, height=6, onefile=F)
pheatmap(corMT, color=hm.col, na_col="lightgrey")#, breaks=seq(0,1,0.02))
dev.off()
}<file_sep>/src/03_CellrangerAggregate.sh
#!/bin/bash
cr="$CODEBASE/cellranger-2.1.0/cellranger"
basePW=$PROCESSED/artemether/results_pipeline/cellranger_count/
cd ${basePW}
sbatch --job-name="10X aggr Mouse samples" --cpus-per-task=5 --ntasks=1 --mem=30000 --partition=mediumq --time=1-00:00:00 \
--wrap="$cr aggr --id=Mouse --csv=$CODEBASE/artemether/metadata/Aggregate_Mouse.csv --normalize=none" \
--output="Mouse.log"
sbatch --job-name="10X aggr MouseLTI samples" --cpus-per-task=5 --ntasks=1 --mem=30000 --partition=mediumq --time=1-12:00:00 \
--wrap="$cr aggr --id=MouseLTI --csv=$CODEBASE/artemether/metadata/Aggregate_Mouse_withLTI.csv --normalize=none" \
--output="MouseLTI.log"
file=Human1
sbatch --job-name="10X aggr $file" --cpus-per-task=5 --ntasks=1 --mem=30000 --partition=mediumq --time=1-00:00:00 \
--wrap="$cr aggr --id=$file --csv=$CODEBASE/artemether/metadata/Aggregate_$file.csv --normalize=none" \
--output="$file.log"
file=Human1_2
sbatch --job-name="10X aggr $file" --cpus-per-task=5 --ntasks=1 --mem=30000 --partition=mediumq --time=1-00:00:00 \
--wrap="$cr aggr --id=$file --csv=$CODEBASE/artemether/metadata/Aggregate_$file.csv --normalize=none" \
--output="$file.log"
file=Human3
sbatch --job-name="10X aggr $file" --cpus-per-task=5 --ntasks=1 --mem=30000 --partition=mediumq --time=1-00:00:00 \
--wrap="$cr aggr --id=$file --csv=$CODEBASE/artemether/metadata/Aggregate_$file.csv --normalize=none" \
--output="$file.log"<file_sep>/src/FIG_GEO.R
require(project.init)
project.init2("artemether")
out <- "GEO/"
dir.create(dirout(out))
outFTP <- paste0(out, "FTP/")
dir.create(dirout(outFTP))
# FIND ALL FASTQs ---------------------------------------------------------
bsf.dirs <- unique(c(
"/data/groups/lab_bsf/sequences/BSF_0409_HNCYFBBXX_l1_l2_l3_l4_l5_l6_l7_10x/fastq_path/HNCYFBBXX/",
"/data/groups/lab_bsf/sequences/BSF_0410_HNF7TBBXX_l1_10x/fastq_path/HNF7TBBXX/",
"/data/groups/lab_bsf/sequences/BSF_0412_HNJH5BBXX_l1_10x/fastq_path/HNJH5BBXX/",
"/data/groups/lab_bsf/sequences/BSF_0429_HNTVGBBXX_l5_l6_l7_l8_10x/fastq_path/HNTVGBBXX/",
"/data/groups/lab_bsf/sequences/BSF_0409_HNCYFBBXX_l1_l2_l3_l4_l5_l6_l7_10x/fastq_path/HNCYFBBXX/",
"/data/groups/lab_bsf/sequences/BSF_0410_HNF7TBBXX_l1_10x/fastq_path/HNF7TBBXX/",
"/data/groups/lab_bsf/sequences/BSF_0412_HNJH5BBXX_l1_10x/fastq_path/HNJH5BBXX/",
"/data/groups/lab_bsf/sequences/BSF_0429_HNTVGBBXX_l5_l6_l7_l8_10x/fastq_path/HNTVGBBXX/",
"/data/groups/lab_bsf/sequences/BSF_0460_HV235BBXX_l1_l7_l8_10x/fastq_path/HV235BBXX/",
"/data/groups/lab_bsf/sequences/BSF_0525_H2K53BBXY_l2_l3_l4_l5_l6_l7_l8_10x/fastq_path/H2K53BBXY/"
))
ff <- do.call(c, lapply(bsf.dirs, function(x){list.files(x, recursive=T, full.names=T)}))
names(ff) <- basename(ff)
ff <- ff[grepl("hIslet", names(ff)) | grepl("mIslet", names(ff)) | grepl("MF179", names(ff))]
# LIST OF RAW FASTQ FILES -----------------------------------------------------
if(!file.exists(dirout(out, "RawAnnotation.tsv"))){
raw.ann <- data.table(path = ff)
raw.ann[,file := basename(path)]
raw.ann[,single := ifelse(grepl("I1", file), "single", "paired")]
raw.ann[grepl("I1", file), length := 8]
raw.ann[grepl("R1", file), length := 26]
raw.ann[grepl("R2", file), length := 58]
raw.ann[, sample := gsub("_S\\d{1,3}_.+$", "", file)]
with(raw.ann, table(sample, length))
for(i in 1:nrow(raw.ann)){
raw.ann[i, checksum := md5sum(path)]
}
raw.ann <- raw.ann[!grepl("pla2g16", sample)]
raw.ann <- raw.ann[!grepl("LT1", sample)]
stopifnot(nrow(raw.ann) == length(unique(raw.ann$file)))
write.tsv(raw.ann, dirout(out, "RawAnnotation.tsv"))
}
# LIST OF PAIRED-END RAW FILES
raw.ann <- fread(dirout(out, "RawAnnotation.tsv"))
paired.ann <- raw.ann[grepl("R1", file), "file", with=F]
paired.ann[,file2 := gsub("R1", "R2", file)]
write.tsv(paired.ann, dirout(out, "PairedAnnotation.tsv"))
# COLLECT PROCESSED DATA ----------------------------------------------------------
outFTP_processed <- paste0(out, "FTP_processed/")
dir.create(dirout(outFTP_processed))
outZIP <- paste0(out, "ZIP/")
dir.create(dirout(outZIP))
all.samples <- c("Human1_2", "Human3", "MouseLTI", "MF179")
samplex <- all.samples[1]
sample.to.run <- data.table()
for(samplex in all.samples){
# Clean annotation
meta <- NA
if(samplex == "Human1_2") meta <- loadHMetaUnfiltered()
if(samplex == "MouseLTI") meta <- loadMMetaUnfiltered()
if(samplex == "Human3") meta <- loadH3MetaUnfiltered()
if(samplex == "MF179") meta <- fread(dirout("05_SpikeIns_Clean/", "CrossSpecies_Alignment.tsv"))
if("treatment" %in% colnames(meta)) meta <- meta[treatment != "pla2g16"]
write.tsv(meta, dirout(outFTP_processed, samplex, "_CellAnnotation_final.tsv"))
# Raw annotation
if(samplex != "MF179"){
merge.csv <- fread(paste0(Sys.getenv("PROCESSED"), '/artemether/results_pipeline/cellranger_count/',samplex,'/outs/aggregation_csv.csv'), header=T)
sample.to.run <- rbind(sample.to.run, data.table(sample=samplex, run=sapply(strsplit(merge.csv$molecule_h5, "/"), function(x) rev(x)[3])))
# cell.ann <- fread(paste0(Sys.getenv("PROCESSED"), '/artemether/results_pipeline/cellranger_count/',samplex,'/outs/cell_barcodes.csv'), header=F)
# cell.ann[,i := as.numeric(gsub(".+-(\\d+)", "\\1", V2))]
# cell.ann$sample <- gsub("^\\s*(.+)\\s*$", "\\1", merge.csv[cell.ann$i]$library_id)
# cell.ann <- cell.ann[,c("V2", "sample"), with=F]
# colnames(cell.ann) <- c("Cell barcode", "Sample")
# write.tsv(cell.ann, dirout(outFTP_processed, samplex, "_CellAnnotation_raw.tsv"))
} else {
sample.to.run <- rbind(sample.to.run, data.table(sample=samplex, run=samplex))
}
# Corrected reads
data <- NA
if(samplex == "Human1_2") data <- loadHData()
if(samplex == "MouseLTI") data <- loadMData()
if(samplex == "Human3") data <- loadH3Data()
if(!is.na(data)){
data.export <- [email protected][,data.table([email protected], keep.rownames=T)[!grepl("pla2g16", sample)]$rn]
writeMM([email protected], dirout(outFTP_processed, samplex, "_correctedTPM_Matrix.mtx"))
write.table([email protected]@Dimnames[[1]], dirout(outFTP_processed, samplex, "_correctedTPM_Matrix_genes.txt"), col.names=F, quote=F, row.names=F)
write.table([email protected]@Dimnames[[2]], dirout(outFTP_processed, samplex, "_correctedTPM_Matrix_barcodes.txt"), col.names=F, quote=F, row.names=F)
#system(paste("zip", dirout(outFTP_processed, samplex, "_correctedTPM_Matrix.zip"), dirout(outZIP, samplex, "_correctedTPM_Matrix*")))
}
}
sample.to.run <- sample.to.run[!grepl("pla2g16", run)]
write.tsv(sample.to.run, dirout(out, "Samples2run.mapping.tsv"))
# Generate Table of processed data ----------------------------------------------------------
processed.ann <- data.table(file.path=list.files(dirout(outFTP_processed), full.names=T))
# for(samplex in all.samples){
# fx <- paste0(Sys.getenv("PROCESSED"), '/artemether/results_pipeline/cellranger_count/',samplex, ifelse(samplex == "MF179", "_hmG", ""),'/outs/raw_gene_bc_matrices_h5.h5')
# stopifnot(file.exists(fx))
# processed.ann <- rbind(processed.ann, data.table(file.path = fx))
# }
for(samplex in all.samples){
processed.ann[grepl(samplex, file.path), sample := samplex]
}
processed.ann[, file := basename(file.path)]
processed.ann[grepl("raw_gene_bc_matrices_h5.h5$", file.path), file := paste0(sample, "_", basename(file.path))]
for(i in 1:nrow(processed.ann)){
processed.ann[i, checksum := md5sum(file.path)]
}
stopifnot(length(unique(processed.ann$file))== nrow(processed.ann))
write.tsv(processed.ann, dirout(out, "ProcessedAnnotation.tsv"))
# List of samples and raw / processed data --------------------------------
processed.ann <- fread(dirout(out, "ProcessedAnnotation.tsv"))
processed.by.sample <- split(processed.ann$file, factor(processed.ann$sample))
processed.by.sample.max <- max(sapply(processed.by.sample,length))
processed.by.sample <- lapply(processed.by.sample, function(x){return(c(x, rep("", times=processed.by.sample.max-length(x))))})
raw.ann <- fread(dirout(out, "RawAnnotation.tsv"))
raw.by.run <- split(raw.ann$file, factor(raw.ann$sample))
raw.by.run.max <- max(sapply(raw.by.run,length))
raw.by.run <- lapply(raw.by.run, function(x){return(c(x, rep("", times=raw.by.run.max-length(x))))})
run.ann <- fread(dirout(out, "Samples2run.mapping.tsv"))
run.ann[sample == "Human3", run := gsub("_human$", "", run)]
run.ann[,molecule := "mRNA"]
run.ann[grepl("^hI", run),organism := "Human"]
run.ann[grepl("^mI", run),organism := "Mouse"]
run.ann[grepl("^MF179", run),organism := "Human/Mouse"]
run.ann[,source_name := "Pancreatic Islet cells"]
run.ann[grepl("DMSO", run), treament:= "DMSO (Control)"]
run.ann[grepl("GABA", run), treament:= "GABA"]
run.ann[grepl("FoxO", run), treament:= "FOXO inhibitor"]
run.ann[is.na(treament), treament:= paste("Artemether (10muM)")]
run.ann[grepl("36hr", run), treament_time := "36hr"]
run.ann[grepl("72hr", run), treament_time := "72hr"]
run.ann[is.na(treament_time), treament_time := "72hr"]
run.ann[is.na(treament_time), treament_time := "72hr"]
run.ann <- cbind(run.ann, do.call(rbind, processed.by.sample[run.ann$sample]))
run.ann <- cbind(run.ann, data.table(do.call(rbind, raw.by.run[run.ann$run])))
write.tsv(run.ann, dirout(out, "Run_Annotation.tsv"))
# Commands to upload files ------------------------------------------------
write("", dirout(out, "Upload_commands.sh"))
processed.ann <- fread(dirout(out, "ProcessedAnnotation.tsv"))
for(i in 1:nrow(processed.ann)){
stopifnot(file.exists(processed.ann[i]$file.path))
write(paste("put -z", processed.ann[i]$file.path, processed.ann[i]$file), dirout(out, "Upload_commands.sh"), append=T)
}
raw.ann <- fread(dirout(out, "RawAnnotation.tsv"))
for(i in 1:nrow(raw.ann)){
stopifnot(file.exists(raw.ann[i]$path))
write(paste("put -z", raw.ann[i]$path, raw.ann[i]$file), dirout(out, "Upload_commands.sh"), append=T)
}
<file_sep>/src/02_Cellranger.sh
cr="$CODEBASE/cellranger-2.1.0/cellranger"
mouseGenome=/home/nfortelny/resources_nfortelny/10X_Genomics/refdata-cellranger-mm10-1.2.0/
humanGenome=/home/nfortelny/resources_nfortelny/10X_Genomics/refdata-cellranger-GRCh38-1.2.0/
combinedGenome=/home/nfortelny/resources_nfortelny/10X_Genomics/refdata-cellranger-hg19_and_mm10-1.2.0/
rfpGenome=$PROCESSED/artemether/custom_genomes/RFP_Genome/refdata-cellranger-mm10-1.2.0_ext/
outPath=$PROCESSED/artemether/results_pipeline/cellranger_count/
###
### DATA FROM BSF 0409 (Jan 24 2018)
###
inPath=/data/groups/lab_bsf/sequences/BSF_0409_HNCYFBBXX_l1_l2_l3_l4_l5_l6_l7_10x/fastq_path/HNCYFBBXX/
mkdir $outPath
cd $outPath
# MURINE DATA (No lineage tracing)
array=("mIslets_I_A1" "mIslets_I_A10" "mIslets_I_DMSO" "mIslets_I_FoxO" "mIslets_I_GABA" "mIslets_II_A1" "mIslets_II_A10" "mIslets_II_DMSO" "mIslets_II_FoxO_1_S33905" "mIslets_II_GABA_1_S33901" "mIslets_III_A1" "mIslets_III_A10" "mIslets_III_DMSO_1_S33909" "mIslets_III_FoxO_1_S33925" "mIslets_III_GABA")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=$file --transcriptome=$rfpGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="$outPath/$file.log"
done
# LINEAGE TRACING
array=("mIslets_LT1_FoxO_1_S33961")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=$file --transcriptome=$rfpGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="$outPath/$file.log"
done
# HUMAN DATA
array=("hIslets_I_A10_1_S33933" "hIslets_I_DMSO_1_S33929")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=$file --transcriptome=$humanGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="$outPath/$file.log"
done
###
### DATA FROM BSF 0410 (Jan 26 2018)
###
inPath=/data/groups/lab_bsf/sequences/BSF_0410_HNF7TBBXX_l1_10x/fastq_path/HNF7TBBXX/
mkdir $outPath
cd $outPath
# HUMAN DATA
array=("hIslets_I_FoxO_1_S33941" "hIslets_I_GABA_1_S33937" "hIslets_I_pla2g16_1_S33945")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=$file --transcriptome=$humanGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="$outPath/$file.log"
done
###
### DATA FROM BSF 0412 (Feb 5 2018)
###
inPath=/data/groups/lab_bsf/sequences/BSF_0412_HNJH5BBXX_l1_10x/fastq_path/HNJH5BBXX/
mkdir $outPath
cd $outPath
# LTI data
array=("mIslets_LT1_A10" "mIslets_LT1_DMSO" "mIslets_LT1_GABA")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=$file --transcriptome=$rfpGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90 --chemistry=SC3Pv2" \
--output="$outPath/$file.log"
done
###
### DATA FROM BSF 0429 (March 19, 2018), Human islets
###
inPath=/data/groups/lab_bsf/sequences/BSF_0429_HNTVGBBXX_l5_l6_l7_l8_10x/fastq_path/HNTVGBBXX/
mkdir $outPath
cd $outPath
array=("hIslets_II_A1" "hIslets_II_A2" "hIslets_II_DMSO" "hIslets_II_FoxO" "hIslets_II_GABA")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=$file --transcriptome=$humanGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}.log"
done
################
################ ALIGN TO MOUSE AND HUMAN
################
###
### DATA FROM BSF 0409 (Jan 24 2018)
###
inPath=/data/groups/lab_bsf/sequences/BSF_0409_HNCYFBBXX_l1_l2_l3_l4_l5_l6_l7_10x/fastq_path/HNCYFBBXX/
mkdir $outPath
cd $outPath
# MURINE DATA (No lineage tracing)
array=("mIslets_I_A1" "mIslets_I_A10" "mIslets_I_DMSO" "mIslets_I_FoxO" "mIslets_I_GABA" "mIslets_II_A1" "mIslets_II_A10" "mIslets_II_DMSO" "mIslets_II_FoxO_1_S33905" "mIslets_II_GABA_1_S33901" "mIslets_III_A1" "mIslets_III_A10" "mIslets_III_DMSO_1_S33909" "mIslets_III_FoxO_1_S33925" "mIslets_III_GABA")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_hmG --transcriptome=$combinedGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="$outPath/${file}_hmG.log"
done
# LINEAGE TRACING
array=("mIslets_LT1_FoxO_1_S33961")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_hmG --transcriptome=$combinedGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="$outPath/${file}_hmG.log"
done
# HUMAN DATA
array=("hIslets_I_A10_1_S33933" "hIslets_I_DMSO_1_S33929")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_hmG --transcriptome=$combinedGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="$outPath/${file}_hmG.log"
done
###
### DATA FROM BSF 0410 (Jan 26 2018)
###
inPath=/data/groups/lab_bsf/sequences/BSF_0410_HNF7TBBXX_l1_10x/fastq_path/HNF7TBBXX/
mkdir $outPath
cd $outPath
# HUMAN DATA
array=("hIslets_I_FoxO_1_S33941" "hIslets_I_GABA_1_S33937" "hIslets_I_pla2g16_1_S33945")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_hmG --transcriptome=$combinedGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="$outPath/${file}_hmG.log"
done
###
### DATA FROM BSF 0412 (Feb 5 2018)
###
inPath=/data/groups/lab_bsf/sequences/BSF_0412_HNJH5BBXX_l1_10x/fastq_path/HNJH5BBXX/
mkdir $outPath
cd $outPath
# LTI data
array=("mIslets_LT1_A10" "mIslets_LT1_DMSO" "mIslets_LT1_GABA")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_hmG --transcriptome=$combinedGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90 --chemistry=SC3Pv2" \
--output="$outPath/${file}_hmG.log"
done
###
### DATA FROM BSF 0429 (March 19, 2018), Human islets
###
inPath=/data/groups/lab_bsf/sequences/BSF_0429_HNTVGBBXX_l5_l6_l7_l8_10x/fastq_path/HNTVGBBXX/
mkdir $outPath
cd $outPath
array=("hIslets_II_A1" "hIslets_II_A2" "hIslets_II_DMSO" "hIslets_II_FoxO" "hIslets_II_GABA" "Hypothalamus_traject_E15" "Hypothalamus_traject_E17" "Hypothalamus_traject_P0" "Hypothalamus_traject_P10" "Hypothalamus_traject_P2" "Hypothalamus_traject_P23" "Hypothalamus_traject_P2SN")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_hmG --transcriptome=$combinedGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}_hmG.log"
done
array=("Hypothalamus_traject_E15" "Hypothalamus_traject_E17" "Hypothalamus_traject_P0" "Hypothalamus_traject_P10" "Hypothalamus_traject_P2" "Hypothalamus_traject_P23" "Hypothalamus_traject_P2SN")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file human" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_human --transcriptome=$humanGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}_human.log"
done
array=("Hypothalamus_traject_E15" "Hypothalamus_traject_E17" "Hypothalamus_traject_P0" "Hypothalamus_traject_P10" "Hypothalamus_traject_P2" "Hypothalamus_traject_P23" "Hypothalamus_traject_P2SN")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file mouse" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_mouse --transcriptome=$mouseGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}_mouse.log"
done
###
### DATA FROM BSF 0429 (March 19, 2018), References
###
inPath=/data/groups/lab_bsf/sequences/BSF_0460_HV235BBXX_l1_l7_l8_10x/fastq_path/HV235BBXX/
mkdir $outPath
cd $outPath
array=("MF179")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_hmG --transcriptome=$combinedGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}_hmG.log"
done
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file human" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_human --transcriptome=$humanGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}_human.log"
done
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file mouse" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_mouse --transcriptome=$mouseGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}_mouse.log"
done
###
### DATA FROM BSF_0525_H2K53BBXY (October 2, 2018), Human islets III
###
inPath=/data/groups/lab_bsf/sequences/BSF_0525_H2K53BBXY_l2_l3_l4_l5_l6_l7_l8_10x/fastq_path/H2K53BBXY/
mkdir $outPath
cd $outPath
array=("hIslets_III_A1_36hr" "hIslets_III_A2_72hr" "hIslets_III_DMSO1_72hr" "hIslets_III_DMSO3_72hr" "hIslets_III_A1_72hr" "hIslets_III_A3_72hr" "hIslets_III_DMSO2_36hr" "hIslets_III_A2_36hr" "hIslets_III_DMSO1_36hr" "hIslets_III_DMSO2_72hr")
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file combined" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_hmG --transcriptome=$combinedGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}_hmG.log"
done
for file in ${array[@]}
do
echo $file
sbatch --job-name="10X $file human" --cpus-per-task=16 --ntasks=1 --mem=90000 --partition=longq --time=5-00:00:00 \
--wrap="$cr count --id=${file}_human --transcriptome=$humanGenome --fastqs=$inPath/${file} --expect-cells=10000 --localcores=16 --localmem=90" \
--output="${file}_human.log"
done<file_sep>/src/06_SpikeIns_Islets.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "06_SpikeIns_Islets/"
dir.create(dirout(out))
# args = commandArgs(trailingOnly=TRUE)
# orgX <- args[1]
# if(is.na(args[1])) orgX <- "mouse"
path <- paste0(getOption("PROCESSED.PROJECT"),'results_pipeline/cellranger_count/')
f <- list.files(path, pattern = paste0("^.Islets", ".+_hmG$"))
f <- list.files(path, pattern = paste0("^hIslets_III_", ".+_hmG$"))
require(doMC); registerDoMC(cores=10)
fX <- f[8]
foreach(fX = f) %dopar% {
orgX <- if(grepl("hIslets", fX)) "human" else "mouse"
message(fX)
outF <- paste0(out, fX, "/")
dir.create(dirout(outF))
# LOAD DATA INTO SEURAT OBJECT --------------------------------------------
scDat.file <- dirout(outF, "scData.RData")
if(!file.exists(scDat.file)){
datH <- Read10X(paste0(path, fX, '/outs/raw_gene_bc_matrices/hg19/'))
datM <- Read10X(paste0(path, fX, '/outs/raw_gene_bc_matrices/mm10/'))
str(datH); str(datM)
stopifnot(all(sort(colnames(datH)) == sort(colnames(datM))))
pbmc.data <- rbind(datH, datM)
# Apply UMI threshold
cell.umis <- Matrix::colSums(pbmc.data)
pbmc.data <- pbmc.data[,cell.umis >= 500]
cell.genes <- Matrix::colSums(pbmc.data != 0)
pbmc.data <- pbmc.data[,cell.genes >= 200]
# Set up Seurat Object
pbmc <- CreateSeuratObject(raw.data = pbmc.data, min.cells = 3, min.genes = 200, scale.factor=1e6, project = "MH")
save(pbmc, file=scDat.file)
} else {
load(scDat.file)
}
# IDENTIFY ORGANISM -------------------------------------------------------
str(pbmc@data)
org.idx <- substr(row.names(pbmc@data), 0,4) == "hg19"
org.reads.H <- Matrix::colSums(<EMAIL>[org.idx, colnames(pbmc@data)])
org.reads.M <- Matrix::colSums(<EMAIL>[!org.idx, colnames(pbmc@data)])
pDat <- data.table(rh = org.reads.H, rm = org.reads.M, barcode=colnames(pbmc@data))
pDat$nGene <- Matrix::colSums(<EMAIL>[, colnames(pbmc@data)] != 0)
pDat[,org := "NA"]
pDat[,ratio := log2(rh/rm)]
pDat[ratio > 2, org := "human"]
pDat[ratio < -2, org := "mouse"]
pDat[,nUMI := rm + rh]
pDat[org == "human",contamination := rm/nUMI]
pDat[org == "mouse",contamination := rh/nUMI]
pDat[org == orgX, contamination := NA]
(p <- ggplot(pDat, aes(x=rh, y=rm, color=org, size=nGene)) + geom_point(alpha=0.3) + geom_abline()+
scale_y_log10() + scale_x_log10() + xlab("Human reads") + ylab("Mouse reads") + theme_bw(12))
ggsave(dirout(outF, "IdentifyOrganism.pdf"), height=4, width=5)
ggsave(dirout(outF, "IdentifyOrganism.jpg"), height=4, width=5)
ggsave(dirout(outF, "IdentifyOrganism2.pdf"), height=4, width=4, plot=p+guides(color=F, fill=F, size=F))
ggsave(dirout(outF, "IdentifyOrganism2.jpg"), height=4, width=4, plot=p+guides(color=F, fill=F, size=F))
# Annotate spike ins via correlation
spike.sig <- fread(dirout("05_SpikeIns_Clean/",ifelse(orgX == "human", "Human", "Mouse"), "_hmG_signature.tsv"))
spike.sig <- spike.sig[gene %in% row.names(pbmc@data)]
corr <- cor(spike.sig$value, as.matrix(pbmc@data[spike.sig$gene,]), use="pairwise.complete.obs")
pDat$corrToSpike <- corr[1,pDat$barcode]
pDat[(corrToSpike > 0.9 & org == orgX) | ! org %in% c("NA", orgX), spikeIn := org]
table(pDat$spikeIn)
write.tsv(pDat[,c("barcode", "org", "ratio", "contamination","corrToSpike", "spikeIn")], file=dirout(outF, "IdentifyOrganism.tsv"))
write.tsv(pDat, file=dirout(outF, "IdentifyOrganism_full.tsv"))
# LOOK AT CONTAMINATION ---------------------------------------------------
genes.use <- if(orgX == "human") row.names(pbmc@data)[org.idx] else row.names(pbmc@data)[!org.idx]
cont <- data.table(inHuman = Matrix::rowMeans(pbmc@data[genes.use,pDat[org == "human"]$barcode]))
cont$inMouse <- Matrix::rowMeans(pbmc@data[genes.use,pDat[org == "mouse"]$barcode])
cont$gene <- if(orgX == "human") gsub("hg19_", "", genes.use) else gsub("mm10_", "", genes.use)
write.tsv(cont, file=dirout(outF, "Contamination.tsv"))
xAxis <- "inMouse";yAxis <- "inHuman"
if(orgX == "human"){
xAxis <- "inHuman";yAxis <- "inMouse"
}
ggplot(cont, aes_string(x=xAxis, y=yAxis)) + geom_point(alpha=0.5, color="grey") #+ geom_text(data=cont[inHuman > 130,], aes(label=gene))
ggsave(dirout(outF, "Contamination_vs_Expression.pdf"), height=5, width=6)
ggplot(cont, aes_string(x=xAxis, y=yAxis)) + geom_point() +
scale_y_log10() + scale_x_log10()
ggsave(dirout(outF, "Contamination_vs_Expression_log.pdf"), height=5, width=6)
}<file_sep>/src/FIG_01_Correlate_Replicates.R
require("project.init")
project.init2("artemether")
out <- "FIG_01_Correlate_Replicates/"
dir.create(dirout(out))
orgx <- "human"
cleanTreatment <- function(vec){ gsub("^FoxO$", "FoxOi", gsub("^A10$", "Artemether", vec)) }
# Get average expression --------------------------------------------------
metaH <- if(orgx == "mouse") loadMMetaUnfiltered() else loadHMetaUnfiltered()
gene.means.raw.file <- dirout(out, "gene.means.raw.RData")
if(!file.exists(gene.means.raw.file)){
if(orgx == "mouse") (load(dirout("07_11_CleanMouse_CleanSpikeIns/","Uncorrected.Data.RData"))) else (load(dirout("07_03_CleanHuman_CleanSpikeIns/","Uncorrected.Data.RData")))
str(data.raw.cells)
data.raw.cells <- toTPM_fromRaw(data.raw.cells, scale.factor=SCALE.FACTOR)
gene.means.raw <- sapply(with(metaH, split(rn, factor(paste(replicate, treatment, celltype2)))), function(rns) Matrix::rowMeans(data.raw.cells[,rns,drop=F]))
str(gene.means.raw)
rm(list=c("data.raw.cells", "meta.raw.cells", "spikeIn.soups", "ml.rho.pred", "ml.rho.pred.with.cv"))
save(gene.means.raw, file=gene.means.raw.file)
} else {
load(gene.means.raw.file)
}
gene.means.cor.file <- dirout(out, "gene.means.cor.RData")
if(!file.exists(gene.means.cor.file)){
pbmcH <- if(orgx == "mouse") loadMData() else loadHData()
data.cor.cells <- toTPM(pbmcH@data)
rm(list="pbmcH")
gene.means.cor <- sapply(with(metaH, split(rn, factor(paste(replicate, treatment, celltype2)))), function(rns) Matrix::rowMeans(data.cor.cells[,rns,drop=F]))
str(gene.means.cor)
save(gene.means.cor, file=gene.means.cor.file)
} else {
load(gene.means.cor.file)
}
# Correlate cell types before after ---------------------------------------
rep <- "I"
res <- data.table()
for(rep in c("I", "II")){
treatx <- "DMSO"
for(treatx in c("DMSO", "A10", "GABA", "FoxO")){
g1 <- paste(rep, treatx, "Beta", sep=" ")
g2 <- paste(rep, treatx, "Alpha", sep=" ")
res <- rbind(res, data.table(replicate=rep, treatment=treatx,
corrected=cor(gene.means.cor[,g1], gene.means.cor[,g2]),
raw=cor(gene.means.raw[,g1], gene.means.raw[,g2])))
}
}
res$treatment <- cleanTreatment(res$treatment)
pDat <- melt(res)
pDat$data.type <- factor(pDat$variable, levels=c("raw", "corrected"))
(p <- ggplot(pDat[!(treatment == "GABA" & replicate == "II")], aes(x=data.type,y=value, color=replicate, group=replicate)) + geom_point() + geom_line() + facet_wrap(~treatment, ncol=2) +
theme_bw(16) + xRot() +
ylab("Correlation of\nalpha and beta cells") + xlab("Data"))
ggsave(dirout(out, "Alpha_Beta_Correlation_guide.pdf"), w=4,h=4)
ggsave(dirout(out, "Alpha_Beta_Correlation.pdf"), w=4,h=5, plot=p+guides(color=F))
# Prepare analysis --------------------------------------------------------
# gg <- names(tail(sort(apply(gene.means.cor, 1, min)), 5000))
# #gg <- rownames(gene.means.cor)
# xx <- list(corrected=gene.means.cor[gg,], raw=gene.means.raw[gg,])
# #xx <- list(corrected=gene.means.cor, raw=gene.means.raw)
# # Correlate replicates ----------------------------------------------------
# res <- data.table()
# for(xnam in names(xx)){
# x <- xx[[xnam]]
# grps <- unique(gsub("^I+ ", "X ", colnames(x)))
# i <- grps[1]
# for(i in grps){
# repl1 <- gsub("^X ", "I ", i)
# repl2 <- gsub("^X ", "II ", i)
# if(repl1 %in% colnames(x) & repl2 %in% colnames(x))
# res <- rbind(res, data.table(grp=gsub("^X ", "", i), type=xnam, value=cor(x[,repl1], x[,repl2], method="spearman")))
# }
# }
#
# res <- cbind(res, do.call(rbind, strsplit(res$grp, " ")))
# res[,treatment := cleanTreatment(V1)]
# ct.use <- c("Beta", "Alpha") #, "Delta", "Gamma")
# ggplot(res[V2 %in% ct.use & V1 != "GABA"], aes(x=type, y=value, color=V2, group=paste(V2, V1))) +
# #geom_jitter(height=0, width=0.1) +
# geom_line() + geom_point() +
# facet_grid(. ~ treatment) + theme_bw(12) + xRot()
# ggsave(dirout(out, "Expr_Alpha_Beta_",orgx,".pdf"),w=6,h=4)
#
# res.wide <- dcast.data.table(res, treatment + V2 ~ type, value.var="value")
# res.wide[,diff := corrected - raw]
# ggplot(res.wide, aes(x=treatment, y=V2, fill=diff)) + geom_tile() + scale_fill_gradient2() + xRot()
# ggsave(dirout(out, "Expr_AllCelltypes_",orgx,".pdf"),w=4,h=6)
#
#
#
# # Correlate log fold changes ----------------------------------------------
# res <- data.table()
# xnam <- names(xx)[1]
# for(xnam in names(xx)){
# x <- xx[[xnam]]
# treatments <- unique(gsub(".+ (.+) .+", "\\1", colnames(x)))
# treatments <- treatments[treatments != "DMSO"]
# treatx <- treatments[1]
# for(treatx in treatments[treatments != "DMSO"]){
# x.treat <- x[,grepl(treatx, colnames(x))]
# grps <- unique(gsub("^I+ ", "X ", colnames(x.treat)))
# i <- grps[1]
# for(i in grps){
# repl1 <- gsub("^X ", "I ", i)
# dmso1 <- gsub("^X ", "I ", gsub(treatx, "DMSO", i))
# repl2 <- gsub("^X ", "II ", i)
# dmso2 <- gsub("^X ", "II ", gsub(treatx, "DMSO", i))
# if(sum(c(repl1, repl2, dmso1, dmso2) %in% colnames(x)) == 4){
# fc1 <- x[,repl1] - x[,dmso1]
# fc2 <- x[,repl2] - x[,dmso2]
# res <- rbind(res, data.table(grp=gsub("^X ", "", i), type=xnam, value=cor(fc1, fc2, method="spearman")))
# }
# }
# }
# }
#
# res <- cbind(res, do.call(rbind, strsplit(res$grp, " ")))
# res[,treatment := cleanTreatment(V1)]
# ct.use <- c("Beta", "Alpha") #, "Delta", "Gamma")
# ggplot(res[V2 %in% ct.use & V1 != "GABA"], aes(x=type, y=value, color=V2, group=paste(V2, V1))) +
# #geom_jitter(height=0, width=0.1) +
# geom_line() + geom_point() +
# facet_grid(. ~ treatment) + theme_bw(12) + xRot()
# ggsave(dirout(out, "logFC_Alpha_Beta_", orgx,".pdf"),w=6,h=4)
#
# res.wide <- dcast.data.table(res, treatment + V2 ~ type, value.var="value")
# res.wide[,diff := corrected - raw]
# ggplot(res.wide, aes(x=treatment, y=V2, fill=diff)) + geom_tile() + scale_fill_gradient2() + xRot()
# ggsave(dirout(out, "logFC_AllCelltypes_", orgx,".pdf"),w=4,h=6)<file_sep>/src/FUNC_Seurat2_fast_simple.R
# THIS SCRIPT REQUIRES:
# pbmc object (seurat)
# outS (output dir)
if(!exists("enrichrDBs")) enrichrDBs <- c("NCI-Nature_2016", "WikiPathways_2016", "Human_Gene_Atlas", "Chromosome_Location")
if(!exists("extra.genes.to.plot")) extra.genes.to.plot <- c()
if(!exists("seurat.diff.test")) seurat.diff.test <- "roc"
if(!exists("seurat.thresh.use")) seurat.thresh.use <- 0.25
if(!exists("max.nr.of.cores")) max.nr.of.cores <- 3
if(!exists("seurat.min.pct")) seurat.min.pct <- 0.25
if(!exists("cellMarker.file")) cellMarker.file <- "metadata/CellMarkers.csv"
if(!exists("enrichGeneList.oddsRatio")) tryCatch(source("src/FUNC_Enrichr.R"), error=function(e) stop("Cannot load Enrichr Functions, need to preload (FUNC_SEURAT2.R)"))
if(!exists("figExt")) figExt <- ".pdf"
if(!exists("clusterings.exclude")) clusterings.exclude <- NULL
print(dim(pbmc@data))
require(data.table)
require(pheatmap)
require(ggplot2)
require(doMC)
require(pryr)
# manage memory and number of tasks used
mem_u <- as.numeric(mem_used())/10**6
cores_u = max(1, min(12, floor(180000/mem_u)-1))
if(is.na(mem_u)) cores_u <- 3
cores_u <- min(cores_u, max.nr.of.cores)
message("Memory used: ", mem_u, " cores: ",cores_u)
registerDoMC(cores=cores_u)
# use colnames from <EMAIL> as clusterings
# only those with >= 2 groups with > 1 cell
clusterings <- colnames(pb<EMAIL>)[apply(pb<EMAIL>, 2, function(x) sum(table(x[x!="IGNORED"])>2)>1)]
clusterings <- clusterings[!clusterings %in% c("nUMI", "nGene", "orig.ident", "percent.mito", "var.ratio.pca")]
# reorder to do the kmeans at the end
clusterings <- clusterings[!grepl("ClusterNames", clusterings)]
# reorder to do the kmeans at the end
(clusterings <- c(clusterings[!grepl("res", clusterings)], clusterings[grepl("res", clusterings)]))
clusterings <- clusterings[!clusterings %in% clusterings.exclude]
message("Clusterings: ", paste(clusterings, collapse=" "))
for(cl.x in clusterings){
print(table([email protected][[cl.x]]))
}
# PLOT MARKERS 2
message("Plotting Known marker genes")
outMarkers <- paste0(outS, "Markers/")
dir.create(dirout(outMarkers))
if(file.exists(cellMarker.file)){
markers <- fread(cellMarker.file)[Marker != ""]
for(i in 1:nrow(markers)){
if(markers[i]$GeneSymbol %in% rownames(pbmc@data)){
if(file.exists(dirout(outMarkers, markers[i]$GeneSymbol,figExt))) next
marDat <- data.table(pbmc@[email protected], Expression=pbmc@data[markers[i]$GeneSymbol,])
ggplot(marDat, aes(x=tSNE_1, y=tSNE_2, color=Expression)) + geom_point(alpha=0.5) +
scale_color_gradientn(colors=c("grey", "blue")) + theme(legend.position = 'none') +
ggtitle(paste0(markers[i]$GeneSymbol, "/", markers[i]$Marker, "\n", markers[i]$CellType))
ggsave(dirout(outMarkers, markers[i]$GeneSymbol,figExt), height=7, width=7)
}
}
}
for(geneSyn in extra.genes.to.plot){
if(file.exists(dirout(outMarkers, geneSyn,figExt))) next
if(geneSyn %in% row.names(pbmc@data)){
marDat <- data.table(pbmc@[email protected], Expression=pbmc@data[geneSyn,])
ggplot(marDat, aes(x=tSNE_1, y=tSNE_2, color=Expression)) + geom_point(alpha=0.5) +
scale_color_gradientn(colors=c("grey", "blue")) + theme(legend.position = 'none') +
ggtitle(paste0(geneSyn))
ggsave(dirout(outMarkers, geneSyn,figExt), height=7, width=7)
}
}
# PLOT UMIS ---------------------------------------------------------------
message("Plotting UMIs")
try({
umip <- ggplot(data.table(pbmc@dr$tsne@cell.<EMAIL>, [email protected]$nUMI), aes(x=tSNE_1,y=tSNE_2, color=log10(UMIs))) +
scale_color_gradient(low="blue", high="red") +
geom_point() + ggtitle(paste(nrow(pbmc@data), "genes\n", ncol(pbmc@data), "cells")) + theme_bw(24)
ggsave(dirout(outS, "UMI", figExt),plot=umip, height=7, width=7)
}, silent = TRUE)
# PLOT CLUSTERS
message("Plotting Clusters")
pDat <- data.table(pbmc@[email protected])
cl.x <- "sample"
for(cl.x in clusterings){
print(cl.x)
pDat[[cl.x]] <[email protected][[cl.x]]
labelCoordinates <- pDat[,.(tSNE_1=median(tSNE_1), tSNE_2=median(tSNE_2)),by=cl.x]
ggplot(pDat[get(cl.x) != "IGNORED"], aes_string(x=cl.x)) + geom_bar() + coord_flip()
ggsave(dirout(outS, "Cluster_counts_", cl.x, ".pdf"), height=7, width=7)
ggplot(pDat, aes_string(x="tSNE_1",y="tSNE_2", color=cl.x)) + geom_point(alpha=0.5) + # ggtitle(sample.x) +
geom_label(data=labelCoordinates, aes_string(x="tSNE_1", y="tSNE_2", label=cl.x), color="black", alpha=0.5)
ggsave(dirout(outS, "Cluster_tSNE_", cl.x, figExt), height=7, width=7)
}
write.table(pDat, dirout(outS,"Cluster.tsv"), sep="\t", quote=F, row.names=F)
clusterCounts <- pDat[,-c("tSNE_1", "tSNE_2"), with=TRUE]
clusterCounts <- do.call(rbind, lapply(names(clusterCounts), function(nam) data.table(clusterCounts[[nam]], nam)))
write.table(clusterCounts[, .N, by=c("V1", "nam")], dirout(outS, "ClusterCounts.tsv"), sep="\t", quote=F,row.names=F)
# Markers for each cluster ------------------------------------------------
message("Plotting cluster Markers")
(cl.x <- clusterings[1])
x <- foreach(cl.x = clusterings) %do% {
if(!is.null([email protected][[cl.x]])){
print(cl.x)
x <- gsub("ClusterNames_","", cl.x)
out.cl <- paste0(outS, "Cluster_",x, "/")
dir.create(dirout(out.cl))
pbmc@ident <- factor([email protected][[cl.x]])
names(pbmc@ident) <- pbmc@cell.<EMAIL> # it needs those names apparently
clusters <- names(table(pbmc@ident))[table(pbmc@ident)>2]
clusters <- clusters[clusters != "IGNORED"]
(cl.i <- clusters[10])
foreach(cl.i = clusters) %dopar% {
# message(cl.i)
if(!file.exists(dirout(out.cl, "Markers_Cluster",cl.i, ".tsv"))){
# print(tt <- Sys.time())
cluster.markers <- FindMarkers(pbmc, ident.1 = cl.i, ident.2 = clusters[clusters != cl.i],
test.use=seurat.diff.test,
min.pct = seurat.min.pct,
thresh.use=seurat.thresh.use)
# print(tt - Sys.time())
write.table(cluster.markers, dirout(out.cl, "Markers_Cluster",cl.i, ".tsv"), sep="\t", quote=F, row.names=TRUE)
try({
pdf(dirout(out.cl,"Markers_Cluster",cl.i,".pdf"), height=15, width=15)
FeaturePlot(pbmc, row.names(cluster.markers)[1:min(nrow(cluster.markers),9)],cols.use = c("grey","blue"))
dev.off()
}, silent=T)
# Plot for all clusters heatmap
}
}
}
}
# Enrichr on first Markers -----------------------------------------------------------------
message("EnrichR on first markers")
cl.x <- "patient"
cl.x <- clusterings[1]
for(cl.x in clusterings){
if(!is.null([email protected][[cl.x]])){
print(cl.x)
x <- gsub("ClusterNames_","", cl.x)
# if(!file.exists(dirout(outS, "Enrichr_",x,".tsv"))){
out.cl <- paste0(outS, "Cluster_",x, "/")
f <- list.files(dirout(out.cl), pattern="^Markers_.+?[^2]\\.tsv$")
genes <- lapply(f, function(fx) fread(dirout(out.cl, fx)))
names(genes) <- gsub("Markers_", "", gsub(".tsv","",f))
if(seurat.diff.test == "roc"){
genes <- genes[sapply(genes, ncol) == 6]
genes <- lapply(genes, function(fx) fx[V4 > 0.7]$V1)
} else {
genes <- genes[sapply(genes, ncol) == 5]
genes <- lapply(genes, function(fx) fx[V2 < 0.05 & V3 > 0.3]$V1)
}
genes <- genes[sapply(genes, length) > 4]
# HEATMAP
hm.file <- dirout(outS, "Cluster_simple_HM_",cl.x, ".pdf")
#if(!file.exists(hm.file)){
try({
cells.to.plot <- do.call(c, lapply(split(row.names(<EMAIL>), factor([email protected][[cl.x]])), function(x) sample(x, min(100, length(x)))))
genes.to.plot <- do.call(c, lapply(genes, function(x) x[1:20]))
genes.to.plot <- names(sort(table(genes.to.plot)))[1:min(200, length(genes.to.plot))]
data.to.plot <- pbmc@data[genes.to.plot, cells.to.plot]
data.to.plot <- data.to.plot/apply(data.to.plot, 1, max)
pdf(hm.file, width=15, height=min(29, 1+length(genes.to.plot)*0.1),onefile=F)
pheatmap(data.to.plot, show_colnames=F, cluster_cols=F, fontsize_row=6,
annotation_col=<EMAIL>[,cl.x, drop=F], color=colorRampPalette(c("lightgrey", "blue", "black"))(50))
dev.off()
}, silent=TRUE)
#}
# ENRICHER RESULTS
enrichRes <- data.table()
for(grp.x in names(genes)){
ret=try(as.data.table(enrichGeneList.oddsRatio(genes[[grp.x]],databases = enrichrDBs)),silent = FALSE)
if(!any(grepl("Error",ret)) && nrow(ret) > 0){
enrichRes <- rbind(enrichRes, data.table(ret, grp = grp.x))
}
}
if(nrow(enrichRes) > 0){
enrichRes <- enrichRes[hitLength >= 3]
write.table(enrichRes, file=dirout(outS, "Enrich_simpleMarkers_",x,".tsv"), sep="\t", quote=F, row.names=F)
# plot
enrClass <- enrichRes$database[1]
for(enrClass in unique(enrichRes$database)){
enrichResX <- enrichRes[database == enrClass]
if(nrow(enrichResX) > 0){
enrichr.plot(enrichResX)
ggsave(dirout(outS, "Enrich_simpleMarkers_", enrClass, "_",x,".pdf"), width=min(29, 6+ length(unique(enrichResX$grp))*0.3), height=min(29, length(unique(enrichResX$category))*0.3 + 4))
}
}
} else {
message("No enrichments for ", cl.x)
}
}
}
message("Analysis pipeline completed successfully!")
<file_sep>/src/FUNC_Enrichr.R
require(enrichR)
require(data.table)
# Get Enrichr gene sets ---------------------------------------------------
enrichrGetGenesets <- function(databases){
setNames(lapply(databases, function(dbx){
fpath <- paste0("http://amp.pharm.mssm.edu/Enrichr/geneSetLibrary?mode=text&libraryName=",dbx)
fhandle <- file(fpath)
dblines <- tryCatch({
readLines(con=fhandle)
}, error=function(e){
message(e, "\nFailed reading database: ", dbx)
NULL
})
close(fhandle)
if(is.null(dblines)){
return(list())
}else {
res <- strsplit(dblines, "\t")
names(res) <- sapply(res, function(x) x[1])
res <- lapply(res, function(x) x[3:length(x)])
return(res)
}
}), databases)
}
# Call Enrichr --------------------------------------------------
enrichGeneList.oddsRatio <- function(gene.list, databases = "KEGG_2016", fdr.cutoff = 0.1, genome.size=20000) {
res <- enrichr(gene.list, databases)
res <- lapply(res, data.table)
res <- res[sapply(res, nrow) > 0]
res <- do.call(rbind, lapply(names(res), function(rnam) data.table(res[[rnam]], database=rnam)))
if(is.null(res)) return(data.table())
res[,Genes := gsub(";", ",", Genes)]
name.map <- list(
c("Term", "category"),
c("P.value", "pval"),
c("Adjusted.P.value", "qval"),
c("Combined.Score", "combinedScore"),
c("Genes", "genes"),
c("Odds.Ratio", "oddsRatio"))
for(i in 1:length(name.map)){
colnames(res)[colnames(res) == name.map[[i]][1]] <- name.map[[i]][2]
}
res[,listLength := length(gene.list)]
res[,dbLength := gsub("(\\d+)\\/(\\d+)", "\\2", Overlap)]
res[,hitLength := gsub("(\\d+)\\/(\\d+)", "\\1", Overlap)]
res <- res[,colnames(res) %in% c("database", "category", "pval", "zScore", "combinedScore", "genes", "qval", "dbLength", "listLength", "hitLength", "oddsRatio"),with=F]
return(res)
}
enrichGeneList.oddsRatio.list <- function(geneLists, enrichrDBs="KEGG_2016"){
enrichRes <- data.table()
for(grp.x in names(geneLists)){
print(paste0("Enrichment of list: ", grp.x))
ret=enrichGeneList.oddsRatio(geneLists[[grp.x]],databases = enrichrDBs)
if(nrow(ret) > 0){
enrichRes <- rbind(enrichRes, data.table(ret, grp = grp.x))
}
}
return(enrichRes)
}
# PLOT ENRICHR ------------------------------------------------------------
enrichr.plot <- function(enrichRes, qval.cap = 4, qval.cutoff = 0.05){
enrichRes$category <- gsub("\\_(\\w|\\d){8}-(\\w|\\d){4}-(\\w|\\d){4}-(\\w|\\d){4}-(\\w|\\d){12}", "", enrichRes$category)
enrichRes$category <- abbreviate(enrichRes$category, minlength=50) # substr(enrichRes$category2, 0, 50)
enrichRes[,term := paste0(category, "_", dbLength)]
enrichRes <- enrichRes[term %in% enrichRes[,.(min(qval)), by="term"][V1 < qval.cutoff]$term]
if(!is.na(qval.cap)) enrichRes[, mLog10Q := pmin(-log10(qval),qval.cap)]
# order terms by similarity (of OR)
if(length(unique(enrichRes$term)) >= 2){
try({
orMT <- t(as.matrix(dcast.data.table(enrichRes, grp ~ term, value.var="oddsRatio")[,-"grp",with=F]))
orMT[is.na(orMT)] <- 1
orMT[orMT == Inf] <- max(orMT[orMT != Inf])
hclustObj <- hclust(dist(orMT))
enrichRes$term <- factor(enrichRes$term, levels=hclustObj$labels[hclustObj$order])
},silent=T)
}
# order groups by similarity (of OR)
if(length(unique(enrichRes$grp)) >= 2){
try({
orMT <- t(as.matrix(dcast.data.table(enrichRes, term ~ grp, value.var="oddsRatio")[,-"term",with=F]))
orMT[is.na(orMT)] <- 1
orMT[orMT == Inf] <- max(orMT[orMT != Inf])
hclustObj <- hclust(dist(orMT))
enrichRes$grp <- factor(enrichRes$grp, levels=hclustObj$labels[hclustObj$order])
}, silent=T)
}
# plot
p <- ggplot(enrichRes, aes(x=grp, y=term, size=log10(oddsRatio), color=mLog10Q)) +
geom_point() + scale_color_gradient(low="grey", high="red") + theme_bw(12) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
if(!is.na(qval.cap)) p <- p + ggtitle(paste0("-log10(q) capped at ", qval.cap))
}
enrichr.plot.many <- function(enrichRes, out, label="Enrichr", hitLengthCutoff = 3,...){
enrichRes <- enrichRes[hitLength >= hitLengthCutoff]
if(nrow(enrichRes) > 0){
write.table(enrichRes, file=paste0(out, label, ".tsv"), sep="\t", quote=F, row.names=F)
enrClass <- enrichRes$database[1]
for(enrClass in unique(enrichRes$database)){
enrichResX <- enrichRes[database == enrClass]
if(nrow(enrichResX) > 0){
enrichr.plot(enrichResX, ...)
ggsave(paste0(out, label, "_", enrClass, ".pdf"), width=min(29, 6+ length(unique(enrichResX$grp))*0.3), height=min(29, length(unique(enrichResX$category))*0.3 + 4))
}
}
}
}
# Fisher exact test with defined background -------------------------------------------------------
fisher.test.enrichment <- function(geneSets, gene.list, bg=NULL){
# geneSets <- list(KEGG=list(x=LETTERS[1:8], y=LETTERS[1:4]), GO=list(x=LETTERS[5:14]))
# gene.list <- list(One=LETTERS[5:10], Two=LETTERS[10:20])
# bg <- LETTERS[1:24]
if(is.null(bg)) bg <- do.call(c, gene.list)
bg <- unique(bg)
res <- data.table()
for(gl in names(gene.list)){
for(db in names(geneSets)){
for(gs in names(geneSets[[db]])){
geneset.x <- unique(geneSets[[db]][[gs]])
genelist.x <- unique(gene.list[[gl]])
cont.table <- table((bg %in% geneset.x) + 1, (bg %in% genelist.x) + 10)
if(!all(dim(cont.table) == c(2,2))){
ft <- list(p.value = 1, estimate=1)
cont.table <- matrix(0, 2,2)
} else {
ft <- fisher.test(cont.table)
}
res <- rbind(res, data.table(
database=db,
geneset=gs,
list=gl,
pval=ft$p.value,
oddsRatio=ft$estimate,
genes=paste(intersect(geneset.x,genelist.x), collapse=","),
geneset.length=sum(cont.table[2,]),
genelist.length=sum(cont.table[,2]),
overlap.length=cont.table[2,2]
))
}
}
}
return(res)
}
<file_sep>/src/FUNCTIONS_HELPERS.R
hierarch.ordering <- function(dt, toOrder, orderBy, value.var, aggregate = FALSE){
if(!aggregate){orMT <- t(as.matrix(dcast.data.table(dt, get(orderBy) ~ get(toOrder), value.var=value.var)[,-"orderBy",with=F]))}
else{orMT <- t(as.matrix(dcast.data.table(dt, get(orderBy) ~ get(toOrder), value.var=value.var, fun.aggregate=mean)[,-"orderBy",with=F]))}
orMT[is.na(orMT)] <- 1
orMT[orMT == Inf] <- max(orMT[orMT != Inf])
hclustObj <- hclust(dist(orMT))
dt[[toOrder]] <- factor(dt[[toOrder]], levels=hclustObj$labels[hclustObj$order])
return(dt)
}
jaccard <- function(ll){
jacc <- matrix(NA, ncol=length(ll), nrow=length(ll))
row.names(jacc) <- names(ll)
colnames(jacc) <- names(ll)
for(g1 in names(ll)){
for(g2 in names(ll)){
g1x <- ll[[g1]]
g2x <- ll[[g2]]
jacc[g1, g2] <- length(intersect(g1x, g2x))/length(union(g1x,g2x))}}
diag(jacc) <- 0
return(jacc)
}
toMT <- function(dt, row, col, val){
retDT <- dcast.data.table(dt, get(row) ~ get(col), value.var=val)
retMT <- as.matrix(retDT[,-"row"])
row.names(retMT) <- retDT$row
return(retMT)
}
toGR <- function(charVec){
if(length(charVec) == 0) return(NULL)
gr <- strsplit(charVec, "_");
gr <- data.table(do.call(rbind, gr[sapply(gr, length) == 3]));
colnames(gr) <- c("CHR","START","END")
gr[, START := as.numeric(START)]
gr[, END := as.numeric(END)]
as(gr, "GRanges")
}
grToDT <- function(gr){
data.table(chr=as.character(seqnames(gr)),
start=start(gr),
end=end(gr))}
grToVec <- function(gr){
x <- grToDT(gr)
paste(x$chr, x$start, x$end, sep="_")
}
goodGrStrings <- function(charVec){
x <- strsplit(charVec, "_")
sapply(x, length) == 3
}
write.tsv <- function(...){
write.table(..., sep="\t", row.names=FALSE, quote=FALSE);
}
mapNumericToColors <- function(x, cols=c("royalblue1", "gray80", "indianred"), alpha=1){
x <- x/max(abs(x))
res <- c()
res[which(x >= 0)] <- apply(colorRamp(c(cols[2], cols[3]))(x[which(x >= 0)]), 1, function(row) rgb(row[1]/255, row[2]/255, row[3]/255, alpha))
res[which(x < 0)] <- apply(colorRamp(c(cols[2], cols[1]))(abs(x[which(x < 0)])), 1, function(row) rgb(row[1]/255, row[2]/255, row[3]/255, alpha))
res
}
xRot <- function(){theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))}
gg.removeGrids <- function(){theme(panel.grid=element_blank())}
cleanDev <- function(n=2){sapply(1:n, function(i){try({dev.off()}, silent=TRUE)}); return(TRUE)}
corS <- function(...){cor(..., method="spearman")}
minMax <- function(x){ (x-min(x))/(max(x) - min(x))}
fishers.method <- function(p){pchisq((sum(log(p))*-2), df=length(p)*2, lower.tail=F)}
<file_sep>/src/30_02_ClusteringExperiments_raw.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
source("src/FUNC_Enrichr.R")
data.raw <- Read10X(paste0(getOption("PROCESSED.PROJECT"), "results_pipeline/cellranger_count/","Human1_2","/outs/raw_gene_bc_matrices_mex/GRCh38/"))
out <- "30_02_ClusteringExperiments_raw/"
dir.create(dirout(out))
# SUBCLUSTER --------------------------------------------------------------
meta <- loadHMeta2()
meta <- meta[!sample %in% c("hIslets_I_pla2g16", "hIslets_II_Aold")]
cellsToKeep.list <- with(meta, split(rn, factor(paste(treatment, replicate, sep="_"))))
str(cellsToKeep.list)
xnam <- names(cellsToKeep.list)[1]
for(xnam in names(cellsToKeep.list)){
# do this for each
outS <- paste0(out, xnam, "/")
if(file.exists(dirout(outS, "SeuratObject",".RData"))) next
cluster.precision <- c()
sample.x <- xnam
pbmc.data <- data.raw[,cellsToKeep.list[[xnam]]]
tryCatch({
source("src/30_02_ClusteringExperiments_raw_SCRIPT.R",echo=TRUE)
ggplot(data.table(pbmc@[email protected]), aes(x=tSNE_1, y=tSNE_2)) + geom_point(alpha=0.1)
ggsave(dirout(outS, "TSNE.jpg"), w=4,h=4)
}, error=function(e) message(e))
}
<file_sep>/src/DropSeq/12_1_INS_GLU.R
require("project.init")
require(Seurat)
require(dplyr)
require(Matrix)
require(methods)
require(gridExtra)
require(glmnet)
require(ROCR)
project.init2("artemether")
out <- "12_INS_GLC/"
dir.create(dirout(out))
load(file=dirout("10_Seurat/", "DropSeq/","DropSeq.RData"))
pDat <- data.table(cell = colnames(pbmc@data), INS=pbmc@data["INS",], GCG=pbmc@data["GCG",],
#NGN3=pbmc@data["NEUROG3",],
[email protected]$sample, nGene = [email protected]$nGene, [email protected]$nUMI,
[email protected],
pbmc@[email protected])
table(pDat$Sample)
# DO THE SAME ON THE RAW DATA ---------------------------------------------
# pDat <- data.table([email protected]["INS",], [email protected]["GCG",], Sample=gsub("(.+?)\\..+", "\\1", colnames([email protected])), nGene = apply([email protected] != 0 , 2, sum), nUMI=apply([email protected], 2, sum))
# pDat[, INS := log(((INSraw)/nUMI) * 1e4)]
# pDat[INS == -Inf, INS := 0]
# pDat[, GCG := log(((GCGraw)/nUMI) * 1e4)]
# pDat[GCG == -Inf, GCG := 0]
# table(pDat$Sample)
# out <- paste0("12_INS_GLC/", "FullData/")
# dir.create(dirout(out))
cutoff <- 5
pDat[,group := "Negative"]
pDat[INS > cutoff,group := "INS+"]
pDat[GCG > cutoff,group := "GCG+"]
pDat[INS > cutoff & GCG > cutoff,group := "INS+ GCG+"]
pDat
# PERCENT OF ALL READS ----------------------------------------------------
#
# dmsoDat <- <EMAIL>[row.names(<EMAIL>),pDat[sample == "DMSO"]$cell]
# sum(dmsoDat["INS",])/sum(dmsoDat)
# sum(dmsoDat["GCG",])/sum(dmsoDat)
#
# arteDat <- <EMAIL>[row.<EMAIL>(<EMAIL>),pDat[sample == "Artemether"]$cell]
# sum(arteDat["INS",])/sum(arteDat)
# sum(arteDat["GCG",])/sum(arteDat)
# FACS LIKE PLOTS ---------------------------------------------------------
ggplot(pDat, aes(x=INS, y=GCG, color=nUMI, size=nGene)) + geom_point(alpha=0.5) + facet_grid(. ~ Sample) + theme_bw(24)
ggsave(dirout(out, "INS_GCG_nGene_nUMI.pdf"),width=16, height=5)
(p <- ggplot(pDat[INS != 0 & GCG != 0], aes(x=INS, y=GCG)) + geom_hex() + facet_grid(. ~ Sample) + theme_bw(24))
ggsave(dirout(out, "INS_GCG_hex.pdf"),width=16, height=5)
(p <- ggplot(pDat, aes(x=INS, y=GCG)) + geom_point(alpha=0.5) + facet_grid(. ~ Sample) + theme_bw(24))
ggsave(dirout(out, "INS_GCG.pdf"),width=16, height=5)
(p + geom_hline(yintercept=4, color="blue", size=1, alpha=0.5) +
geom_vline(xintercept=4, color="blue", size=1, alpha=0.5) +
geom_hline(yintercept=6, color="blue", size=1, alpha=0.5) +
geom_vline(xintercept=6, color="blue", size=1, alpha=0.5)
)
ggsave(dirout(out, "INS_GCG_lines2.pdf"),width=16, height=5)
(p + geom_hline(yintercept=cutoff, color="red", size=2, alpha=0.5) +
geom_vline(xintercept=cutoff, color="red", size=2, alpha=0.5))
ggsave(dirout(out, "INS_GCG_lines.pdf"),width=16, height=5)
# DENSITY PLOTS -----------------------------------------------------------
# INSULIn
ggplot(pDat, aes(x=INS, color=sample)) + stat_ecdf(size=1.5) + theme_bw(24)
ggsave(dirout(out, "INS_ECDF.pdf"),width=8, height=7)
ggplot(pDat, aes(x=INS, fill=sample)) + geom_density(alpha=0.3) + theme_bw(24)
ggsave(dirout(out, "INS_Density.pdf"),width=8, height=7)
# GLUCAGON
ggplot(pDat, aes(x=GCG, color=sample)) + stat_ecdf(size=1.5) + theme_bw(24)
ggsave(dirout(out, "GCG_ECDF.pdf"),width=8, height=7)
ggplot(pDat, aes(x=GCG, fill=sample)) + geom_density(alpha=0.3) + theme_bw(24)
ggsave(dirout(out, "GCG_Density.pdf"),width=8, height=7)
# t-SNE PLOTS -----------------------------------------------------------
ggplot(pDat, aes(x=tSNE_1, y=tSNE_2, color=INS)) + geom_point(alpha=0.5) +
facet_grid(. ~ Sample) + scale_color_gradient(low="grey", high="blue")
ggsave(dirout(out, "INS_tSNE.pdf"),width=16, height=5)
ggplot(pDat, aes(x=tSNE_1, y=tSNE_2, color=GCG)) + geom_point(alpha=0.5) +
facet_grid(. ~ Sample) + scale_color_gradient(low="grey", high="blue")
ggsave(dirout(out, "GCG_tSNE.pdf"),width=16, height=5)
# QC PLOTS ----------------------------------------------------------------
ggplot(pDat, aes(x=INS, y=GCG, color=group)) + geom_point()
ggsave(dirout(out, "QC_Assignment_GROUPS.pdf"), height=7, width=7)
ggplot(pDat, aes(x=group, y=nUMI, fill=group)) + geom_violin() + facet_grid(. ~ Sample) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "QC_nUMI.pdf"),width=16, height=5)
ggplot(pDat, aes(x=group, y=nGene, fill=group)) + geom_violin() + facet_grid(. ~ Sample) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "QC_nGene.pdf"),width=16, height=5)
ggplot(pDat, aes(x=group, y=percent.mito, fill=group)) + geom_violin() + facet_grid(. ~ Sample) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "QC_PercentMito.pdf"),width=16, height=5)
ggplot(pDat, aes(x=tSNE_1, y=tSNE_2, color=group)) + geom_point(alpha=0.5) +
facet_grid(. ~ Sample) + scale_color_manual(values=c("turquoise", "gold", "black", "grey"))
ggsave(dirout(out, "group_tSNE.pdf"),width=16, height=5)
# PERCENTAGE --------------------------------------------------------------
pDat2 <- pDat[,.N, by=c("group", "Sample")]
pDat2[, sampleCount := sum(N), by="Sample"]
pDat2[, percentage := N/sampleCount * 100]
ggplot(pDat2, aes(x=group, fill=Sample, y=percentage)) + geom_bar(stat="identity", position="dodge") +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "DoublePositive_Percentage.pdf"), height=7, width=6)
fisher.test(as.matrix(with(pDat[Sample %in% c("Artemether", "DMSO")], table(group != "INS+ GCG+", Sample))))
fisher.test(as.matrix(with(pDat[Sample %in% c("Artemether", "GABA")], table(group != "INS+ GCG+", Sample))))
# SIGNATURES --------------------------------------------------------------
str(bSig <- fread("metadata//Ackermann2016_Bcell.txt", header=FALSE)$V1)
str(aSig <- fread("metadata//Ackermann2016_Acell.txt", header=FALSE)$V1)
sigs <- rbind(data.table(Gene=bSig, cell="beta"), data.table(Gene=aSig, cell="alpha"))
sigs[Gene == "SYNDIG", Gene := "SYNDIG1"]
sigs[!Gene %in% row.names(pbmc@data)]
"ANXA8" %in% row.names(<EMAIL>)
"ANX8" %in% row.names(<EMAIL>)
"KRTAP" %in% row.names(<EMAIL>)
row.names(<EMAIL>)[grepl("KRTAP", row.names(<EMAIL>))]
"SYNDIG" %in% row.names(<EMAIL>)
sigs <- sigs[Gene %in% row.names(pbmc@data)]
annotSample <- data.frame(Group = pDat$group, row.names=pDat$cell)
annotGene <- data.frame(Cell = sigs$cell, row.names=sigs$Gene)
treatment <- "Artemether"
for(treatment in unique(pDat$Sample)){
cnts <- table(pDat[grepl(treatment, cell)]$group)
pdf(dirout(out, "Signature_", treatment, ".pdf"), height=10, width=10,onefile=F)
pheatmap(pbmc@data[sigs$Gene,pDat[grepl(treatment, cell)][order(group)]$cell],
cluster_rows=FALSE,cluster_cols=FALSE,
show_colnames=FALSE,
annotation_col=annotSample, annotation_row=annotGene,
color=colorRampPalette(c("black", "yellow"))(30), border_color=NA,
gaps_col=c(cnts["GCG+"], sum(cnts[c("GCG+", "INS+")]), sum(cnts[c("GCG+", "INS+", "INS+ GCG+")])))
dev.off()
pdf(dirout(out, "Signature_", treatment, "3.pdf"), height=10, width=10,onefile=F)
pheatmap(pbmc@data[sigs$Gene,pDat[grepl(treatment, cell) & group == "INS+ GCG+"]$cell],
show_colnames=FALSE,
annotation_col=annotSample, annotation_row=annotGene,
color=colorRampPalette(c("black", "yellow"))(30), border_color=NA
)
dev.off()
meanVals <- lapply(unique(pDat$group), function(grp){
m <- matrix(apply(pbmc@data[sigs$Gene, pDat[grepl(treatment, cell) & group == grp]$cell], 1, mean))
colnames(m) <- grp
rownames(m) <- sigs$Gene
m
})
meanVals <- do.call(cbind, meanVals)
meanVals <- meanVals - apply(meanVals, 1, min, na.rm=TRUE)
meanVals <- meanVals / apply(meanVals, 1, max, na.rm=TRUE)
pdf(dirout(out, "Signature_", treatment, "2.pdf"), height=10, width=3,onefile=F)
pheatmap(meanVals[apply(meanVals, 1, sum,na.rm=TRUE) > 0,colnames(meanVals) != "Negative"],
annotation_row=annotGene, cluster_rows=FALSE,
color=colorRampPalette(c("black", "yellow"))(30))
dev.off()
}
# PREDICTION --------------------------------------------------------------
stopifnot(all(pDat$cell == colnames(pbmc@data)))
predMeta <- pDat[Sample == "DMSO" & group %in% c("GCG+", "INS+")]
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$cell]))
# CROSS VALIDATION ON DMSO
trainIndex <- createDataPartition(predMeta$group, p = .75, list = TRUE, times = 3)
trainRes <- data.table()
for(trainX in 1:length(trainIndex)){
idx <- trainIndex[[trainX]]
message(trainX)
for(alpha in seq(0, 1, 0.2)){
glmFit <- glmnet(y=factor(predMeta[idx]$group),
x=dat[idx,],
family="binomial",
alpha=alpha
)
pred <- predict(glmFit, dat[-idx,], type="response")
for(i in 1:ncol(pred)){
(auc <- performance(prediction(pred[,i], predMeta[-idx]$group),"auc")@y.values[[1]])
trainRes <- rbind(trainRes, data.table(auc=auc, alpha=alpha, lambda = glmFit$lambda[i], indx=trainX))
}
}
}
trainRes[, maxAUC := max(auc), by="indx"]
trainRes[auc == maxAUC]
with(trainRes[auc == maxAUC], table(alpha, indx))
trainRes[indx == 2 & alpha==0]
ggplot(trainRes, aes(x=lambda, y=auc)) + geom_point() + facet_grid(factor(alpha) ~ indx) +
scale_x_log10() + theme_bw(12)
ggsave(dirout(out, "Prediction_training.pdf"), height=14, width=14)
# TRAIN ONE FINAL MODEL
# glmFit <- glmnet(y=factor(predMeta$group), x=dat,family="binomial",alpha=0,lambda=5)
set.seed(5001)
glmFit <- glmnet(y=factor(predMeta$group), x=dat,family="binomial",alpha=1,lambda=0.1)
save(glmFit, file=dirout(out, "Prediction_LogisticRegression.RData"))
predMeta <- pDat
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$cell]))
predMeta$class <- predict(glmFit, dat, type="response")
ggplot(predMeta, aes(x=group, y=class, fill=group)) + geom_violin() + theme_bw(12) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) +
facet_grid(. ~ sample) + ylab("beta cell probability") + xlab("") + ylim(0,1)
ggsave(dirout(out, "Prediction_ClassProbabilities.pdf"),width=7, height=5)
# ERROR ON DMSO, GABA, and Artemether
treat <- "DMSO"
for(treat in unique(pDat$Sample)){
predMeta <- pDat[Sample == treat]
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$cell]))
predMeta$class <- predict(glmFit, dat, type="response")
(auc <- performance(prediction(
predMeta[group %in% c("INS+", "GCG+")]$class,
predMeta[group %in% c("INS+", "GCG+")]$group),"auc")@y.values[[1]])
ggplot(predMeta, aes(x=group, y=class)) + geom_violin() + ggtitle(paste("DMSO,",treat,"= ", round(auc,4)))
ggsave(dirout(out, "Prediction_",treat,".pdf"),height=7,width=7)
}
# # Make sure I actually filtered INS GCG
# c("INS", "GCG") %in% row.names(pbmc@data)
# c("INS", "GCG") %in% colnames(dat)
# c("INS", "GCG") %in% colnames(dat2)
# head(colnames(dat))
# head(colnames(dat2))
#
# Calculate z score for up and down - is this different between double pos and double neg
(feat <- data.table(as.matrix(coef(glmFit)),keep.rownames=TRUE)[order(abs(s0),decreasing=TRUE)][s0 != 0][rn != "(Intercept)"])
stopifnot(all(colnames(pbmc@data) == pDat$cell))
pDat$Beta <- apply(pbmc@data[feat[s0 > 0]$rn,pDat$cell] * feat[s0 > 0]$s0, 2, sum)
pDat$Alpha <- apply(pbmc@data[feat[s0 < 0]$rn,pDat$cell]* feat[s0 < 0]$s0, 2, sum)
ggplot(pDat, aes(x=group, y=Beta, fill=group)) + geom_violin() + theme_bw(12) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) +
facet_grid(. ~ sample) + ylab("beta features") + xlab("")
ggsave(dirout(out, "Features_Beta.pdf"), width=16, height=7)
ggplot(pDat, aes(x=group, y=Alpha, fill=group)) + geom_violin() + theme_bw(12) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) +
facet_grid(. ~ sample) + ylab("alpha features") + xlab("")
ggsave(dirout(out, "Features_Alpha.pdf"), width=16, height=7)
ggplot(pDat, aes(x=Beta, y=Alpha, color=group)) + geom_point(alpha=0.5) +
facet_grid(. ~ sample)+ theme_bw(24) +
scale_color_manual(values=c("turquoise", "gold", "black", "grey"))
ggsave(dirout(out, "Features_points.pdf"), width=16, height=5)
# PLOT FEATURES IN HEATMAP ------------------------------------------------
annotGene2 <- data.frame(weight=feat$s0, row.names=feat$rn)
treatment <- "Artemether"
for(treatment in unique(pDat$Sample)){
pDatX <- pDat[Sample == treatment]
cnts <- table(pDatX$group)
pdf(dirout(out, "Features_", treatment, ".pdf"), height=5, width=10,onefile=F)
pheatmap(pbmc@data[feat$rn,pDatX[order(group)]$cell],
cluster_rows=FALSE,cluster_cols=FALSE,
show_colnames=FALSE,
annotation_col=annotSample, annotation_row=annotGene2,
color=colorRampPalette(c("black", "yellow"))(30), border_color=NA,
gaps_col=c(cnts["GCG+"], sum(cnts[c("GCG+", "INS+")]), sum(cnts[c("GCG+", "INS+", "INS+ GCG+")])))
dev.off()
}
g <- "PAX4"
g <- "ARX"
g <- "GABARG2"
g <- "GABARB3"
g <- "GPHN"
g <- "INS"
g %in% row.names(pbmc@data)
table(pbmc@data[g,] == 0)
<file_sep>/src/16_02_H3_DiffGenes_NoInsulin_FindMore.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "16_H3_02_DiffGenes/"
dir.create(dirout(out))
list.files(dirout("15_Counts/"))
meta <- loadH3Meta2()
meta[,celltype := celltype2]
meta[treatment == "DMSO", replicate := gsub("III\\d", "III", replicate)]
table(meta$celltype)
pbmc <- loadH3Data2()
marker.genes <- c("INS", "GCG", "SST", "PPY")
# Diff expression of marker genes -----------------------------------------
outTreat <- paste0(out, "VsDMSO_negbinom_onlyIns/")
seurat.genes.use <- marker.genes
seurat.thresh.use <- 0
source("src/12_DiffGenes_SCRIPT_AverageDMSO.R", echo=TRUE)
ff <- list.files(dirout(outTreat), pattern="III\\d_.+_.+_.+\\.tsv$")
res <- data.table(); for(f in ff){print(f);res <- rbind(res, data.table(fread(dirout(outTreat, f)), file=f), fill=T)}
res[, file := gsub("SI_", "SI.", file)]
res[, file := gsub("Acinar_like", "Acinar.like", file)]
res[, file := gsub("\\.tsv$", "", file)]
res <- cbind(res, data.table(do.call(rbind, strsplit(res$file, "_"))))
colnames(res) <- make.unique(colnames(res))
res$qval <- p.adjust(res$p_val, method="BH")
res[, direction := ifelse(avg_diff > 0, "up", "down")]
# res[[7]] <- NULL
# res
# res[V1 == "INS" & V4 == "Alpha"]
# ExpMean(meta[replicate == "III1_72" & treatment == "A10" & celltype2 == "Alpha"]$INS) - ExpMean(meta[replicate == "III1_72" & treatment == "DMSO" & celltype2 == "Alpha"]$INS)
# ggplot(meta[replicate == "III1_72" & celltype2 == "Alpha"], aes(x=INS, color=treatment)) + stat_ecdf()
save(res, file=dirout(outTreat, "AllRes.RData"))
# ggplot(res[!grepl("^\\d", V1)], aes(x=V4, y=V1.1, color=avg_diff, size=pmin(5, -log10(qval)))) + geom_point() + facet_grid(V1 ~ V2) +
# theme_bw(12) + scale_color_gradient2(low="blue", high="red") + xRot()
# ggsave(dirout(out, "VsDMSO_negbinom_onlyIns.pdf"), width=15, height=8)
rm(list=c("seurat.genes.use", "seurat.thresh.use", "outTreat"))
# Diff expression without marker genes -----------------------------------------
pbmcOrig <- pbmc
gg <- row.names(pbmcOrig@data)
rawDat <- pbmcOrig@<EMAIL>[gg[!gg %in% marker.genes], [email protected]]
str(rawDat)
pbmc <- CreateSeuratObject(raw.data = rawDat, min.cells = 3, min.genes = -Inf, scale.factor=SCALE.FACTOR, project = "X")
pbmc <- NormalizeData(object = pbmc, normalization.method = "LogNormalize", scale.factor = SCALE.FACTOR)
# dmso <- log(mean(toTPM(pbmc@data["AC004556.1", meta[treatment == "DMSO" & replicate == "I" & celltype == "Beta"]$rn, drop=F]))+1)
# foxo <- log(mean(toTPM(pbmc@data["AC004556.1", meta[treatment == "FoxO" & replicate == "I" & celltype == "Beta"]$rn, drop=F]))+1)
# a10 <- log(mean(toTPM(pbmc@data["AC004556.1", meta[treatment == "A10" & replicate == "I" & celltype == "Beta"]$rn, drop=F]))+1)
# foxo-dmso
# a10-dmso
rm(list=c("pbmcOrig"))
outTreat <- paste0(out, "VsDMSO_negbinom_noIns/")
seurat.thresh.use <- 0.1
source("src/12_DiffGenes_SCRIPT_AverageDMSO.R", echo=TRUE)
ff <- list.files(dirout(outTreat), pattern="III\\d_.+_.+_.+\\.tsv$")
res <- data.table(); for(f in ff){print(f);res <- rbind(res, data.table(fread(dirout(outTreat, f)), file=f), fill=T)}
res[, file := gsub("SI_", "SI.", file)]
res[, file := gsub("Acinar_like", "Acinar.like", file)]
res[, file := gsub("\\.tsv$", "", file)]
res <- cbind(res, data.table(do.call(rbind, strsplit(res$file, "_"))))
colnames(res) <- make.unique(colnames(res))
res$qval <- p.adjust(res$p_val, method="BH")
res[, direction := ifelse(avg_diff > 0, "up", "down")]
save(res, file=dirout(outTreat, "AllRes.RData"))<file_sep>/src/10_M_01_Seurat.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
sample.labels <- fread("metadata/Aggregate_Mouse_withLTI.csv")
data.path <- dirout("07_11_CleanMouse_CleanSpikeIns/CorrectedData.RData")
outS <- "10_M_01_Seurat/"
seurat.file <- dirout(outS, "SeuratObject",".RData")
if(!file.exists(seurat.file)){
source("src/10_SCRIPT_01_Seurat.R")
} else {
load(seurat.file)
}
# SEURAT ANALYSIS ---------------------------------------------------------
source("src/FUNC_Enrichr.R")
str(extra.genes.to.plot <- unique(fread("metadata//PancreasMarkers.tsv")$Mouse_GeneName))
seurat.diff.test <- "roc"
figExt <- ".jpg"
max.nr.of.cores <- 5
clusterings.exclude <- c("sample")
enrichrDBs <- c("NCI-Nature_2016", "WikiPathways_2016", "Human_Gene_Atlas", "Chromosome_Location", "NCI-60_Cancer_Cell_Lines")
source("src/FUNC_Seurat2_fast_simple.R",echo=TRUE)
max.nr.of.cores <- 1
source("src/FUNC_Seurat2_fast_simple.R",echo=TRUE)
# SUBCLUSTER --------------------------------------------------------------
outSOrig <- outS
outS <- paste0(outS, "Subcluster/")
cellsToKeep <- row.names(subset([email protected], res.0.5 %in% as.character(c(0:2,5:6))))
cluster.precision <- 0.5
sample.x <- "subcluster"
seurat.file.sub <- dirout(outS, "data",".RData")
source("src/FUNC_Seurat_subcluster.R",echo=TRUE)
# SEURAT
max.nr.of.cores <- 5
source("src/FUNC_Seurat2_fast_simple.R",echo=TRUE)
max.nr.of.cores <- 1
source("src/FUNC_Seurat2_fast_simple.R",echo=TRUE)
<file_sep>/src/DropSeq/14_1_Alpha_Beta.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
inDir <-
outS <- "14_1_Alpha_Beta/"
dir.create(dirout(outS))
cluster.precision <- c(0.5, 1.0, 1.5, 2.0)
cell <- "Alpha_Beta"
if(!file.exists(dirout(outS, cell,".RData"))){
(load(file=dirout("10_Seurat/", "DropSeq/","DropSeq.RData")))
pDat <- fread(dirout("13_2_CellTypes_noGABA/", "MetaData.tsv"))
stopifnot(all(row.names(subset([email protected], sample %in% c("Artemether", "DMSO"))) == pDat$cell))
[email protected]$Celltype <- pDat[match(pbmc@cell.<EMAIL>, pDat$cell)]$Celltype
pbmcOrig <- pbmc
print(unique([email protected]$Celltype))
# SUBSET DATA -------------------------------------------------------------
str(cellToKeep <- row.names(subset([email protected], Celltype %in% c("INS+", "GCG+", "INS+ GCG+"))))
dir.create(dirout(outS))
pbmc <- SubsetData(pbmcOrig, cells.use = cellToKeep)
pDat <- data.table(pbmcOrig@[email protected],keep.rownames=T)
pDat$selected <- "no"
pDat[rn %in% cellToKeep, selected := "yes"]
ggplot(pDat, aes(x=tSNE_1, y=tSNE_2, color=selected)) + geom_point(alpha=0.3)
ggsave(dirout(outS, "SelectedCells.pdf"))
# PREP DATASET ------------------------------------------------------------
pbmc <- FindVariableGenes(pbmc, x.low.cutoff = 0.0125, x.high.cutoff = 3, y.cutoff = 0.5)
pbmc <- RunPCA(pbmc, pc.genes = [email protected], do.print = TRUE, pcs.print = 5, genes.print = 5)
pbmc <- RunTSNE(pbmc, dims.use = 1:10, do.fast = F)
# Clustering
for(x in cluster.precision){
pbmc <- FindClusters(pbmc, reduction.type="pca", dims.use = 1:10, resolution = x, print.output = 0, save.SNN = T)
pbmc <- StashIdent(pbmc, save.name = paste0("ClusterNames_", x))
}
[email protected][["Alpha_Beta"]] <- NULL
save(pbmc, file=dirout(outS, cell,".RData"))
} else {
load(file=dirout(outS, cell,".RData"))
update <- FALSE
for(x in cluster.precision){
if(is.null([email protected][[paste0("ClusterNames_", x)]])){
update <- TRUE
pbmc <- FindClusters(pbmc, reduction.type="pca", dims.use = 1:10, resolution = x, print.output = 0, save.SNN = T)
pbmc <- StashIdent(pbmc, save.name = paste0("ClusterNames_", x))
}
}
resNames <- colnames([email protected])[grepl("res\\.", colnames([email protected]))]
for(rr in resNames[! resNames %in% paste0("res.", cluster.precision)]){
[email protected][[rr]] <- NULL
update <- TRUE
}
if(update){
save(pbmc, file=dirout(outS, cell,".RData"))
}
}
pDat <- data.table([email protected], pbmc@[email protected], SST = pbmc@data["SST",])
ggplot(pDat, aes(x=PC1, y=PC2, color=Celltype)) + geom_point()
ggplot(pDat, aes(x=PC1, y=PC2, color=SST)) + geom_point(alpha=0.5) +scale_color_gradient(low="lightgrey", high="blue")
extra.genes.to.plot <- unique(fread("metadata//PancreasMarkers.tsv")$Human_GeneName)
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Seurat2.R"), echo=TRUE)
(load(paste(Sys.getenv("CODEBASE"), "slice/data/hs_km.Rda", sep="")))
SLICE.km <- km
SLICE.cellIdentity <- factor([email protected]$sample)
source(paste0(Sys.getenv("CODEBASE"), "slice/slice.R"))
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_SLICE2.R"), echo=TRUE)
Monocle.metadata.fields <- c("Slice2")
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Monocle.R"), echo=TRUE)
extra.genes.to.plot <- unique(fread("metadata//PancreasMarkers.tsv")$Human_GeneName)
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Seurat2.R"), echo=TRUE)
<file_sep>/src/15_Counts.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "15_Counts/"
dir.create(dirout(out))
# ORIGINAL COUNTS ---------------------------------------------------------
metaH <- loadHMeta()
metaM <- loadMMeta()
metaH3 <- loadH3Meta()
ggplot(metaH, aes(x=celltype, fill=treatment)) + geom_bar(position="dodge") + facet_grid(replicate ~ .)
ggsave(dirout(out, "Raw_Human.pdf"), height=8,width=15)
ggplot(metaH3, aes(x=celltype, fill=treatment)) + geom_bar(position="dodge") + facet_grid(replicate ~ .)
ggsave(dirout(out, "Raw_Human3.pdf"), height=8,width=15)
ggplot(metaM, aes(x=celltype, fill=treatment)) + geom_bar(position="dodge") + facet_grid(replicate ~ .)
ggsave(dirout(out, "Raw_Mouse.pdf"), height=8,width=15)
# PREDICTED GROUPS --------------------------------------------------------
inDir <- "14_03_Classifier_moreCelltypes_noEndocrine/"
list.files(dirout(inDir))
predMetaH <- fread(dirout(inDir, "human/Prediction.tsv"), header=T)
predMetaH$PredictedCell <- apply(as.matrix(predMetaH[,unique(intersect(colnames(predMetaH), metaH$celltype)), with=F]),1,function(row) names(row)[which(row == max(row))])
metaH <- merge(metaH, predMetaH[,c("rn", "PredictedCell")], by="rn", all.x=T)
metaH[,celltype2 := celltype]
metaH[celltype == "Endocrine", celltype2 := PredictedCell]
predMetaH3 <- fread(dirout(inDir, "human3/Prediction.tsv"), header=T)
predMetaH3$PredictedCell <- apply(as.matrix(predMetaH3[,unique(intersect(colnames(predMetaH3), metaH3$celltype)), with=F]),1,function(row) names(row)[which(row == max(row))])
metaH3 <- merge(metaH3, predMetaH3[,c("rn", "PredictedCell")], by="rn", all.x=T)
metaH3[,celltype2 := celltype]
metaH3[celltype == "Endocrine", celltype2 := PredictedCell]
predMetaM <- fread(dirout(inDir, "mouse/Prediction.tsv"), header=T)
x <- as.matrix(predMetaM[,unique(intersect(colnames(predMetaM), metaM$celltype)), with=F])
head(x)
head(apply(x,1,max))
x2 <- apply(x,1,sort)
x2 <- t(x2)
head(x2)
quantile(x2[,8]-x2[,7])
predMetaM$PredictedCell <- apply(as.matrix(predMetaM[,unique(intersect(colnames(predMetaM), metaM$celltype)), with=F]),1,function(row) names(row)[which(row == max(row))])
metaM <- merge(metaM, predMetaM[,c("rn", "PredictedCell")], by="rn", all.x=T)
metaM[,celltype2 := celltype]
metaM[celltype == "Endocrine", celltype2 := PredictedCell]
ggplot(predMetaM, aes(x=Alpha, color=treatment)) + stat_ecdf() + facet_grid(replicate ~ .)
ggsave(dirout(out, "Alpha_cell_Probablity_Mouse.pdf"), width=4, height=12)
ggplot(predMetaH, aes(x=Alpha, color=treatment)) + stat_ecdf() + facet_grid(replicate ~ .)
ggsave(dirout(out, "Alpha_cell_Probablity_Human.pdf"), width=4, height=8)
ggplot(predMetaH3, aes(x=Alpha, color=treatment)) + stat_ecdf() + facet_grid(replicate ~ .)
ggsave(dirout(out, "Alpha_cell_Probablity_Human3.pdf"), width=4, height=8)
pDat <- metaH[,.N, by=c("celltype2", "replicate", "treatment", "celltype")]
pDat[,sum := sum(N), by=c("replicate", "treatment")]
pDat[,percent := N / sum * 100]
ggplot(pDat, aes(x=treatment,y=percent, fill=celltype=="Endocrine")) + geom_bar(stat="identity", position="stack") + facet_grid(replicate ~ celltype2) +
scale_fill_manual(values=c("grey", "blue")) + theme_bw(12)+ xRot()
ggsave(dirout(out, "Predicted_Human.pdf"), height=8,width=15)
pDat <- metaH3[,.N, by=c("celltype2", "replicate", "treatment", "celltype")]
pDat[,sum := sum(N), by=c("replicate", "treatment")]
pDat[,percent := N / sum * 100]
ggplot(pDat, aes(x=treatment,y=percent, fill=celltype=="Endocrine")) + geom_bar(stat="identity", position="stack") + facet_grid(replicate ~ celltype2) +
scale_fill_manual(values=c("grey", "blue")) + theme_bw(12)+ xRot()
ggsave(dirout(out, "Predicted_Human3.pdf"), height=8,width=15)
pDat <- metaM[,.N, by=c("celltype2", "replicate", "treatment", "celltype")]
pDat[,sum := sum(N), by=c("replicate", "treatment")]
pDat[,percent := N / sum * 100]
ggplot(pDat, aes(x=treatment,y=percent, fill=celltype=="Endocrine")) + geom_bar(stat="identity", position="stack") + facet_grid(replicate ~ celltype2) +
scale_fill_manual(values=c("grey", "blue")) + theme_bw(12)+ xRot()
ggsave(dirout(out, "Predicted_Mouse.pdf"), height=8,width=15)
# CORRECTED DISTRIBUTIONS -------------------------------------------------
pbmcH <- loadHData()
pbmcM <- loadMData()
pbmcH3 <- loadH3Data()
assignGenesMeta <- function(genes, metaX, seuratObj){
for(gg in genes){
if(!gg %in% row.names(seuratObj@data)) stop(gg, " not found in sc data")
metaX[[gg]] <- seuratObj@data[gg,metaX$rn]
}
metaX
}
metaH <- assignGenesMeta(c("INS", "GCG"), metaH, pbmcH)
metaH3 <- assignGenesMeta(c("INS", "GCG"), metaH3, pbmcH3)
metaM <- assignGenesMeta(c("Ins2", "Gcg"), metaM, pbmcM)
celltypes.of.interest <- c("Alpha", "Beta", "Gamma", "Delta", "Endocrine")
treat <- "A10"
gg <- "INS"
ct <- "Beta"
org <- "human3"
outGG <- paste0(out, "Details/")
dir.create(dirout(outGG))
for(org in c("human", "mouse", "human3")){
meta <- metaH3
if(org == "mouse") meta <- metaM
if(org == "human") meta <- metaH
for(treat in unique(meta[treatment != "DMSO"]$treatment)){
for(gg in c("INS", "GCG", "Ins2", "Gcg")){
if(!gg %in% colnames(meta)) next
pDat <- meta[treatment %in% c("DMSO", treat) & celltype2 %in% celltypes.of.interest]
pDat$treatment <- factor(pDat$treatment, levels = c("DMSO", treat))
ggplot(pDat, aes_string(x=gg, color="treatment")) + geom_density() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red"))
ggsave(dirout(out, org, "_", treat, "_", gg, ".pdf"),height=9,width=16)
ggplot(pDat, aes_string(x=gg, color="treatment")) + stat_ecdf() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red"))
ggsave(dirout(out, org, "_", treat, "_", gg, "_ECDF.pdf"),height=9,width=16)
pDat$Expression <- pDat[[gg]]
ggplot(pDat, aes(x=Expression, color=treatment, alpha=(celltype != "Endocrine"))) + stat_ecdf() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red")) + xlab(gg)
ggsave(dirout(out, org, "_", treat, "_", gg, "_ECDF_Endocrine.pdf"),height=9,width=16)
for(ct in celltypes.of.interest){
if(!gg %in% colnames(meta)) next
pDat <- meta[treatment %in% c("DMSO", treat) & celltype2 %in% ct]
if(nrow(pDat) == 0) next
pDat$treatment <- factor(pDat$treatment, levels = c("DMSO", treat))
pDat$celltype <- factor(pDat$celltype, levels = c(ct, "Endocrine"))
ggplot(pDat, aes_string(x=gg, color="treatment", linetype = "celltype")) + geom_density() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red"))
ggsave(dirout(outGG, org, "_", treat, "_", ct, "_", gg, ".pdf"),height=6,width=6)
ggplot(pDat, aes_string(x=gg, color="treatment", linetype = "celltype")) + stat_ecdf() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red"))
ggsave(dirout(outGG, org, "_", treat, "_", ct, "_", gg, ".pdf"),height=6,width=6)
}
}
}
}
write.tsv(metaH, dirout(out,"Reassigned_Human.tsv"))
write.tsv(metaM, dirout(out,"Reassigned_Mouse.tsv"))
write.tsv(metaH3, dirout(out,"Reassigned_Human3.tsv"))
metaH$org <- "human"
metaM$org <- "mouse"
metaX <- rbind(metaH, metaM, fill=T)
metaX[,Insulin := sum(INS, Ins2, na.rm=T), by=c("rn", "org")]
metaX[,Glucagon := sum(GCG, Gcg, na.rm=T), by=c("rn", "org")]
ggplot(metaX[treatment %in% c("DMSO", "A10") & celltype2 %in% c("Beta", "Alpha")], aes(x=replicate, y=exp(Insulin) - 1, fill=treatment)) + geom_violin() +
facet_grid(celltype2 ~ org, scales="free") + theme_bw(12)
ggsave(dirout(out, "Org_Compare_Insulin.pdf"), width=8, height=4)
ggplot(metaX[treatment %in% c("DMSO", "A10") & celltype2 %in% c("Beta", "Alpha")], aes(x=replicate, y=exp(Glucagon) - 1, fill=treatment)) + geom_violin() +
facet_grid(celltype2 ~ org, scales="free") + theme_bw(12)
ggsave(dirout(out, "Org_Compare_Glucagon.pdf"), width=8, height=4)
write.tsv(metaX, dirout(out,"Reassigned_Combined.tsv"))
<file_sep>/src/10_H3_01_Seurat.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
sample.labels <- fread("metadata/Aggregate_Human3.csv")
data.path <- dirout("07_04_CleanHuman3_CleanSpikeIns/CorrectedData.RData")
outS <- "10_H3_01_Seurat/"
dir.create(dirout(outS))
seurat.file <- dirout(outS, "SeuratObject",".RData")
if(!file.exists(seurat.file)){
source("src/10_SCRIPT_01_Seurat.R")
} else {
load(seurat.file)
}
# SEURAT ANALYSIS ---------------------------------------------------------
source("src/FUNC_Enrichr.R")
str(extra.genes.to.plot <- unique(fread("metadata//PancreasMarkers.tsv")$Human_GeneName))
seurat.diff.test <- "roc"
figExt <- ".jpg"
# max.nr.of.cores <- 5
clusterings.exclude <- c("sample")
enrichrDBs <- c("NCI-Nature_2016", "WikiPathways_2016", "Human_Gene_Atlas", "Chromosome_Location", "NCI-60_Cancer_Cell_Lines")
# source("src/FUNC_Seurat2_fast_simple.R",echo=TRUE)
max.nr.of.cores <- 1
source("src/FUNC_Seurat2_fast_simple.R",echo=TRUE)
# SUBCLUSTER --------------------------------------------------------------
outSOrig <- outS
outS <- paste0(outS, "Subcluster/")
cellsToKeep <- row.names(subset([email protected], res.0.5 %in% as.character(c(0:2,4,5,7,15))))
cluster.precision <- 0.5
sample.x <- "subcluster"
source("src/FUNC_Seurat_subcluster.R",echo=TRUE)
# SEURAT ANALYSIS ---------------------------------------------------------
max.nr.of.cores <- 5
source("src/FUNC_Seurat2_fast_simple.R",echo=TRUE)
max.nr.of.cores <- 1
source("src/FUNC_Seurat2_fast_simple.R",echo=TRUE)
<file_sep>/src/DropSeq/11_MembraneGenes.R
require("project.init")
require(Seurat)
require(dplyr)
require(Matrix)
require(methods)
require(gridExtra)
project.init2("artemether")
out <- "11_Find_Sort_Markers/"
dir.create(dirout(out))
mem <- fread(dirout(out, "uniprot-goa%3A%28_membrane+part+%5B0044425%5D_%29+AND+reviewed%3Ayes+AND+org--.tab"))
mem <- sapply(strsplit(mem[["Gene names"]], " "), function(v) v[1])
(alpha.markers <- fread(dirout("10_Seurat/DropSeq/Cluster_res.0.5/Markers_Cluster0_version2.tsv"))[V3 %in% mem])
(beta.markers <- fread(dirout("10_Seurat/DropSeq/Cluster_res.0.5/Markers_Cluster1_version2.tsv"))[V3 %in% mem])
(alpha.markers <- fread(dirout("10_Seurat/DropSeq/Cluster_res.0.5/Markers_Cluster0.tsv"))[V1 %in% mem & V3 > 0])
(beta.markers <- fread(dirout("10_Seurat/DropSeq/Cluster_res.0.5/Markers_Cluster1.tsv"))[V1 %in% mem & V3 > 0])
load(file=dirout("10_Seurat/", "DropSeq/","DropSeq.RData"))
pbmc@ident <- factor([email protected]$res.0.5)
names(pbmc@ident) <- colnames(pbmc@data)
DoHeatmap(object = pbmc, genes.use = c("GCG", alpha.markers$V1,"INS", beta.markers$V1), slim.col.label = TRUE, remove.key = TRUE)
ggsave(dirout(out, "PotentialMarkers.jpg"), width=7, height=15)
pDat <- data.table(pbmc@dr$ts<EMAIL>, sample=<EMAIL>$sample)
glist <- list()
for(tr in unique(pDat$sample)){
glist[[tr]] <- ggplot(pDat, aes(x=tSNE_1, y=tSNE_2)) +
geom_point(data=pDat, color="lightgrey") +
geom_point(data=pDat[sample == tr], color="blue", alpha=0.5, size=0.5) + ggtitle(tr)
}
(p <- grid.arrange(grobs=glist, ncol=3))
ggsave(dirout(out, "Treatment.pdf"),width=10, height=5,plot=p)
pDat <- data.table(INS=pbmc@data["INS",], GCG=pbmc@data["GCG",], Sample=<EMAIL>$sample, nGene = <EMAIL>$nGene, nUMI=<EMAIL>$nUMI)
ggplot(pDat, aes(x=INS, y=GCG, color=nUMI, size=nGene)) + geom_point(alpha=0.5) + facet_grid(. ~ Sample) + theme_bw(24)
ggsave(dirout(out, "INS_GCG.pdf"),width=16, height=5)
pDat$group <- "Negative"
pDat[INS > 5, group := "INS+"]
pDat[GCG > 5, group := "GCG+"]
pDat[GCG > 5 & INS > 5, group := "INS+ GCG+"]
<EMAIL>$Alpha_Beta <- pDat$group
max.nr.of.cores <- 2
extra.genes.to.plot <- c()
outS <- paste0("10_Seurat/", "DropSeq/")
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Seurat2.R"), echo=TRUE)
#save(pbmc, file=dirout("10_Seurat/", "DropSeq/","DropSeq.RData"))
(double.markers <- fread(dirout("10_Seurat/DropSeq/Cluster_Alpha_Beta/Markers_ClusterDoublePos.tsv"))[V1 %in% mem & V3 > 0]$V1)
pbmc@ident <- factor([email protected]$Alpha_Beta)
names(pbmc@ident) <- colnames(pbmc@data)
DoHeatmap(object = pbmc, genes.use = c("GCG", "INS", double.markers), slim.col.label = TRUE, remove.key = TRUE)
ggsave(dirout(out, "PotentialMarkers_DoublePos1.jpg"), width=7, height=7)
DoHeatmap(object = pbmc, genes.use = c("GCG", alpha.markers$V1,"INS", beta.markers$V1), slim.col.label = TRUE, remove.key = TRUE)
ggsave(dirout(out, "PotentialMarkers_DoublePos2.jpg"), width=7, height=15)
<file_sep>/src/FIG_01_Contamination.R
require("project.init")
require(SoupX)
project.init2("artemether")
out <- "FIG_01_Contamination/"
dir.create(dirout(out))
# LOAD EVERYTHING ----------------------------------------------------------
cleanTreatment <- function(vec){ gsub("FoxO", "FoxOi", gsub("A10", "Artemether", vec)) }
# LOAD RAW DATA
data.raw <- Read10X(paste0(getOption("PROCESSED.PROJECT"), "results_pipeline/cellranger_count/","Human1_2","/outs/raw_gene_bc_matrices_mex/GRCh38/"))
# LOAD OTHER STUFF
list.files(dirout("07_03_CleanHuman_CleanSpikeIns"), pattern="RData$")
(load(dirout("07_03_CleanHuman_CleanSpikeIns/","Uncorrected.Data.RData")))
#"ml.rho.pred" "ml.rho.cv" "ml.rho.pred.with.cv" "data.raw.cells" "meta.raw.cells" "spikeIn.soups"
(load(dirout("07_03_CleanHuman_CleanSpikeIns/","CorrectedData.RData")))
# "corr.export"
(load(dirout("07_03_CleanHuman_CleanSpikeIns/","Soup.results.RData")))
(load(dirout("07_03_CleanHuman_CleanSpikeIns/", "Meta.raw.RData")))
metaH <- loadHMetaUnfiltered()
# CLEAN ANNOTATION --------------------------------------------------------
meta.raw.cells$library_id <- cleanTreatment(meta.raw.cells$library_id)
colnames(spikeIn.soups) <- cleanTreatment(colnames(spikeIn.soups))
names(soupX.contFrac) <- cleanTreatment(names(soupX.contFrac))
names(soupX.rho) <- cleanTreatment(names(soupX.rho))
names(soupX.soup) <- cleanTreatment(names(soupX.soup))
colnames(soupX.soup.tpm) <- cleanTreatment(colnames(soupX.soup.tpm))
names(soupX.strainedCells) <- cleanTreatment(names(soupX.strainedCells))
meta.raw$library_id <- cleanTreatment(meta.raw$library_id)
# remove samples not used
table(meta.raw.cells$library_id)
rm.samples <- c("hIslets_II_Aold", "hIslets_I_pla2g16")
metaH <- metaH[!sample %in% rm.samples]
meta.raw <- meta.raw[!library_id %in% rm.samples]
meta.raw.cells <- meta.raw.cells[!library_id %in% rm.samples]
meta.raw.spikes <- meta.raw[spikeIn != "NA"]
meta.raw.spikes <- meta.raw.spikes[!library_id %in% rm.samples]
for(samplex in rm.samples){
soupX.soup[[samplex]] <- NULL
soupX.strainedCells[[samplex]] <- NULL
}
# limit raw data to cells used
data.raw <- data.raw[,meta.raw$rn]
# ASSIGN DATA -------------------------------------------------------------
# Cell data
data.tpm.cells <- t(t(data.raw.cells) / Matrix::colSums(data.raw.cells)) * SCALE.FACTOR
data.log.cells <- toLogTPM(data.tpm.cells)
# Spike in data
data.raw.spike <- data.raw[,meta.raw.spikes$rn]
data.tpm.spike <- t(t(data.raw.spike) / Matrix::colSums(data.raw.spike)) * SCALE.FACTOR
spikeIn.soups.tpm <- t(t(spikeIn.soups)/colSums(spikeIn.soups)) * SCALE.FACTOR
# external spike ins
(load(dirout("05_SpikeIns_Clean/SpikeData_human.RData")))
spike.clean <- add.genes.sparseMatrix(toTPM(dat.log.spike), row.names(data.raw))
spike.clean.meta <- fread(dirout("05_SpikeIns_Clean/SpikeMeta_human.tsv"))
spike.clean.diffOrg <- Matrix::rowMeans(spike.clean[,spike.clean.meta[org == "mouse"]$barcode])
spike.clean.sameOrg <- Matrix::rowMeans(spike.clean[,spike.clean.meta[org == "human"]$barcode])
# Pancreatic genes
pancGenes <- intersect(unique(fread("metadata//PancreasMarkers.tsv")$Human_GeneName), row.names(data.raw))
# Samples
samples <- unique(meta.raw$library_id)
# Contaminating genes
(cont.genes <- intersect(names(tail(sort(rowMeans(spikeIn.soups)), 100)), pancGenes))
# Corrected values tpm (regenerated from exported count values)
nUMIs <- Matrix::colSums(data.raw.cells[,colnames(corr.export)])
ml.corr.values.all.merge <- t(t(corr.export/nUMIs) * SCALE.FACTOR)
# CORRECT DATA FROM SPIKE-INS in mouse and human spike-ins ---------------------------------------------
ml.corr.values <- lapply(samples, function(x){
rn <- meta.raw.spikes[library_id == x]$rn
ret <- data.tpm.spike[,rn] - (spikeIn.soups[row.names(data.tpm.spike),paste(x, "spikeIn")] %o% ml.rho.pred.with.cv[rn])
ret[ret < 0] <- 0
t(t(ret) / Matrix::colSums(ret)) * SCALE.FACTOR
})
ml.corr.values.merge <- do.call(cbind, ml.corr.values)
# COMPARE ESTIMATED TO SPIKE IN TRUTH -------------------------------------------
(sum.I <- sum(data.raw.cells[,meta.raw.cells[grepl("_I_", library_id)]$rn]))
(ins.I <- Matrix::rowSums(data.raw.cells[c("INS", "GCG"),meta.raw.cells[grepl("_I_", library_id)]$rn]))
ins.I / sum.I
(sum.II <- sum(data.raw.cells[,meta.raw.cells[grepl("_II_", library_id)]$rn]))
(ins.II <- Matrix::rowSums(data.raw.cells[c("INS", "GCG"),meta.raw.cells[grepl("_II_", library_id)]$rn]))
ins.II / sum.II
write.tsv(meta.raw.spikes, file=dirout(out, "Meta.raw.spikes.tsv"))
median(meta.raw.spikes[grepl("_I_", library_id)]$contamination, na.rm=T)
median(meta.raw.spikes[grepl("_II_", library_id)]$contamination, na.rm=T)
max(meta.raw.spikes$contamination, na.rm=T)
# COMPARE ESTIMATED RHO
# Soup
meta.raw.spikes$contSoupX <- soupX.rho.agg[meta.raw.spikes$rn]
(p <- ggplot(meta.raw.spikes[!is.na(contamination)], aes(x=contSoupX, y=contamination, color=library_id)) + geom_point(alpha=0.5) +
theme_bw(12) + xlim(0,.7) + ylim(0,.7) + geom_abline(size=2, color="lightgrey", alpha=0.5) +
xlab("Contamination soupX") + ylab("Contamination cross-alignment")) +
ggtitle(with(meta.raw.spikes[!is.na(contamination)], cor(contSoupX, contamination), method="pearson"))
ggsave(dirout(out, "Rho_estimation_SOUP.pdf"), height=4, width=4)
ggsave(dirout(out, "Rho_estimation_SOUP_NoGuid.pdf"), height=4, width=4, plot=p + guides(color=F))
# machine learning
meta.raw.spikes$contMLCV <- ml.rho.cv[meta.raw.spikes$rn]
with(meta.raw.spikes, table(is.na(contMLCV), spikeIn))
(p <- ggplot(meta.raw.spikes[!is.na(contamination)], aes(x=contMLCV, y=contamination, color=library_id)) + geom_point(alpha=0.5) +
theme_bw(12) + xlim(0,.4) + ylim(0,.4) + geom_abline(size=2, color="lightgrey", alpha=0.5) +
xlab("Contamination spike-ins") + ylab("Contamination cross-alignment") +
ggtitle(with(meta.raw.spikes[!is.na(contamination)], cor(contMLCV, contamination), method="pearson")))
ggsave(dirout(out, "Rho_estimation_ML.pdf"), height=4, width=4)
ggsave(dirout(out, "Rho_estimation_ML_noGuide.pdf"), height=4, width=4, plot=p + guides(color=F))
write.tsv(meta.raw.spikes, dirout(out, "Rho_estimnation_Numbers.tsv"))
# COMPARE ESTIMATED CONTAMINATION (SOUP)
stopifnot(all(round(colSums(spikeIn.soups.tpm)) == 1e6))
stopifnot(all(colSums(soupX.soup.tpm) == 1e6))
for(x in unique(meta.raw.spikes$library_id)){
qplot(spikeIn.soups.tpm[,paste0(x, " spikeIn")], soupX.soup.tpm[row.names(spikeIn.soups),x]) +
geom_abline(size=2, color="grey", alpha=0.5) + scale_x_log10() + scale_y_log10() + theme_bw(12) +
xlab("Signature spike-ins") + ylab("Signature soupX") +
annotate("text", x=10, y=10000, label=paste("R =", round(corS(spikeIn.soups.tpm[,paste0(x, " spikeIn")], soupX.soup.tpm[row.names(spikeIn.soups),x]),3)))
ggsave(dirout(out, "Soup_estimation_",x,".jpg"), height=4, width=4)
}
# COMPARE CORRECTED VALUES
compare.values <- fread(dirout("07_03_CleanHuman_CleanSpikeIns/", "Values_compare.tsv"))
compare.values$V3 <- cleanTreatment(compare.values$V3)
compare.values <- compare.values[!V3 %in% c("pla2g16", "Aold")]
ggplot(compare.values, aes(x=V3, y=value, color=V4)) + geom_boxplot() + facet_grid(V5 ~ V2, space="free_x", scale="free_x") +
theme_bw(12) + ylab("Correlation to reference") + xlab("Replicate") + xRot()
ggsave(dirout(out, "Values_compare_human.pdf"), height=4, width=8)
# P values
compare.values[,id2 := paste(V2, V3, V5)]
compare.values.p <- sapply(unique(compare.values$id2), function(idx)
t.test(compare.values[id2 == idx][V4 == "spikeIns"]$value, compare.values[id2 == idx][V4 == "original"]$value, alternative="greater")$p.value)
compare.values.p.soupX <- sapply(unique(compare.values$id2), function(idx)
t.test(compare.values[id2 == idx][V4 == "soupX"]$value, compare.values[id2 == idx][V4 == "original"]$value, alternative="greater")$p.value)
write.tsv(
rbind(
data.table(names(compare.values.p), p=compare.values.p, type="SpikeIns"),
data.table(names(compare.values.p.soupX), p=compare.values.p.soupX, type="SoupX")
),dirout(out, "Values_compare_human_p.values.tsv"))
ggplot(compare.values[V4 != "soupX"], aes(x=V3, y=value, color=V4)) + geom_boxplot() +
facet_grid(V5 ~ V2, space="free_x", scale="free_x") +
theme_bw(12) + guides(color=F) + ylab("Correlation to reference") + xlab("Replicate") +
scale_color_manual(values=c("black", "red")) + xRot()
ggsave(dirout(out, "Values_compare_NoSoupX.pdf"), height=4, width=5)
# MOUSE
compare.values <- fread(dirout("07_11_CleanMouse_CleanSpikeIns/", "Values_compare.tsv"))
compare.values$V3 <- cleanTreatment(compare.values$V3)
compare.values <- compare.values[!V3 %in% c("A1")]
table(compare.values$V3)
ggplot(compare.values[V4 != "soupX"], aes(x=V3, y=value, color=V4)) + geom_boxplot() +
facet_grid(V5 ~ V2, space="free_x", scale="free_x") +
theme_bw(12) + guides(color=F) + ylab("Correlation to reference") + xlab("Replicate") +
scale_color_manual(values=c("black", "red")) + xRot()
ggsave(dirout(out, "Values_compare_NoSoupX_mouse.pdf"), height=4, width=5)
# P values
compare.values[,id2 := paste(V2, V3, V5)]
compare.values.p <- sapply(unique(compare.values$id2), function(idx)
t.test(compare.values[id2 == idx][V4 == "spikeIns"]$value, compare.values[id2 == idx][V4 == "original"]$value, alternative="greater")$p.value)
compare.values.p.soupX <- sapply(unique(compare.values$id2), function(idx)
t.test(compare.values[id2 == idx][V4 == "soupX"]$value, compare.values[id2 == idx][V4 == "original"]$value, alternative="greater")$p.value)
write.tsv(
rbind(
data.table(names(compare.values.p), p=compare.values.p, type="SpikeIns"),
data.table(names(compare.values.p.soupX), p=compare.values.p.soupX, type="SoupX")
),dirout(out, "Values_compare_mouse_p.values.tsv"))
# Plots for individual comparisons
outValCompare <- paste0(out, "Values_compare/")
dir.create(dirout(outValCompare))
for(x in samples){
for(orgXX in c("human", "mouse")){
spikeRef <- spike.clean.sameOrg; if(orgXX != "human") spikeRef <- spike.clean.diffOrg
rn <- meta.raw.spikes[library_id == x & spikeIn == orgXX]$rn
pDat <- data.table(
Reference = spikeRef[row.names(data.tpm.spike)],
Corrected = Matrix::rowMeans(ml.corr.values.merge[row.names(data.tpm.spike), rn]),
Original = Matrix::rowMeans(data.tpm.spike[, rn]))
ggplot(pDat, aes(x=Reference, y=Original)) + geom_abline(size=2, color="lightgrey", alpha=0.5) +
geom_point(alpha=0.3) + geom_point(aes(y=Corrected), color="red", alpha=0.3) + theme_bw(12) +
ylab("Expression in spike-ins") +
annotate("text", x=2000, y=19000, label=paste("R =", round(cor(pDat$Reference, pDat$Original),3)), color="black") +
annotate("text", x=2000, y=21000, label=paste("R =", round(cor(pDat$Reference, pDat$Corrected),3)), color="red")
ggsave(dirout(outValCompare, "0_", orgXX, "_", x, ".jpg"), height=4, width=4)
ggsave(dirout(outValCompare, "0_", orgXX, "_", x, ".pdf"), height=4, width=4)
}}
gg <- "GCG"
for(gg in cont.genes){
m <- meta.raw.spikes
pDat <- rbind (
data.table(m, Gene=soupX.strainedCells.all[gg,m$rn], type="soupX"),
data.table(m, Gene=ml.corr.values.merge[gg,m$rn], type="ML"),
data.table(m, Gene=data.tpm.spike[gg,m$rn],type="raw"))
ggplot(pDat, aes(x=library_id, y=Gene, color=type)) + geom_boxplot() + theme_bw(16) +
facet_grid(spikeIn ~ .) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) + ylab(gg)
ggsave(dirout(out, "GeneAfterCorr_",gg,".pdf"), height=8, width=9)
}
# PLOTS SHOWING CONTAMINATION IN ALL CELLS ---------------------------------------------------
# Raw data INS vs GCG
# Cleaned data
pDat <- fread(dirout("07_03_CleanHuman_CleanSpikeIns/", "Cont.Genes.Data_HUMAN.tsv"))
pDat$library_id <- cleanTreatment(pDat$library_id)
pDat <- pDat[!library_id %in% c("hIslets_I_pla2g16", "hIslets_II_Aold")]
table(pDat$library_id)
plot.genes <- gsub("_corrected", "", grep("_corrected", colnames(pDat), value=T))
pDat <- melt(pDat,id.vars="library_id", measure.vars=paste0(plot.genes, rep(c("_corrected", "_raw"), times=length(plot.genes))))
pDat <- cbind(pDat, do.call(rbind, strsplit(as.character(pDat$variable), "_")))
pDat$V2 <- factor(pDat$V2, levels=c("raw", "corrected"))
ggplot(pDat[V1 %in% c("INS", "GCG")], aes(x=gsub(".+Islets\\_(.+)", "\\1", library_id),y=value, fill=V2)) +
geom_violin(color=NA) + theme_bw(12) + xlab("Replicate") + ylab("Log(TPM)") +
scale_fill_manual(values=c("black", "red")) +
facet_grid(. ~ V1) + guides(fill=F, color=F) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "Contamination_INSvsGCG.pdf"), height=4, width=8)
ggplot(pDat[V2 == "raw" & V1 %in% c("INS", "GCG")], aes(x=gsub(".+Islets\\_(.+)", "\\1", library_id),y=value, fill=V2)) +
geom_violin(color=NA) + theme_bw(12) + xlab("Replicate") + ylab("Log(TPM)") +
scale_fill_manual(values=c("black", "red")) +
facet_grid(. ~ V1) + guides(fill=F, color=F) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "Contamination_INSvsGCG_original.pdf"), height=4, width=4)
# xx <- fread(dirout("EXT_HCA/Hormones.tsv"))
# xx <- data.table(melt(xx[,-"barcode",with=T]), library_id = "Human cell atlas", V2="raw")
# xx$V1 <- xx$variable
# xx <- rbind(xx, pDat, fill=T)
# ggplot(xx[V2 == "raw" & V1 %in% c("INS", "GCG")],
# aes(x=gsub(".+Islets\\_(.+)", "\\1", library_id),y=value, fill=V2)) +
# geom_violin(color=NA) + theme_bw(12) + xlab("Replicate") + ylab("Log(TPM)") +
# scale_fill_manual(values=c("black", "red")) +
# facet_grid(. ~ V1) + guides(fill=F, color=F) +
# theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
# CONTAMINATION IN SPIKE INS --------------------------------------------------------
# HEATMAP
pDat <- cbind(
spike.clean.diffOrg[row.names(data.tpm.cells)],
spike.clean.sameOrg[row.names(data.tpm.cells)])
colnames(pDat) <- paste(gsub("^(.)", "\\U\\1", c("mouse", "human"), perl=T), "reference")
for(x in samples){
for(orgX in c("mouse", "human")){
pDat <- cbind(pDat, Matrix::rowMeans(data.tpm.spike[,meta.raw.spikes[library_id == x & spikeIn == orgX]$rn]))
colnames(pDat)[ncol(pDat)] <- paste(gsub(".+Islets\\_(.+)", "Rep \\1", x), orgX)
}
}
pDat <- pDat[,!grepl("pla2g16", colnames(pDat))]
pDat <- log(pDat + 1)
x <- rowMeans(pDat[,grepl("Rep", colnames(pDat))]) - rowMeans(pDat[,grepl("reference", colnames(pDat))])
tail(sort(x))
head(sort(x))
n <- 20
cleanDev()
pdf(dirout(out, "Contamination_vsSpikeIns_HM.pdf"), height=8, width=6, onefile=F)
pheatmap(pDat[c(names(head(sort(x), n)), names(tail(sort(x), n))),], cluster_rows=F)
dev.off()
# BOXPLOT
pDat <- data.table()
genes <- c("INS", "GCG","TTR")
for(orgX in c("human", "mouse")){
for(gg in genes){
pDat <- rbind(pDat, data.table(Gene = gg, Expression = spike.clean[gg,spike.clean.meta[org == orgX]$barcode], sample=paste("Reference", gsub("^(.)", "\\U\\1", orgX, perl=T))))}}
for(x in samples){
for(orgX in c("mouse", "human")){
for(gg in genes){
pDat <- rbind(pDat, data.table(Gene = gg, Expression = data.tpm.spike["INS",meta.raw.spikes[library_id == x & spikeIn == orgX]$rn], sample=paste(gsub(".+Islets\\_(.+)", "\\1", x), orgX)))}}}
pDat[,Expression := log(Expression + 1)]
ggplot(pDat, aes(x=sample, y=Expression))+
geom_boxplot(alpha=0.4) +
#geom_violin(color="white", fill="lightblue") + geom_jitter(height=0, width=0.1, alpha=0.1) +
theme_bw(12) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) + facet_grid(Gene ~ .) + xlab("")
ggsave(dirout(out, "Contamination_vsSpikeIns_INS_Boxplot.pdf"), height=8, width=5)
# FRACTION OF CONTAMINATION
# Contamination cross-alignment
ggplot(meta.raw.spikes[spikeIn == "mouse"], aes(x=gsub(".+Islets\\_(.+)", "\\1", library_id), y=contamination * 100)) + geom_boxplot() +
theme_bw(12) + xlab("Replicate") + ylab("Contamination (%)")+ theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "Contamination_CrossAlignment.pdf"), height=4, width=2)
# Correlate this to reads in cells
meta.raw.spikes[spikeIn == "mouse"]
seqstats <- fread(dirout("04_SequencingStats/SequencingStats_..tsv"),check.names=T)
stopifnot(all(unique(meta.raw.spikes$old_id) %in% seqstats$dataset))
meta.raw.spikes <- cbind(meta.raw.spikes, do.call(rbind, strsplit(meta.raw.spikes$library_id, "_")))
pDat <- merge(meta.raw.spikes[spikeIn == "mouse"][,median(contamination), by=c("V3", "V2", "old_id")],
seqstats[dataset %in% meta.raw.spikes$old_id][,c("dataset", "Fraction.Reads.in.Cells")],
by.x="old_id", by.y="dataset")
pDat[,rc := as.numeric(gsub("%", "", Fraction.Reads.in.Cells))]
ggplot(pDat, aes(x=V1*100, y=rc)) + geom_point(shape=1) + theme_bw(12) +
xlab("Contamination (%)") + ylab("Reads in cells (%)") + xlim(5,20)
ggsave(dirout(out, "Contamination_CrossAlignment_vs_fractionReadsInCells.pdf"), w=2,h=2)
# correlation of contamination
write("sample,spearman",dirout(out, "Contamination_CrossAlignment_Correlation.tsv"), append=F)
for(x in unique(meta.raw.spikes$old_id)){
cont <- fread(dirout("06_SpikeIns_Islets/",x, "_hmG/Contamination.tsv"))
labx <- gsub("^.Islets_(I+)_(.+)", "\\2 Replicate \\1", meta.raw.spikes[old_id == x]$library_id[1])
corX <- round(corS(cont$inHuman, cont$inMouse), 3)
ggplot(cont, aes(x=inHuman, y=inMouse)) + geom_point(alpha=0.2) + theme_bw(12) +
scale_x_log10() + scale_y_log10() +
annotate("text", x=0.01, y=100, label=paste("R =",corX )) +
xlab("Expression in human") + ylab("Contamination in mouse") +
ggtitle(labx)
ggsave(dirout(out, "Contamination_CrossAlignment_Correlation_",x,".pdf"), height=4, width=4)
ggsave(dirout(out, "Contamination_CrossAlignment_Correlation_",x,".jpg"), height=4, width=4)
write(paste(x,corX, sep=","),dirout(out, "Contamination_CrossAlignment_Correlation.tsv"), append=T)
pDat.org <- fread(dirout("06_SpikeIns_Islets/",x, "_hmG/IdentifyOrganism_full.tsv"))
max.reads <- max(c(pDat.org$rh, pDat.org$rm))
min.reads <- max(min(c(pDat.org$rh, pDat.org$rm)), 1)
(p <- ggplot(pDat.org, aes(x=rh, y=rm, color=org, size=nGene)) + geom_point(alpha=0.3) + geom_abline()+ ggtitle(labx) +
scale_y_log10(limits=c(min.reads,max.reads)) + scale_x_log10(limits=c(min.reads,max.reads)) + xlab("Human reads") + ylab("Mouse reads") + theme_bw(12))
ggsave(dirout(out, "IdentifyOrganism_",x,".jpg"), height=4, width=5)
ggsave(dirout(out, "IdentifyOrganism_",x,".pdf"), height=4, width=5)
ggsave(dirout(out, "IdentifyOrganism2_",x,".jpg"), height=4, width=4, plot=p+guides(color=F, fill=F, size=F))
}
# Numbers for Identify Organism plots
ff <- list.files(dirout("06_SpikeIns_Islets"))
fx <- ff[1]
res <- data.table()
for(fx in ff){
pDat.org <- fread(dirout("06_SpikeIns_Islets/",fx,"/IdentifyOrganism_full.tsv"))
res <- rbind(res, data.table(pDat.org[,.N, by="org"], sample=fx))
}
res[, Percent := N/sum(N)*100, by="sample"]
res[,sample := gsub("_S\\d+$", "", gsub("_hmG$", "", sample))]
res <- cbind(res, do.call(rbind, strsplit(res$sample, "_")))
res[is.na(org), org := "Ambiguous"]
write.tsv(res, dirout(out, "IdentifyOrganism_AmbiguousCellNumbers.tsv"))
# NUMBER OF GENES BEFORE / AFTER CORRECTION -------------------------------
x <- as(object=corr.export, "dgCMatrix")
metaH$nGene.corr <- diff(x[,metaH$rn]@p)
x <- as(object=data.raw.cells, "dgCMatrix")
metaH$nGene.raw <- diff(x[,metaH$rn]@p)
metaH[,treatment := cleanTreatment(treatment)]
pDat <- melt(metaH[!grepl("^\\d+$", celltype2)][!grepl("_", celltype2)],measure.vars=c("nGene.corr", "nGene.raw"), id.vars=c("celltype2", "replicate", "treatment"))
ggplot(pDat, aes(x=celltype2, color=variable, y=value)) + geom_boxplot(coef=Inf) + facet_grid(treatment ~ replicate) +
theme_bw(12) + xlab("Cell type") + ylab("Number of Genes") + scale_color_manual(values=c("red", "black")) +
xRot() + guides(color=F)
ggsave(dirout(out, "nGene_cor_vs_raw.pdf"), height=6, width=6)
# EXAMPLE PLOT ------------------------------------------------------------
set.seed(1219)
expr.cont <- runif(5) * 1:10
for(i in c(1219, 3433)){
set.seed(i*2)
nGenes <- 10
expr <- runif(5) * 1:10
prop <- 0.8
pDat <- rbind(
data.table(value=prop * expr, gene=1:nGenes, type="true", label = "raw"),
data.table(value=(1-prop) * expr.cont, gene=1:nGenes, type="cont", label = "raw"))
#pDat$label <- factor(pDat$label, levels=c("raw", "corrected","clean"))
ggplot(pDat, aes(x=as.factor(gene), y=value,fill=type)) + geom_bar(stat="identity") + theme_bw(12) +
scale_fill_manual(values=c("blue", "grey")) + ylab("TPM") + xlab("Gene") + guides(fill=F)
ggsave(dirout(out, "Example_",i,".pdf"), width=3, height=2)
}
# LINEAR REGRESSION EXAMPLE -----------------------------------------------
x <- meta.raw.spikes$library_id[1]
pp <- list()
for(gg in c("INS", "GCG", "TTR")){
m <- meta.raw.spikes[library_id == x & spikeIn == "mouse"]
m$Expression <- data.tpm.spike[gg,m$rn]
fit <- lm(contamination ~ Expression + 0,data=m)
a = coef(fit)[1]
pp[[gg]] <- ggplot(m, aes(x=Expression, y=contamination)) + #geom_point(alpha=.1, color="black") +
geom_abline(intercept=0, slope=a) + ylab("") + theme_classic() +
theme(axis.ticks.x=element_blank(), axis.ticks.y=element_blank()) +
theme(axis.text.x=element_blank(), axis.text.y=element_blank(),panel.grid=element_blank()) +
xlim(0, max(m$Expression, na.rm=T)) + ylim(0, max(m$contamination,na.rm=T)) +
xlab(gg)
}
(p <- gridExtra::grid.arrange(grobs=pp,ncol=3))
ggsave(dirout(out, "LinearRegression.pdf"), plot=p, height=1, width=3)
<file_sep>/src/EXPORT_01_Averages.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "EXPORT_01_Averages/"
dir.create(dirout(out))
# Read in Data ------------------------------------------------------------
metaH <- loadHMeta2()
pbmcH <- loadHData()
load(dirout("07_03_CleanHuman_CleanSpikeIns/Uncorrected.Data.RData"))
quantile(Matrix::colSums(data.raw.cells[,1:20]))
dat.uncorr.tpm <- toTPM_fromRaw(data.raw.cells, 1e6)
dat.uncorr.log <- toLogTPM(dat.uncorr.tpm)
rowMeansLog <- function(m){
log(Matrix::rowMeans(toTPM(m)) + 1)
}
# AVERAGES ACROSS SAMPLES -------------------------------------------------
avDat.uncor <- sapply(split(metaH$rn, factor(metaH$sample)), function(rns) rowMeansLog(dat.uncorr.log[,rns]))
write.csv(avDat.uncor[row.names(pbmcH@data),], dirout(out, "Full_Sample_Averages_uncorrected.csv"))
avDat <- sapply(split(metaH$rn, factor(metaH$sample)), function(rns) rowMeansLog(pbmcH@data[,rns]))
write.csv(avDat, dirout(out, "Full_Sample_Averages.csv"))
# Markers -----------------------------------------------------------------
(load(dirout("20_01_AlphaCells/", "Markers.RData")))
markers <- markers[V4 > 0.5]
markers <- markers[V2.1 == "human"]
genes <- markers[,c("V1", "V1.1")]
colnames(genes) <- c("gene", "group")
genes <- rbind(genes, data.table(fread("metadata/Dediff_DOWN.csv"), group = "Dediff_down"))
genes <- rbind(genes, data.table(fread("metadata/Dediff_UP.csv"), group = "Dediff_up"))
# Get averages for those genes --------------------------------------------
genes <- genes[gene %in% row.names(pbmcH@data)]
for(ct in c("Alpha", "Beta")){
for(repl in c("I", "II")){
for(treat in c("DMSO", "A10", "FoxO")){
genes[[paste(treat, ct, repl, sep="_")]] <- rowMeansLog(pbmcH@data[genes$gene, metaH[celltype2 == ct & replicate == repl & treatment == treat]$rn])
}
}
}
write.tsv(genes, dirout(out, "AverageData.tsv"))
# HEATMAP -----------------------------------------------------------------
genes <- fread("AverageData.tsv")
genes$gene.unique <- make.unique(genes$gene)
mt <- as.matrix(genes[,3:14])
row.names(mt) <- genes$gene.unique
pdf(dirout(out, "Heatmap.pdf"), width=7, height=15, onefile=F)
pheatmap(mt, annotation_row=data.frame(row.names=genes$gene.unique, group=genes$group), cluster_rows=T, fontsize_row=6)
dev.off()
# plot for specific gene groups -------------------------------------------
genes[group %in% c("Alpha", "Beta"), c("gene.unique", "group", "DMSO_Alpha_I", "FoxO_Alpha_I", "DMSO_Alpha_II", "FoxO_Alpha_II")]
genes[group %in% c("Alpha", "Beta"), c("gene.unique", "group", "DMSO_Alpha_I", "A10_Alpha_I", "DMSO_Alpha_II", "A10_Alpha_II")]
for(ct in c("Alpha", "Beta")){
for(repl in c("I", "II")){
for(treat in c("A10", "FoxO", "DMSO")){
val.treat <- genes[group %in% c("Alpha", "Beta")][[paste(treat, ct, repl, sep="_")]]
val.dmso <- genes[group %in% c("Alpha", "Beta")][[paste("DMSO", ct, repl, sep="_")]]
qplot(val.treat, val.dmso) +
xlab(treat) + ylab("DMSO") + ggtitle(paste(treat, ct, repl, round(cor(val.treat, val.dmso, method='spearman'),3), sep=" "))
ggsave(dirout(out, paste("Cor", treat, ct, repl, sep="_"), ".pdf"))
}
}
}<file_sep>/src/FIG_02_SingleCellAnalyses.R
require("project.init")
project.init2("artemether")
out <- "FIG_02_SingleCellAnalyses/"
dir.create(dirout(out))
cleanTreatment <- function(vec){ gsub("^FoxO$", "FoxOi", gsub("^A10$", "Artemether", vec)) }
cleanTreatment2 <- function(vec){ gsub("FoxO", "FoxOi", gsub("A10", "Artemether", vec)) }
# LOAD DATA ---------------------------------------------------------------
plot.data.files <- dirout(out, "Data.RData")
if(!file.exists(plot.data.files)){
metaH <- loadHMetaUnfiltered()
pbmcH <- loadHData()
metaM <- loadMMetaUnfiltered()()
pbmcM <- loadMData()
metaH <- assignGenesMeta(c("INS", "GCG"), metaH, pbmcH)
metaM <- assignGenesMeta(c("Ins2", "Gcg"), metaM, pbmcM)
metaM[,INS := Ins2]
metaM[,GCG := Gcg]
metaH <- metaH[!sample %in% c("hIslets_II_GABA", "hIslets_I_pla2g16")]
dat.log <- list(human=pbmcH@data[,metaH$rn], mouse=pbmcM@data[,metaM$rn])
dat.raw <- list(human=<EMAIL>[,metaH$rn], [email protected][,metaM$rn])
meta <- list(human=metaH, mouse=metaM)
save(dat.log, dat.raw, meta, file=plot.data.files)
} else {
load(plot.data.files)
}
meta <- lapply(meta, function(x){x$treatment <- cleanTreatment(x$treatment);x})
metaH <- meta$human
metaM <- meta$mouse
names(COLORS.TREATMENTS) <- cleanTreatment(names(COLORS.TREATMENTS))
#pancGenes <- intersect(unique(fread("metadata//PancreasMarkers.tsv")$Human_GeneName), row.names(data.raw))
celltypes.of.interest <- c("Alpha", "Beta")
use.treatments <- c("Artemether", "GABA", "FoxOi")
# EXPORT NUMBERS ----------------------------------------------------------
write.tsv(rbind(data.table(metaH[,.N, by=c("replicate", "treatment")], organism = "human"),data.table(metaM[,.N, by=c("replicate", "treatment")], organism = "mouse"))[order(organism, replicate, treatment)],
dirout(out, "Supp_CellNumbers.tsv"))
# JACCARD OF BARCODES -----------------------------------------------------
x <- gdata::read.xls("metadata/MF153_mouse_human_Islets_10x_sample_annotation_sheet.xlsx",sheet=4)
x <- data.table(x)
x <- x[,c("Library.Name", "Sample.Name"),with=F]
x$Sample.Name <- gsub("_\\d+$", "", x$Sample.Name)
x <- unique(x[Sample.Name != ""])
x$Pool <- as.numeric(factor(x$Library.Name))
name.map <- rbind(fread("metadata/Aggregate_Human1_2.csv"), fread("metadata/Aggregate_Mouse_withLTI.csv"))
name.map[,x := basename(gsub("/outs/molecule_info.h5", "", molecule_h5))]
name.map[,x := gsub("_\\d+?_?S\\d+$", "", x)]
annot <- merge(x, name.map, by.x="Sample.Name", by.y="x")
annot <- data.frame(row.names=annot$library_id, Pool=gsub("MF153_P", "Pool", annot$Library.Name))
ll <- c(split(gsub("-\\d+", "", metaH$rn), factor(metaH$sample)), split(gsub("-\\d+", "", metaM$rn), factor(metaM$sample)))
ll <- ll[names(ll) %in% row.names(annot)]
names(ll) <- cleanTreatment2(names(ll))
row.names(annot) <- cleanTreatment2(row.names(annot))
annot <- annot[names(ll),,drop=F]
annot.col <- list(Pool=RColorBrewer::brewer.pal(n=length(unique(annot$Pool)),name="Accent"))
names(annot.col$Pool) <- unique(annot$Pool)
jac <- jaccard(ll)
jac2 <- jac/max(jac)
cleanDev()
pdf(dirout(out, "Barcode_Overlap.pdf"),width=7, height=6, onefile=F)
pheatmap(jac, clustering_distance_rows= as.dist(1-jac2), clustering_distance_cols=as.dist(1-jac2), annotation_row=annot, annotation_col=annot,
annotation_colors=annot.col)
dev.off()
# nUMI in samples (including GABAII) --------------------------------------
metaH.old <- loadHMeta()[sample != "hIslets_I_pla2g16"]
metaH.old$treatment <- cleanTreatment(metaH.old$treatment)
ggplot(metaH.old, aes(x=treatment, y=nUMI)) + geom_boxplot(coef=Inf) +
facet_grid(replicate ~ .) + theme_bw(16) + xRot()
ggsave(dirout(out, "nUMI_Human.pdf"), height=6, width=4)
ggplot(metaM, aes(x=treatment, y=nUMI)) + geom_boxplot(coef=Inf) +
facet_grid(replicate ~ .) + theme_bw(16) + xRot()
ggsave(dirout(out, "nUMI_Mouse.pdf"), height=6, width=4)
# nGene and class probabilities -------------------------------------------
options(stringsAsFactors=T)
(p <- ggplot(metaH, aes(y=nGene, x=nUMI)) + stat_density_2d(aes(fill=stat(level)), geom="polygon") +
theme_bw(16) + xlab("Number of UMIs") + ylab("Number of genes"))
ggsave(dirout(out, "nGene_nUMI.pdf"), h=4,w=4, plot=p+ guides(fill=F))
ggsave(dirout(out, "nGene_nUMI_Guide.pdf"), h=4,w=4, plot=p)
options(stringsAsFactors=F)
(p <- ggplot(metaH, aes(y=nGene, x=nUMI)) + geom_hex() +
theme_bw(16) + xlab("Number of UMIs") + ylab("Number of genes"))
ggsave(dirout(out, "nGene_nUMI_hex.pdf"), h=4,w=4, plot=p+ guides(fill=F))
ggsave(dirout(out, "nGene_nUMI_hex_Guide.pdf"), h=4,w=4, plot=p)
class.probs <- fread(dirout("14_03_Classifier_moreCelltypes_noEndocrine/human/Prediction.tsv"), check.names=T)
class.probs$maxProb <- rowMax(as.matrix(class.probs[, colnames(class.probs)[15:26], with=F]))
class.probs$maxSecond <- apply(as.matrix(class.probs[, colnames(class.probs)[15:26], with=F]), 1, function(row) sort(row, decreasing=T)[2])
ggplot(class.probs, aes(x=maxProb)) + geom_density() + theme_bw(16) + xlab("Largest class probability") + ylab("Density")
ggsave(dirout(out, "Class_probability_Density.pdf"), h=4,w=4)
(p <- ggplot(class.probs, aes(y=nGene, x=maxProb)) + geom_hex() +
theme_bw(16) + xlab("Largest class probability") + ylab("Number of genes"))
ggsave(dirout(out, "nGene_maxProb.pdf"), h=4,w=4, plot=p+guides(fill=F))
ggsave(dirout(out, "nGene_maxProb_guide.pdf"), h=4,w=4, plot=p)
metaH.strict <- metaH[celltype != "Endocrine" | rn %in% class.probs[maxProb/2 > maxSecond]$rn]
write.tsv(metaH.strict, dirout(out, "Reassigned_Human_Strict.tsv"))
# T-SNE Plots of celltypes -------------------------------------------------------------
# Celltypes
cl.x <- "celltype"
pDat <- metaH
clPlot <- function(pDat, cl.x, label){
labelCoordinates <- pDat[,.(tSNE_1=median(tSNE_1), tSNE_2=median(tSNE_2)),by=cl.x]
plim <- ceiling(max(max(abs(pDat$tSNE_1)), max(abs(pDat$tSNE_2)))/10)*10
(p <- ggplot(pDat, aes_string(x="tSNE_1",y="tSNE_2", color=cl.x)) + theme_bw(16) + xlim(-plim, plim) + ylim(-plim,plim) +
xlab("t-SNE dimension 1") + ylab("t-SNE dimension 2"))
ggsave(dirout(out, label, ".jpg"), height=6, width=6, plot=p + geom_point(alpha=0.3) + guides(color=F))
ggsave(dirout(out, label, ".pdf"), height=6, width=6,
plot=p + geom_point(data=pDat[rn %in% sapply(split(pDat$rn, factor(pDat[[cl.x]])), function(x) x[1])], alpha=0.3))
ggsave(dirout(out, label, "Labels.pdf"), height=6, width=6,
plot=p + geom_label(data=labelCoordinates, aes_string(x="tSNE_1", y="tSNE_2", label=cl.x), color="black", alpha=0.5) + theme(panel.grid=element_blank()))
ggsave(dirout(out, label, "Done.jpg"), height=6, width=6,
plot=p + geom_point(alpha=0.3) + guides(color=F) + geom_label(data=labelCoordinates, aes_string(x="tSNE_1", y="tSNE_2", label=cl.x), color="black", alpha=0.5))
}
clPlot(metaH, "celltype", "tSNE_human")
clPlot(metaM, "celltype", "tSNE_mouse")
metaH.E <- fread(dirout("10_H_01_Seurat/Subcluster/MetaData_AnnotatedCells.tsv"))[!sample %in% c("hIslets_II_GABA", "hIslets_I_pla2g16")]
metaM.E <- fread(dirout("10_M_01_Seurat/Subcluster/MetaData_AnnotatedCells.tsv"))
clPlot(metaH.E, "celltype", "tSNE_human_endocrine")
clPlot(metaM.E, "celltype", "tSNE_mouse_endocrine")
# MARKERS
marker.plot <- function(pDat, genes, dat, label, ncol=3){
plots <- list()
gg <- "INS"
for(gg in genes){
pDat$E <- dat[gg,pDat$rn]
pDat[, E := E/max(pDat$E)]
plots[[gg]] <- ggplot(pDat, aes_string(x="tSNE_1",y="tSNE_2", color="E")) + theme_bw(16) + geom_point(alpha=0.3) +
scale_color_gradient(low="lightgrey", high="blue") + ggtitle(gg) +
guides(color=F) + theme(axis.text=element_blank(), axis.ticks=element_blank(), axis.title=element_blank())
}
p <- gridExtra::grid.arrange(grobs=plots, ncol=ncol)
ggsave(dirout(out, label, "_Markers.jpg"), width=ncol*3, height=ceiling(length(genes)/ncol)*3, plot=p)
}
"Reg1a" %in% row.names(dat.log$mouse)
marker.plot(metaH, c("INS", "GCG", "REG1A", "KRT8", "SPARC", "SPP1"), dat.log$human, "tSNE_human")
marker.plot(metaH.E, c("INS", "GCG", "SST", "PPY"), dat.log$human, "tSNE_human_endocrine_small", ncol=2)
marker.plot(metaH.E, c("INS", "GCG", "SST", "PPY", "TTR", "REG1A"), dat.log$human, "tSNE_human_endocrine")
marker.plot(metaM, c("Ins2", "Gcg", "Sparc", "Cd14", "Ptprc", "Ttr"), dat.log$mouse, "tSNE_mouse")
marker.plot(metaM.E, c("Ins2", "Gcg", "Sst", "Ppy", "Ttr", 'Iapp'), dat.log$mouse, "tSNE_mouse_endocrine")
# MARKER DISTRIBUTIONS USED
pDat <- data.table()
for(gg in c("INS", "GCG", "SST", "PPY", "REG1A")){
pDat <- rbind(pDat, data.table(meta$human, Expression = dat.log$human[gg, meta$human$rn], gene=gg))}
ggplot(pDat, aes(x=Expression, color=replicate, linetype=treatment)) + geom_density() + facet_wrap(~gene, ncol=1) + theme_bw(16) + xlab("") +
geom_vline(data=data.table(gene=c("INS","GCG","SST","PPY","REG1A"), value=c(rep(7.5,4), 1.5)), aes(xintercept=value), size=2, color="black")
ggsave(dirout(out, "Marker_cutoffs.human.pdf"), height=15, width=7)
pDat <- data.table()
for(gg in c("Ins2", "Gcg", "Sst", "Ppy")){
pDat <- rbind(pDat, data.table(meta$mouse, Expression = dat.log$mouse[gg, meta$mouse$rn], gene=gg))}
ggplot(pDat, aes(x=Expression, color=replicate, linetype=treatment)) + geom_density() + facet_wrap(~gene, ncol=1) + theme_bw(16) + xlab("") +
geom_vline(data=data.table(gene=c("Ins2","Gcg","Sst","Ppy"), value=c(rep(7.5,4))), aes(xintercept=value), size=2, color="black")
ggsave(dirout(out, "Marker_cutoffs.mouse.pdf"), height=15, width=10)
x <- meta$human; x[is.na(spikeIn), spikeIn := "NA"]; ggplot(x, aes(x=factor(res.0.5), fill=spikeIn)) + geom_bar() + theme_bw(16) + xRot() + ylab("Cells") + xlab("Cluster")
ggsave(dirout(out, "Marker_Spikeins_human.pdf"), height=4, width=6)
x <- meta$mouse; x[is.na(spikeIn), spikeIn := "NA"]; ggplot(x, aes(x=factor(res.0.5), fill=spikeIn)) + geom_bar() + theme_bw(16) + xRot() + ylab("Cells") + xlab("Cluster")
ggsave(dirout(out, "Marker_Spikeins_mouse.pdf"), height=4, width=6)
# Celltype TSNEs - individual ----------------------------------------------
xnam <- "30_04_ClusteringExperiments"
for(xnam in c("30_04_ClusteringExperiments", "30_05_ClusteringExperiments")){
ff <- list.files(dirout(xnam), pattern="MetaData_tSNE.tsv", recursive=T)
names(ff) <- make.names(dirname(ff))
pDat <- lapply(names(ff), function(fnam){x <- fread(dirout(xnam, "/", ff[[fnam]])); x$sample <- fnam; return(x)})
pDat <- do.call(rbind, pDat)
pDat <- merge(pDat, loadHMetaUnfiltered()()[!sample %in% c("hIslets_I_pla2g16")][,c("rn", "PredictedCell"), with=F], by="rn")
pDat <- cbind(pDat, do.call(rbind, strsplit(pDat$sample, "_")))
pDat <- cbind(pDat, do.call(rbind, strsplit(pDat$V1, "\\.")))
colnames(pDat) <- make.unique(colnames(pDat))
pDat[,treatment := cleanTreatment(V2.1)]
p <- ggplot(pDat[PredictedCell %in% c("Alpha", "Beta", "Gamma", "Delta")][V1 != "Aold"],
aes(x=tSNE_1, y=tSNE_2, color=PredictedCell)) +
scale_color_manual(values=c(Alpha="#6a3d9a", Beta="#33a02c", Gamma="#ff7f00", Delta="#e31a1c")) +
geom_point(alpha=0.5) + facet_grid(V1.1 + V2 ~ treatment) +
xlab("t-SNE dimension 1") + ylab("t-SNE dimension 2") + theme_bw(16)
ggsave(dirout(out, "IndividualTSNEs_guides_",xnam,".pdf"), w=16,h=16, plot=p)
ggsave(dirout(out, "IndividualTSNEs_",xnam,".jpg"), w=16,h=16, plot=p+guides(color=F))
}
# xx.list <- list(corrected = "30_01_ClusteringExperiments", raw="30_02_ClusteringExperiments_raw", raw2="30_03_ClusteringExperiments_raw_subcluster")
# xx.nam <- "raw2"
# for(xx.nam in c("corrected", "raw", "raw2")){
# ff <- list.files(dirout(xx.list[[xx.nam]], "/"), pattern="MetaData_tSNE.tsv", recursive=T)
# names(ff) <- dirname(ff)
# pDat <- lapply(names(ff), function(fnam){x <- fread(dirout(xx.list[[xx.nam]], "/", ff[[fnam]])); x$sample <- fnam; return(x)})
# pDat <- do.call(rbind, pDat)
# pDat <- merge(pDat, loadHMetaUnfiltered()()[!sample %in% c("hIslets_I_pla2g16")][,c("rn", "PredictedCell"), with=F], by="rn")
# pDat <- cbind(pDat, do.call(rbind, strsplit(pDat$sample, "_")))
# pDat[,treatment := cleanTreatment(V1)]
# p <- ggplot(pDat[PredictedCell %in% c("Alpha", "Beta", "Gamma", "Delta")][V1 != "Aold"],
# aes(x=tSNE_1, y=tSNE_2, color=PredictedCell)) +
# scale_color_manual(values=c(Alpha="#6a3d9a", Beta="#33a02c", Gamma="#ff7f00", Delta="#e31a1c")) +
# geom_point(alpha=0.5) + facet_grid(V2 ~ treatment) +
# xlab("t-SNE dimension 1") + ylab("t-SNE dimension 2") + theme_bw(16)
# ggsave(dirout(out, "IndividualTSNEs_guides_",xx.nam,".pdf"), w=16,h=8, plot=p)
# ggsave(dirout(out, "IndividualTSNEs_",xx.nam,".jpg"), w=16,h=8, plot=p+guides(color=F))
# }
# CELLTYPE PREDICTION -----------------------------------------------------
# PLOT PREDICTIONS
for(orgx in c("human", "mouse")){
predH <- fread(dirout("14_03_Classifier_moreCelltypes_noEndocrine/",orgx,"/", "Prediction.tsv"))
predH <- predH[!sample %in% c("hIslets_II_GABA", "hIslets_I_pla2g16")]
predH$treatment <- cleanTreatment(predH$treatment)
classes <- intersect(colnames(predH), predH$celltype)
meanDat <- melt(predH, id.vars=c("treatment", "replicate", "celltype"), measure.vars=classes)[,.(value = mean(value)), by=c("treatment", "replicate", "celltype","variable")]
ggplot(meanDat, aes(x=treatment, y=variable, fill=value)) + geom_tile() +
theme_bw(12) + xlab("") + ylab("") +
facet_grid(replicate ~ celltype) + xRot() +
scale_fill_gradient(name="Mean Prob", low="white", high="red",limits=c(0,1))
ggsave(dirout(out, "Predictions_",orgx,".pdf"), width=15, height=5)
# PLOT ACCURACY
predH$PredictedCell <- apply(as.matrix(predH[,unique(intersect(colnames(predH), predH$celltype)), with=F]),1,function(row) names(row)[which(row == max(row))])
predH.acc <- predH[celltype %in% classes, sum(celltype == PredictedCell)/.N, by=c("celltype", "replicate", "treatment")]
predH.acc$Class <- predH.acc$celltype
ggplot(predH.acc,aes(x=treatment, y=V1,color=Class, shape=Class)) +
geom_jitter(width=0.1, height=0) + ylim(0,1) +
scale_shape_manual(values=rep(c(1,16,2,18,3,4), 20)) +
facet_wrap(. ~ replicate, scales="free_x") +theme_bw(16) + xRot() +
xlab("Treatment") + ylab("Precision")
ggsave(dirout(out, "Predictions_Precision_",orgx,".pdf"), height=4, width=3*length(unique(predH$replicate)))
}
# Do the initially unassignable cells have more genes (doublets?)
pDat <- meta$human[celltype2 %in% c("Alpha", "Beta", "Gamma", "Delta")]
#pDat$celltype <- factor(pDat$celltype, levels=c("Endocrine", "Alpha", "Beta", "Gamma", "Delta"))
ggplot(pDat, aes(x=(celltype=="Endocrine"), y=nGene)) + geom_boxplot(coef=Inf) + theme_bw(16) +
facet_grid(treatment ~ celltype2) + xRot() +
xlab("Reassigned cells") + ylab("Number of Genes")
ggsave(dirout(out, "Predictions_nGene.pdf"),w=8,h=8)
# COUNTS - Alpha/Beta cell ratio ------------------------------------------
# Human Counts
for(orgx in c("human", "mouse")){
pDat <- meta[[orgx]][celltype2 != "",.N, by=c("celltype2", "replicate", "treatment", "celltype")]
pDat[,sum := sum(N), by=c("replicate", "treatment")]
pDat[,percent := N / sum * 100]
pDat[celltype == "Endocrine", X := "Predicted"]
pDat[celltype != "Endocrine", X := "Assigned"]
ggplot(pDat, aes(x=treatment,y=percent, fill=X)) + geom_bar(stat="identity", position="stack") + facet_grid(replicate ~ celltype2) +
scale_fill_manual(name="", values=c("grey", "blue")) + theme_bw(16)+ xRot() + xlab("") + ylab("Percent")
ggsave(dirout(out, "Predicted_",orgx,".pdf"), height=length(unique(pDat$replicate))* 2,width=18)
}
# Endocrine of all / beta cells
pDat <- rbind(
data.table(meta$human[, length(rn[celltype=="Endocrine"])/.N*100, by=c("sample", "replicate", "treatment")][order(sample)], type="All", org="human"),
data.table(meta$mouse[, length(rn[celltype=="Endocrine"])/.N*100, by=c("sample", "replicate", "treatment")][order(sample)], type="All", org="mouse"),
data.table(meta$human[, length(rn[celltype=="Endocrine" & celltype2=="Beta"])/.N*100, by=c("sample", "replicate", "treatment")][order(sample)], type="Beta", org="human"),
data.table(meta$mouse[, length(rn[celltype=="Endocrine" & celltype2=="Beta"])/.N*100, by=c("sample", "replicate", "treatment")][order(sample)], type="Beta", org="mouse"),
data.table(meta$human[, length(rn[celltype=="Endocrine" & celltype2=="Alpha"])/.N*100, by=c("sample", "replicate", "treatment")][order(sample)], type="Alpha", org="human"),
data.table(meta$mouse[, length(rn[celltype=="Endocrine" & celltype2=="Alpha"])/.N*100, by=c("sample", "replicate", "treatment")][order(sample)], type="Alpha", org="mouse"))
ggplot(pDat, aes(x=treatment, y=V1, fill=treatment)) + geom_bar(stat="identity") + facet_grid(type ~ paste(org, replicate), space="free_x", scales="free") + theme_bw(16) +xRot() +
xlab("Treatment") + ylab("Percent of cells") + scale_fill_manual(values=COLORS.TREATMENTS)
ggsave(dirout(out, "Endocrine_Percent.pdf"), height=6,width=8)
# Alpha vs Beta
pDat <- rbind(data.table(meta$mouse[,sum(celltype2 == "Alpha")/ sum(celltype2 == "Beta"), by=c("treatment", "replicate")], org = "mouse"),
data.table(meta$human[,sum(celltype2 == "Alpha")/ sum(celltype2 == "Beta"), by=c("treatment", "replicate")][order(replicate)], org = "human"))
pDat[,grp := paste(org, replicate)]; pDat$grp <- factor(pDat$grp, levels=unique(pDat$grp))
ggplot(pDat, aes(x=treatment, y=V1, fill=treatment)) + geom_bar(stat="identity") +
facet_wrap(~grp,scales="free",ncol=3) +
theme_bw(16) + xRot() + ylab("Alpha / beta cell ratio") + xlab("") +
scale_fill_manual(values=COLORS.TREATMENTS) + guides(fill=F)
ggsave(dirout(out, "AlphaBetaRatio.pdf"), height=6,width=5)
# INS / GCG distributions -------------------------------------------------
for(org in c("human", "mouse")){
for(ct in celltypes.of.interest){
ttt <- intersect(use.treatments, meta[[org]]$treatment)
pDat <- do.call(rbind, lapply(ttt, function(treat) data.table(meta[[org]][treatment %in% c("DMSO", treat)], treatx=treat)))
gg <- if(ct == "Beta") "INS" else "GCG"
for(gg in c("GCG", "INS")){
pDat <- pDat[celltype2 == ct]
ggplot(pDat, aes_string(x=gg, color="treatment")) + stat_ecdf() +
theme_bw(16) + facet_grid(replicate ~ treatx, scale="free") +
scale_color_manual(values=COLORS.TREATMENTS)+ guides(color=F) +
ylab("Fraction of cells")
ggsave(dirout(out, "ECDF_", org, "_", ct,"_", gg, ".pdf"),height=2*length(unique(pDat$replicate)),width=length(unique(pDat$treatx)) * 2 + 1)
}}}
# QUANTILE DIFFERENCES ----------------------------------------------------
ct <- celltypes.of.interest[1]
org <- "human"
for(ct in celltypes.of.interest){
#for(gg in c("GCG", "INS")){
res <- data.table()
for(org in c("human", "mouse")){
for(replx in unique(meta[[org]]$replicate)){
for(treatX in use.treatments){
gg <- if(ct == "Beta") "INS" else "GCG"
pDat <- meta[[org]][celltype2 == ct & replicate == replx]
q1 <- quantile(pDat[treatment == treatX & replicate == replx][[gg]], probs=seq(0,1,1e-2))
q2 <- quantile(pDat[treatment == "DMSO" & replicate == replx][[gg]], probs=seq(0,1,1e-2))
res <- rbind(res, data.table(diff= q1 - q2,treatment = treatX, replicate=replx, org=org, gene=gg))
}
}
}
ggplot(res, aes(y=diff, color=replicate, x=org)) +
geom_boxplot(coef=Inf) + theme_bw(16) +
#scale_fill_manual(values=c("white", "grey")) +
facet_grid(. ~ treatment, scales="free", space="free") + xRot() +
xlab("Treatment") + ylab(paste(gg, " difference to DMSO")) + ggtitle(ct)
ggsave(dirout(out, "ECDF_Quantiles_", ct, "_", gg, ".pdf"),height=6, width=6)
#}
}
# DIFF GENES SIMILARITIES -------------------------------------------------
file.copy(dirout("17_02_06_Gene_plots_q0.1_ByGroup/HM_Similarity_human.pdf"), dirout(out))
file.copy(dirout("17_02_06_Gene_plots_q0.1_ByGroup/HM_Similarity_mouse.pdf"), dirout(out))
<file_sep>/src/30_04_ClusteringExperiments.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "30_04_ClusteringExperiments/"
dir.create(dirout(out))
# LOAD META DATA --------------------------------------------------------------
meta <- loadHMeta2()
meta <- meta[!sample %in% c("hIslets_I_pla2g16", "hIslets_II_Aold")]
cellsToKeep.list <- with(meta, split(rn, factor(paste(treatment, replicate, sep="_"))))
str(cellsToKeep.list)
# LOAD COUNT DATA -----------------------------------------------------------
(load(dirout("07_03_CleanHuman_CleanSpikeIns/","Uncorrected.Data.RData")))
(load(dirout("07_03_CleanHuman_CleanSpikeIns/", "CorrectedData.RData")))
# All meta barcodes are in both matrices
stopifnot(all(meta$rn %in% colnames(data.raw.cells)))
stopifnot(all(meta$rn %in% colnames(corr.export)))
# they have the same format
stopifnot(class(corr.export) == "dgCMatrix")
data.raw.cells <- as(data.raw.cells, "dgCMatrix")
# The have the same column names
stopifnot(length(intersect(colnames(corr.export),colnames(data.raw.cells))) == ncol(corr.export))
data.raw.cells <- data.raw.cells[,colnames(corr.export)]
stopifnot(all(colnames(corr.export) == colnames(data.raw.cells)))
# The have the same column sums
stopifnot(all(round(Matrix::colSums(data.raw.cells[,1:10])) == round(Matrix::colSums(corr.export[,1:10]))))
# Genes to use --------------------------------------------------------------
genes.to.use.file <- dirout(out, "Genes.to.use.tsv")
if(!file.exists(genes.to.use.file)){
data.final.h <- loadHData()
genes.to.use <- row.names(data.final.h@data)
write.tsv(data.table(genes=genes.to.use), genes.to.use.file)
} else {
genes.to.use <- fread(genes.to.use.file)$genes
}
stopifnot(all(genes.to.use %in% row.names(corr.export)))
stopifnot(all(genes.to.use %in% row.names(data.raw.cells)))
# raw or corrected data ---------------------------------------------------
typex <- "raw"
for(typex in c("raw", "corrected")){
out2 <- paste0(out, "/", typex)
dir.create(dirout(out2))
xnam <- names(cellsToKeep.list)[1]
for(xnam in names(cellsToKeep.list)){
# do this for each
outS <- paste0(out2, "/", xnam, "/")
if(file.exists(dirout(outS, "SeuratObject",".RData"))) next
pbmc.data <- if(typex == "raw") data.raw.cells else corr.export
pbmc.data <- pbmc.data[genes.to.use,cellsToKeep.list[[xnam]]]
cluster.precision <- c()
sample.x <- xnam
tryCatch({
source("src/30_ClusteringExperiments_SCRIPT.R",echo=TRUE)
ggplot(data.table(pbmc@[email protected]), aes(x=tSNE_1, y=tSNE_2)) + geom_point(alpha=0.1)
ggsave(dirout(outS, "TSNE.jpg"), w=4,h=4)
ggplot(data.table(INS=pbmc@data["INS",]), aes(x=INS)) + geom_density()
ggsave(dirout(outS, "INS.jpg"), w=4,h=4)
}, error=function(e) message(e))
}
}
<file_sep>/src/11_M_AssignCelltypes.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
(load(dirout("10_M_01_Seurat/SeuratObject.RData")))
inDirFull <- "10_M_01_Seurat/"
inDirSub <- paste0(inDirFull, "Subcluster/")
# Cell Type assignment ----------------------------------------------------
# ENDOCRINE
meta <- fread(dirout(inDirSub, "MetaData_tSNE.tsv"))
ggplot(meta, aes(x=tSNE_1, y=tSNE_2, color=sample)) + geom_point()
ggsave(dirout(inDirSub, "tSNE_sample", '.jpg'), width=7, height=7)
data <- pbmc@data
for(gg in c("Ins2", "Gcg", "Sst", "Ppy")){
stopifnot(gg %in% row.names(data))
meta[[gg]] <- data[gg,meta$rn]
ggplot(meta, aes_string(x=gg, color="sample")) + geom_density()
ggsave(dirout(inDirSub, "Density_",gg, '.pdf'), width=7, height=5)
}
x <- list()
for(gg in c("Ins2", "Gcg", "Sst", "Ppy")){
x[[gg]] <- meta[get(gg) > 7.5]$rn}
pdf(dirout(inDirSub, "Venn.pdf"))
gplots::venn(x)
dev.off()
meta[,nr_celltypes := sum(c(Ins2, Gcg, Sst, Ppy) > 7.5),by="rn"]
ggplot(meta, aes(x=tSNE_1, y=tSNE_2, color=nr_celltypes)) + geom_point() + scale_color_gradient(low="white", high="red")
ggsave(dirout(inDirSub, "tSNE_nr_celltypes", '.jpg'), width=7, height=7)
meta$celltype <- ""
meta[Ins2 > 7.5 & Gcg < 7.5 & Sst < 7.5,celltype := "Beta"]
meta[Ins2 < 7.5 & Gcg > 7.5 & Sst < 7.5,celltype := "Alpha"]
meta[Ins2 < 7.5 & Gcg < 7.5 & Sst > 7.5,celltype := "Delta"]
meta[Ppy > 7.5 & Ins2 < 7.5 & Gcg < 7.5 & Sst < 7.5,celltype := "Gamma"]
meta[celltype == "", celltype := "Endocrine"]
# tail(sort(meta[celltype == "Beta"]$Gcg),20)
ggplot(meta, aes(x=tSNE_1, y=tSNE_2, color=celltype)) + geom_point(alpha=0.3)
ggsave(dirout(inDirSub, "tSNE_celltypes", '.jpg'), width=7, height=7)
write.tsv(meta, dirout(inDirSub, "MetaData_AnnotatedCells.tsv"))
rm(list="meta")
# ALL CELLTYPES
metaSub <- fread(dirout(inDirSub, "MetaData_AnnotatedCells.tsv"))
metaFull <- fread(dirout(inDirFull, "MetaData_tSNE.tsv"))
metaFull <- merge(metaFull, metaSub[,c("rn", "celltype")], by="rn", all.x=T)
metaFull[is.na(celltype), celltype := res.0.5]
# Spike ins
meta.spikeIns <- fread(list.files(dirout("07_11_CleanMouse_CleanSpikeIns/"), pattern="Cont.Genes.Data.+tsv", full.names=T))
metaFull <- merge(metaFull, meta.spikeIns[,c("spikeIn", "rn"),with=F], by="rn", all.x=T)
metaFull[is.na(spikeIn), spikeIn := "NA"]
with(metaFull, table(celltype, as.character(spikeIn)))
# assign more celltypes
metaFull[ celltype == "7",celltype := "SI_Human"]
metaFull[ celltype == "8",celltype := "Acinar"]
metaFull[ celltype == "9",celltype := "Endothelial1"] # SPARC
metaFull[ celltype == "12",celltype := "Endothelial2"] # SPARC
metaFull[ celltype == "14",celltype := "SI_Mouse"]
write.tsv(metaFull, dirout(inDirFull, "MetaData_AnnotatedCells.tsv"))
<file_sep>/src/11_H3_AssignCelltypes.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
(load(dirout("10_H3_01_Seurat/SeuratObject.RData")))
inDirFull <- "10_H3_01_Seurat/"
inDirSub <- paste0(inDirFull, "Subcluster/")
# Cell Type assignment ----------------------------------------------------
# IN ENDOCRINE CELLS
meta <- fread(dirout(inDirSub, "MetaData_tSNE.tsv"))
ggplot(meta, aes(x=tSNE_1, y=tSNE_2, color=sample)) + geom_point()
ggsave(dirout(inDirSub, "tSNE_sample", '.jpg'), width=7, height=7)
data <- pbmc@data
for(gg in c("INS", "GCG", "SST", "PPY", "REG1A")){
stopifnot(gg %in% row.names(data))
meta[[gg]] <- data[gg,meta$rn]
ggplot(meta, aes_string(x=gg, color="sample")) + geom_density()
ggsave(dirout(inDirSub, "Density_",gg, '.pdf'), width=7, height=5)
}
meta[,nr_celltypes := sum(c(INS, GCG, SST, PPY) > 7.5),by="rn"]
ggplot(meta, aes(x=tSNE_1, y=tSNE_2, color=nr_celltypes)) + geom_point() + scale_color_gradient(low="white", high="red")
ggsave(dirout(inDirSub, "tSNE_nr_celltypes", '.jpg'), width=7, height=7)
x <- 7.5; dpF <- data.table()
for(x in seq(0,15,0.5)){
dpF <- rbind(dpF, data.table(meta[, sum(GCG > x & INS > x) / .N, by="sample"], cutoff=x))}
dpF <- data.table(dpF, do.call(rbind, strsplit(dpF$sample, "_")))
ggplot(dpF, aes(x=cutoff, y=V1, color=V3)) + geom_line() + facet_grid(V2 ~ .)
ggsave(dirout(inDirSub, "DoublePositives", '.pdf'), width=10, height=7)
meta$celltype <- ""
meta[INS > 7.5 & GCG < 7.5 & SST < 7.5,celltype := "Beta"]
meta[INS < 7.5 & GCG > 7.5 & SST < 7.5,celltype := "Alpha"]
meta[INS < 7.5 & GCG < 7.5 & SST > 7.5,celltype := "Delta"]
meta[PPY > 7.5 & INS < 7.5 & GCG < 7.5 & SST < 7.5,celltype := "Gamma"]
meta[REG1A > 1.25 & tSNE_1 > 25 & tSNE_2 < 4 & tSNE_2 > -10,celltype := "Acinar_like"]
meta[celltype == "", celltype := "Endocrine"]
# tail(sort(meta[celltype == "Beta"]$GCG),20)
ggplot(meta, aes(x=tSNE_1, y=tSNE_2, color=celltype)) + geom_point(alpha=0.3)
ggsave(dirout(inDirSub, "tSNE_celltypes", '.jpg'), width=7, height=7)
ggplot(meta, aes(x=tSNE_1, y=tSNE_2, color=celltype)) + geom_point(alpha=0.3) + facet_grid(.~celltype)
ggsave(dirout(inDirSub, "tSNE_celltypes_wide", '.jpg'), width=20, height=7)
write.tsv(meta, dirout(inDirSub, "MetaData_AnnotatedCells.tsv"))
rm(list="meta")
# IN ALL CELLTYPES
metaSub <- fread(dirout(inDirSub, "MetaData_AnnotatedCells.tsv"))
metaFull <- fread(dirout(inDirFull, "MetaData_tSNE.tsv"))
metaFull <- merge(metaFull, metaSub[,c("rn", "celltype")], by="rn", all.x=T)
metaFull[is.na(celltype), celltype := res.0.5]
# Spike ins
meta.spikeIns <- fread(list.files(dirout("07_04_CleanHuman3_CleanSpikeIns/"), pattern="Cont.Genes.Data.+tsv", full.names=T))
metaFull <- merge(metaFull, meta.spikeIns[,c("spikeIn", "rn"),with=F], by="rn", all.x=T)
metaFull[is.na(spikeIn), spikeIn := "NA"]
with(metaFull, table(celltype, as.character(spikeIn)))
# assign more celltypes
metaFull[ celltype == "3",celltype := "Ductal"]
metaFull[ celltype == "6",celltype := "Acinar"]
metaFull[ celltype %in% c("8", "12", "10"),celltype := "Endothelial"] # CD3
metaFull[ celltype == "9",celltype := "SI_human"]
metaFull[spikeIn == "mouse", celltype := "SI_mouse"]
write.tsv(metaFull, dirout(inDirFull, "MetaData_AnnotatedCells.tsv"))
<file_sep>/src/14_02_Classifier_moreCelltypes_NoEndocrine.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
require(doMC)
require(glmnet)
require(ROCR)
project.init2("artemether")
out <- "14_03_Classifier_moreCelltypes_noEndocrine/"
dir.create(dirout(out))
metaH <- loadHMeta()
pbmcH <- loadHData()
metaH3 <- loadH3Meta()
pbmcH3 <- loadH3Data()
metaM <- loadMMeta()
pbmcM <- loadMData()
with(metaH[treatment == "DMSO"], table(celltype, sample))
with(metaM[treatment == "DMSO"], table(celltype, sample))
with(metaH3[treatment == "DMSO"], table(celltype, sample))
org <- "human"
# c("mouse", "human", "human3")
for(org in c("mouse", "human", "human3")){
meta <- metaH3
data <- pbmcH3@data
predGeneExclude <- c("INS", "GCG", "SST", "PPY")
if(org == "mouse"){
meta <- metaM
data <- pbmcM@data
predGeneExclude <- c("Ins2", "Gcg", "Sst", "Ppy")
}
if(org == "human"){
meta <- metaH
data <- pbmcH@data
}
celltypes.to.use <- names(which(table(meta[treatment == "DMSO"]$celltype) > 50))
celltypes.to.use <- celltypes.to.use[celltypes.to.use != "Endocrine"]
replicates <- length(unique(meta$replicate))
outOrg <- paste0(out, org, "/")
dir.create(dirout(outOrg))
fit.file <- dirout(outOrg, "ModelFit.RData")
if(!file.exists(fit.file)){
trainData <- meta[treatment == "DMSO" & celltype %in% celltypes.to.use]
set.seed(2121)
cells.to.use <- unique(do.call(c, lapply(split(trainData$rn, factor(paste0(trainData$celltype, trainData$replicate))), function(x) sample(x, 100, replace=T))))
trainData <- trainData[rn %in% cells.to.use]
ggplot(trainData, aes(x=celltype, fill=replicate)) + geom_bar() + xRot()
ggsave(dirout(outOrg, "TrainingCounts.pdf"), width=5, height=5)
dat <- t(as.matrix(data[-which(rownames(data) %in% predGeneExclude),trainData$rn]))
registerDoMC(cores=3)
glmFit <- cv.glmnet(y=factor(trainData$celltype), x=dat[trainData$rn,],family="multinomial",alpha=1, parallel=TRUE, keep=TRUE, nfolds=5)
str(coef(glmFit))
trainData$fold <- glmFit$foldid
classes <- glmFit$glmnet.fit$classnames
lambda <- glmFit$lambda.1se
lambda.idx <- which(glmFit$lambda == lambda)
save(glmFit, trainData, lambda, lambda.idx, classes, file=fit.file)
} else { load(fit.file)}
with(trainData, table(fold, celltype))
str(glmFit$fit.preval)
# GET CV PERFORMANCE ------------------------------------------------------
clx <- classes[1]
cvRoc <- data.table()
for(clx in classes){
clx.i <- which(classes == clx)
labels <- (trainData$celltype == clx) + 0
predX <- prediction(predictions=glmFit$fit.preval[,clx.i,lambda.idx], labels=labels)
auc <- performance(prediction.obj=predX, measure="auc")@y.values[[1]]
perf <- performance(prediction.obj=predX, measure="tpr", x.measure="fpr")
cvRoc <- rbind(cvRoc, data.table(celltype=clx, [email protected][[1]], [email protected][[1]], auc=auc, random=NA))
for(rand.i in 1:50){
predX <- prediction(predictions=glmFit$fit.preval[,clx.i,lambda.idx], labels=sample(labels))
auc <- performance(prediction.obj=predX, measure="auc")@y.values[[1]]
perf <- performance(prediction.obj=predX, measure="tpr", x.measure="fpr")
cvRoc <- rbind(cvRoc, data.table(celltype=clx, [email protected][[1]], [email protected][[1]], auc=auc, random=rand.i))
}
}
save(cvRoc, file=dirout(outOrg, "cvRoc.RData"))
# CV
cvRoc[,realData := is.na(random)]
p <- ggplot(cvRoc, aes(x=fpr, y=tpr)) +
theme_bw(16) +
facet_grid(celltype ~ .) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(outOrg, "ROC_CV.pdf"), width=4, height=length(classes) * 2 + 1,plot=p + geom_path(data=cvRoc[realData == TRUE], alpha=1))
ggsave(dirout(outOrg, "ROC_CV_rand.jpg"), width=4, height=length(classes) * 2 + 1, plot=p+geom_path(data=cvRoc[realData == FALSE], alpha=0.3, color="grey", aes(group=random)))
write.tsv(unique(cvRoc[realData==TRUE, c("celltype", "auc")]), file=dirout(outOrg, "AUC.tsv"))
# COEFFICIENTS
cfs <- sapply(classes, function(clx) coef(glmFit$glmnet.fit)[[clx]][,lambda.idx])
cfs <- cfs[apply(cfs, 1, sum) > 0.1,]
pdf(dirout(outOrg, "Coefficients.pdf"), width=length(classes) + 1, height=nrow(cfs) * 0.2 + 1, onefile=F); pheatmap(cfs); dev.off()
# PREDICT
pred.file <- dirout(outOrg, "Prediction.tsv")
if(!file.exists(pred.file)){
predData <- meta[!rn %in% trainData$rn]
dat <- t(as.matrix(data[-which(rownames(data) %in% predGeneExclude),predData$rn]))
pred <- predict(glmFit, dat, type = "response")
predData <- cbind(predData,data.table(pred[predData$rn,,1]))
write.tsv(predData, pred.file)
} else {
predData <- fread(pred.file)
}
# PREDICT
pred.all.file <- dirout(outOrg, "Prediction_allCells.tsv")
if(!file.exists(pred.all.file)){
predDataAll <- copy(meta)
dat <- t(as.matrix(data[-which(rownames(data) %in% predGeneExclude),predDataAll$rn]))
pred <- predict(glmFit, dat, type = "response")
predDataAll <- cbind(predDataAll,data.table(pred[predDataAll$rn,,1]))
write.tsv(predDataAll, pred.all.file)
} else {
predDataAll <- fread(pred.all.file)
}
accData <- predData[treatment == "DMSO" & celltype %in% classes]
accData$predCell <- apply(as.matrix(accData[,classes, with=F]),1,function(row) classes[which(row == max(row))])
write.tsv(sum(accData$celltype == accData$predCell)/nrow(accData), dirout(outOrg, "Accuracy_test.tsv"))
meanDat <- melt(predData, id.vars=c("treatment", "replicate", "celltype"), measure.vars=classes)[,.(value = mean(value)), by=c("treatment", "replicate", "celltype","variable")]
ggplot(meanDat, aes(x=treatment, y=variable, fill=value)) + geom_tile() + facet_grid(replicate ~ celltype) + xRot() +
scale_fill_gradient(low="white", high="red")
ggsave(dirout(outOrg, "Predictions.pdf"), width=20, height=3*replicates)
clx <- classes[1]
for(clx in c("Alpha", "Beta")){
ggplot(predData[celltype %in% c("Beta", "Alpha")], aes_string(x=clx, color="treatment", linetype="treatment")) +
facet_grid(celltype ~ replicate, scales="free") + stat_ecdf() + theme_bw(12)
ggsave(dirout(outOrg, "Predict_", clx, ".pdf"), width=8, height=4*replicates)
}
}
#ggplot(predData[treatment == "A10"], aes(x=Alpha, y=Beta)) + geom_point(alpha=0.3) + facet_grid(replicate ~ celltype) + theme_bw(12)
<file_sep>/src/README.md
# Analysis scripts
Note that scripts are ordered based on the analysis workflow.
## Alignment based on 10x CellRanger
### 10x Alignments
02_Cellranger.sh
### Script to generate genome with RFP protein
02_make_custom_10x_ref.sh
### Aggregate samples into one
03_CellrangerAggregate.sh
## Statistical analysis in R
### Sets up R environment (called by each script)
00-init.R
### External datasets required prior to analysis
1. GEO datasets
EXT_01_GetGEO.sh
EXT_02_GEOAnalysis.R
2. Human Cell Atlas
EXT_03_HCA.R
3. Organ mixture experiments from 10x Genomics
EXT_04_OrganismMixtureExperiments.sh
### Get 10x sequencing statistics
04_SequencingStats.R
### Process reference spike in cells
05_PrepSpikeIns_Clean.R
### Processes in-sample spike-ins
06_SpikeIns_Islets.R
### Clean up data
07_03_CleanHuman_CleanSpikeIns.R
07_04_CleanHuman3_CleanSpikeIns.R
07_11_CleanMouse_CleanSpikeIns.R
### Seurat analyses
10_H_01_Seurat.R
10_H3_01_Seurat.R
10_M_01_Seurat.R
10_SCRIPT_01_Seurat.R
### Cell type assignment based on marker genes
11_H3_AssignCelltypes.R
11_H_AssignCelltypes.R
11_M_AssignCelltypes.R
### Script to identify differential genes (called later)
12_DiffGenes_SCRIPT.R
### Machine-learning-based annotation of cell types
14_02_Classifier_moreCelltypes_NoEndocrine.R
### Some simple analyses on the cells
15_Counts.R
### Identification of differential genes (based on script 12)
16_02_H3_DiffGenes_NoInsulin_FindMore.R
16_02_H_DiffGenes_NoInsulin_FindMore.R
16_02_M_DiffGenes_NoInsulin_FindMore.R
### Summarizing of differential genes
17_02_06_GenePlots_ByGroup_q0.1_noGABAII.R
### Identification of alpha and beta cell signatures
20_01_AlphaCellSignature2.R
20_02_AlphaCellSignature.R
### Calculation of correlation to alpha and beta cell signatures
21_01_CellCorrelation.R
### Additional clustering experiments
30_01_ClusteringExperiments.R
### Analysis of drop-seq dataset
DropSeq
### Export gene averages across cells
EXPORT_01_Averages.R
### Figures related to contamination
FIG_01_Contamination.R
### Demonstration that data look better after correction
FIG_01_Correlate_Replicates.R
### Analyses of single-cell dataset (clustering, celltypes,...)
FIG_02_SingleCellAnalyses.R
### Differential expression
FIG_03_DiffExpr.R
### Additional, detailed analyses of spike-in cells, contamination
FIG_04_SpikeInDetails.R
## R Functions
FUNC_Enrichr.R
FUNC_Seurat2_fast_simple.R
FUNC_Seurat_subcluster.R
FUNCTIONS_HELPERS.R
FUNCTIONS.R
FUNCTIONS_Synonyms_etc.R<file_sep>/src/EXT_01_GetGEO.sh
cd $PROCESSED/artemether/analysis/
mkdir EXT_01_GEO
cd EXT_01_GEO
geo=GSE73727
geo=GSE81547
geo=GSE84133
array=("GSE73727" "GSE81547" "GSE84133" "GSE85241" "GSE83139" "GSE81608")
array=("GSE85241")
for geo in ${array[@]}
do
geo_short=${geo:0:5}
echo $geo
echo $geo_short
files=$(curl -l ftp://ftp.ncbi.nlm.nih.gov/geo/series/${geo_short}nnn/$geo/suppl/)
for ff in ${files[@]}
do
echo $ff
curl -O ftp://ftp.ncbi.nlm.nih.gov/geo/series/${geo_short}nnn/$geo/suppl/$ff
done
files=$(curl -l ftp://ftp.ncbi.nlm.nih.gov/geo/series/${geo_short}nnn/$geo/matrix/)
for ff in ${files[@]}
do
echo $ff
curl -O curl -O ftp://ftp.ncbi.nlm.nih.gov/geo/series/${geo_short}nnn/$geo/matrix/$ff
done
mkdir $geo
files=$(ls ${geo}*tar)
for ff in ${files[@]}
do
echo $ff
tar -xvf $ff -C $geo/
done
done
curl -O https://www.ebi.ac.uk/arrayexpress/files/E-MTAB-5061/E-MTAB-5061.processed.1.zip
curl -O https://www.ebi.ac.uk/arrayexpress/files/E-MTAB-5061/E-MTAB-5061.sdrf.txt
unzip E-MTAB-5061.processed.1.zip
mv pancreas_refseq_rpkms_counts_3514sc.txt E-MTAB-5061.pancreas_refseq_rpkms_counts_3514sc.txt<file_sep>/src/FIG_05_Human_3.R
require("project.init")
project.init2("artemether")
out <- "FIG_05_Human_3/"
dir.create(dirout(out))
# meta.filtered <- loadH3Meta2.filtered()
meta <- loadH3Meta2()
sobj <- loadH3Data2()
# Cell Numbers H3 ---------------------------------------------------------
write.tsv(data.table(meta[,.N, by=c("replicate", "treatment")], organism = "human"),dirout(out, "Supp_CellNumbers.tsv"))
# GET AVERAGES -----------------------------------------
for(typex in c("")){
avg.file <- dirout(out, "Avgerages",typex,".csv")
if(!file.exists(avg.file)){
# metaX <- if(typex == "") meta else meta.filtered
metaX <- meta
metaX <- metaX[celltype2 %in% c("Beta", "Alpha")]
avg <- sapply(split(metaX$rn, factor(with(metaX, paste(celltype2, treatment, replicate)))), function(rns){
log(Matrix::rowMeans(toTPM(sobj@data[,rns])) + 1)
})
# write files
write.csv(avg, avg.file)
if(typex == "") save(avg, file=dirout(out, "Averages", typex, ".RData"))
}
}
(load(dirout(out, "Averages.RData")))
# CORRELATE AVERAGES ------------------------------------------------------
ctx <- "Alpha"
for(ctx in c("Alpha", "Beta")){
idx <- grepl(ctx, colnames(avg))
cMT <- corS(avg[,idx])
dMT <- as.dist(1-cMT)
diag(cMT) <- NA
stopifnot(all(colnames(cMT) == colnames(avg[,idx])))
stopifnot(all(attr(dMT, "Labels") == colnames(avg[,idx])))
stopifnot(all(colnames(cMT) == row.names(cMT)))
cleanDev(); pdf(dirout(out, "Clustering_Replicates_",ctx,".pdf"), w=5,h=5)
pheatmap(cMT, clustering_distance_rows=dMT, clustering_distance_cols=dMT)
dev.off()
}
# ALPHA + cells -----------------------------------------------------------
res <- data.table()
metaO <- copy(meta)
metaO[, time := gsub(".+_", "", metaO$replicate)]
metaO[, replicate := gsub("_\\d+", "", replicate)]
for(timex in unique(metaO$time)){
metaO[INS > 0, insulin := "INS+"]
metaO[!INS > 0, insulin := "INS-"]
for(treatx in c("A10")){
# for(repx in unique(metaO$replicate)){
# if(!timex %in% unique(metaO[treatment == treatx & replicate == repx]$time)) next
# m <- with(metaO[treatment %in% c("DMSO", treatx)][replicate == repx][celltype == "Alpha"][time == timex], table(insulin, treatment))
# m <- m[c("INS+", "INS-"),c(treatx, "DMSO")]
# f <- fisher.test(m)
# res <- rbind(res, data.table(time=timex, treatment = treatx, replicate=repx, pvalue=f$p.value, oddsRatio=f$estimate, insulin="INS"))
# }
m <- with(metaO[treatment %in% c("DMSO", treatx)][celltype == "Alpha"][time == timex], table(insulin, treatment))
m <- m[c("INS+", "INS-"),c(treatx, "DMSO")]
f <- fisher.test(m)
res <- rbind(res, data.table(time=timex, treatment = treatx, replicate="All", pvalue=f$p.value, oddsRatio=f$estimate, insulin="INS"))
}
}
res
write.tsv(res, dirout(out, "INS_Pos_FisherTest_Human3.tsv"))
<file_sep>/src/FUNCTIONS.R
toTPM_fromRaw <- function(m, scale.factor){t(t(m)/Matrix::colSums(m)) * scale.factor}
toTPM <- function(m){m@x <- exp(m@x) - 1; return(m)}
toLogTPM <- function(m){m@x <- log(m@x + 1); return(m)}
corS <- function(...){cor(..., method="spearman")}
add.genes.sparseMatrix <- function(m, genes){
gX <- genes[which(!genes %in% row.names(m))]
m2 <- matrix(0, nrow=length(gX), ncol=ncol(m))
m2 <- as(m2, "dgTMatrix")
row.names(m2) <- gX
rbind(m, m2)
}
toSparseMT <- function(mt){
ret <- as(mt, "dgTMatrix")
row.names(ret) <- row.names(mt)
colnames(ret) <- colnames(mt)
ret
}
ggS <- function(..., w=4, h=4){ggsave(..., width=4, height=4)}
assignGenesMeta <- function(genes, metaX, seuratObj, strict=T){
for(gg in genes){
if(!gg %in% row.names(seuratObj@data)){
if(strict){
stop(gg, " not found in sc data")
}
}
metaX[[gg]] <- seuratObj@data[gg,metaX$rn]
}
metaX
}<file_sep>/src/FUNC_Seurat_subcluster.R
require(methods)
require(Seurat)
require(dplyr)
require(Matrix)
require(pheatmap)
require(data.table)
require(ggplot2)
# REQUIRES
# sample.x - sample name
# data.path - path for input data
# outS - output folder (with dirout)
stopifnot(!is.null(outS))
# OPTIONAL:
#if(!exists("seurat.min.genes")) seurat.min.genes <- 200
#if(!exists("seurat.mito.cutoff")) seurat.mito.cutoff <- 0.15
#if(!exists("seurat.max.genes")) seurat.max.genes <- 5000
# if(!exists("seurat.min.UMIs")) seurat.min.UMIs <- 500
if(!exists("cluster.precision")) cluster.precision <- c(seq(0.5,2.0,0.5))
sessionInfo()
# DEFINE OUTPUT DIRECTORY ------------------------------------------------------------------
dir.create(dirout(outS))
message(" -- saved in -- ", outS)
# ANALYSIS ----------------------------------------------------
# IF RData file exists (preprocessing) just load it
if(!file.exists(dirout(outS, "data.RData"))){
# stopifnot(!is.null(seurat.mito.cutoff))
# stopifnot(!is.null(seurat.max.genes))
stopifnot(!is.null(cellsToKeep))
stopifnot(all(cellsToKeep %in% [email protected]))
stopifnot(!is.null(pbmc))
pbmcOrig <- pbmc
# # Apply UMI threshold --> NOT DONE DOESNT WORK, should be done before in full dataset
# cell.umis <- Matrix::colSums(pbmc.data)
# if(!is.null(seurat.min.UMIs)){
# pbmc.data <- pbmc.data[,cell.umis >= seurat.min.UMIs]
# }
# cell.genes <- Matrix::colSums(pbmc.data != 0)
# if(!is.null(seurat.min.genes)){
# pbmc.data <- pbmc.data[,cell.genes >= seurat.min.genes]
# }
pbmc <- SubsetData(pbmcOrig, cells.use = cellsToKeep)
# Plot in original tsne ---------------------------------------------------
tryCatch({
pDat <- data.table(pbmcOrig@[email protected],keep.rownames=T)
pDat$selected <- "no"
pDat[rn %in% cellsToKeep, selected := "yes"]
ggplot(pDat, aes(x=tSNE_1, y=tSNE_2, color=selected)) + geom_point(alpha=0.3)
ggsave(dirout(outS, "SelectedCells.jpg"),height=7, width=7)
}, error= function(e) message(e))
# Mitochondrial genes
mito.genes <- grep(pattern = "^MT-", x = rownames(x = pbmc@data), value = TRUE, ignore.case=TRUE)
percent.mito <- Matrix::colSums(<EMAIL>[mito.genes, ])/Matrix::colSums(pbmc@raw.<EMAIL>)
pbmc <- AddMetaData(object = pbmc, metadata = percent.mito, col.name = "percent.mito")
ggplot(<EMAIL>, aes(y=percent.mito, x=nUMI)) + geom_point(alpha=0.3) +
#geom_hline(yintercept=seurat.mito.cutoff) +
ggtitle(paste(nrow(<EMAIL>), "cells"))
ggsave(dirout(outS, "QC_MitoPlot.pdf"))
# Number of genes (many genes probably duplets) ---------------------------
ggplot(<EMAIL>, aes(x=nUMI, y=nGene)) + geom_point(alpha=0.3) +
#geom_hline(yintercept=seurat.max.genes) +
ggtitle(paste(nrow(<EMAIL>), "cells"))
ggsave(dirout(outS, "QC_GenePlot.pdf"))
# Filter genes
VlnPlot(object = pbmc, features.plot = c("nGene", "nUMI", "percent.mito"), nCol = 3)
ggsave(dirout(outS, "QC_Summary.pdf"), height=7, width=7)
#pbmc <- FilterCells(object = pbmc, subset.names = c("nGene", "percent.mito"),low.thresholds = c(-Inf, -Inf), high.thresholds = c(Inf, Inf))
VlnPlot(object = pbmc, features.plot = c("nGene", "nUMI", "percent.mito"), nCol = 3)
ggsave(dirout(outS, "QC_Summary2.pdf"), height=7, width=7)
# Normalize and Scale
pbmc <- NormalizeData(object = pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
pbmc <- ScaleData(object = pbmc, vars.to.regress = c("nUMI", "percent.mito"))
# Variable genes
pbmc <- FindVariableGenes(object = pbmc, mean.function = ExpMean, dispersion.function = LogVMR, x.low.cutoff = 0.0125, x.high.cutoff = 3, y.cutoff = 0.5)
#ggsave(dirout(outS, "QC_VariableGenes.pdf"))
# Dimensionality reduction
pbmc <- RunPCA(pbmc, pc.genes = <EMAIL>, do.print = TRUE, pcs.print = 5, genes.print = 5)
pdf(dirout(outS, "QC_PCs.pdf"), height=20, width=20); PCHeatmap(object = pbmc, pc.use = 1:20, cells.use = 500, do.balanced = TRUE, label.columns = FALSE, use.full = FALSE); dev.off()
ggplot(data.table(StandDev=pbmc@dr$pca@sdev, PC=1:20), aes(x=PC, y=StandDev)) + geom_point(); ggsave(dirout(outS, "QC_PC_SD.pdf"), height=7, width=7)
pbmc <- RunTSNE(pbmc, dims.use = 1:10, do.fast = T)
# Clustering
for(x in cluster.precision){
pbmc <- FindClusters(pbmc, reduction.type="pca", dims.use = 1:10, resolution = x, print.output = 0, save.SNN = T)
pbmc <- StashIdent(pbmc, save.name = paste0("ClusterNames_", x))
}
# WRITE META DATA AND TSNE ------------------------------------------------
write.table(
merge(data.table(<EMAIL>@<EMAIL>, keep.rownames=T), data.table(pbmc@[email protected], keep.rownames=T), by="rn"),
file=dirout(outS, "MetaData_tSNE.tsv"), sep="\t", quote=F, row.names=F)
save(pbmc, file=dirout(outS,"data.RData"))
} else {
message("Loading processed data")
# LOAD DATA AND UPDATE IF REQUIRED
load(dirout(outS, "data.RData"))
update <- FALSE
if(!.hasSlot(pbmc, "version")){
pbmc <- UpdateSeuratObject(pbmc)
message("Updating Object Seurat Version")
update <- TRUE
}
# Additional clustering if needed
# for(x in cluster.precision){
# if(is.null([email protected][[paste0("ClusterNames_", x)]])){
# update <- TRUE
# message("Adding clustering")
# pbmc <- FindClusters(pbmc, pc.use = 1:10, resolution = x, print.output = 0, save.SNN = T)
# pbmc <- StashIdent(pbmc, save.name = paste0("ClusterNames_", x))
# }
# }
# SAVE NEW DATASET IF NEEDED
if(update){
save(pbmc, file=dirout(outS,"data.RData"))
}
}
<file_sep>/src/00-init.R
require(data.table)
require(pheatmap)
require(Seurat)
require(Matrix)
require(methods)
ENRICHR.DBS <- c("NCI-Nature_2016", "WikiPathways_2016", "Human_Gene_Atlas", "Chromosome_Location", "ENCODE_and_ChEA_Consensus_TFs_from_ChIP-X", "TRANSFAC_and_JASPAR_PWMs")
SCALE.FACTOR <- 1e6
MIN.GENES <- 200
MIN.UMIS <- 500
source("src/FUNCTIONS_HELPERS.R")
source("src/FUNCTIONS.R")
options(stringsAsFactors=F)
annMeta <- function(meta){
meta[,replicate := gsub(".Islets_(.+)_(.+)", "\\1", sample)]
meta[,treatment := gsub(".Islets_(.+)_(.+)", "\\2", sample)]
meta
}
# human
loadHMeta <- function(){annMeta(fread(dirout("10_H_01_Seurat/", "/MetaData_AnnotatedCells.tsv")))}
loadHData <- function(){load(dirout("10_H_01_Seurat/SeuratObject.RData")); return(pbmc)}
# human 3
loadH3Meta <- function(){
meta <- fread(dirout("10_H3_01_Seurat/", "/MetaData_AnnotatedCells.tsv"))
meta[,replicate := gsub("hIslets_III_(.+)_(.+)_(\\d)", "III\\3_\\2", sample)]
meta[,treatment := gsub("hIslets_III_(.+)_(.+)_(\\d)", "\\1", sample)]
return(meta)
}
loadH3Data <- function(){load(dirout("10_H3_01_Seurat/SeuratObject.RData")); return(pbmc)}
# Mouse
loadMMeta <- function(){annMeta(fread(dirout("10_M_01_Seurat/", "/MetaData_AnnotatedCells.tsv")))}
loadMData <- function(){load(dirout("10_M_01_Seurat/SeuratObject.RData")); return(pbmc)}
# Reassigned
loadHMeta2 <- function(){fread(dirout("15_Counts/", "/Reassigned_Human.tsv"))}
loadMMeta2 <- function(){fread(dirout("15_Counts/", "/Reassigned_Mouse.tsv"))}
loadH3Meta2 <- function(){fread(dirout("15_Counts/", "/Reassigned_Human3.tsv"))}
# loadH3Meta2.filtered <- function(){fread(dirout("18_01_Filtered_H3/", "Meta_Filtered.tsv"))}
# Reassigned unfiltered
loadHMetaUnfiltered <- function(){fread(dirout("15_Counts/", "/Reassigned_Human_unfiltered.tsv"))}
loadMMetaUnfiltered <- function(){fread(dirout("15_Counts/", "/Reassigned_Mouse_unfiltered.tsv"))}
loadH3MetaUnfiltered <- function(){fread(dirout("15_Counts/", "/Reassigned_Human3_unfiltered.tsv"))}
# Filtered Data
loadHData2 <- function(){load(dirout("15_Counts/SeuratObject_human.RData")); return(pbmc)}
loadH3Data2 <- function(){load(dirout("15_Counts/SeuratObject_human3.RData")); return(pbmc)}
loadMData2 <- function(){load(dirout("15_Counts/SeuratObject_mouse.RData")); return(pbmc)}
# Colors for plots --------------------------------------------------------
COLORS.TREATMENTS <- c("#33a02c", "#a6cee3", "#1f78b4", "#ff7f00", "#000080", "#000000")
names(COLORS.TREATMENTS) <- c("GABA", "A1", "A10", "FoxO", "Aold", "DMSO")
<file_sep>/src/12_DiffGenes_SCRIPT.R
# Diff vs DMSO ------------------------------------------------------------
if(!exists("outTreat")) stop("MISSING outTreat")
if(!exists("pbmc")) stop("MISSING pbmc")
if(!exists("meta")) stop("MISSING meta")
if(!exists("nrCores")) nrCores <- 5
if(!exists("seurat.thresh.use")) seurat.thresh.use <- 0.25
if(!exists("seurat.genes.use")) seurat.genes.use <- row.names(pbmc@data)
dir.create(dirout(outTreat))
treat <- "FoxO"
cl <- "Beta"
repl <- "I"
meta <- meta[match(row.names(<EMAIL>), meta$rn)]
stopifnot(all(meta$rn == row.names([email protected])))
require(doMC); registerDoMC(cores=nrCores)
for(repl in unique(meta$replicate)){
meta.rpl <- meta[replicate == repl]
for(treat in unique(meta.rpl[treatment != "DMSO"]$treatment)){
ctxx <- unique(meta.rpl[treatment == treat][!is.na(celltype)]$celltype)
foreach(cl = ctxx) %dopar% {
message(paste(repl, treat, cl, sep="_"))
(ff <- dirout(outTreat, repl, "_", treat, "_", cl, ".tsv"))
print(ff)
if(!file.exists(ff)){
print('starting analysis')
bar.treat <- meta[replicate == repl & treatment == treat & celltype == cl]$rn
bar.dmso <- meta[replicate == repl & treatment == "DMSO" & celltype == cl]$rn
if(length(bar.treat) > 10 & length(bar.dmso) > 10){
cluster.markers <- FindMarkers(pbmc,
thresh.use=seurat.thresh.use,
genes.use=seurat.genes.use,
test.use="negbinom",
ident.1 = bar.treat,
ident.2 = bar.dmso)
write.table(cluster.markers, ff, sep="\t", quote=F, row.names=TRUE)
}
}
}
}
}
source("src/FUNC_Enrichr.R")
# AGGREGATE
ff <- list.files(dirout(outTreat), pattern="I_.+_.+\\.tsv$")
res <- data.table(); for(f in ff){print(f);res <- rbind(res, data.table(fread(dirout(outTreat, f)), file=f), fill=T)}
res[, file := gsub("SI_", "SI.", file)]
res[, file := gsub("Acinar_like", "Acinar.like", file)]
res[, file := gsub("\\.tsv$", "", file)]
res <- cbind(res, data.table(do.call(rbind, strsplit(res$file, "_"))))
colnames(res) <- make.unique(colnames(res))
res$qval <- p.adjust(res$V2, method="BH")
res[, direction := ifelse(V3 > 0, "up", "down")]
save(res, file=dirout(outTreat, "AllRes.RData"))
# INDIVIDUAL LISTS
# res0 <- res[qval < 0.05 & abs(V3) > log(3)]
# ggplot(res0, aes(x=V3.1, fill=direction)) + geom_bar(position="dodge") + facet_grid(V1.1 ~ V2.1) + theme(axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5)); ggsave(dirout(outTreat, "0_Numbers.pdf"), width=20, height=10)
# write.tsv(res0, dirout(outTreat, "0_IndividualHits.tsv"))
# # analyze individual lists
# ll <- with(res0, split(V1, factor(paste0(file, "_", direction))))
# # enr <- enrichGeneList.oddsRatio.list(ll, enrichrDBs=ENRICHR.DBS)
# # enrichr.plot.many(enrichRes=enr, out=dirout(outTreat), label="0_Enrichr_vsDMSO")
# pdf(dirout(outTreat, "0_Jaccard.pdf"), height=29, width=29,onefile=F)
# pheatmap(jaccard(ll),cluster_rows=T, cluster_cols=T,color=colorRampPalette(c("grey", "blue"))(50))
# dev.off()
#
# # AGGREGATED LISTS ACROSS REPLICATES
# res.agg <- res0[, .(count = .N, logFC = mean(V3)), by=c("V1", "V2.1", "V3.1", "direction")][count == length(unique(res0$V1.1))]
# ggplot(res.agg, aes(x=V3.1, fill=direction)) + geom_bar(position="dodge") + facet_grid(. ~ V2.1) + theme(axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5)); ggsave(dirout(outTreat, "2_Agg_Numbers.pdf"), width=20, height=5)
# write.tsv(res.agg, dirout(outTreat, "2_Agg_Genes.tsv"))
# res.agg <- res.agg[!grepl("SI\\.", V3.1)]
# ll2 <- with(res.agg, split(V1, factor(paste(V2.1, V3.1, direction, sep="_"))))
# pdf(dirout(outTreat, "2_Agg_Jaccard.pdf"), height=6, width=6,onefile=F)
# pheatmap(jaccard(ll2),cluster_rows=T, cluster_cols=T,color=colorRampPalette(c("grey", "blue"))(50))
# dev.off()
# enr <- enrichGeneList.oddsRatio.list(ll2, enrichrDBs=ENRICHR.DBS)
# enrichr.plot.many(enrichRes=enr, out=dirout(outTreat), label="2_Enrichr_vsDMSO")
# res.agg[,x := paste0(V2.1, V3.1)]
# res.agg <- hierarch.ordering(res.agg, toOrder="V1", orderBy="x", value.var="logFC")
# ggplot(res.agg[!grepl("SI\\.", V3.1)], aes(x=V3.1, y=V1, color=logFC)) + geom_point() + facet_grid(. ~ V2.1) + theme_bw(12) +
# scale_color_gradient2(low="blue", high="red") + xRot()
# ggsave(dirout(outTreat, "2_Agg_Genes.pdf"), height=20, width=7)
#
#
#
#
# # AGGREGATE WITH LESS STRICTNESS ------------------------------------------
# res.agg <- res[qval < 0.05, .(count = .N, logFC = mean(V3)), by=c("V1", "V2.1", "V3.1", "direction")][count == length(unique(res0$V1.1))]
# ggplot(res.agg, aes(x=V3.1, fill=direction)) + geom_bar(position="dodge") + facet_grid(. ~ V2.1) + theme(axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5)); ggsave(dirout(outTreat, "3_Agg_Numbers.pdf"), width=20, height=5)
# write.tsv(res.agg, dirout(outTreat, "3_Agg_Genes.tsv"))
# res.agg <- res.agg[!grepl("SI\\.", V3.1)]
# ll2 <- with(res.agg, split(V1, factor(paste(V2.1, V3.1, direction, sep="_"))))
# pdf(dirout(outTreat, "3_Agg_Jaccard.pdf"), height=15, width=15,onefile=F)
# pheatmap(jaccard(ll2),cluster_rows=T, cluster_cols=T,color=colorRampPalette(c("grey", "blue"))(50))
# dev.off()
# enr <- enrichGeneList.oddsRatio.list(ll2, enrichrDBs=ENRICHR.DBS)
# enrichr.plot.many(enrichRes=enr, out=dirout(outTreat), label="3_Agg_Enrichr_vsDMSO")
#
# res.agg[,grp := paste(V2.1, V3.1, direction, sep="_")]
# x <- toMT(dt=res.agg,row="V1", col="grp",val="logFC")
# x[is.na(x)] <- 0
# pdf(dirout(outTreat, "3_Agg_Overlaps.pdf"), height=25, width=5, onefile=F)
# pheatmap(x[rowSums(x != 0) > 1,], fontsize_row=3, fontsize_col=5, color=colorRampPalette(c("blue", "white","red"))(50))
# dev.off()
<file_sep>/src/04_SequencingStats.R
require(data.table)
require(project.init)
project.init2("artemether")
out <- "04_SequencingStats/"
dir.create(dirout(out))
datasets <- c(".")
for(dataset.x in datasets){
ds <- list.dirs(path=paste0(Sys.getenv("PROCESSED"), "artemether/results_pipeline/cellranger_count/"), recursive=F)
ds <- ds[grepl(dataset.x, ds)]
ff <- list.files(paste0(ds, "/outs/"), pattern="^metrics_summary.csv$", recursive=F, full.names=T)
st <- lapply(ff, fread)
names(st) <- basename(gsub("\\/outs.+", "", ff))
cc <- data.table()
for(i in names(st)){
cc <- rbind(cc, data.table(st[[i]], dataset=i), fill=T)
}
write.tsv(cc, dirout(out, "SequencingStats_", dataset.x, ".tsv"))
}
<file_sep>/src/15_04_Assign_RmDoublets.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
project.init2("artemether")
out <- "15_Counts/"
dir.create(dirout(out))
celltypes.of.interest <- c("Alpha", "Beta", "Gamma", "Delta", "Endocrine")
# ORIGINAL COUNTS ---------------------------------------------------------
metaH <- loadHMeta()
metaM <- loadMMeta()
metaH3 <- loadH3Meta()
ggplot(metaH, aes(x=celltype, fill=treatment)) + geom_bar(position="dodge") + facet_grid(replicate ~ .)
ggsave(dirout(out, "Raw_Human.pdf"), height=8,width=15)
ggplot(metaH3, aes(x=celltype, fill=treatment)) + geom_bar(position="dodge") + facet_grid(replicate ~ .)
ggsave(dirout(out, "Raw_Human3.pdf"), height=8,width=15)
ggplot(metaM, aes(x=celltype, fill=treatment)) + geom_bar(position="dodge") + facet_grid(replicate ~ .)
ggsave(dirout(out, "Raw_Mouse.pdf"), height=8,width=15)
# PREDICTED GROUPS --------------------------------------------------------
inDir <- "14_03_Classifier_moreCelltypes_noEndocrine/"
list.files(dirout(inDir))
# HUMAN
predMetaH <- fread(dirout(inDir, "human/Prediction_allCells.tsv"), header=T)
cts <- unique(intersect(colnames(predMetaH), metaH$celltype))
predMetaH$PredictedCell <- apply(as.matrix(predMetaH[,cts, with=F]),1,function(row) names(row)[which(row == max(row))])
predMetaH$PredictionMax <- apply(as.matrix(predMetaH[,cts, with=F]),1, max)
predMetaH$PredictionConf <- apply(as.matrix(predMetaH[,cts, with=F]),1,function(row) max(row)/sort(row, decreasing=T)[2])
metaH <- merge(metaH, predMetaH[,c("rn", "PredictedCell", "PredictionConf", "PredictionMax")], by="rn", all.x=T)
stopifnot(nrow(metaH[is.na(PredictionMax)]) == 0)
# metaH[,celltype2 := celltype]
# metaH[celltype == "Endocrine", celltype2 := PredictedCell]
# HUMAN 3
predMetaH3 <- fread(dirout(inDir, "human3/Prediction_allCells.tsv"), header=T)
cts <- unique(intersect(colnames(predMetaH3), metaH3$celltype))
predMetaH3$PredictedCell <- apply(as.matrix(predMetaH3[,cts, with=F]),1,function(row) names(row)[which(row == max(row))])
predMetaH3$PredictionMax <- apply(as.matrix(predMetaH3[,cts, with=F]),1, max)
predMetaH3$PredictionConf <- apply(as.matrix(predMetaH3[,cts, with=F]),1,function(row) max(row)/sort(row, decreasing=T)[2])
metaH3 <- merge(metaH3, predMetaH3[,c("rn", "PredictedCell", "PredictionConf", "PredictionMax")], by="rn", all.x=T)
stopifnot(nrow(metaH3[is.na(PredictionMax)]) == 0)
# metaH3[,celltype2 := celltype]
# metaH3[celltype == "Endocrine", celltype2 := PredictedCell]
# MOUSE
predMetaM <- fread(dirout(inDir, "mouse/Prediction_allCells.tsv"), header=T)
cts <- unique(intersect(colnames(predMetaM), metaH3$celltype))
predMetaM$PredictedCell <- apply(as.matrix(predMetaM[,cts, with=F]),1,function(row) names(row)[which(row == max(row))])
predMetaM$PredictionMax <- apply(as.matrix(predMetaM[,cts, with=F]),1, max)
predMetaM$PredictionConf <- apply(as.matrix(predMetaM[,cts, with=F]),1,function(row) max(row)/sort(row, decreasing=T)[2])
metaM <- merge(metaM, predMetaM[,c("rn", "PredictedCell", "PredictionConf", "PredictionMax")], by="rn", all.x=T)
stopifnot(nrow(metaM[is.na(PredictionMax)]) == 0)
# metaM[,celltype2 := celltype]
# metaM[celltype == "Endocrine", celltype2 := PredictedCell]
# Identify cutoff for doublets --------------------------------------------
metas <- list(human=metaH, mouse=metaM, human3=metaH3)
metas$human <- metas$human[!grepl("II_GABA", sample)]
for(mnam in names(metas)){
metas[[mnam]][,celltype2 := celltype]
metas[[mnam]][celltype == "Endocrine", celltype2 := PredictedCell]
for(sx in unique(metas[[mnam]]$sample)){
for(ctx in unique(metas[[mnam]][sample == sx]$celltype2)){
x <- metas[[mnam]][sample == sx][celltype2 == ctx]$nGene
nGene.peak.x <- if(length(x) > 10){
d <- density(x)
d$x[which(d$y == max(d$y))]
} else {
mean(x)
}
metas[[mnam]][sample == sx & celltype2 == ctx, nGene.peak := nGene.peak.x]
}
}
metas[[mnam]][, nGene.doublet := "Keep"]
metas[[mnam]][(nGene > (nGene.peak + (nGene.peak))), nGene.doublet := "nGene.too.high"]
metas[[mnam]][(nGene < (nGene.peak - (nGene.peak / 2))), nGene.doublet := "nGene.too.low"]
}
for(mnam in names(metas)){
ggplot(metas[[mnam]][celltype2 %in% celltypes.of.interest], aes(x=nGene, fill=nGene.doublet)) +
geom_histogram() + facet_grid(treatment + replicate ~ celltype2)
ggsave(dirout(out, "Doublets_nGene_Cutoff_",mnam,".pdf"), w=25,h=25)
ggplot(metas[[mnam]][celltype != "Endocrine"], aes(x=PredictionConf, color=nGene.doublet)) +
geom_density() + facet_grid(replicate ~ treatment) + scale_x_log10()
ggsave(dirout(out, "Doublets_PredictionConf_",mnam,".pdf"), w=15,h=15)
}
for(mnam in names(metas)){
ggplot(metas[[mnam]][celltype2 %in% celltypes.of.interest], aes(x=treatment, fill=nGene.doublet)) + geom_bar() + facet_grid(celltype2 ~ replicate, scales="free_y")
ggsave(dirout(out, "Doublets_nGene_Numbers_",mnam,".pdf"), w=15,h=15)
metas[[mnam]][is.na(PredictionConf), PredictionConf := 10]
ggplot(metas[[mnam]][celltype2 %in% celltypes.of.interest], aes(x=(PredictionConf > 3), fill=nGene.doublet)) + geom_bar(position="stack") +
facet_grid(celltype2 ~ replicate + treatment, scales="free_y") + xRot()
ggsave(dirout(out, "Doublets_nGene_PredictionConf_Numbers_",mnam,".pdf"), w=15,h=15)
}
# # PLOT ALPHA PROBABILITY --------------------------------------------------
# ggplot(predMetaM, aes(x=Alpha, color=treatment)) + stat_ecdf() + facet_grid(replicate ~ .)
# ggsave(dirout(out, "Alpha_cell_Probablity_Mouse.pdf"), width=4, height=12)
#
# ggplot(predMetaH, aes(x=Alpha, color=treatment)) + stat_ecdf() + facet_grid(replicate ~ .)
# ggsave(dirout(out, "Alpha_cell_Probablity_Human.pdf"), width=4, height=8)
#
# ggplot(predMetaH3, aes(x=Alpha, color=treatment)) + stat_ecdf() + facet_grid(replicate ~ .)
# ggsave(dirout(out, "Alpha_cell_Probablity_Human3.pdf"), width=4, height=8)
#
# Compare to ambiguous cells ----------------------------------------------
amb.file <- dirout(out, "AmbientCellNumbers.tsv")
if(!file.exists(amb.file)){
ff <- list.files(dirout("06_SpikeIns_Islets/"), pattern="IdentifyOrganism_full.tsv", recursive=T)
names(ff) <- gsub("(\\_\\d)?(\\_S\\d+)?\\_hmG", "", dirname(ff))
ambDT <- do.call(rbind, lapply(names(ff), function(fnam) data.table(fread(dirout("06_SpikeIns_Islets/",ff[[fnam]]))[,.N, by="org"], sample=fnam)))
write.tsv(ambDT, amb.file)
} else {
ambDT <- fread(amb.file)
}
ambDT[, orgSample := ifelse(grepl("hIslets", sample), "human", "mouse")]
ambDT <- merge(ambDT[is.na(org)], ambDT[org != orgSample | is.na(org)][,.(TotalSum = sum(N)), by="sample"])
ambDT[, percentAmbiguous := N/TotalSum * 100]
ambDT[, sample := gsub("hIslets_III_A(\\d+)_(.+)hr", "hIslets_III_A10_\\2_\\1", sample)]
ambDT[, sample := gsub("hIslets_III_DMSO(\\d+)_(.+)hr", "hIslets_III_DMSO_\\2_\\1", sample)]
# Count removed cells from cutoff
mDT <- do.call(rbind, lapply(names(metas), function(xnam) data.table(metas[[xnam]], ds=xnam)))
mDT2 <- merge(mDT[PredictionConf > 3 & nGene.doublet != "nGene.too.high"][,.N, by="sample"], mDT[,.N, by="sample"], by="sample")
mDT2[, doubletsRmPercent := 100*(1-N.x/N.y)]
# plot, test, export
pDT <- merge(mDT2, ambDT, by="sample")[sample != "hIslets_II_FoxO"]
pDT <- merge(pDT, unique(mDT[,c("sample", "ds"),with=F]))
ggplot(pDT, aes(x=doubletsRmPercent, y=percentAmbiguous)) + geom_point() + facet_wrap(~ds, scales="free") +
theme_bw(12)
ggsave(dirout(out, "Removed_vs_Ambiguous.pdf"), w=10,h=4)
write.tsv(pDT, dirout(out, "Removed_vs_Ambiguous.tsv"))
write.tsv(pDT[, cor(doubletsRmPercent, percentAmbiguous), by="ds"], dirout(out, "Removed_vs_Ambiguous_Correlation.tsv"))
# Plot predicted and Numbers ----------------------------------------------
metaH <- metas$human
metaH3 <- metas$human3
metaM <- metas$mouse
pDat <- metaH[,.N, by=c("celltype2", "replicate", "treatment", "celltype")]
pDat[,sum := sum(N), by=c("replicate", "treatment")]
pDat[,percent := N / sum * 100]
ggplot(pDat, aes(x=treatment,y=percent, fill=celltype=="Endocrine")) + geom_bar(stat="identity", position="stack") + facet_grid(replicate ~ celltype2) +
scale_fill_manual(values=c("grey", "blue")) + theme_bw(12)+ xRot()
ggsave(dirout(out, "Predicted_Human.pdf"), height=8,width=15)
pDat <- metaH3[,.N, by=c("celltype2", "replicate", "treatment", "celltype")]
pDat[,sum := sum(N), by=c("replicate", "treatment")]
pDat[,percent := N / sum * 100]
ggplot(pDat, aes(x=treatment,y=percent, fill=celltype=="Endocrine")) + geom_bar(stat="identity", position="stack") + facet_grid(replicate ~ celltype2) +
scale_fill_manual(values=c("grey", "blue")) + theme_bw(12)+ xRot()
ggsave(dirout(out, "Predicted_Human3.pdf"), height=8,width=15)
pDat <- metaM[,.N, by=c("celltype2", "replicate", "treatment", "celltype")]
pDat[,sum := sum(N), by=c("replicate", "treatment")]
pDat[,percent := N / sum * 100]
ggplot(pDat, aes(x=treatment,y=percent, fill=celltype=="Endocrine")) + geom_bar(stat="identity", position="stack") + facet_grid(replicate ~ celltype2) +
scale_fill_manual(values=c("grey", "blue")) + theme_bw(12)+ xRot()
ggsave(dirout(out, "Predicted_Mouse.pdf"), height=8,width=15)
# ANNOTATE WITH INS / GCG EXPRESSION DATA -------------------------------------------------
pbmcH <- loadHData()
pbmcM <- loadMData()
pbmcH3 <- loadH3Data()
assignGenesMeta <- function(genes, metaX, seuratObj){
for(gg in genes){
if(!gg %in% row.names(seuratObj@data)) stop(gg, " not found in sc data")
metaX[[gg]] <- seuratObj@data[gg,metaX$rn]
}
metaX
}
metaH <- assignGenesMeta(c("INS", "GCG"), metaH, pbmcH)
metaH3 <- assignGenesMeta(c("INS", "GCG"), metaH3, pbmcH3)
metaM <- assignGenesMeta(c("Ins2", "Gcg"), metaM, pbmcM)
# EXPORT UNFILTERED -------------------------------------------------
write.tsv(metaH, dirout(out,"Reassigned_Human_unfiltered.tsv"))
write.tsv(metaM, dirout(out,"Reassigned_Mouse_unfiltered.tsv"))
write.tsv(metaH3, dirout(out,"Reassigned_Human3_unfiltered.tsv"))
# FILTER -------------------------------------------------
metaH <- metaH[PredictionConf > 3 & nGene.doublet != "nGene.too.high"]
metaH3 <- metaH3[PredictionConf > 3 & nGene.doublet != "nGene.too.high"]
metaM <- metaM[PredictionConf > 3 & nGene.doublet != "nGene.too.high"]
write.tsv(metaH, dirout(out,"Reassigned_Human.tsv"))
write.tsv(metaM, dirout(out,"Reassigned_Mouse.tsv"))
write.tsv(metaH3, dirout(out,"Reassigned_Human3.tsv"))
# PLOT DISTRIBUTIONS -------------------------------------------------
celltypes.of.interest <- c("Alpha", "Beta", "Gamma", "Delta", "Endocrine")
treat <- "A10"
gg <- "INS"
ct <- "Beta"
org <- "human3"
outGG <- paste0(out, "Details/")
dir.create(dirout(outGG))
for(org in c("human", "mouse", "human3")){
meta <- metaH3
if(org == "mouse") meta <- metaM
if(org == "human") meta <- metaH
for(treat in unique(meta[treatment != "DMSO"]$treatment)){
for(gg in c("INS", "GCG", "Ins2", "Gcg")){
if(!gg %in% colnames(meta)) next
pDat <- meta[treatment %in% c("DMSO", treat) & celltype2 %in% celltypes.of.interest]
pDat$treatment <- factor(pDat$treatment, levels = c("DMSO", treat))
ggplot(pDat, aes_string(x=gg, color="treatment")) + geom_density() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red"))
ggsave(dirout(out, org, "_", treat, "_", gg, ".pdf"),height=9,width=16)
ggplot(pDat, aes_string(x=gg, color="treatment")) + stat_ecdf() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red"))
ggsave(dirout(out, org, "_", treat, "_", gg, "_ECDF.pdf"),height=9,width=16)
pDat$Expression <- pDat[[gg]]
ggplot(pDat, aes(x=Expression, color=treatment, alpha=(celltype != "Endocrine"))) + stat_ecdf() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red")) + xlab(gg)
ggsave(dirout(out, org, "_", treat, "_", gg, "_ECDF_Endocrine.pdf"),height=9,width=16)
for(ct in celltypes.of.interest){
if(!gg %in% colnames(meta)) next
pDat <- meta[treatment %in% c("DMSO", treat) & celltype2 %in% ct]
if(nrow(pDat) == 0) next
pDat$treatment <- factor(pDat$treatment, levels = c("DMSO", treat))
pDat$celltype <- factor(pDat$celltype, levels = c(ct, "Endocrine"))
ggplot(pDat, aes_string(x=gg, color="treatment", linetype = "celltype")) + geom_density() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red"))
ggsave(dirout(outGG, org, "_", treat, "_", ct, "_", gg, ".pdf"),height=6,width=6)
ggplot(pDat, aes_string(x=gg, color="treatment", linetype = "celltype")) + stat_ecdf() +
theme_bw(12) + facet_grid(replicate ~ celltype2, scale="free") +
scale_color_manual(values=c("black", "red"))
ggsave(dirout(outGG, org, "_", treat, "_", ct, "_", gg, ".pdf"),height=6,width=6)
}
}
}
}
pbmc <- SubsetData(object=pbmcH, cells.use=metaH$rn)
save(pbmc, file=dirout(out, "SeuratObject_human.RData"))
pbmc <- SubsetData(object=pbmcM, cells.use=metaM$rn)
save(pbmc, file=dirout(out, "SeuratObject_mouse.RData"))
pbmc <- SubsetData(object=pbmcH3, cells.use=metaH3$rn)
save(pbmc, file=dirout(out, "SeuratObject_human3.RData"))
# metaH$org <- "human"
# metaM$org <- "mouse"
#
# metaX <- rbind(metaH, metaM, fill=T)
# metaX[,Insulin := sum(INS, Ins2, na.rm=T), by=c("rn", "org")]
# metaX[,Glucagon := sum(GCG, Gcg, na.rm=T), by=c("rn", "org")]
# ggplot(metaX[treatment %in% c("DMSO", "A10") & celltype2 %in% c("Beta", "Alpha")], aes(x=replicate, y=exp(Insulin) - 1, fill=treatment)) + geom_violin() +
# facet_grid(celltype2 ~ org, scales="free") + theme_bw(12)
# ggsave(dirout(out, "Org_Compare_Insulin.pdf"), width=8, height=4)
#
# ggplot(metaX[treatment %in% c("DMSO", "A10") & celltype2 %in% c("Beta", "Alpha")], aes(x=replicate, y=exp(Glucagon) - 1, fill=treatment)) + geom_violin() +
# facet_grid(celltype2 ~ org, scales="free") + theme_bw(12)
# ggsave(dirout(out, "Org_Compare_Glucagon.pdf"), width=8, height=4)
#
# write.tsv(metaX, dirout(out,"Reassigned_Combined.tsv"))
<file_sep>/src/DropSeq/13_1_MarkerPlot.R
require("project.init")
require(Seurat)
require(dplyr)
require(Matrix)
require(methods)
require(gridExtra)
require(glmnet)
require(ROCR)
project.init2("artemether")
out <- "13_CellTypes/"
dir.create(dirout(out))
load(file=dirout("10_Seurat/", "DropSeq/","DropSeq.RData"))
pDat <- data.table(<EMAIL>@<EMAIL>, data.table(pbmc@[email protected], keep.rownames=TRUE))
table(pDat$res.0.5)
pDat[res.0.5 == 0, Celltype := "Alpha"]
pDat[res.0.5 == 1, Celltype := "Beta"]
pDat[res.0.5 == 2, Celltype := "Endothelial"]
pDat[res.0.5 %in% c(3), Celltype := "Ductal"]
pDat[res.0.5 %in% c(4), Celltype := "Acinar"]
pDat[res.0.5 == 5, Celltype := "Unclear1"]
pDat[res.0.5 == 6 & tSNE_1 < 0, Celltype := "Tcell"]
pDat[res.0.5 == 6 & tSNE_1 > 0, Celltype := "Dendrites"]
pDat[res.0.5 == 7, Celltype := "Unclear2"]
pDat
write.table(pDat, file=dirout(out, "MetaData.tsv"), sep="\t", quote=F, row.names=F)
markers <- c(fread("metadata/PancreasMarkers.tsv")$Human_GeneName,
fread("metadata/CellMarkers.csv")$GeneSymbol)
inPath <- dirout("10_Seurat/", "DropSeq/", "Cluster_res.0.5/")
for(f in list.files(inPath, pattern="_version2.tsv")){
markers <- c(markers, fread(paste0(inPath, f))[V4 > 0.1]$V3)
}
markers <- unique(markers[markers %in% row.names(pbmc@data)])
meanMar <- foreach(cl = unique(pDat$Celltype)) %do% {
apply(pbmc@data[markers,pDat[Celltype == cl]$rn], 1, mean)
}
names(meanMar) <- unique(pDat$Celltype)
meanMar <- do.call(cbind, meanMar)
# meanMar <- meanMar - apply(meanMar, 1, min)
# meanMar <- meanMar / apply(meanMar, 1, max)
pdf(dirout(out, "MarkerMatrix.pdf"), height=20, width=7, onefile=F)
# pheatmap(meanMar, color=colorRampPalette(c("lightgrey", "blue"))(10))
pheatmap(meanMar, scale="row")
dev.off()
cl.x <- "Celltype"
labelCoordinates <- pDat[,.(tSNE_1=median(tSNE_1), tSNE_2=median(tSNE_2)),by=cl.x]
ggplot(pDat, aes_string(x="tSNE_1",y="tSNE_2", color=cl.x)) + geom_point(alpha=0.5) + # ggtitle(sample.x) +
geom_label(data=labelCoordinates, aes_string(x="tSNE_1", y="tSNE_2", label=cl.x), color="black", alpha=0.5)
ggsave(dirout(out, "Cluster_tSNE_", cl.x, ".pdf"), width=7, height=7)
# Multinomial model -------------------------------------------------------
predMeta <- pDat[sample == "DMSO" & !Alpha_Beta == "DoublePos"]
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$rn]))
set.seed(5001)
glmFit <- glmnet(y=factor(predMeta$Celltype), x=dat,family="multinomial",alpha=1,lambda=0.1)
str(coef(glmFit))
treat <- "DMSO"
for(treat in unique(pDat$sample)){
message(treat)
predMeta <- pDat[sample == treat]
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$rn]))
predMeta$class <- predict(glmFit, dat, type="class")
jac <- matrix(NA, length(unique(predMeta$class)), length(unique(predMeta$Celltype)))
row.names(jac) <- unique(predMeta$class)
colnames(jac) <- unique(predMeta$Celltype)
for(cl1 in unique(predMeta$class)){ for(cl2 in unique(predMeta$Celltype)){
x1 <- predMeta[class == cl1]$rn
x2 <- predMeta[Celltype == cl2]$rn
jac[cl1, cl2] <- length(intersect(x1, x2))/length(union(x1,x2))
}}
pdf(dirout(out, "Prediction_Accuracy_", treat,".pdf"), width=10, height=7, onefile=F)
pheatmap(jac,main= paste(treat, "\nAccuracy = ", round(sum(predMeta$Celltype == predMeta$class)/nrow(predMeta),3)))
dev.off()
}
cf <- do.call(cbind, lapply(coef(glmFit), function(m) as.matrix(m)))
colnames(cf) <- names(coef(glmFit))
pdf(dirout(out, "Prediction_Coefficient.pdf"), width=7, height=10, onefile=F)
pheatmap(as.matrix(cf[apply(cf, 1, sum) != 0 & row.names(cf) != "",]))
dev.off()
predMeta <- pDat[sample == "Artemether"]
predMeta[Alpha_Beta == "DoublePos", Celltype := "INS+ GCG+"]
dat <- t(as.matrix(pbmc@data[-which(rownames(pbmc@data) %in% c("INS", "GCG")),predMeta$rn]))
resp <- predict(glmFit, dat, type="response")[,,1]
rowAnnot <- data.frame(predMeta[,"Celltype", with=F], row.names=predMeta$rn)
pdf(dirout(out, "Prediction_Artemether_Probabilities.pdf"), width=7, height=12, onefile=F)
pheatmap(resp[order(predMeta$Celltype),], annotation_row=rowAnnot, cluster_rows=F, show_rownames=F)
dev.off()
<file_sep>/src/EXT_03_HCA.R
require(project.init)
require(Matrix)
require("rhdf5")
require("project.init")
project.init2("artemether")
out <- "EXT_HCA/"
dir.create(dirout(out))
#require(cellrangerRkit)
read_h5 <- function(file, genome){
dset <- h5read(file, name = genome)
sparse_mat <- sparseMatrix(i = dset$indices + 1, p = dset$indptr, x = as.numeric(dset$data), dims = dset$shape, giveCsparse = FALSE)
row.names(sparse_mat) <- as.character(dset$gene_names)
colnames(sparse_mat) <- as.character(dset$barcodes)
H5close()
return(sparse_mat)
}
# READ AND MERGE TWO SAMPLES ----------------------------------------------
# Datasets downloaded from: https://preview.data.humancellatlas.org/
datBM <- read_h5(file=paste0("~/projects_shared/pathway_learning/external_data/HCA/ica_bone_marrow_h5.h5"), genome="GRCh38")
datCB <- read_h5(file=paste0("~/projects_shared/pathway_learning/external_data/HCA/ica_cord_blood_h5.h5"), genome="GRCh38")
str(datCB)
str(datBM)
quantile(as(datCB, "dgCMatrix")@i) # 0 - 33691
dim(datCB)
dim(datBM)
stopifnot(length(union(colnames(datCB), colnames(datBM))) == sum(ncol(datCB), ncol(datBM)))
head(colnames(datCB))
tail(colnames(datCB))
tail(colnames(datBM))
fullMat <- cbind(datCB, datBM)
#colnames(fullMat) <- gsub("Manton", "", gsub("_HiSeq_", "", colnames(fullMat)))
fullMat.counts <- fullMat
dim(fullMat)
# IDENTIFY CELLS -----------------------------------------------------
cell.umis <- Matrix::colSums(fullMat)
fullMat <- fullMat[,cell.umis >= 500]
cell.genes <- Matrix::colSums(fullMat != 0)
fullMat <- fullMat[,cell.genes >= 200]
mito.genes <- grep(pattern = "^MT-", x = rownames(fullMat), value = TRUE, ignore.case=TRUE)
percent.mito <- Matrix::colSums(fullMat[mito.genes, ])/Matrix::colSums(fullMat)
fullMat <- fullMat[,percent.mito < 0.15]
gc()
dim(fullMat)
fullLogTPM <- toTPM_fromRaw(fullMat, 1e6)
fullLogTPM <- toLogTPM(fullLogTPM)
hormoneDT <- data.table(
barcode=colnames(fullLogTPM),
INS=fullLogTPM["INS",],
GCG=fullLogTPM["GCG",]
)
write.tsv(hormoneDT, file=dirout(out, "Hormones.tsv"))
quantile(fullLogTPM["CST3",])
quantile(fullLogTPM["CD19",])
quantile(fullLogTPM["IL32",])
<file_sep>/src/FIG_04_SpikeInDetails.R
require("project.init")
project.init2("artemether")
out <- "FIG_04_SpikeInDetails/"
dir.create(dirout(out))
cleanTreatment <- function(vec){ gsub("^FoxO$", "FoxOi", gsub("^A10$", "Artemether", vec)) }
cleanTreatment2 <- function(vec){ gsub("FoxO", "FoxOi", gsub("A10", "Artemether", vec)) }
# Base contamination ------------------------------------------------------
csa <- fread(dirout("05_SpikeIns_Clean/CrossSpecies_Alignment.tsv"))
(load(dirout("05_SpikeIns_Clean/scData.RData")))
rn <- split(row.names(pbmc@data), factor(gsub("(.+?)_.+", "\\1", row.names(pbmc@data))))
cnts <- sapply(rn, function(gg) Matrix::colSums([email protected][gg,]))
cnts <- data.table(cnts,keep.rownames=T)
cnts[,sum := hg19 + mm10]
cnts <- merge(cnts, csa, by.x="rn", by.y="barcode")
cnts[org == "human", cont := mm10/sum]
cnts[org == "mouse", cont := hg19/sum]
ggplot(cnts, aes(x=org, y=cont * 100)) +
geom_violin(aes(fill=org)) +
geom_boxplot(color="black", fill=NA,coef=Inf) +
theme_bw(12) + guides(color=F, fill=F) + xRot() +
xlab("") + ylab("Contamination (%)")
ggsave(dirout(out, "Mouse_Human_ReferenceCont.pdf"), w=2,h=3)
# Base contamination external ---------------------------------------------
ff <- list.files(dirout("EXT_04_SpeciesMixtures/", "/"), full.names=T, pattern="x$")
fx <- ff[1]
res <- data.table()
for(fx in ff){
x <- Read10X(fx)
outfile <- dirout(out, "CrossSpecies_", gsub("_filter.+$", "", basename(fx)), ".tsv")
if(file.exists(outfile)) next
rn <- split(row.names(x), factor(gsub("(.+?)_.+", "\\1", row.names(x))))
cnts <- sapply(rn, function(gg) Matrix::colSums(x[gg,]))
cnts <- data.table(cnts,keep.rownames=T)
cnts[,sum := hg19 + mm10]
cnts[,ratio := log2(hg19/mm10)]
cnts[ratio > 2, org := "human"]
cnts[ratio < -2, org := "mouse"]
cnts[org == "human", cont := mm10/sum]
cnts[org == "mouse", cont := hg19/sum]
write.tsv(cnts, outfile)
}
ff <- list.files(dirout(out), pattern="CrossSpecies", full.names=T)
xx <- lapply(ff, function(fx){
x <- fread(fx)
x[,sample := gsub("CrossSpecies_(.+).tsv", "\\1", basename(fx))]
})
xx <- do.call(rbind, xx)
ggplot(xx[!is.na(org)], aes(x=org, y=cont * 100)) +
geom_violin(aes(fill=org)) + facet_grid(. ~ sample) +
geom_boxplot(color="black", fill=NA,coef=Inf) +
theme_bw(12) + guides(color=F, fill=F) + xRot() +
xlab("") + ylab("Contamination (%)")
ggsave(dirout(out, "Mouse_Human_ExternalCont.pdf"), w=5,h=3)
# Correlation of contamination in single cells -----------------------------------------------
nam.map <- fread("metadata/Aggregate_Human1_2.csv")
res <- data.table()
fx <- "hIslets_I_DMSO_1_S33929_hmG"
for(fx in list.files(dirout("06_SpikeIns_Islets/"))){
nam.clean <- nam.map[grepl(gsub("_hmG", "", fx), molecule_h5)]$library_id
message(fx)
print(nam.clean)
if(length(nam.clean) == 0) next
if(nam.clean %in% res$ds) next
(load(dirout("06_SpikeIns_Islets/", fx, "/scData.RData")))
org.assign <- fread(dirout("06_SpikeIns_Islets/",fx, "/IdentifyOrganism.tsv"))
print(nrow(org.assign[org != orgX]))
org.idx <- substr(row.names(pbmc@data), 0,4) == "hg19"
orgX <- if(grepl("hIslets", fx)) "human" else "mouse"
genes.use <- if(orgX == "human") row.names(pbmc@data)[org.idx] else row.names(pbmc@data)[!org.idx]
m <- pbmc@data[genes.use,org.assign[org != orgX]$barcode]
m <- toTPM_fromRaw(m,scale.factor=1e6)
corMT <- cor(as.matrix(m)) #[,sample(colnames(m), 100)]))
res <- rbind(res, data.table(cor=corMT[upper.tri(corMT)], ds=nam.clean))
}
res[,treatment := gsub(".Islets_I+_", "", cleanTreatment2(ds))]
res[,Donor := paste("Donor", gsub(".Islets_(I+)_.+", "\\1", ds))]
ggplot(res[!treatment %in% c("Aold", "pla2g16")], aes(x=treatment, y=cor)) + geom_boxplot(coef=Inf) + facet_grid(. ~ Donor) + theme_bw(12) + xRot() +
xlab("") + ylab("Correlation")
ggsave(dirout(out, "Contamination_Correlation_singleCells.pdf"), width=4,h=4)
# INS / GCG plots ---------------------------------------------------------
metaH <- loadHMeta2()
pDat <- fread(dirout("07_03_CleanHuman_CleanSpikeIns/", "Cont.Genes.Data_HUMAN.tsv"))
metaH <- merge(metaH, pDat[,c("rn", "INS_raw", "GCG_raw")], by="rn")
metaH <- metaH[treatment == "DMSO"]
pDat <- melt(metaH, measure.vars=c("INS_raw", "GCG_raw"))
pDat[,variable := gsub("_raw", "", variable)]
ggplot(pDat, aes(x=value, color=replicate, fill=replicate)) +
xlim(-1, max(pDat$value)) +
geom_density() + facet_wrap(~variable, ncol=1, strip.position="right") +
theme_bw(12) +
theme(panel.grid=element_blank()) +
xlab("Expression log(TPM)") + ylab("Density") + guides(linetype=F, fill=F, color=F) +
scale_fill_manual(values=c(I="#b2df8a99", II="#cab2d699")) +
scale_color_manual(values=c(I="#b2df8a", II="#cab2d6")) +
geom_vline(xintercept=0, color="#e31a1c", linetype=2)
ggsave(dirout(out, "INS_GCG.pdf"), width=4,h=4)
<file_sep>/src/02_make_custom_10x_ref.sh
#!/bin/bash
#
# execute:
# $ ./make_custom_10x_ref.sh <NAME-OF-GENOME-IN-RESOURCE-FOLDER> <OUTPUT-FOLDER> [<FASTA-FILE> <FASTA-FILE> ..ls]
# (each FASTA file *must* contain exactly (and only) one sequence entry including a header line)
#
# see also: https://github.com/epigen/crop-seq/blob/master/src/guides_to_ref.py
GENOME=$1
OUTROOT=$2
CELLRANGER=/home/nfortelny/code/cellranger-2.1.0/cellranger
GENOME_ROOT_10X=/scratch/lab_bock/nfortelny/resources/10X_Genomics/
mkdir -p ${OUTROOT}
# gather and filter genome sequence...
if [ ! -f ${OUTROOT}/${GENOME}-ext.fa ] ; then
#SRC=${RESOURCES}/genomes/${GENOME}/${GENOME}.fa
SRC=${GENOME_ROOT_10X}/${GENOME}/fasta/genome.fa
echo "Get reference from $SRC"
cp ${SRC} ${OUTROOT}/${GENOME}-ext.fa
fi
# ... and gene annotation:
if [ ! -f ${OUTROOT}/${GENOME}-ext.gtf ] ; then
#SRC=${RESOURCES}/genomes/${GENOME}/${GENOME}.gtf
SRC=${GENOME_ROOT_10X}/${GENOME}/genes/genes.gtf
echo "Get annotations from $SRC"
# N.B. this uses only protein-coding genes
#${CELLRANGER} mkgtf ${SRC} ${OUTROOT}/${GENOME}-ext.gtf --attribute=gene_biotype:protein_coding
cp ${SRC} ${OUTROOT}/${GENOME}-ext.gtf
fi
# append the sequence from each provided FASTA file to the genome (as a "chromosome")
# and add a mock annotation entry for a "gene" spanning the entire pseudo-chromosome
for FASTA in "${@:3}"
do
if [ -f $FASTA ] ; then
NAME=$(basename $FASTA)
NAME=${NAME/.fa/}
echo "$NAME ($FASTA)"
echo "assuming one sequence per file (EVERYTHING ELSE WILL CRASH AND BURN!)"
echo " * add to FASTA"
echo ">${NAME}_chrom" >> ${OUTROOT}/${GENOME}-ext.fa
tail -n +2 $FASTA >> ${OUTROOT}/${GENOME}-ext.fa
echo " * add to GTF"
LEN=$(tail -n +2 $FASTA | wc -m)
echo "${NAME}_chrom ext gene 1 ${LEN} . + . gene_id \"${NAME}_gene\"; gene_name \"${NAME}_gene\"; gene_source \"ext\"; gene_biotype \"lincRNA\";
${NAME}_chrom ext transcript 1 ${LEN} . + . gene_id \"${NAME}_gene\"; transcript_id \"${NAME}_transcript\"; gene_name \"${NAME}_gene\"; gene_source \"ext\"; gene_biotype \"lincRNA\"; transcript_name \"${NAME}_transcript\"; transcript_source \"ext\";
${NAME}_chrom ext exon 1 ${LEN} . + . gene_id \"${NAME}_gene\"; transcript_id \"${NAME}_transcript\"; exon_number \"1\"; gene_name \"${NAME}_gene\"; gene_source \"ext\"; gene_biotype \"lincRNA\"; transcript_name \"${NAME}_transcript\"; transcript_source \"ext\"; exon_id \"${NAME}_exon\"" >> ${OUTROOT}/${GENOME}-ext.gtf
else
echo "File not found: $FASTA"
fi
done
# then build the 10x-compatible reference:
cd ${OUTROOT}
${CELLRANGER} mkref --genome=${GENOME}_ext --fasta=${GENOME}-ext.fa --genes=${GENOME}-ext.gtf
<file_sep>/src/EXT_02_GEOAnalysis.R
require("project.init")
require(Matrix)
require(methods)
project.init2("artemether")
out <- "EXT_02_GEO_Analysis/"
inDir <- "EXT_01_GEO/"
dir.create(dirout(out))
list.files(dirout(inDir))
# GSE73727
file.GSE73727 <- dirout(out, "GSE73727.RData")
if(!file.exists(file.GSE73727)){
pathGSE73727 <- dirout(inDir, "/GSE73727/")
data.GSE73727 <- do.call(cbind, lapply(list.files(pathGSE73727, pattern="RPKM"), function(f){
x <- read.table(paste0(pathGSE73727, f), sep="\t", header=TRUE)
x <- data.table(x)[,max(RPKM), by="ensG"]
data.frame(data=x$V1, row.names=x$ensG)
}))
mt.GSE73727 <- as.matrix(data.GSE73727)
mt.GSE73727 <- toSparseMT(mt.GSE73727)
colnames(mt.GSE73727) <- gsub("(GSM\\d+).+", "\\1", list.files(pathGSE73727, pattern="RPKM"))
str(mt.GSE73727)
#design
des <- readLines(dirout(inDir, "/GSE73727_series_matrix.txt.gz"))
substr(des, 0,40)
des <- data.table(
sample=gsub('\\"', "", strsplit(des[36], "\t")[[1]]),
cell_type=gsub("assigned cell type: ", "", gsub('\\"', "", strsplit(des[44], "\t")[[1]])))
colnames(mt.GSE73727) <- make.unique(des[match(colnames(mt.GSE73727), des$sample)]$cell_type)
save(mt.GSE73727, file=file.GSE73727)
}else { load(file.GSE73727)}
# GSE81547
file.GSE81547 <- dirout(out, "GSE81547.RData")
if(!file.exists(file.GSE81547)){
pathGSE81547 <- dirout(inDir, "/GSE81547/")
data.GSE81547 <- do.call(cbind, lapply(list.files(pathGSE81547), function(f){
read.table(paste0(pathGSE81547, f),row.names=1)
}))
mt.GSE81547 <- as.matrix(data.GSE81547)
mt.GSE81547 <- toSparseMT(mt.GSE81547)
colnames(mt.GSE81547) <- gsub("(GSM\\d+).+", "\\1", list.files(pathGSE81547))
#design
des <- readLines(dirout(inDir, "/GSE81547_series_matrix.txt.gz"))
substr(des, 0,40)
des <- data.table(
sample=gsub('\\"', "", strsplit(des[32], "\t")[[1]]),
cell_type=gsub("inferred_cell_type: ", "", gsub('\\"', "", strsplit(des[42], "\t")[[1]])))
colnames(mt.GSE81547) <- make.unique(des[match(colnames(mt.GSE81547), des$sample)]$cell_type)
save(mt.GSE81547, file=file.GSE81547)
} else { load(file.GSE81547)}
# GSE81608
file.GSE81608 <- dirout(out, "GSE81608.RData")
if(!file.exists(file.GSE81608)){
data <- read.table(dirout(inDir, "/GSE81608_human_islets_rpkm.txt.gz"), sep="\t", header=T)
str(data)
# Design
des <- readLines(dirout(inDir, "/GSE81608_series_matrix.txt.gz"))
#substr(des, 0,40)
des <- data.table(
sample=strsplit(des[28], "\t")[[1]],
cell_type=strsplit(des[43], "\t")[[1]])
des <- des[-1]
des[,sample := gsub("Pancreatic islet cell s", "S", sample)]
des[,cell_type := gsub("cell subtype: ", "", cell_type)]
row.names(data) <- paste0("Gene_", data$gene.id)
data$gene.id <- NULL
des[,sample := gsub(" ", "_", sample)]
des[,sample := gsub('\\"', "", sample)]
des[,cell_type := gsub('\\"', "", cell_type)]
head(des)
colnames(data) <- make.unique(des[match(colnames(data), des$sample)]$cell_type)
mt.GSE81608 <- as.matrix(data)
mt.GSE81608 <- toSparseMT(mt.GSE81608)
save(mt.GSE81608, file=file.GSE81608)
}else { load(file.GSE81608)}
# GSE83139
file.GSE83139 <- dirout(out, "GSE83139.RData")
if(!file.exists(file.GSE83139)){
data.GSE83139 <- read.table(dirout(inDir, "GSE83139_tbx-v-f-norm-ntv-cpms.csv.gz"), sep="\t", header=T)
mt.GSE83139 <- data.GSE83139
row.names(mt.GSE83139) <- make.names(mt.GSE83139$gene)
mt.GSE83139 <- as.matrix(mt.GSE83139[,8:ncol(mt.GSE83139)])
mt.GSE83139 <- toSparseMT(mt.GSE83139)
str(mt.GSE83139)
save(mt.GSE83139, file=file.GSE83139)
}else { load(file.GSE83139)}
# GSE84133
file.GSE84133 <- dirout(out, "GSE84133.RData")
if(!file.exists(file.GSE84133)){
pathGSE84133 <- dirout(inDir, "/GSE84133/")
data.GSE84133 <- lapply(list.files(pathGSE84133), function(f){
message(f)
x <- read.csv(paste0(pathGSE84133, f))
row.names(x) <- make.unique(paste0(gsub(".+(lib\\d+).+", "\\1", x$X), "_", x$assigned_cluster))
x1 <- t(as.matrix(x[,4:ncol(x)]))
print(str(x1))
x2 <- toSparseMT(x1)
print(str(x2))
return(x2)
})
lapply(data.GSE84133, str)
names(data.GSE84133) <- gsub("GSM\\d+_(.+)_umifm_counts.csv.gz", "\\1", list.files(pathGSE84133))
data.GSE84133 <- lapply(data.GSE84133, function(x){
x <- x[,Matrix::colSums(x) > MIN.UMIS]
x <- x[,Matrix::colSums(x != 0) > MIN.GENES]
x <- toTPM_fromRaw(x, SCALE.FACTOR)
})
save(data.GSE84133, file=file.GSE84133)
} else { { load(file.GSE84133)}}
# GSE85241
file.GSE85241 <- dirout(out, "GSE85241.RData")
if(!file.exists(file.GSE85241)){
data.GSE85241 <- read.table(dirout(inDir, "GSE85241_cellsystems_dataset_4donors_updated.csv.gz"), sep="\t", header=T)
mt.GSE85241 <- data.GSE85241
row.names(mt.GSE85241) <- make.unique(gsub("__chr.+$", "", row.names(mt.GSE85241)))
mt.GSE85241 <- as.matrix(mt.GSE85241)
mt.GSE85241 <- toSparseMT(mt.GSE85241)
mt.GSE85241 <- t(t(mt.GSE85241)/Matrix::colSums(mt.GSE85241)) * SCALE.FACTOR
save(mt.GSE85241, file=file.GSE85241)
}else { load(file.GSE85241)}
# E-MTAB-5061
file.MTAB_5061 <- dirout(out, "MTAB_5061.RData")
if(!file.exists(file.MTAB_5061)){
data.MTAB_5061 <- read.table(dirout(inDir, "E-MTAB-5061.pancreas_refseq_rpkms_counts_3514sc.txt"), sep="\t", header=F)
row.names(data.MTAB_5061) <- make.unique(data.MTAB_5061$V1)
he <- readLines(dirout(inDir, "E-MTAB-5061.pancreas_refseq_rpkms_counts_3514sc.txt"))
he1 <- strsplit(he[1], "\t")[[1]]
he1 <- he1[-1]
mt.MTAB_5061 <- data.MTAB_5061[,3:(length(he1) + 2)]
colnames(mt.MTAB_5061) <- he1
mt.MTAB_5061 <- as.matrix(mt.MTAB_5061)
mt.MTAB_5061 <- toSparseMT(mt.MTAB_5061)
#design
des <- fread(dirout(inDir, "/E-MTAB-5061.sdrf.txt"))
des <- des[match(colnames(mt.MTAB_5061), des[["Source Name"]])]
colnames(mt.MTAB_5061) <- make.unique(des[["Factor Value[cell type]"]])
stopifnot(all(des[["Source Name"]] == colnames(mt.MTAB_5061)))
colnames(mt.MTAB_5061) <- make.unique(des[match(colnames(mt.MTAB_5061), des[["Source Name"]])][["Factor Value[cell type]"]])
save(mt.MTAB_5061, file=file.MTAB_5061)
} else { (load(file.MTAB_5061))}
getExprGene <- function(mt, gene){
if(gene == "INS") ids=c("INS", "Ins2", "ENSG00000254647")
if(gene == "GCG") ids=c("GCG", "Gcg", "ENSG00000115263")
mt[ids[which(ids %in% row.names(mt))],]
}
pDat <- data.table()
for(gg in c("INS", "GCG")){
pDat <- rbind(pDat, data.table(
Gene=gg, Expr=getExprGene(mt.GSE73727, gg), Sample=colnames(mt.GSE73727),
Name="<NAME> al.",Type="Sorted"),fill=T)
pDat <- rbind(pDat, data.table(
Gene=gg, Expr=getExprGene(mt.GSE81547, gg), Sample=colnames(mt.GSE81547),
Name="Enge et al.",Type="Sorted"),fill=T)
# pDat <- rbind(pDat, data.table(Gene=gg, Expr=getExprGene(mt.GSE81608, gg), Name="Xin et al.",Sample=colnames(mt.GSE81608)),fill=T)
pDat <- rbind(pDat, data.table(
Gene=gg, Expr=getExprGene(mt.GSE83139, gg), Sample=colnames(mt.GSE83139),
Name="<NAME> al.",Type="Sorted"),fill=T)
pDat <- rbind(pDat, do.call(rbind, lapply(names(data.GSE84133), function(x) data.table(
Gene=gg,
Expr=getExprGene(data.GSE84133[[x]], gg),
Name=paste("Baron et al.", x),
Type="Droplet",
Sample=paste0(x, ".", colnames(data.GSE84133[[x]]))))),fill=T)
pDat <- rbind(pDat, data.table(
Gene=gg, Expr=getExprGene(mt.GSE85241, gg), Sample=colnames(mt.GSE85241),
Name="Muraro et al.",Type="Sorted"),fill=T)
pDat <- rbind(pDat, data.table(
Gene=gg, Expr=getExprGene(mt.MTAB_5061, gg), Sample=colnames(mt.MTAB_5061),
Name="<NAME>.",Type="Sorted"),fill=T)
}
pDat[grepl("alpha", Sample), cell_type := "alpha"]
pDat[grepl("beta", Sample), cell_type := "beta"]
pDat[is.na(cell_type), cell_type := "other"]
write.tsv(pDat, dirout(out, "INS_GCG_Data.tsv"))
pDat$Type <- factor(pDat$Type, levels=c("Sorted", "Droplet"))
pDat$cell_type <- factor(pDat$cell_type, levels=c("alpha", "beta", "other"))
ggplot(pDat, aes(x=Name, y=log(Expr+1))) + geom_violin(fill="lightblue") +
facet_grid(Gene ~ Type, space="free_x", scale="free") +
theme_bw(12) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) +
xlab('') + ylab("Log expression")
ggsave(dirout(out, "AllExpression.pdf"), height=4, width=4)
ggplot(pDat, aes(x=Name, y=log(Expr+1), fill=cell_type)) + geom_violin() +
facet_grid(Gene ~ Type, space="free_x", scale="free") +
theme_bw(12) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) +
xlab('') + ylab("Log expression") +
scale_fill_manual(values=c("red", "blue", "black"))
ggsave(dirout(out, "CellTypes.pdf"), height=4, width=8)
lapply(data.GSE84133, function(x){
ret <- colnames(x)
tail(sort(table(gsub("\\.\\d+", "", lapply(strsplit(ret, "_"), function(xx) xx[2])))),4)
})<file_sep>/src/FUNCTIONS_Synonyms_etc.R
# TO DOWNLOAD THE RELEVANT DATA:
# ###
# ### HomoloGene
# ###
# cd ~/resources_nfortelny
# mkdir HomoloGene
# cd HomoloGene
# wget ftp://ftp.ncbi.nih.gov/pub/HomoloGene/build68/homologene.data -O build68.tsv
# cd ../
#
# ###
# ### Human and Mouse gene data and synonyms
# ###
# cd ~/resources_nfortelny
# wget ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/GENE_INFO/Mammalia/Mus_musculus.gene_info.gz -O NCI_mouse_gene_Info.tsv
# wget ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/GENE_INFO/Mammalia/Homo_sapiens.gene_info.gz -O NCI_human_gene_Info.tsv
# SYNONYMS ----------------------------------------------------------------
syn <- readLines("~/resources_nfortelny/NCI_human_gene_Info.tsv")
syn[1]
syn <- syn[-1]
syn <- t(sapply(strsplit(syn, "\t"), function(x) c(x[3], x[5])))
syn.split <- strsplit(syn[,2], "\\|")
synDT.human <- data.table(gene=do.call(c,sapply(1:nrow(syn), function(x) rep(syn[x,1], length(syn.split[[x]])))), syn=do.call(c,syn.split))
synDT.human <- synDT.human[!syn %in% synDT.human$gene] #syn %in% synDT[,.N, by="syn"][N == 1]$syn &
rm(list=c("syn"))
# MOUSE
syn <- readLines("~/resources_nfortelny/NCI_mouse_gene_Info.tsv")
syn[1]
syn <- syn[-1]
syn <- t(sapply(strsplit(syn, "\t"), function(x) c(x[3], x[5])))
syn.split <- strsplit(syn[,2], "\\|")
synDT.mouse <- data.table(gene=do.call(c,sapply(1:nrow(syn), function(x) rep(syn[x,1], length(syn.split[[x]])))), syn=do.call(c,syn.split))
synDT.mouse <- synDT.mouse[!syn %in% synDT.mouse$gene] #syn %in% synDT[,.N, by="syn"][N == 1]$syn &
rm(list=c("syn"))
# FUNCTION
cleanGenes3 <- function(v, synDT){
ret <- v
for(i in unique(ret[!ret %in% synDT$gene])){
gxx <- synDT[syn == i]$gene
if(length(gxx) == 1){
ret[ret == i] <- gxx
} else{
message("Can't map ", i, ", it maps to ", paste(gxx, collapse=" "))
}
}
return(ret)
}
# HOMOLOGENE --------------------------------------------------------------
# mm.genes <- readLines("~/resources_nfortelny/NCI_mouse_gene_Info.tsv")
HOMOLOGENE <- fread("~/resources_nfortelny/HomoloGene/build68.tsv")
homologene <- HOMOLOGENE[V2 %in% c(9606, 10090)]
table(table(homologene$V1))
# Filter to only one to one mapping
homologene1to1 <- homologene[V1 %in% homologene[,.(count=.N, orgs=length(unique(V2))), by="V1"][count==2 & orgs==2]$V1]
homol <- data.table(mouse=homologene1to1[V2==10090][order(V1)]$V4, human=homologene1to1[V2==9606][order(V1)]$V4)
homol[toupper(mouse) != human]
<file_sep>/src/DropSeq/10_DropSeq.R
require("project.init")
require(Seurat)
require(dplyr)
require(Matrix)
require(methods)
project.init2("artemether")
R.version
seurat.diff.test <- "negbinom"
seurat.min.genes <- 200
seurat.mito.cutoff <- 0.15
seurat.nGene.cutoff <- 3000
clustering.precision <- seq(0.5, 2.0, 0.5)
out <- "10_Seurat/"
dir.create(dirout(out))
outS <- paste0(out, "DropSeq/")
dir.create(dirout(outS))
cell <- "DropSeq"
if(!file.exists(dirout(outS, cell,".RData"))){
rawData <- read.csv(dirout(outS, "new.csv"))
rawData2 <- as.matrix(rawData[,2:ncol(rawData)])
row.names(rawData2) <- rawData$GENE
pbmc <- CreateSeuratObject(raw.data = rawData2, min.cells = 3, min.genes = seurat.min.genes,
project = "artemether_Dropseq")
mito.genes <- grep(pattern = "^MT-", x = rownames(x = pbmc@data), value = TRUE)
percent.mito <- Matrix::colSums([email protected][mito.genes, ])/Matrix::colSums([email protected])
pbmc <- AddMetaData(object = pbmc, metadata = percent.mito, col.name = "percent.mito")
VlnPlot(object = pbmc, features.plot = c("nGene", "nUMI", "percent.mito"), nCol = 3)
ggsave(dirout(outS, "QC_Summary.pdf"), height=7, width=7)
ggplot([email protected], aes(y=percent.mito, x=nUMI)) + geom_point(alpha=0.3) +
geom_hline(yintercept=seurat.mito.cutoff) +
ggtitle(paste(nrow(<EMAIL>), "cells"))
ggsave(dirout(outS, "QC_MitoPlot.pdf"))
# Number of genes (many genes probably duplets) ---------------------------
ggplot(<EMAIL>, aes(x=nUMI, y=nGene)) + geom_point(alpha=0.3) +
geom_hline(yintercept=seurat.nGene.cutoff) + ggtitle(paste(nrow(<EMAIL>), "cells"))
ggsave(dirout(outS, "QC_GenePlot.pdf"))
pbmc <- FilterCells(object = pbmc, subset.names = c("nGene", "percent.mito"),
low.thresholds = c(seurat.min.genes, -Inf), high.thresholds = c(seurat.nGene.cutoff, seurat.mito.cutoff))
VlnPlot(object = pbmc, features.plot = c("nGene", "nUMI", "percent.mito"), nCol = 3)
ggsave(dirout(outS, "QC_Summary2.pdf"), height=7, width=7)
pbmc <- NormalizeData(object = pbmc, normalization.method = "LogNormalize", scale.factor = 10000)
pbmc <- ScaleData(object = pbmc, vars.to.regress = c("nUMI", "percent.mito"))
# PREP DATASET ------------------------------------------------------------
pbmc <- FindVariableGenes(object = pbmc, mean.function = ExpMean, dispersion.function = LogVMR, x.low.cutoff = 0.0125, x.high.cutoff = 3, y.cutoff = 0.5)
ggsave(dirout(outS, "QC_VariableGenes.pdf"))
pbmc <- RunPCA(pbmc, pc.genes = <EMAIL>, do.print = TRUE, pcs.print = 5, genes.print = 5)
pbmc <- RunTSNE(pbmc, dims.use = 1:10, do.fast = F)
# Clustering
for(x in clustering.precision){
pbmc <- FindClusters(pbmc, reduction.type="pca", dims.use = 1:10, resolution = x, print.output = 0, save.SNN = T)
pbmc <- StashIdent(pbmc, save.name = paste0("ClusterNames_", x))
}
[email protected]$sample <- gsub("(.+?)\\.(N|A|C|T|G)+", "\\1", colnames(pbmc@data))
save(pbmc, file=dirout(outS, cell,".RData"))
} else {
load(file=dirout(outS, cell,".RData"))
update <- FALSE
for(x in clustering.precision){
if(is.null([email protected][[paste0("ClusterNames_", x)]])){
update <- TRUE
pbmc <- FindClusters(pbmc, reduction.type="pca", dims.use = 1:10, resolution = x, print.output = 0, save.SNN = T)
pbmc <- StashIdent(pbmc, save.name = paste0("ClusterNames_", x))
}
}
if(update){
save(pbmc, file=dirout(outS, cell,".RData"))
}
}
max.nr.of.cores <- 4
extra.genes.to.plot <- unique(fread("metadata//PancreasMarkers.tsv")$Human_GeneName)
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Enrichr.R"))
source(paste0(Sys.getenv("CODEBASE"), "10x_datasets/src/FUNC_Seurat2.R"), echo=TRUE)
<file_sep>/src/FIG_03_DiffExpr.R
require("project.init")
project.init2("artemether")
out <- "FIG_03_DiffEXPR/"
dir.create(dirout(out))
# CLEAN FUNCTION ----------------------------------------------------------
cleanTreatment <- function(vec){ gsub("^FoxO$", "FoxOi", gsub("^A10$", "Artemether", vec)) }
# LOAD DATA ---------------------------------------------------------------
plot.data.files <- dirout(out, "Data.RData")
if(!file.exists(plot.data.files)){
metaH <- loadHMeta2()
pbmcH <- loadHData2()
metaM <- loadMMeta2()
pbmcM <- loadMData2()
metaH3 <- loadH3Meta2()
pbmcH3 <- loadH3Data2()
metaM[,INS := Ins2]
metaM[,GCG := Gcg]
metaH <- metaH[!sample %in% c("hIslets_II_GABA", "hIslets_I_pla2g16")]
dat.log <- list(human=pbmcH@data[,metaH$rn], mouse=pbmcM@data[,metaM$rn], human3=pbmcH3@data[,metaH3$rn])
dat.raw <- list([email protected][,metaH$rn], mouse=pbmcM@raw.<EMAIL>[,metaM$rn], [email protected][,metaH3$rn])
meta <- list(human=metaH, mouse=metaM, human3=metaH3)
# dat.log$human3 <- pbmcH3@data[,metaH3$rn]
# dat.raw$human3 <- pbmcH3@raw.<EMAIL>[,metaH3$rn]
# meta$human3 <- metaH3
save(dat.log, dat.raw, meta, file=plot.data.files)
} else {
load(plot.data.files)
}
meta <- lapply(meta, function(x){x$treatment <- cleanTreatment(x$treatment);x})
save(meta, file=dirout(out, "Meta.RData"))
celltypes.of.interest <- c("Alpha", "Beta")
use.treatments <- c("Artemether", "GABA", "A1", "FoxOi")
# MetaData export ---------------------------------------------------------
meta.export <- meta
gg <- c("Ins1", "Ins2", "Gcg", "Sst", "Ppy","INS", "GCG", "SST", "PPY", "PDX1", "MAFA")
for(mnam in names(meta.export)){
for(g in gg){
if(g %in% row.names(dat.log[[mnam]])){
meta.export[[mnam]][[g]] <- dat.log[[mnam]][g, meta[[mnam]]$rn]
}
}
write.tsv(meta.export[[mnam]], dirout(out, "MetaData_Export_", mnam, ".tsv"))
}
# Clean log data (normalized after removing insulin, glucagon,...)
genes.exclude <- c("Ins1", "Ins2", "Gcg", "Sst", "Ppy","INS", "GCG", "SST", "PPY")
dat.log.clean <- list()
for(org in names(dat.raw)){
dat.log.clean[[org]] <- toLogTPM(toTPM_fromRaw(dat.raw[[org]][!row.names(dat.raw[[org]]) %in% genes.exclude,], scale.factor=1e6))
}
# Load diff genes
diffGenes.file <- dirout(out, "DiffGenes.RData")
if(!file.exists(diffGenes.file)){
(load(dirout("16_H_02_DiffGenes/VsDMSO_negbinom_noIns/AllRes.RData")))
resH <- res[V2 != "pla2g16" & !(V1.1=="II" & V2=="GABA")]
resH[,org:="human"]
(load(dirout("16_M_02_DiffGenes/VsDMSO_negbinom_noIns/AllRes.RData")))
resM <- res
resM[,org:="mouse"]
(load(dirout("16_H3_02_DiffGenes/VsDMSO_negbinom_noIns/AllRes.RData")))
resH3 <- res
resH3Ag <- copy(resH3)
resH3Ag[,direction:=ifelse(avg_diff > 0, "up", "down")]
resH3Ag <- resH3Ag[,.(p_val = fishers.method(p_val), dir = length(unique(direction)), avg_diff = mean(avg_diff), pct.1 = mean(pct.1), pct.2 = mean(pct.2)), by=c("V1", "V2", "V3", "V4")]
resH3Ag[,file := paste(V2, V3, V4, sep="_")]
resH3Ag <- resH3Ag[dir == 1][,c("V1", "p_val", "avg_diff", "pct.1", "pct.2", "file", "V2", "V3", "V4")]
resH3Ag[,direction:=ifelse(avg_diff > 0, "up", "down")]
resH3Ag[,org:="human3aggregated"]
resH3[,org:="human3"]
resH3[,timepoint := V2]
resH3$V2 <- NULL
resH3Ag[,timepoint := V2]
resH[,timepoint := NA]
resM[,timepoint := NA]
resH[,qval := p.adjust(p_val, method="BH")]
resM[,qval := p.adjust(p_val, method="BH")]
resH3[,qval := p.adjust(p_val, method="BH")]
resH3Ag[,qval := p.adjust(p_val, method="BH")]
resX <- list(resH, resM, resH3, resH3Ag)
resX <- lapply(resX, function(x){
colnames(x)[1:9] <- c("gene", "pval", "logFC", "perc1", "perc2", "group", "replicate", "treatment", "celltype")
return(x)
})
resX <- do.call(rbind, resX)
source("src/FUNCTIONS_Synonyms_etc.R")
resX <- merge(resX, homol, by.x="gene", by.y="human", all.x=T)
resX <- merge(resX, homol, by.x="gene", by.y="mouse", all.x=T)
resX[org == "mouse", mouse := gene]
resX[grepl("human", org), human := gene]
diffGenes <- resX
diffGenes[,direction:=ifelse(logFC > 0, "up", "down")]
save(diffGenes, file=diffGenes.file)
write.tsv(homol, dirout(out, "Homology_unique.tsv"))
write.tsv(diffGenes, dirout(out, "DiffGenes_byReplicate.tsv"))
write.tsv(diffGenes[celltype %in% c("Beta", "Alpha")], dirout(out, "DiffGenes_byReplicate_AlphaBetaOnly.tsv"))
} else {
(load(diffGenes.file))
}
diffGenes$treatment <- cleanTreatment(diffGenes$treatment)
table(diffGenes$treatment)
# HORMONE DIFF RES --------------------------------------------------------
(load(dirout("16_H_02_DiffGenes/VsDMSO_negbinom_noIns/AllRes.RData")))
resH <- res[V2 != "pla2g16" & !(V1.1=="II" & V2=="GABA")]
resH[,org:="human"]
(load(dirout("16_M_02_DiffGenes/VsDMSO_negbinom_noIns/AllRes.RData")))
resM <- res
resM[,org:="mouse"]
(load(dirout("16_H3_02_DiffGenes/VsDMSO_negbinom_noIns/AllRes.RData")))
resH3 <- res
# Supplementary table
diffGenes[,direction := ifelse(logFC > 0, "up", "down")]
write.tsv(diffGenes[!treatment %in% c("A1", "Aold")][qval < 0.1][,-"group"], dirout(out, "DiffGenes_SuppTable_q0.1.tsv"))
# DIFF GENES CHERRY PICKED EXAMPLES -----------------------------------------------------
# x <- data.table(gdata::read.xls("metadata/TopHits_v2_Brenda_2018_09_17.xlsx",sheet=1))[,1:4,with=F]
# names(x) <- paste(rep(c("human", "mouse"),each=2), x[1,])
# x <- as.list(x[-1,])
# x$"human beta 2" <- data.table(gdata::read.xls("metadata/TopHits_v2_Brenda_2018_09_17.xlsx",sheet=2))$Gene
# x$"mouse beta 2" <- data.table(gdata::read.xls("metadata/TopHits_v2_Brenda_2018_09_17.xlsx",sheet=2))$Gene
# xnam <- names(x)[1]
# for(xnam in names(x)){
# xnam.split <- strsplit(xnam, " ")[[1]]
# pDat <- diffGenes[toupper(gene) %in% c(x[[xnam]])][org == xnam.split[1]][toupper(celltype) == toupper(xnam.split[2])]
# pDat <- hierarch.ordering(pDat, "gene", "group","logFC")
# ggplot(pDat, aes(x=replicate, y=gene, color=logFC, size=pmin(5, -log10(qval)))) +
# geom_point() + facet_grid(celltype ~ treatment, scales="free", space="free") +
# scale_color_gradient2(name="logFC", high="indianred", low="navyblue") + theme_bw(16) +
# scale_size_continuous(name=expression(-log[10](q))) +
# xlab("Replicate") + ylab("")
# ggsave(dirout(out, "DiffGenes_", xnam, ".pdf"), width=length(unique(pDat$group)) * 0.35 + 3.5, height=length(unique(pDat$gene))*0.25+1)
# }
# mouse vs human
# pDat <- diffGenes[!is.na(mouse) & !is.na(human)][human %in% do.call(c, x[c("human beta", "mouse beta")]) | toupper(mouse) %in% do.call(c, x[c("human beta", "mouse beta")])][treatment == "Artemether" & celltype == "Beta"]
# pDat[, id := paste(group, org)]
# pDat <- hierarch.ordering(pDat, "human", "id","logFC")
# ggplot(pDat, aes(x=replicate, y=human, color=logFC, size=pmin(5, -log10(qval)))) +
# geom_point() + facet_grid(celltype ~ org, scales="free", space="free") +
# scale_color_gradient2(name="logFC", high="indianred", low="navyblue") + theme_bw(16) +
# scale_size_continuous(name=expression(-log[10](q))) +
# xlab("Replicate") + ylab("")
# ggsave(dirout(out, "DiffGenes_MouseVsHuman_Artemether_Beta", ".pdf"), width=length(unique(pDat$id)) * 0.35 + 2.5, height=length(unique(pDat$human))*0.25+1)
# LOG FOLD CHANGES -----------------------------------------
avg.logFC.file <- dirout(out, "Avg.logfc.RData")
if(!file.exists(avg.logFC.file)){
avg <- list()
org <- names(meta)[1]
for(org in c("human", "mouse")){
metaX <- meta[[org]][celltype2 %in% c("Beta", "Alpha")]
avg[[org]] <- sapply(split(metaX$rn, factor(with(metaX, paste(org, celltype2, treatment, replicate)))), function(rns){
log(Matrix::rowMeans(toTPM(dat.log.clean[[org]][,rns])) + 1)
})
}
logfcs <- list()
for(org in names(meta)){
x <- avg[[org]]
for(i in colnames(x)){
x[,i] <- avg[[org]][,i] - avg[[org]][,gsub("(.+) (.+) (.+) (.+)", "\\1 \\2 DMSO \\4",i)]
}
logfcs[[org]] <- x[,!grepl("DMSO", colnames(x))]
}
source("src/FUNCTIONS_Synonyms_etc.R")
# Averages mapped to homologs
avg.homol <- avg
row.names(avg.homol$mouse) <- homol[match(row.names(avg.homol$mouse), homol$mouse)]$human
avg.homol$mouse <- avg.homol$mouse[!is.na(row.names(avg.homol$mouse)) & row.names(avg.homol$mouse) %in% row.names(avg.homol$human),]
avg.homol$human <- avg.homol$human[row.names(avg.homol$mouse),]
stopifnot(all(row.names(avg.homol$human) == row.names(avg.homol$mouse)))
sapply(avg.homol, dim)
# logfc mapped to homologs
logfcs.homol <- logfcs
row.names(logfcs.homol$mouse) <- homol[match(row.names(logfcs.homol$mouse), homol$mouse)]$human
logfcs.homol$mouse <- logfcs.homol$mouse[!is.na(row.names(logfcs.homol$mouse)) & row.names(logfcs.homol$mouse) %in% row.names(logfcs.homol$human),]
logfcs.homol$human <- logfcs.homol$human[row.names(logfcs.homol$mouse),]
stopifnot(all(row.names(logfcs.homol$human) == row.names(logfcs.homol$mouse)))
sapply(logfcs.homol, dim)
# write files
for(org in names(avg)){
write.csv(avg[[org]], dirout(out, "Averages_", org, ".csv"))
write.csv(avg.homol[[org]], dirout(out, "Averages_Homol_", org, ".csv"))
write.csv(logfcs[[org]], dirout(out, "LogFC_", org, ".csv"))
write.csv(logfcs.homol[[org]], dirout(out, "LogFC_Homol_", org, ".csv"))
}
save(avg, avg.homol, logfcs, logfcs.homol, file=avg.logFC.file)
} else {
(load(avg.logFC.file))
}
# Artemether vs FoxOi replicates -------------------------------------------------------------------
# plot Artemether vs FoxOi for each replicate
org <- "human"
repl <- "I"
for(org in c("human", "mouse")){
for(repl in unique(meta[[org]]$replicate)){
pDat <- data.table(
FoxOi = logfcs[[org]][,paste(org, "Beta", "FoxOi", repl)],
Artemether = logfcs[[org]][,paste(org, "Beta", "Artemether", repl)],
Gene=row.names(logfcs[[org]]))
pDat[Gene %in% diffGenes[celltype == "Beta" & treatment == "FoxOi" & replicate == repl & qval < 0.05]$gene, FoxOisig := "FoxOi"]
pDat[Gene %in% diffGenes[celltype == "Beta" & treatment == "Artemether" & replicate == repl & qval < 0.05]$gene, AmSig := "Am"]
pDat[,sig := gsub("_NA$", "", gsub("^NA_", "", paste0(FoxOisig, "_", AmSig)))]
ggplot(pDat, aes(x=FoxOi, y=Artemether)) +
geom_point(data=pDat[sig == "NA"], alpha=0.2) +
geom_point(data=pDat[sig != "NA"], aes(color=sig), alpha=0.2) +
theme_bw(16) + ggtitle(round(cor(pDat$FoxOi, pDat$Artemether, method="spearman"),3))
ggsave(dirout(out, "Diff_FoxOi_Artemether_", org, "_", repl, ".pdf"), height=4, width=5)
ggsave(dirout(out, "Diff_FoxOi_Artemether_", org, "_", repl, ".jpg"), height=4, width=5)
}
}
# Artemether vs FoxOi averages ----------------------------------------------------
logfcs.comb <- cbind(logfcs.homol$human, logfcs.homol$mouse)
logfcs.comb <- sapply(split(colnames(logfcs.comb), factor(gsub(" I+", "", colnames(logfcs.comb)))), function(cc) rowMeans(logfcs.comb[,cc,drop=F]))
pDT <- data.table(logfcs.comb)
colnames(pDT) <- make.names(colnames(pDT))
ggplot(pDT, aes(y=human.Beta.Artemether,x =human.Beta.FoxOi)) + geom_point(alpha=0.1) +
theme_bw(16) + ggtitle(round(cor(pDT$human.Beta.Artemether, pDT$human.Beta.FoxOi, method="spearman"),3))
ggsave(dirout(out, "Diff_FoxOi_Artemether_human_comb.pdf"), height=4, width=4)
ggsave(dirout(out, "Diff_FoxOi_Artemether_human_comb.jpg"), height=4, width=4)
ggplot(pDT, aes(y=mouse.Beta.Artemether,x =mouse.Beta.FoxOi)) + geom_point(alpha=0.1) +
theme_bw(16) + ggtitle(round(cor(pDT$mouse.Beta.Artemether, pDT$mouse.Beta.FoxOi, method="spearman"),3))
ggsave(dirout(out, "Diff_FoxOi_Artemether_mouse_comb.pdf"), height=4, width=4)
ggsave(dirout(out, "Diff_FoxOi_Artemether_mouse_comb.jpg"), height=4, width=4)
# mouse vs human -------------------------------------------------------------------
# plot mouse vs human Artemether
pDat <- data.table(
human= rowMeans(logfcs.homol$human[,grepl("Beta Artemether", colnames(logfcs.homol$human))]),
mouse= rowMeans(logfcs.homol$mouse[,grepl("Beta Artemether", colnames(logfcs.homol$mouse))]),
gene= row.names(logfcs.homol$human))
ggplot(pDat, aes(x=human, y=mouse)) + geom_point(alpha=0.2) +
ggtitle(round(cor(pDat$mouse, pDat$human, method="spearman"),3))
ggsave(dirout(out, "Diff_human_mouse_Artemether.pdf"), height=4, width=5)
ggsave(dirout(out, "Diff_human_mouse_Artemether.jpg"), height=4, width=5)
# plot mouse vs human FoxOi
pDat <- data.table(
human= rowMeans(logfcs.homol$human[,grepl("Beta FoxOi", colnames(logfcs.homol$human))]),
mouse= rowMeans(logfcs.homol$mouse[,grepl("Beta FoxOi", colnames(logfcs.homol$mouse))]),
gene= row.names(logfcs.homol$human))
ggplot(pDat, aes(x=human, y=mouse)) + geom_point(alpha=0.2) +
ggtitle(round(cor(pDat$mouse, pDat$human, method="spearman"),3))
ggsave(dirout(out, "Diff_human_mouse_FoxOi.pdf"), height=4, width=5)
ggsave(dirout(out, "Diff_human_mouse_FoxOi.jpg"), height=4, width=5)
# HM OF CORRELATIONS ------------------------------------------------------
# Beta
x <- cbind(logfcs.homol$human, logfcs.homol$mouse)
x <- x[,grepl("Beta Artemether", colnames(x)) | grepl("Beta FoxOi", colnames(x)) | grepl("Beta GABA", colnames(x))]
cleanDev()
# pdf(dirout(out, "Diff_human_mouse_Beta_HM_all.pdf"),width=5, height=5)
# pheatmap(cor(x, method="spearman"))
# dev.off()
x <- x[rownames(x) %in% diffGenes[celltype == "Beta" & treatment %in% c("Artemether", "FoxOi", "GABA") & qval < 0.05]$gene,]
cMT <- cor(x, method="spearman")
diag(cMT) <- NA
pdf(dirout(out, "Diff_human_mouse_Beta_HM_sig.pdf"),width=6, height=6)
pheatmap(cMT,clustering_distance_rows=dist(1-cMT), clustering_distance_cols=dist(1-cMT),
color=colorRampPalette(c("#edf8fb", "#8c96c6", "#810f7c"))(50))
dev.off()
pdf(dirout(out, "Diff_human_mouse_Beta_Clustering_sig.pdf"),width=6, height=6)
plot(hclust(dist(1-cMT)))
dev.off()
# Alpha
x <- cbind(logfcs.homol$human, logfcs.homol$mouse)
x <- x[,grepl("Alpha Artemether", colnames(x)) | grepl("Alpha FoxOi", colnames(x)) | grepl("Alpha GABA", colnames(x))]
cleanDev()
# pdf(dirout(out, "Diff_human_mouse_Alpha_HM_all.pdf"),width=5, height=5)
# pheatmap(cor(x, method="spearman"))
# dev.off()
x <- x[rownames(x) %in% diffGenes[celltype == "Alpha" & treatment %in% c("Artemether", "FoxOi", "GABA") & qval < 0.05]$gene,]
cMT <- cor(x, method="spearman")
diag(cMT) <- NA
pdf(dirout(out, "Diff_human_mouse_Alpha_HM_sig.pdf"),width=6, height=6)
pheatmap(cMT,clustering_distance_rows=dist(1-cMT), clustering_distance_cols=dist(1-cMT),
color=colorRampPalette(c("#edf8fb", "#8c96c6", "#810f7c"))(50))
dev.off()
pdf(dirout(out, "Diff_human_mouse_Alpha_Clustering_sig.pdf"),width=6, height=6)
plot(hclust(dist(1-cMT)))
dev.off()
# INS pos ALPHA cells -------------------------------------------------------------
ab.cor <- list()
(load(dirout("21_01_CellCorrelation/Markers/human.RData")))
ab.cor[["human"]] <- meta2[!sample %in% c("hIslets_I_pla2g16", "hIslets_II_GABA")]
(load(dirout("21_01_CellCorrelation/Markers/mouse.RData")))
ab.cor[["mouse"]] <- meta2
(load(dirout("21_01_CellCorrelation/Markers/human3.RData")))
ab.cor[["human3"]] <- meta2
orgx <- "human3"
for(orgx in c("human", "mouse", "human3")){
pDat <- ab.cor[[orgx]]
pDat <- pDat[celltype2 == "Alpha"]
ins.gene <- if(grepl("human", orgx)) "INS" else "Ins2"
pDat$ins <- c("INS-", "INS+")[(pDat[[ins.gene]] > 0) + 1]
ggplot(pDat, aes(x=alphaCor, y=betaCor, color=ins)) + geom_point() +
scale_color_manual(name="", values=c("#00000020", "#0000ff80")) + theme_bw(14) +
xlab("Correlation to alpha cells") + ylab("Correlation to beta cells")
ggsave(dirout(out, "INS_POS_ALPHA_", orgx, ".pdf"), width=5, height=4)
ggsave(dirout(out, "INS_POS_ALPHA_", orgx, ".jpg"), width=5, height=4)
ggplot(pDat, aes(x=alphaCor, color=ins)) + geom_density() +
scale_color_manual(name="", values=c("#00000080", "#0000ff80")) + theme_bw(14) +
xlab("Correlation to alpha cells") + ylab("Density")
ggsave(dirout(out, "INS_POS_ALPHAcor_", orgx, ".pdf"), width=5, height=4)
ggplot(pDat, aes(x=betaCor, color=ins)) + geom_density() +
scale_color_manual(name="", values=c("#00000080", "#0000ff80")) + theme_bw(14) +
xlab("Correlation to beta cells") + ylab("Density")
ggsave(dirout(out, "INS_POS_BETAcor_", orgx, ".pdf"), width=5, height=4)
if(orgx == "human3"){
ggplot(pDat, aes(x=alphaCor, y=betaCor, color=ins)) + geom_point() + facet_wrap(~replicate) +
scale_color_manual(name="", values=c("#00000020", "#0000ff80")) + theme_bw(14) +
xlab("Correlation to alpha cells") + ylab("Correlation to beta cells")
ggsave(dirout(out, "INS_POS_ALPHA_", orgx, "_byGroup.pdf"), width=15, height=8)
ggsave(dirout(out, "INS_POS_ALPHA_", orgx, "_byGroup.jpg"), width=15, height=8)
}
}
# Enrichment tests for INS+ -----------------------------
(load(dirout(out, "Meta.RData")))
meta$mouse$Ins1 <- dat.log$mouse["Ins1", meta$mouse$rn]
meta$mouse$INS <- NULL
res <- data.table()
for(orgx in names(meta)){
for(insx in c("Ins1", "Ins2", "INS")){
metaO <- meta[[orgx]]
if(!insx %in% colnames(metaO)) next
metaO[get(insx) > 0, insulin := "INS+"]
metaO[!get(insx) > 0, insulin := "INS-"]
for(treatx in c("Artemether", "FoxOi")){
for(repx in c("I", "II", "III")){
if(!repx %in% unique(metaO$replicate)) next
m <- with(metaO[treatment %in% c("DMSO", treatx)][replicate == repx][celltype == "Alpha"], table(insulin, treatment))
m <- m[c("INS+", "INS-"),c(treatx, "DMSO")]
f <- fisher.test(m)
res <- rbind(res, data.table(organism=orgx, treatment = treatx, replicate=repx, pvalue=f$p.value, oddsRatio=f$estimate, insulin=insx))
}
m <- with(metaO[treatment %in% c("DMSO", treatx)][celltype == "Alpha"], table(insulin, treatment))
m <- m[c("INS+", "INS-"),c(treatx, "DMSO")]
f <- fisher.test(m)
res <- rbind(res, data.table(organism=orgx, treatment = treatx, replicate="All", pvalue=f$p.value, oddsRatio=f$estimate, insulin=insx))
}
}
}
res
write.tsv(res, dirout(out, "INS_Pos_FisherTest.tsv"))
(load(dirout(out, "Meta.RData")))
# INS+ Alpha cells - Alpha cell probability cutoff -----------------------------------------------------------------
#list.files(dirout("14_03_Classifier_moreCelltypes_noEndocrine/human/"))
orgx <- "human"
for(orgx in c("human", "mouse")){
probs <- fread(dirout("14_03_Classifier_moreCelltypes_noEndocrine/",orgx,"/Prediction.tsv"))
probs <- merge(meta[[orgx]], probs[,c("rn", "Alpha", "Beta"),with=F], by="rn")[celltype == "Alpha" | (celltype == "Endocrine" & PredictedCell == "Alpha")]
probs[,Alpha2 := Alpha]
probs[celltype == "Alpha", Alpha2 := 1]
alpha2.co <- 0.5
res <- data.table()
for(alpha2.co in unique(sort(floor(probs$Alpha2*100)/100))){
res <- rbind(res, data.table(probs[Alpha2 >= alpha2.co, .(INSpos = sum(INS > 0), INSneg = sum(INS <= 0)), by=c("treatment", "replicate")], cutoff=alpha2.co))
}
res[,percentPos := INSpos/(INSpos + INSneg) * 100]
ggplot(res, aes(x=cutoff, y=percentPos, color=treatment)) + facet_grid(. ~ replicate) +
geom_line() + theme_bw(16) + xlab("Alpha cell probability") + ylab("Percent of INS+ cells")
ggsave(dirout(out, "INSpos_",orgx,"_AlphaProbCutoff.pdf"), width=length(unique(res$replicate)) * 4 + 1, height=4)
write.tsv(res, dirout(out, "INSpos_",orgx,"_AlphaProbCutoff.tsv"))
ggplot(probs, aes(x=Alpha2, color=treatment)) + stat_ecdf() + facet_grid(. ~ replicate) + theme_bw(16) + xlab("Alpha cell probability") + ylab("ECDF")
ggsave(dirout(out, "INSpos_",orgx,"_AlphaProbDistr_ECDF.pdf"), width=length(unique(res$replicate)) * 4 + 1, height=4)
ggplot(probs, aes(x=Alpha2, color=treatment)) + geom_density() + facet_grid(. ~ replicate) + theme_bw(16) + xlab("Alpha cell probability")
ggsave(dirout(out, "INSpos_",orgx,"_AlphaProbDistr_Density.pdf"), width=length(unique(res$replicate)) * 4 + 1, height=4)
}
# INS Differential expression ---------------------------------------------
# without replicates
res <- data.table()
meta.de <- meta
meta.de$human3_36 <- meta.de$human3[grepl("_36", replicate)]
meta.de$human3_72 <- meta.de$human3[grepl("_72", replicate)]
meta.de$human3 <- NULL
for(orgx in names(meta.de)){
orgx.dat <- if(grepl("human3_", orgx)) "human3" else orgx
x <- CreateSeuratObject(raw.data=dat.raw[[orgx.dat]], min.cells=0, min.genes=0)
x@data <- dat.log[[orgx.dat]][row.names(x<EMAIL>), colnames(x@<EMAIL>)]
for(ctx in c("Alpha", "Beta")){
mx <- meta.de[[orgx]][celltype == ctx]
for(treatx in c("FoxOi", "Artemether")){
if(treatx == "FoxOi" & grepl("human3_", orgx)) next
bar.dmso <- mx[treatment == "DMSO"]$rn
bar.treat <- mx[treatment == treatx]$rn
genes.to.use <- if(grepl("human", orgx)) c("INS", "GCG", "SST", "PPY") else c("Ins1", "Ins2", "Gcg", "Sst", "Ppy")
stopifnot(all(colnames(<EMAIL>) == colnames(x<EMAIL>)))
stopifnot(all(row.names(<EMAIL>) == row.names(x@<EMAIL>)))
stopifnot(all(bar.dmso %in% colnames(<EMAIL>)))
stopifnot(all(bar.treat %in% colnames(<EMAIL>)))
stopifnot(all(genes.to.use %in% row.names(<EMAIL>)))
dtest <- data.table(FindMarkers(object = x, min.pct=0, ident.1=bar.treat, ident.2 = bar.dmso, genes.use = genes.to.use, thresh.use=0, test.use="negbinom"), keep.rownames=T)
#p <- data.table(Seurat:::NegBinomDETest(object = x, cells.1 = bar.treat, cells.2 = bar.dmso, genes.use = genes.to.use, latent.vars = "nUMI", print.bar = TRUE, min.cells = 10), keep.rownames=T)
res <- rbind(res, data.table(dtest, organism=orgx, celltype=ctx, treatment=treatx))
}
}
}
write.tsv(res, dirout(out, "DE_NoReplicates_Insulin.tsv"))
# with replicates
resx <- data.table()
for(x in c("H", "H3", "M")){
(load(dirout("16_",x,"_02_DiffGenes/VsDMSO_negbinom_onlyIns/AllRes.RData")))
res <- res[,1:6]
colnames(res) <- paste0("V",1:6)
resx <- rbind(resx, data.table(res, dataset=x), fill=T)
}
write.tsv(resx[V1 %in% c("INS", "Ins1", "Ins2")][(grepl("Fox", V6) | grepl("A10", V6))][grepl("Alpha", V6) | grepl("Beta", V6)], dirout(out, "DE_Replicates_Insulin.tsv"))
write.tsv(resx[(grepl("Fox", V6) | grepl("A10", V6))][grepl("Alpha", V6) | grepl("Beta", V6)], dirout(out, "DE_Replicates_Hormones.tsv"))
# FoxOi Literature ----------------------------------------------------------
foxoList <- fread("metadata/FoxO_Genes_Literature.csv")
foxoList <- merge(foxoList, homol, by.x="gene", by.y="mouse")
colnames(foxoList) <- gsub(" \\(.+$", "", colnames(foxoList))
foxoList <- foxoList[human %in% row.names(avg.homol$human)]
foxoList.cor <- cor(cbind(logfcs.homol$human[foxoList$human,], logfcs.homol$mouse[foxoList$human,]), foxoList$LogFC, method="spearman")
pDat <- data.table(Correlation=foxoList.cor[,1], do.call(rbind, strsplit(row.names(foxoList.cor), " ")))
ggplot(pDat, aes(x=V3, y=Correlation, color=V4)) +
facet_grid(V2 ~ V1, scales="free_x") +
geom_jitter(height=0, width=0.1,size=2, alpha=0.7)+
theme_bw(16) + xRot()
ggsave(dirout(out, "FoxoLiterature_LogFC_Correlation.pdf"), width=5, height=6)
# Enrichments -------------------------------------------------------------
diffGenes.cnt <- diffGenes[celltype %in% c("Beta", "Alpha") & treatment %in% c("Artemether", "FoxOi")][,.N, by=c("org", "treatment", "celltype", "direction", "gene")]
diffGenes.cnt <- diffGenes.cnt[(org == "mouse" & N == 3) | (org == "human" & N == 2)]
diffGenes.cnt <- dcast.data.table(diffGenes.cnt, org + celltype + gene ~ treatment,value.var="direction")
diffGenes.cnt[,Artemether_FoxOi := gsub("NA", "x", paste0(Artemether, "_", FoxOi))]
enr.lists <- split(diffGenes.cnt$gene, factor(with(diffGenes.cnt, paste(celltype, Artemether_FoxOi, org))))
enr.file <- dirout(out, "Enr.RData")
source("src/FUNC_Enrichr.R")
if(!file.exists(enr.file)){
enr <- enrichGeneList.oddsRatio.list(geneLists=enr.lists, enrichrDBs=c("WikiPathways_2016", "NCI-Nature_2016","Reactome_2016","KEGG_2016"))
save(enr, diffGenes.cnt, file=enr.file)
} else {
load(enr.file)
}
enr2 <- cbind(enr, do.call(rbind, strsplit(enr$grp, " ")))
enrichr.plot.many(enrichRes=enr2, out=dirout(out),label="Enrichr")
# Contamination percent in spike-ins --------------------------------------
(load(dirout("07_03_CleanHuman_CleanSpikeIns/","Uncorrected.Data.RData")))
#"ml.rho.pred" "ml.rho.cv" "ml.rho.pred.with.cv" "data.raw.cells" "meta.raw.cells" "spikeIn.soups"
(load(dirout("07_03_CleanHuman_CleanSpikeIns/","CorrectedData.RData")))
# "corr.export"
metaH <- meta$human
data.raw.log <- data.raw.cells[row.names(dat.log$human),colnames(dat.log$human)]
data.raw.log <- toTPM_fromRaw(data.raw.log, scale.factor=SCALE.FACTOR)
data.raw.log <- toLogTPM(data.raw.log)
metaH$INS_Raw <- data.raw.log["INS", metaH$rn]
# RAW INSULIN IN SPIKE-INS ------------------------------------------------
ggplot(metaH[celltype2 == "SI_mouse" & treatment %in% c("Artemether", "DMSO")], aes(x=treatment, y=INS_Raw, color=treatment)) +
geom_boxplot(coef=Inf) + geom_jitter(height=0, shape=1) +
facet_grid(. ~ replicate) + theme_bw(14) +
xlab("") + ylab("INS Log(TPM)") + guides(color=F)
ggsave(dirout(out, "INS_RAW_SPIKE_INS.pdf"), width=4, height=4)
ggplot(metaH[celltype2 == "SI_mouse" & treatment %in% c("Artemether", "DMSO")], aes(x=treatment, y=exp(INS_Raw)-1, color=treatment)) +
geom_boxplot(coef=Inf) + geom_jitter(height=0, shape=1) +
facet_grid(. ~ replicate) + theme_bw(14) +
xlab("") + ylab("INS TPM") + guides(color=F)
ggsave(dirout(out, "INS_RAW_SPIKE_INS_TPM.pdf"), width=4, height=4)
<file_sep>/src/07_11_CleanMouse_CleanSpikeIns.R
require("project.init")
require(Seurat)
require(Matrix)
require(methods)
require(SoupX)
project.init2("artemether")
out <- "07_11_CleanMouse_CleanSpikeIns/"
dir.create(dirout(out))
org.sample <- "mouse"
org.spikeIns <- if(org.sample == "mouse") "human" else "mouse"
# LOAD DATA ---------------------------------------------------------------
data.raw <- Read10X(paste0(getOption("PROCESSED.PROJECT"), "results_pipeline/cellranger_count/","MouseLTI","/outs/raw_gene_bc_matrices_mex/refdata-cellranger-mm10-1.2.0_ext/"))
# external spike ins
(load(dirout("05_SpikeIns_Clean/SpikeData_",org.sample,".RData")))
spike.clean <- add.genes.sparseMatrix(toTPM(dat.log.spike), row.names(data.raw))
spike.clean.meta <- fread(dirout("05_SpikeIns_Clean/SpikeMeta_",org.sample,".tsv"))
spike.clean.diffOrg <- Matrix::rowMeans(spike.clean[,spike.clean.meta[org == org.spikeIns]$barcode])
spike.clean.sameOrg <- Matrix::rowMeans(spike.clean[,spike.clean.meta[org == org.sample]$barcode])
str(pancGenes <- intersect(unique(fread("metadata//PancreasMarkers.tsv")$Mouse_GeneName), row.names(data.raw)))
# PREPARE CELL ANNOTATION -------------------------------------------------
sample.annot <- fread("metadata/Aggregate_Mouse_withLTI.csv")
sample.annot$nr <- as.character(1:nrow(sample.annot))
sample.annot[,old_id := gsub(".+cellranger_count\\/(.+)\\/outs.+", "\\1", molecule_h5)]
meta.raw.file <- dirout(out, "Meta.raw.RData")
if(!file.exists(meta.raw.file)){
meta.raw <- data.table(rn = colnames(data.raw))
meta.raw[,barcode := gsub("(.+)\\-(\\d+)", "\\1", rn)]
meta.raw[,nr := gsub("(.+)\\-(\\d+)", "\\2", rn)]
meta.raw <- merge(meta.raw, sample.annot, by="nr", all.x=T)
meta.raw$molecule_h5 <- NULL
islet.spike.annot <- do.call(rbind, lapply(list.files(dirout("06_SpikeIns_Islets/"), pattern="^.Islets"), function(x){
data.table(fread(dirout("06_SpikeIns_Islets/", x, "/IdentifyOrganism.tsv")), old_id = gsub("_hmG$", "", x))}))
meta.raw <- merge(meta.raw, islet.spike.annot, by=c("barcode", "old_id"), all.x=T)
meta.raw$nUMI <- Matrix::colSums(data.raw[,meta.raw$rn])
meta.raw$nGene <- Matrix::colSums(data.raw[,meta.raw$rn] != 0)
save(meta.raw, file=meta.raw.file)
} else {
load(meta.raw.file)
}
meta.raw <- meta.raw[!grepl("LT1", library_id)]
data.raw <- data.raw[,meta.raw$rn]
table(meta.raw$library_id)
str(data.raw)
# Define cells
meta.raw.cells <- meta.raw[nUMI >= MIN.UMIS & nGene >= MIN.GENES]
data.raw.cells <- data.raw[,meta.raw.cells$rn]
data.tpm.cells <- t(t(data.raw.cells) / Matrix::colSums(data.raw.cells)) * SCALE.FACTOR
data.log.cells <- toLogTPM(data.tpm.cells)
# Define spike Ins
meta.raw.spikes <- meta.raw[spikeIn != "NA"]
with(meta.raw.spikes, table(library_id, spikeIn))
meta.raw.spikes <- meta.raw.spikes[spikeIn == "human"]
data.raw.spike <- data.raw[,meta.raw.spikes$rn]
data.tpm.spike <- t(t(data.raw.spike) / Matrix::colSums(data.raw.spike)) * SCALE.FACTOR
# Samples
(samples <- unique(meta.raw$library_id))
with(meta.raw.spikes, table(spikeIn, library_id))
# SOUP ANALYSIS -----------------------------------------------------------
soupX.file <- dirout(out, "Soup.results.RData")
if(!file.exists(soupX.file)){
#estimate soup
soupX.soup <- lapply(samples, function(x) estimateSoup(tod=data.raw[,meta.raw[library_id == x]$rn]))
names(soupX.soup) <- samples
soupX.soup.tpm <- do.call(cbind, lapply(soupX.soup, function(dt){ret <- dt$cnts/dt$total * SCALE.FACTOR; names(ret) <- row.names(dt); ret}))
# estimate contaminated fraction
soupX.contFrac <- lapply(samples, function(x){
calculateContaminationFraction(
toc=data.raw[,meta.raw.spikes[library_id == x]$rn],
soupProfile=soupX.soup[[x]],
nonExpressedGeneList=pancGenes,
excludeMethod="qCut")})
names(soupX.contFrac) <- samples
# estimate rho
soupX.rho <- lapply(samples, function(x){
interpolateCellContamination(
rhos=soupX.contFrac[[x]],
nUMIs=Matrix::colSums(data.raw[,meta.raw.spikes[library_id == x]$rn]))})
names(soupX.rho) <- samples
str(soupX.rho)
soupX.rho.agg <- do.call(c, lapply(samples, function(x){names(soupX.rho[[x]]) <- meta.raw.spikes[library_id == x]$rn; soupX.rho[[x]]}))
# clean cell
soupX.strainedCells <- lapply(samples, function(x){
strainCells(
toc=data.raw[,meta.raw.spikes[library_id == x]$rn],
rhos=soupX.rho[[x]],
soupProfiles=soupX.soup[[x]],
retainSparsity=TRUE)})
names(soupX.strainedCells) <- samples
soupX.strainedCells.all <- do.call(cbind, soupX.strainedCells)
soupX.strainedCells.all <- t(t(soupX.strainedCells.all)/Matrix::colSums(soupX.strainedCells.all))*SCALE.FACTOR
stopifnot(all(round(Matrix::colSums(soupX.strainedCells.all)) == SCALE.FACTOR))
# save
save(list=ls()[grepl("^soupX\\.", ls())], file=soupX.file)
} else {
(load(soupX.file))
}
# CALCULATE ESTIMATED SOUP FROM SPIKE INS ---------------------------------
spikeIn.soups <- do.call(cbind, lapply(samples, function(x){
m <- meta.raw.spikes[library_id == x & spikeIn == org.spikeIns]
cont <- t(t(data.tpm.spike[,m$rn]) * 1/(1-m$contamination)) - spike.clean.diffOrg[row.names(data.tpm.spike)]
cont[cont < 0] <- 0
soup <- Matrix::rowMeans(t(t(cont) / m$contamination))
#soup <- Matrix::rowMeans(t(t(cont) / Matrix::colSums(cont) * SCALE.FACTOR))
return(soup)
}))
colnames(spikeIn.soups) <- paste0(samples, " spikeIn")
spikeIn.soups.tpm <- t(t(spikeIn.soups)/colSums(spikeIn.soups)) * SCALE.FACTOR
# ESTIMATED RHOS FROM MACHINE LEARNING -------------------------------------------------------
(cont.genes <- intersect(names(tail(sort(rowMeans(spikeIn.soups)), 200)), pancGenes))
(cont.genes <- cont.genes[-which(cont.genes == "Ins1")])
# Cross validation
gg <- gene.ins
pred.cv <- list()
for(gg in cont.genes){
message(gg)
pred.cv[[gg]] <- c()
sampleX <- meta.raw.spikes$library_id[1]
for(sampleX in unique(meta.raw.spikes$library_id)){
m <- meta.raw.spikes[library_id == sampleX & spikeIn == org.spikeIns]
folds <- caret::createFolds(m$contamination, k=3)
f <- folds[[1]]
for(f in folds){
lm.dat <- data.table(cont=m$contamination, gene=data.tpm.spike[gg,m$rn], rn=m$rn)
fit <- lm(cont ~ gene + 0, data=lm.dat[-f])
res <- predict(fit, lm.dat[f])
names(res) <- lm.dat[f]$rn
pred.cv[[gg]] <- c(pred.cv[[gg]], res)
}}}
ml.rho <- do.call(cbind, lapply(pred.cv, function(vec) vec[meta.raw.spikes$rn]))
ml.rho[ml.rho == 0] <- NA
ml.rho <- ml.rho[!is.na(row.names(ml.rho)),]
str(ml.rho)
ml.rho.cv <- rowMedians(ml.rho, na.rm=T)
names(ml.rho.cv) <- row.names(ml.rho)
# Prediction
pred.final <- list()
gg <- gene.ins
for(gg in cont.genes){
message(gg)
pred.final[[gg]] <- c()
sampleX <- meta.raw.cells$library_id[1]
for(sampleX in unique(meta.raw.cells$library_id)){
# Prediction
m <- meta.raw.cells[library_id == sampleX]
m$gene <- data.tpm.cells[gg,m$rn]
fit <- lm(contamination ~ gene + 0, data=m[spikeIn == org.spikeIns])
res <- predict(fit, m);names(res) <- m$rn
pred.final[[gg]] <- c(pred.final[[gg]], res)
}}
ml.rho.final <- do.call(cbind, lapply(pred.final, function(vec) vec[meta.raw.cells$rn]))
ml.rho.final[ml.rho.final == 0] <- NA
ml.rho.final <- ml.rho.final[!is.na(row.names(ml.rho.final)),]
str(ml.rho.final)
ml.rho.pred <- rowMedians(ml.rho.final, na.rm=T)
names(ml.rho.pred) <- row.names(ml.rho.final)
ml.rho.pred.with.cv <- ml.rho.pred
ml.rho.pred.with.cv[names(ml.rho.cv)] <- ml.rho.cv
ggplot(data.table(contamination=ml.rho.pred), aes(x=contamination)) + geom_density() + xlim(0,1) + geom_vline(xintercept=0.1, color='red', size=1) +theme_bw(12)
ggsave(dirout(out, "Capped_Contamination.pdf"), width=4, heigh=4)
#ml.rho.pred.with.cv[ml.rho.pred.with.cv > 0.2] <- 0.2
ml.rho.pred[ml.rho.pred > 0.1] <- 0.1
# CORRECT DATA FROM SPIKE-INS in mouse and human spike-ins ---------------------------------------------
ml.corr.values <- lapply(samples, function(x){
rn <- meta.raw.spikes[library_id == x]$rn
ret <- data.tpm.spike[,rn] - (spikeIn.soups[row.names(data.tpm.spike),paste(x, "spikeIn")] %o% ml.rho.pred.with.cv[rn])
ret[ret < 0] <- 0
t(t(ret) / Matrix::colSums(ret)) * SCALE.FACTOR
})
ml.corr.values.merge <- do.call(cbind, ml.corr.values)
# CORRECT ALL DATA FROM SPIKE-INS ---------------------------------------------
ml.corr.values.all <- lapply(samples, function(x){
rn <- meta.raw.cells[library_id == x]$rn
ret <- data.tpm.cells[,rn] - (spikeIn.soups[row.names(data.tpm.cells),paste(x, "spikeIn")] %o% ml.rho.pred[rn])
ret[ret < 0] <- 0
t(t(ret) / Matrix::colSums(ret)) * SCALE.FACTOR
})
ml.corr.values.all.merge <- do.call(cbind, ml.corr.values.all)
corr.export <- ml.corr.values.all.merge
nUMIs <- Matrix::colSums(data.raw.cells[,colnames(corr.export)])
corr.export <- t(t(corr.export/SCALE.FACTOR) * nUMIs)
stopifnot(all(round(Matrix::colSums(corr.export)) == round(nUMIs)))
save(corr.export, file=dirout(out, "CorrectedData.RData"))
save(ml.rho.pred, data.raw.cells, meta.raw.cells, spikeIn.soups, file=dirout(out, "Uncorrected.Data.RData"))
# COMPARE ESTIMATED TO SPIKE IN TRUTH -------------------------------------------
# COMPARE ESTIMATED RHO
# Soup
meta.raw.spikes$contSoupX <- soupX.rho.agg[meta.raw.spikes$rn]
ggplot(meta.raw.spikes[!is.na(contamination)], aes(x=contSoupX, y=contamination, color=library_id)) + geom_point(alpha=0.5) +
theme_bw(12) + xlim(0,.7) + ylim(0,.7) + geom_abline(size=2, color="lightgrey", alpha=0.5) +
xlab("Contamination soupX") + ylab("Contamination cross-alignment") + guides(color=F)
ggsave(dirout(out, "Rho_estimation_SOUP.pdf"), height=4, width=4)
# machine learning
meta.raw.spikes$contMLCV <- ml.rho.cv[meta.raw.spikes$rn]
with(meta.raw.spikes, table(is.na(contMLCV), spikeIn))
ggplot(meta.raw.spikes[!is.na(contamination)], aes(x=contMLCV, y=contamination, color=library_id)) + geom_point(alpha=0.5) +
theme_bw(12) + xlim(0,.4) + ylim(0,.4) + geom_abline(size=2, color="lightgrey", alpha=0.5) +
xlab("Contamination spike-ins") + ylab("Contamination cross-alignment") + guides(color=F)
ggsave(dirout(out, "Rho_estimation_ML.pdf"), height=4, width=4)
# COMPARE ESTIMATED CONTAMINATION (SOUP)
stopifnot(all(round(colSums(spikeIn.soups.tpm)) == 1e6))
stopifnot(all(colSums(soupX.soup.tpm) == 1e6))
for(x in unique(meta.raw.spikes$library_id)){
qplot(spikeIn.soups.tpm[,paste0(x, " spikeIn")], soupX.soup.tpm[row.names(spikeIn.soups),x]) +
geom_abline(size=2, color="grey", alpha=0.5) + scale_x_log10() + scale_y_log10() + theme_bw(12) +
xlab("Signature spike-ins") + ylab("Signature soupX") +
annotate("text", x=10, y=10000, label=paste("R =", round(corS(spikeIn.soups.tpm[,paste0(x, " spikeIn")], soupX.soup.tpm[row.names(spikeIn.soups),x]),3)))
ggsave(dirout(out, "Soup_estimation_",x,".jpg"), height=4, width=4)
}
pdf(dirout(out, "Soup_estimation_Correlation.pdf"), width=11, height=10, onefile=F)
pheatmap(corS(cbind(spikeIn.soups.tpm, soupX.soup.tpm[row.names(spikeIn.soups),])),cluster_rows=F, cluster_cols=F);
dev.off()
# COMPARE CORRECTED VALUES
compare.values <- data.table()
for(dataType in c("original", "soupX", "spikeIns")){
for(orgXX in c("human", "mouse")){
datX <- data.tpm.spike;
if(dataType == "soupX") datX <- soupX.strainedCells.all;
if(dataType == "spikeIns") datX <- ml.corr.values.merge
spikeRef <- spike.clean.sameOrg; if(orgXX != "human") spikeRef <- spike.clean.diffOrg
# cor
corRes <- lapply(samples, function(x){
apply(as.matrix(datX[, meta.raw.spikes[library_id == x & spikeIn == orgXX]$rn]), 2, function(col) cor(col, spikeRef))
}); names(corRes) <- paste(samples, dataType, orgXX, sep="_")
compare.values <- rbind(compare.values, data.table(melt(corRes)))
}
}
compare.values <- cbind(compare.values, data.table(do.call(rbind, strsplit(compare.values$L1, "_"))))
ggplot(compare.values, aes(x=V3, y=value, color=V4)) + geom_boxplot() + facet_grid(V5 ~ V2, space="free_x", scale="free_x") +
theme_bw(12) + ylab("Correlation to reference") + xlab("Replicate") + xRot()
ggsave(dirout(out, "Values_compare.pdf"), height=4, width=8)
ggplot(compare.values[V4 != "soupX"], aes(x=V3, y=value, color=V4)) + geom_boxplot() + facet_grid(V5 ~ V2, space="free_x", scale="free_x") +
theme_bw(12) + guides(color=F) + ylab("Correlation to reference") + xlab("Replicate") +
scale_color_manual(values=c("black", "red")) + xRot()
ggsave(dirout(out, "Values_compare_NoSoupX.pdf"), height=4, width=8)
write.tsv(compare.values, file=dirout(out, "Values_compare.tsv"))
# Plots for individual comparisons
outValCompare <- paste0(out, "Values_compare/")
dir.create(dirout(outValCompare))
for(x in samples){
for(orgXX in c("human", "mouse")){
spikeRef <- spike.clean.sameOrg; if(orgXX != "human") spikeRef <- spike.clean.diffOrg
rn <- meta.raw.spikes[library_id == x & spikeIn == orgXX]$rn
pDat <- data.table(
Reference = spikeRef[row.names(data.tpm.spike)],
Corrected = Matrix::rowMeans(ml.corr.values.merge[row.names(data.tpm.spike), rn]),
Original = Matrix::rowMeans(data.tpm.spike[, rn]))
ggplot(pDat, aes(x=Reference, y=Original)) + geom_abline(size=2, color="lightgrey", alpha=0.5) +
geom_point(alpha=0.3) + geom_point(aes(y=Corrected), color="red", alpha=0.3) + theme_bw(12) +
ylab("Expression in spike-ins") +
annotate("text", x=2000, y=19000, label=paste("R =", round(cor(pDat$Reference, pDat$Original),3)), color="black") +
annotate("text", x=2000, y=21000, label=paste("R =", round(cor(pDat$Reference, pDat$Corrected),3)), color="red")
ggsave(dirout(outValCompare, "0_", orgXX, "_", x, ".jpg"), height=4, width=4)
ggsave(dirout(outValCompare, "0_", orgXX, "_", x, ".pdf"), height=4, width=4)
}}
gg <- gene.gcg
for(gg in cont.genes){
m <- meta.raw.spikes
pDat <- rbind (
data.table(m, Gene=soupX.strainedCells.all[gg,m$rn], type="soupX"),
data.table(m, Gene=ml.corr.values.merge[gg,m$rn], type="ML"),
data.table(m, Gene=data.tpm.spike[gg,m$rn],type="raw"))
ggplot(pDat, aes(x=library_id, y=Gene, color=type)) + geom_boxplot() + theme_bw(16) +
facet_grid(spikeIn ~ .) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) + ylab(gg)
ggsave(dirout(out, "GeneAfterCorr_",gg,".pdf"), height=8, width=9)
}
# CONTAMINATION FIGURES ---------------------------------------------------
# Cleaned data
pDat <- meta.raw.cells
plot.genes <- c('Ins1', cont.genes)
for(gg in plot.genes){
pDat[[paste0(gg, "_corrected")]] <- log(ml.corr.values.all.merge[gg,][pDat$rn] + 1)
pDat[[paste0(gg, "_raw")]] <- data.log.cells[gg,][pDat$rn]
}
write.tsv(pDat,dirout(out, "Cont.Genes.Data.tsv"))
pDat <- melt(pDat,id.vars="library_id", measure.vars=paste0(plot.genes, rep(c("_corrected", "_raw"), times=length(plot.genes))))
pDat <- cbind(pDat, do.call(rbind, strsplit(as.character(pDat$variable), "_")))
pDat$V2 <- factor(pDat$V2, levels=c("raw", "corrected"))
ggplot(pDat[V1 %in% c("Ins1", "Ins2", "Gcg")], aes(x=gsub(".+Islets\\_(.+)", "\\1", library_id),y=value, fill=V2)) +
geom_violin(color=NA) + theme_bw(12) + xlab("Replicate") + ylab("Log(TPM)") +
scale_fill_manual(values=c("black", "red")) +
facet_grid(. ~ V1) + guides(fill=F, color=F) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "Contamination_INSvsGCG.pdf"), height=4, width=8)
ggplot(pDat[V2 == "raw" & V1 %in% c("Ins1", "Ins2", "Gcg")], aes(x=gsub(".+Islets\\_(.+)", "\\1", library_id),y=value, fill=V2)) +
geom_violin(color=NA) + theme_bw(12) + xlab("Replicate") + ylab("Log(TPM)") +
scale_fill_manual(values=c("black", "red")) +
facet_grid(. ~ V1) + guides(fill=F, color=F)+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "Contamination_INSvsGCG_original.pdf"), height=4, width=6)
# SPIKE IN FIGURES --------------------------------------------------------
# HEATMAP
pDat <- cbind(
spike.clean.diffOrg[row.names(data.tpm.cells)],
spike.clean.sameOrg[row.names(data.tpm.cells)])
colnames(pDat) <- paste(gsub("^(.)", "\\U\\1", c(org.spikeIns, org.sample), perl=T), "reference")
for(x in samples){
for(orgX in c("mouse", "human")){
pDat <- cbind(pDat, Matrix::rowMeans(data.tpm.spike[,meta.raw.spikes[library_id == x & spikeIn == orgX]$rn]))
colnames(pDat)[ncol(pDat)] <- paste(gsub(".+Islets\\_(.+)", "\\1", x), orgX)
}
}
pDat <- log(pDat + 1)
pDat <- pDat[,apply(pDat, 2, function(col) !all(is.na(col)))]
x <- rowMeans(pDat[,!grepl("reference", colnames(pDat))]) - rowMeans(pDat[,grepl("reference", colnames(pDat))])
tail(sort(x))
head(sort(x))
n <- 20
pdf(dirout(out, "Contamination_vsSpikeIns_HM.pdf"), height=8, width=6, onefile=F)
pheatmap(pDat[c(names(head(sort(x), n)), names(tail(sort(x), n))),], cluster_rows=F)
dev.off()
# BOXPLOT
# pDat <- data.table()
# genes <- c(gene.ins, gene.gcg,"Iapp")
# for(orgX in c("human", "mouse")){
# for(gg in genes){
# pDat <- rbind(pDat, data.table(Gene = gg, Expression = spike.clean[gg,spike.clean.meta[org == orgX]$barcode], sample=paste(gsub("^(.)", "\\U\\1", orgX, perl=T), "reference")))}}
# for(x in samples){
# for(orgX in c("mouse", "human")){
# for(gg in genes){
# pDat <- rbind(pDat, data.table(Gene = gg, Expression = data.tpm.spike[gene.ins,meta.raw.spikes[library_id == x & spikeIn == orgX]$rn], sample=paste(gsub(".+Islets\\_(.+)\\_DMSO", "Rep \\1", x), orgX)))}}}
# pDat[,Expression := log(Expression + 1)]
# ggplot(pDat, aes(x=sample, y=Expression))+
# geom_boxplot(alpha=0.4) +
# #geom_violin(color="white", fill="lightblue") + geom_jitter(height=0, width=0.1, alpha=0.1) +
# theme_bw(12) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) + facet_grid(Gene ~ .) + xlab("")
# ggsave(dirout(out, "Contamination_vsSpikeIns_INS_Boxplot.pdf"), height=8, width=2.5)
#
# Contamination cross-alignment
ggplot(meta.raw.spikes[spikeIn == org.spikeIns], aes(x=gsub(".+Islets\\_(.+)", "\\1", library_id), y=contamination * 100)) + geom_boxplot() +
theme_bw(12) + xlab("Replicate") + ylab("Contamination (%)") + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5))
ggsave(dirout(out, "Contamination_CrossAlignment.pdf"), height=4, width=4)
for(x in unique(meta.raw.spikes$old_id)){
cont <- fread(dirout("06_SpikeIns_Islets/",x, "_hmG/Contamination.tsv"))
ggplot(cont, aes(x=inHuman, y=inMouse)) + geom_point(alpha=0.2) + theme_bw(16) +
scale_x_log10() + scale_y_log10() +
annotate("text", x=0.1, y=100, label=paste("R =", round(corS(cont$inHuman, cont$inMouse), 3))) +
xlab("Expression in cells") + ylab("Contamination in spike-ins")
ggsave(dirout(out, "Contamination_CrossAlignment_Correlation_",x,".pdf"), height=4, width=4)
ggsave(dirout(out, "Contamination_CrossAlignment_Correlation_",x,".jpg"), height=4, width=4)
pDat.org <- fread(dirout("06_SpikeIns_Islets/",x, "_hmG/IdentifyOrganism_full.tsv"))
max.reads <- max(c(pDat.org$rh, pDat.org$rm))
min.reads <- max(min(c(pDat.org$rh, pDat.org$rm)), 1)
(p <- ggplot(pDat.org, aes(x=rh, y=rm, color=org, size=nGene)) + geom_point(alpha=0.3) + geom_abline()+
scale_y_log10(limits=c(min.reads,max.reads)) + scale_x_log10(limits=c(min.reads,max.reads)) + xlab("Human reads") + ylab("Mouse reads") + theme_bw(12))
ggsave(dirout(out, "IdentifyOrganism_",x,".jpg"), height=4, width=5)
ggsave(dirout(out, "IdentifyOrganism2_",x,".jpg"), height=4, width=4, plot=p+guides(color=F, fill=F, size=F))
}
|
a6aa843b2b66341b4f69ff3396769b41cb10b075
|
[
"Markdown",
"R",
"Shell"
] | 56 |
R
|
epigen/Artemether_scRNA
|
32ad59d409649bb3b6139fa383c5ff4e3846e5ac
|
f92de6ed8ca25ff538633f6b79ac5a477e006b43
|
refs/heads/master
|
<file_sep>package hr.ferit.tumiljanovic.osnoverwima_lv1;
import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class DividerItemDecorator extends RecyclerView.ItemDecoration {
private final int verticalSpaceHeight;
public DividerItemDecorator(Context context) {
this.verticalSpaceHeight = (int) context.getResources().getDimension(R.dimen.divider_space_height) ;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount()) {
outRect.bottom = verticalSpaceHeight;
}
}
}
|
b7a1592a60c7ff46dc577a0690671f40788db66b
|
[
"Java"
] | 1 |
Java
|
TeaUmily/ORWIMA
|
133e02d5de32c2a238b38021198afe36679870a0
|
1194c714efed930b420d56b1dba099f6b5b5e41b
|
refs/heads/master
|
<file_sep>/**
初始化数据库OpenISA
*/
CREATE DATABASE IF NOT EXISTS `openisa` DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
use `openisa`;
SET foreign_key_checks=0;
/**
初始化用户表
*/
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`user_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`user_name` VARCHAR(32) NOT NULL COMMENT '用户名',
`password` VARCHAR(32) NOT NULL COMMENT '用户密码',
`age` TINYINT(4) UNSIGNED NULL DEFAULT NULL COMMENT '年龄',
`email` VARCHAR(64) NULL DEFAULT NULL COMMENT '电子邮箱',
`phone` VARCHAR(20) NULL DEFAULT NULL COMMENT '电话',
`create_time` DATETIME NOT NULL COMMENT '创建日期',
`modify_time` DATETIME NULL DEFAULT NULL COMMENT '修改日期',
PRIMARY KEY(`user_id`)
)ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COMMENT '用户信息表';
INSERT INTO `t_user` VALUES (1,'guoguo1','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (2,'guoguo2','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (3,'guoguo3','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (4,'guoguo4','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (5,'guoguo5','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (6,'guoguo6','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (7,'guoguo7','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (8,'guoguo8','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (9,'guoguo9','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (10,'guoguo10','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (11,'guoguo11','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (12,'guoguo12','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (13,'guoguo13','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (14,'guoguo14','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (15,'guoguo15','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (16,'guoguo16','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (17,'guoguo17','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (18,'guoguo18','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (19,'guoguo19','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
INSERT INTO `t_user` VALUES (20,'guoguo20','guoguo', 28, '<EMAIL>', 'wtf2019', '2019-06-06 12:00:00', NULL);
/**
初始化角色表
*/
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
`role_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '角色ID',
`role_name` VARCHAR(32) NOT NULL COMMENT '角色名',
`desc` VARCHAR(127) NULL DEFAULT NULL COMMENT '角色描述',
PRIMARY KEY(`role_id`)
)ENGINE=InnoDB DEFAULT CHARSET utf8 COMMENT '角色信息表';
INSERT INTO `t_role` VALUES (1, '超级管理员', '超级管理员');
INSERT INTO `t_role` VALUES (2, '系统管理员', '系统管理员');
INSERT INTO `t_role` VALUES (3, '权限管理员', '权限管理员');
INSERT INTO `t_role` VALUES (4, '运维管理员', '运维管理员');
/**
初始化权限表
*/
DROP TABLE IF EXISTS `t_authority`;
CREATE TABLE `t_authority` (
`auth_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '权限ID',
`auth_name` VARCHAR(32) NOT NULL COMMENT '权限名称',
`desc` VARCHAR(127) NULL DEFAULT NULL COMMENT '权限描述',
PRIMARY KEY(`auth_id`)
)ENGINE=InnoDB DEFAULT CHARSET utf8 COMMENT '权限信息表';
INSERT INTO `t_authority` VALUES (1, '界面查看', '界面查看');
INSERT INTO `t_authority` VALUES (2, '系统配置', '系统运维管理');
INSERT INTO `t_authority` VALUES (3, '数据库管理', '数据库管理');
/**
初始化用户角色关系表
*/
DROP TABLE IF EXISTS `t_user_role`;
CREATE TABLE `t_user_role` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT(11) UNSIGNED NOT NULL,
`role_id` INT(11) UNSIGNED NOT NULL,
PRIMARY KEY(`id`),
KEY `fk_user_role_user`(`user_id`),
KEY `fk_user_role_role`(`role_id`),
CONSTRAINT `fk_user_role_user` FOREIGN kEY(`user_id`) REFERENCES `t_user`(`user_id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_user_role_role` FOREIGN kEY(`role_id`) REFERENCES `t_role`(`role_id`) ON DELETE NO ACTION ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET utf8 COMMENT '用户角色关系表';
INSERT INTO `t_user_role` VALUES (1, 1, 1);
INSERT INTO `t_user_role` VALUES (2, 2, 2);
INSERT INTO `t_user_role` VALUES (3, 3, 3);
INSERT INTO `t_user_role` VALUES (4, 4, 4);
INSERT INTO `t_user_role` VALUES (5, 5, 4);
INSERT INTO `t_user_role` VALUES (6, 6, 1);
INSERT INTO `t_user_role` VALUES (7, 7, 1);
INSERT INTO `t_user_role` VALUES (8, 8, 3);
INSERT INTO `t_user_role` VALUES (9, 9, 2);
INSERT INTO `t_user_role` VALUES (10, 10, 3);
INSERT INTO `t_user_role` VALUES (11, 11, 1);
/**
初始化角色权限表
*/
DROP TABLE IF EXISTS `t_role_auth`;
CREATE TABLE `t_role_auth` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`role_id` INT(11) UNSIGNED NOT NULL,
`auth_id` INT(11) UNSIGNED NOT NULL,
PRIMARY KEY(`id`),
KEY `fk_role_auth_role`(`role_id`),
KEY `fk_role_auth_auth`(`auth_id`),
CONSTRAINT `fk_role_auth_role` FOREIGN KEY(`role_id`) REFERENCES `t_role`(`role_id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_role_auth_auth` FOREIGN KEY(`auth_id`) REFERENCES `t_authority`(`auth_id`) ON DELETE NO ACTION ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET utf8 COMMENT '角色权限关系表';
INSERT INTO `t_role_auth` VALUES (1, 1, 2);
INSERT INTO `t_role_auth` VALUES (2, 2, 2);
INSERT INTO `t_role_auth` VALUES (3, 3, 1);
INSERT INTO `t_role_auth` VALUES (4, 4, 3);
SET foreign_key_checks=1;
<file_sep>/**
*
*/
package review.thread;
import java.util.concurrent.locks.Lock;
/**
* @author guoguo
* @version 创建时间: 2019年5月8日 上午11:45:54
* 类说明
*/
/**
* @author dell
*
*/
public class MultiThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void sayHello() {
}
public class ThreadTest extends Thread {
}
}
<file_sep>/**
* @Title: ThreadPoolTest.java
* @Package: review.thread
* @Description: TODO
*
*/
package review.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author Leslie
* @version 创建时间:2019年5月30日
*
*/
public class ThreadPoolTest {
public void start() {
ThreadPoolExecutor exe = new ThreadPoolExecutor(5, 10, 100, TimeUnit.MICROSECONDS,
new ArrayBlockingQueue<Runnable>(5), new ThreadPoolExecutor.AbortPolicy());
ExecutorService service = Executors.newFixedThreadPool(10);
for(int i = 0; i < 20; i++) {
Task task = new Task(i);
exe.execute(task);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("线程池中线程数目:" + exe.getPoolSize() + ", 队列中等待执行任务数目:" +
exe.getQueue().size() + ", 已执行完的任务数目:" + exe.getCompletedTaskCount());
}
exe.shutdown();
}
public class Task implements Runnable {
private int taskId;
public Task(int id) {
this.taskId = id;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("正在执行任务:" + taskId);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("执行任务" + taskId + "完成");
}
}
/**
* @author: Leslie
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadPoolTest tp = new ThreadPoolTest();
tp.start();
}
}
<file_sep>/**
* @Title: Father.java
* @Package: review.oop
* @Description: TODO
*
*/
package review.oop;
/**
* @author Leslie
* @version 创建时间:2019年5月23日
*
*/
public class Father extends AbstractAncestor{
private String name;
private int age;
public Father(String name, int age) {
System.out.println("I'm " + name + " ," + age);
this.name = name;
this.age = age;
}
public void say() {
System.out.println("I'm " + name + " , your father, call me daddy!");
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @author: Leslie
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void happy() {
// TODO Auto-generated method stub
System.out.println("I'm your Father. I'm so happy");
}
}
<file_sep>我的妈啊
这TMD也行
<file_sep>/**
* @Title: GrandChild.java
* @Package: review.oop
* @Description: TODO
*
*/
package review.oop;
/**
* @author Leslie
* @version 创建时间:2019年5月23日
*
*/
public class GrandChild extends Child{
public GrandChild(String name, int age) {
super(name, age);
}
public void say() {
System.out.println("What are you fucking saying dad, He's my grandfather");
}
/**
* @author: Leslie
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
<file_sep># Spring4All
Spring Boot/Cloud demo
<file_sep>/**
* @Title: HibernateTest.java
* @Package: review.database
* @Description: TODO
*
*/
package review.database;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
/**
* @author Leslie
* @version 创建时间:2019年6月12日
*
*/
public class HibernateTest {
/**
* @author: Leslie
* @param args
*/
@Test
public void hibernateTest() {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User user = new User("hibernate1", "hibernate123", "2019-06-12 17:00:00");
Role role = new Role("hibernate", "desc");
session.save(user);
session.save(role);
transaction.commit();
session.close();
}
}
<file_sep>/**
* @Title: RedisTest.java
* @Package: review.nosql
* @Description: TODO
*
*/
package review.nosql;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* @author Leslie
* @version 创建时间:2019年6月26日
*
*/
public class RedisTest {
@Test
public void redis() {
Jedis jedis = new Jedis("192.168.76.100");
//System.out.println(jedis.configGet("*"));
System.out.println(jedis.hgetAll("user"));
jedis.close();
}
@Test
public void jedisPool() {
JedisPoolConfig jpc = new JedisPoolConfig();
//最大闲置个数
jpc.setMaxIdle(30);
//最小闲置个数
jpc.setMinIdle(10);
//最大连接数
jpc.setMaxTotal(100);
//创建连接池
JedisPool jedisPool = new JedisPool(jpc, "192.168.76.100");
Jedis jedis = jedisPool.getResource();
System.out.println(jedis.hgetAll("user"));
jedisPool.close();
}
}
<file_sep>/**
* @Title: Sort.java
* @Package: review.algorithm
* @Description: TODO
*
*/
package review.algorithm;
/**
* @author Leslie
* @version 创建时间:2019年6月19日
*
*/
public class Sort {
}
<file_sep>/**
* @Title: DataStructure.java
* @Package: review
* @Description: TODO
*
*/
package review.datastructure;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;
import java.util.Vector;
/**
* @author Leslie
* @version 创建时间:2019年5月23日
*
*/
public class DataStructure {
private enum Color {
RED("红"),GREEN("绿"),BLUE("蓝");
private final String color;
private Color(String color) {
this.color = color;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
};
public static void vecTest() {
Vector<String> vector = new Vector<String>();
for(int i = 0; i < 10; i++) {
vector.add("0^0 " + i + ",");
}
Enumeration<String> colors = vector.elements();
while(colors.hasMoreElements()) {
System.out.print(colors.nextElement());
}
}
public static void stackTest() {
Stack<String> stack = new Stack<String>();
stack.push("Holdooor");
stack.push("Brannnn");
stack.push("youKnowNothing");
stack.add("Johnnnn");
System.out.println(stack.peek());
for(String str : stack) {
System.out.println(str);
}
int size = stack.size();
//这里直接用stack.size()进行循环则不对
for(int i = 0; i < size; i++) {
System.out.print(stack.pop() + "$");
}
}
public static void listTest() {
//ArrayList<Integer> list = new ArrayList<Integer>();
LinkedList<Integer> list = new LinkedList<Integer>();
for(int i = 0; i < 10000000; i++) {
list.add(i);
}
long sum = 0;
long timeStart = System.currentTimeMillis();
// for(int i = 0; i < list.size(); i++) {
// sum += list.get(i);
// }
// for(Integer i : list) {
// sum += i;
// }
Iterator<Integer> iter = list.iterator();
while(iter.hasNext()) {
sum += iter.next();
}
System.out.println(sum);
long timeEnd = System.currentTimeMillis();
System.out.println("List take " + (timeEnd-timeStart) + "ms");
}
public static void setTest() {
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < 10000000; i++) {
set.add(i);
}
long sum = 0;
long timeStart = System.currentTimeMillis();
for(Integer i : set) {
sum += i;
}
// Iterator<Integer> iter = set.iterator();
// while(iter.hasNext()) {
// sum += iter.next();
// }
System.out.println(sum);
long timeEnd = System.currentTimeMillis();
System.out.println("Set take " + (timeEnd-timeStart) + "ms");
}
public static void mapTest() {
HashMap<String, String> map = new HashMap<String, String>();
for(int i = 0; i < 10000000; i++) {
map.put(String.valueOf(i), "wooow");
}
long timeStart = System.currentTimeMillis();
long sum = 0;
// Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
// while(it.hasNext()) {
// Map.Entry<String, String> entry = it.next();
// String key = entry.getKey();
// String value = entry.getValue();
// System.out.println(key + " = " + value);
//
// }
// Iterator<String> itKey = map.keySet().iterator();
// while(itKey.hasNext()) {
// String key = itKey.next();
// String value = map.get(key);
// System.out.println(key + " = " + value);
// }
for(Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}
System.out.println(sum);
long timeEnd = System.currentTimeMillis();
System.out.println("Map take " + (timeEnd - timeStart) + "ms");
}
/**
* @author: Leslie
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
vecTest();
for(int i = 0; i < Color.values().length; i++) {
System.out.println(Color.values()[i].getColor());
}
// stackTest();
// listTest();
// setTest();
mapTest();
}
}
<file_sep>/**
* @Title: SocketTest.java
* @Package: review.network
* @Description: TODO
*
*/
package review.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import org.junit.Test;
/**
* @author Leslie
* @version 创建时间:2019年6月17日
*
*/
public class SocketTest {
public void init() {
Server server = new Server(9999);
server.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Client client = new Client("127.0.0.1", 9999);
new Thread(client).start();
}
@Test
public void socketTest() {
new SocketTest().init();
}
private class Server extends Thread {
private String name = "服务器";
private int port = 9999;
public Server(int port) {
this.port = port;
}
@Override
public void run() {
try {
ServerSocket server = new ServerSocket(port);
System.out.println("Server " + name + " is Listening on port:" + port);
Socket socket = server.accept();
System.out.println("Connection is established!");
InputStream inputStream = socket.getInputStream();
OutputStream outStream = socket.getOutputStream();
byte[] buff = new byte[1024];
int len;
StringBuilder strBuilder = new StringBuilder();
while((len = inputStream.read(buff)) > 0) {
strBuilder.append(new String(buff, 0, len, "UTF-8"));
}
System.out.println("Server " + name + " get a message from client: " + strBuilder);
outStream.write("Ok! Client I get the message.".getBytes("UTF-8"));
inputStream.close();
outStream.close();
socket.close();
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class Client implements Runnable {
private String name = "客户端";
private String host = "127.0.0.1";
private int port = 9999;
public Client(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
Socket socket = new Socket(host, port);
System.out.println("Hello! Server I'm " + name);
OutputStream outStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
// Scanner scanner = new Scanner(System.in);
// while(scanner.hasNextLine()) {
// String message = scanner.nextLine();
// if(message.equalsIgnoreCase("quit")) {
// System.out.println("I give you some message");
// break;
// } else {
// outStream.write(message.getBytes("UTF-8"));
// }
// }
String message = "fjoajvajjaljff乖乖adlf";
outStream.write(message.getBytes("UTF-8"));
System.out.println("I give you some message: " + message);
socket.shutdownOutput();
byte[] buff = new byte[1024];
int len;
StringBuilder strBuilder = new StringBuilder();
while((len = inputStream.read(buff)) > 0) {
strBuilder.append(new String(buff, 0, len, "UTF-8"));
}
System.out.println("I get message from server:" + strBuilder);
inputStream.close();
outStream.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<file_sep>/**
* @Title: WebService.java
* @Package: review
* @Description: TODO
*
*/
package review.web;
/**
* @author Leslie
* @version 创建时间:2019年5月8日
*
*/
public class WebService {
/**
*
*/
public WebService() {
// TODO Auto-generated constructor stub
}
/**
* @author: Leslie
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* @author: Leslie
* @return
*/
public String getName() {
return "name";
}
}
<file_sep># FluentMark
<h>Java Thread 详解<h>
<file_sep>package review;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author Leslie
* @version 创建时间:2019年5月8日
*
*/
public class JavaReview {
/**
* strTest
*/
private static String strTest = "Hello, Leslie";
private static Logger logger = LogManager.getLogger(JavaReview.class);
/**
* @author: Leslie
* @param args
* @throws Throwable
*/
public static void main(String[] args) throws Throwable {
// TODO Auto-generated method stub
Character ch = '5';
System.out.println(Character.isDigit(ch));
System.out.println(new SimpleDateFormat("yyyy.MM.dd hh:mm:ss").format(new Date(1234567891234L)));
Pattern pattern = Pattern.compile(".*llo(.*?)Leslie");
Matcher matcher = pattern.matcher(strTest);
if(matcher.find()) {
System.out.println(matcher.groupCount());
System.out.print("find " + matcher.group(1) + "\n");
} else {
System.out.println("Nothing");
}
JavaReview review = new JavaReview();
Inner inner1 = review.new Inner(1);
Inner inner2 = review.getInner(2);
inner1 = null;
inner2.finalize();
System.gc();
/*review.conlInput();
for(int i = 0; i < 1024*1024; i++) {
logger.trace("I'm trace");
logger.debug("I'm debug");
logger.info("I'm info");
logger.warn("I'm warn");
logger.error("I'm error");
logger.fatal("I'm fatal");
Thread.sleep(10);
}*/
}
public void conlInput() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true) {
try {
char c = (char)br.read();
System.out.print(c);
if(c == 'q')
break;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Inner getInner(int n) {
return new Inner(n);
}
public class Inner {
private int id;
public Inner(int n) {
id = n;
System.out.println("inner " + id);
}
protected void finalize() throws Throwable {
super.finalize();
System.out.println("Inner " + id + " is disposed");
}
}
}
|
9b98cd7a894c2a5794c1fd49d31b013f16fc85fb
|
[
"Java",
"SQL",
"Markdown",
"INI"
] | 15 |
SQL
|
CechrGG/Spring4All
|
96ca8cdd10140d73a0e23fb7cd91663b74835f62
|
27049d315c4c6a642681ea1a8963107d6cc75a93
|
refs/heads/master
|
<repo_name>gpibarra/UNLaM_SOA_TP_Arduino<file_sep>/InterfaceWifi.h
#ifndef __INTERFACEWIFI_H__
#define __INTERFACEWIFI_H__
#include <Arduino.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
#endif
#define MAX_CLIENTES_UDP 4
class InterfaceWifi {
public:
WiFiEspUDP* sktUDPDatos;
WiFiEspUDP* serverUDPConexion;
WiFiEspUDP* sktUDPClienteEnviaComandos;
private:
int intEstado=0; //0 Stop, 1 Config, 2 Automatico, 3 Manual
int intEstadoAnterior=0;
private:
struct ClienteConectado {
IPAddress ip;
bool blActivo;
unsigned int intKeepAlive;
char strClave[8];
};
public:
int status = WL_IDLE_STATUS; // the Wifi radio's status
ClienteConectado arrClientesConectados[MAX_CLIENTES_UDP];
private:
String myMacAddress="";
int intCantClienteUDP=0;
int intPosProxClienteUDPDisponible=0;
void buscarProxPosClienteUDPDisponible();
unsigned int puertoDatos;
unsigned int puertoServidorUDPConexion;
unsigned int puertoClienteUDPComandos;
unsigned long timeoutCheckKeepAlive = 3000;
unsigned long lastCheckKeepAlive = millis();
int maxRetryCheckKeepAlive = 10;
unsigned long timeoutViewState = 30000;
unsigned long lastViewState = millis();
public:
InterfaceWifi();
public:
void init(HardwareSerial *espSerial,unsigned int intVelWifi);
#ifndef HAVE_HWSERIAL1
void init(SoftwareSerial *espSerial,unsigned int intVelWifi);
#endif
private: void init();
public:
void connect(char* ssid, const char *passphrase);
void iniciarPuertoDatos(unsigned int puertoCliente);
void iniciarServidorUDPConexion(unsigned int puertoCliente);
void iniciarPuertoUDPEnvio(unsigned int puertoCliente);
void printWifiStatus();
void listNetworks();
private:
void printEncryptionType(int thisType);
String getStringMacAddress();
public:
void recibirConexionesNuevas();
void buscarConexionesCaidas();
void enviarTodosUDPClientes(String data);
void enviarUDPCliente(String data, IPAddress ip);
int getCantClientes();
void imprimirEstado();
String getModeString();
int setModeAutomaticRadar();
int setModeManualRadar();
void setStartRadar();
void setStopRadar();
bool isModeAutomaticRadar();
bool isModeManualRadar();
bool isStartedRadar();
bool isConfiguringRadar();
void setTimeoutCheckKeepAlive(unsigned long t);
void setMaxRetryKeepAlive(int m);
void setTimeouViewState(unsigned long t);
private:
void recibirUDP();
void responderServicio(String data);
void enviarUDP(String data, IPAddress ip, unsigned int port);
private:
int chequearClienteYaConectado(IPAddress ip);
void generarClaveCliente(ClienteConectado* cliente);
int chequearClaveCliente(String data, int intIni);
int chequearIPCliente(String data, int intIni, IPAddress ipCliente);
};
#endif /* #ifndef __INTERFACEWIFI_H__ */
<file_sep>/TPSOA.ino
#include <Servo.h>
#include <Ultrasonic.h>
#define HAVE_HWSERIAL1
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif
#include "InterfaceWifi.h"
/*
* Click in Sketch > Include Library > Manage Libraries...;
* In the search field type: ultrasonic;
* In the list, look for Ultrasonic by <NAME>;
* Click on Install.
* In the search field type: wifiesp;
* In the list, look for WiFiEsp by bportaluri;
* Click on Install.
*/
/*
* COMPONENTES
* Servo: SG90
* - GND (Marr�n), VCC (Rojo), SIG (Naranja)
* Servo 360: DS04-NFC
* - GND (Negro), VCC (Rojo), SIG (Blanco)
* UltraSonido: HC-SR04
* - GND, ECHO, TRIG, VCC
* Wifi: ESP8266
* - RX,-,-,GND,VCC(3.3v),CH_PD(3.3v),TX
* LCD: DFR0009
*
* Wifi
* http://www.prometec.net/arduino-wifi/
* Ultrasonido
* http://elcajondeardu.blogspot.com.ar/2014/03/tutorial-sensor-ultrasonidos-hc-sr04.html
*/
/*
* Serial velocidades comunes: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200
* 110, 300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600, 1843200, 3686400
*/
Servo *objServo;
Ultrasonic *objUltrasonic[4];
unsigned long intVelSerial = 115200;
unsigned long intDlyCiclo = 25; //Delay entre ciclo y ciclo
unsigned long intCicloEnvios = 0;
unsigned long intDlyCiclosEnvios = 2; //Ciclos solo responde ping y comandos por cada movimiento del sensor
unsigned long timeoutCheckKeepAlive = 3000;
int maxRetryCheckKeepAlive = 12;
unsigned long timeoutViewState = 3000;
int intCantSens = 2;
int blIsMotor360 = false;
int intPaso = 3;
int intSentido;
int intAnguloMax;
int intPos[4];
int intNumPinServo;
int intNumPinUltrasonidoInput[4];
int intNumPinUltrasonidoOutput[4];
unsigned long ulngTimeoutUltrasonido = 4000;
float fltValorDist;
String strValores;
unsigned long intVelWifi = 115200;
//GI:Medrano
//char ssid[] = "D3-PidaPermiso"; // your network SSID (name)
//char pass[] = ""; // your network password
//GI:Paso
//char ssid[] = "Fidel"; // your network SSID (name)
//char pass[] = "<PASSWORD>"; // your network password
//GI:Cervantes
//char ssid[] = "IBARRA"; // your network SSID (name)
//char pass[] = "<PASSWORD>"; // your network password
//HS:HJulian
//char ssid[] = "claro"; // your network SSID (name)
//char pass[] = "<PASSWORD>"; // your network password
//LAB
char ssid[] = "SOa-IoT-N750"; // your network SSID (name)
char pass[] = "<PASSWORD>"; // your network password
bool blTestStopRadar=false;
bool blTestValues=false;
bool blTestWifiServer=true;
bool blTestUDP=false;
bool blTestPoolUDP=true;
bool blTestSerial=false;
IPAddress ipTestUDP=IPAddress(0,0,0,0);
//IPAddress ipTestUDP=IPAddress(192,168,0,28);
//IPAddress ipTestUDP=IPAddress(192,168,100,103);
//IPAddress ipTestUDP=IPAddress(192,168,0,16);
//GI:Medrano:PC
//IPAddress ipTestUDP=IPAddress(192,168,0,23);
//GI:Cervantes:G3
//IPAddress ipTestUDP=IPAddress(192,168,1,149);
//GI:Cervantes:PC
//IPAddress ipTestUDP=IPAddress(192,168,1,113);
//HG:HJulian:Sms
//IPAddress ipTestUDP=IPAddress(192,168,100,100);
//HG:HJulian:PC
//IPAddress ipTestUDP=IPAddress(192,168,100,102);
unsigned int puertoDatos = 5416; //Puerto local/remoto para enviar datos a los clientes (UDP)
unsigned int puertoServidorRecibeComandos = 5417; //Puerto local del servidor que responde para que el cliente descubra dispositivos y chequear desconexiones (UDP)
unsigned int puertoClienteEnviaComandos = 5418; //Puerto local del servidor que que envia al cliente (UDP)
InterfaceWifi objWifi;
/********************************************************************************************/
void setup() {
//intEstado = 1;
// initialize serial for debugging
Serial.begin(intVelSerial);
Serial.println("SETUP INI");
//PINES
//Motor
intNumPinServo = 46;
//Ultrasonidos Trig
intNumPinUltrasonidoInput[0]=40;
intNumPinUltrasonidoInput[1]=32;
intNumPinUltrasonidoInput[2]=30;
intNumPinUltrasonidoInput[3]=28;
//Ultrasonidos Echo
intNumPinUltrasonidoOutput[0]=41;
intNumPinUltrasonidoOutput[1]=33;
intNumPinUltrasonidoOutput[2]=31;
intNumPinUltrasonidoOutput[3]=29;
//Init
initSetupPre();
//Check
String strErrorCheck=checkSetup();
if(strErrorCheck != "") {
Serial.println(strErrorCheck);
exit(1);
}
//Init objects
initSetupPost();
Serial.println("SETUP FIN");
objWifi.setStartRadar();
//exit(1);
}
/********************************************************************************************/
/********************************************************************************************/
/********************************************************************************************/
void loop() {
//exit(1);
//Por cada ultrasonidos
if (!objWifi.isConfiguringRadar()) {
if (objWifi.isModeAutomaticRadar()) {
if (intCicloEnvios%intDlyCiclosEnvios==0) {
//Automatico
intCicloEnvios=0;
if (intSentido == 0) {
intSentido = -1;
}
for (int i=0; i<intCantSens; i++) {
fltValorDist = leerSensor(i);
enviarDatoSensor(i,fltValorDist);
}
//Sentido de giro (unico sentido todos los ultrasonidos)
int tmpPos = intPos[0]+(intSentido*intPaso);
if (tmpPos < 0 || tmpPos > intAnguloMax) {
intSentido = intSentido*-1;
}
for (int i=0; i<intCantSens; i++) {
intPos[i]+=(intSentido*intPaso);
}
//Mueve servo (unico servo todos los ultrasonidos)
if (!blTestStopRadar) {
objServo->write(intPos[0]);
}
digitalWrite(13, HIGH);
}
}
else if (objWifi.isModeManualRadar()) {
//Manual
if (intCicloEnvios%intDlyCiclosEnvios==0) {
intCicloEnvios=0;
digitalWrite(13, HIGH);
}
}
else if (!objWifi.isStartedRadar()) {
if (intCicloEnvios%(intDlyCiclosEnvios*2)==0) {
//Stop
for (int i=0; i<intCantSens; i++) {
enviarDatoSensor(i,-1);
}
digitalWrite(13, LOW);
}
}
intCicloEnvios++;
objWifi.imprimirEstado();
//Responde servicio de discover y configuracion
if(blTestWifiServer) {
objWifi.recibirConexionesNuevas();
}
delay(intDlyCiclo);
}
else {
//Config
}
}
/********************************************************************************************/
/********************************************************************************************/
/********************************************************************************************/
/********************************************************************************************/
float leerSensor(int intNumSensor) {
float fltValorDist;
if (!blTestValues) {
fltValorDist = objUltrasonic[intNumSensor]->distanceRead();
}
else {
fltValorDist = random(0,30);
}
return fltValorDist;
}
void enviarDatoSensor(int intNumSensor, float fltValorDist) {
String data;
if (objWifi.isStartedRadar()) {
data = ""+String(intNumSensor)+";"+String(intSentido)+";"+"1"+";"+String(intPos[intNumSensor])+";"+String(fltValorDist);
}
else {
data = "-1;0;0;-1;-1";
}
if(blTestSerial) {
Serial.println(data);
}
if(blTestPoolUDP) {
objWifi.enviarTodosUDPClientes(data);
}
if(blTestUDP) {
objWifi.enviarUDPCliente(data, ipTestUDP);
}
return;
}
/********************************************************************************************/
/********************************************************************************************/
/********************************************************************************************/
void initSetupPre() {
//Calcula Parametros
intSentido = 0;
intAnguloMax = (360/intCantSens)-1;
if (intCantSens==1 && !blIsMotor360) {
intAnguloMax = 180-1;
}
intPos[0] = 0;
if (intCantSens >= 2) {
intPos[1] = 180;
}
if (intCantSens == 4) {
intPos[2] = 90;
intPos[3] = 270;
}
return;
}
String checkSetup() {
if (intCantSens!=1 && intCantSens!=2 && intCantSens!=4) {
return "ERROR 1: CANTIDAD DE SENSORES";
}
if (((intAnguloMax+1)%intPaso)!=0) {
return "ERROR 2: PASO ERRONEO";
}
return "";
}
void initSetupPost() {
//LED 13
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
//SERVO
objServo = new Servo();
objServo->attach(intNumPinServo);
objServo->write(0);
//ULTRASONIDOS
for (int i=0; i<intCantSens; i++) {
objUltrasonic[i] = new Ultrasonic(intNumPinUltrasonidoInput[i],intNumPinUltrasonidoOutput[i],ulngTimeoutUltrasonido);
}
//WIFI
if (blTestWifiServer || blTestUDP) {
Serial1.begin(intVelWifi);
objWifi.init(&Serial1,intVelWifi);
//// scan for existing networks
//Serial.println("Scanning available networks...");
//objWifi.listNetworks();
// attempt to connect to WiFi network
Serial.println("Connect...");
objWifi.connect(ssid, pass);
Serial.println("Connected to wifi");
objWifi.printWifiStatus();
if (blTestWifiServer) {
objWifi.iniciarServidorUDPConexion(puertoServidorRecibeComandos);
objWifi.iniciarPuertoUDPEnvio(puertoDatos);
}
objWifi.iniciarPuertoDatos(puertoDatos);
}
objWifi.setTimeoutCheckKeepAlive(timeoutCheckKeepAlive);
objWifi.setMaxRetryKeepAlive(maxRetryCheckKeepAlive);
objWifi.setTimeouViewState(timeoutViewState);
//delay(3000);
}
<file_sep>/InterfaceWifi.cpp
#include "InterfaceWifi.h"
InterfaceWifi::InterfaceWifi() {
for (int i=0;i<MAX_CLIENTES_UDP;i++) {
this->arrClientesConectados[i].blActivo = false;
}
}
void InterfaceWifi::init(HardwareSerial *espSerial,unsigned int intVelWifi) {
// initialize serial for ESP module
//espSerial->begin(intVelWifi);
// initialize ESP module
WiFi.init(&Serial1);
WiFi.reset();
this->init();
}
#ifndef HAVE_HWSERIAL1
void init(SoftwareSerial *espSerial,unsigned int intVelWifi) {
// initialize serial for ESP module
//espSerial->begin(intVelWifi);
// initialize ESP module
WiFi.init(espSerial);
WiFi.reset();
this->init();
}
#endif
void InterfaceWifi::init() {
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
this->myMacAddress=this->getStringMacAddress();
}
void InterfaceWifi::connect(char* ssid, const char *passphrase) {
while ( this->status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
this->status = WiFi.begin(ssid, passphrase);
}
}
void InterfaceWifi::iniciarPuertoDatos(unsigned int puertoCliente) {
this->puertoDatos = puertoCliente;
Serial.println("Starting port UDP: "+String(puertoCliente));
this->sktUDPDatos = new WiFiEspUDP;
this->sktUDPDatos->begin(this->puertoClienteUDPComandos);
}
void InterfaceWifi::iniciarServidorUDPConexion(unsigned int puertoCliente) {
this->puertoServidorUDPConexion = puertoCliente;
Serial.println("Starting port server UDP: "+String(puertoCliente));
// if you get a connection, report back via serial:
this->serverUDPConexion = new WiFiEspUDP;
this->serverUDPConexion->begin(puertoCliente);
}
void InterfaceWifi::iniciarPuertoUDPEnvio(unsigned int puertoCliente) {
this->puertoClienteUDPComandos = puertoCliente;
Serial.println("Starting port aux UDP: "+String(puertoCliente));
}
void InterfaceWifi::buscarProxPosClienteUDPDisponible() {
if (this->intPosProxClienteUDPDisponible==-1 || this->arrClientesConectados[this->intPosProxClienteUDPDisponible].blActivo) {
int tmpIntProx = this->intPosProxClienteUDPDisponible + 1;
for(int i=0;i<MAX_CLIENTES_UDP;i++) {
if(tmpIntProx>=MAX_CLIENTES_UDP) {
tmpIntProx=0;
}
if (!this->arrClientesConectados[tmpIntProx].blActivo) {
this->intPosProxClienteUDPDisponible = tmpIntProx;
return;
}
tmpIntProx++;
}
this->intPosProxClienteUDPDisponible = -1;
return;
}
}
int InterfaceWifi::chequearClienteYaConectado(IPAddress ip) {
for(int i=0;i<MAX_CLIENTES_UDP;i++) {
if (this->arrClientesConectados[i].blActivo) {
if (this->arrClientesConectados[i].ip==ip) {
return i;
}
}
}
return -1;
}
void InterfaceWifi::recibirConexionesNuevas() {
this->buscarConexionesCaidas();
//UDP comando PING
this->recibirUDP();
}
void InterfaceWifi::recibirUDP() {
int lenPacket = 100;
char packetBuffer[lenPacket];
String data = "";
int len;
int packetSize = this->serverUDPConexion->parsePacket();
if (packetSize) {
len = this->serverUDPConexion->read(packetBuffer, lenPacket);
if (len > 0) {
packetBuffer[len] = 0;
String data(packetBuffer);
Serial.print("Se recibio UDP: ");
Serial.println(data);
Serial.print("Desde: ");
Serial.print(this->serverUDPConexion->remoteIP());
Serial.print(":");
Serial.print(this->serverUDPConexion->remotePort());
//Serial.print(this->serverUDPConexion->puertoServidorUDPConexion());
Serial.println();
this->responderServicio(data);
}
}
}
void InterfaceWifi::responderServicio(String data) {
if(data.startsWith("PING")) {
Serial.println("Cliente nuevo");
//this->enviarUDP("ACK;"+this->myMacAddress, this->serverUDPConexion->remoteIP(), this->serverUDPConexion->remotePort());
this->enviarUDP("ACK;"+this->myMacAddress, this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
return;
}
else if(data.startsWith("ACK")) {
int tmpIntID = chequearIPCliente(data,4,this->serverUDPConexion->remoteIP());//ACK:
if (tmpIntID>=0) {
this->arrClientesConectados[tmpIntID].intKeepAlive = 0;
}
}
else if(data.startsWith("CONNECT")) {
int tmpIntID;
bool blClienteReg=false;
int tmpIntIDConectado = this->chequearClienteYaConectado(this->serverUDPConexion->remoteIP());
if (tmpIntIDConectado>=0) {
blClienteReg=true;
}
else {
blClienteReg=false;
tmpIntID = this->intPosProxClienteUDPDisponible;
}
if (tmpIntID>=0) {
if (blClienteReg) {
tmpIntID = tmpIntIDConectado;
Serial.print("Cliente ya registrado: ");
Serial.println(tmpIntID);
}
else {
Serial.print("Cliente registrado: ");
Serial.println(tmpIntID);
this->intCantClienteUDP++;
}
this->arrClientesConectados[tmpIntID].ip = this->serverUDPConexion->remoteIP();
this->arrClientesConectados[tmpIntID].blActivo = true;
this->arrClientesConectados[tmpIntID].intKeepAlive = 0;
this->generarClaveCliente(&(this->arrClientesConectados[tmpIntID]));
this->buscarProxPosClienteUDPDisponible();
this->enviarUDP("OK;"+String(tmpIntID)+";"+String(this->arrClientesConectados[tmpIntID].strClave)+"", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
delay(10);
Serial.print("Cliente proximo disponible: ");
Serial.println(this->intPosProxClienteUDPDisponible);
return;
}
else {
Serial.println("No se pueden tomar nuevas conexiones, se descarta conexion");
this->enviarUDP("ERROR", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
return;
}
}
else if(data.startsWith("DISCONNECT")) {
//int tmpIntID = chequearClaveCliente(data,11);//DISCONNECT:
int tmpIntID = chequearIPCliente(data,11,this->serverUDPConexion->remoteIP());//DISCONNECT:
if (tmpIntID >=0) {
//Serial.println("CLAVE OK");
Serial.println("IP OK");
Serial.print("Cliente borrado: ");
Serial.println(tmpIntID);
this->arrClientesConectados[tmpIntID].ip = IPAddress(0,0,0,0);
this->arrClientesConectados[tmpIntID].blActivo = false;
this->arrClientesConectados[tmpIntID].intKeepAlive = 0;
this->buscarProxPosClienteUDPDisponible();
this->intCantClienteUDP--;
this->enviarUDP("OK;", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
Serial.print("Cliente proximo disponible: ");
Serial.println(this->intPosProxClienteUDPDisponible);
}
else if (tmpIntID ==-1) {
// Serial.println("CLAVE ERRONEA");
Serial.println("ID ERRONEO");
this->enviarUDP("ERROR", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
}
else if (tmpIntID ==-2) {
Serial.println("CLAVE MAL FORMADA");
this->enviarUDP("ERROR", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
}
else {
Serial.println("CLAVE ERROR DESCONOCIDO");
this->enviarUDP("ERROR", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
}
} else if(data.startsWith("START")) {
//int tmpIntID = chequearClaveCliente(data,6);//START:
int tmpIntID = chequearIPCliente(data,6,this->serverUDPConexion->remoteIP());//START:
if (tmpIntID >=0) {
//Serial.println("CLAVE OK");
Serial.println("IP OK");
Serial.print("Iniciando: ");
if (!this->isStartedRadar()) {
Serial.println("INICIADO OK");
this->enviarUDP("OK;", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
this->setStartRadar();
}
else {
Serial.println("ERROR-YA ESTA INICIADO");
this->enviarUDP("OK;YA ESTA INICIADO;", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
}
}
else {
Serial.println("ID ERRONEO/CLAVE MAL FORMADA");
this->enviarUDP("ERROR;ID ERRONEO", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
}
}
else if(data.startsWith("STOP")) {
//int tmpIntID = chequearClaveCliente(data,5);//STOP:
int tmpIntID = chequearIPCliente(data,5,this->serverUDPConexion->remoteIP());//STOP:
if (tmpIntID >=0) {
//Serial.println("CLAVE OK");
Serial.println("IP OK");
Serial.print("Deteniendo: ");
if (this->isStartedRadar()) {
Serial.println("DETENIDO OK");
this->enviarUDP("OK;", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
this->setStopRadar();
}
else {
Serial.println("ERROR-YA ESTA DETENIDO");
this->enviarUDP("OK;YA ESTA DETENIDO;", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
}
}
else {
Serial.println("ERROR-ID ERRONEO/CLAVE MAL FORMADA");
this->enviarUDP("ERROR;ID ERRONEO", this->serverUDPConexion->remoteIP(), this->puertoServidorUDPConexion);
}
}
else if(data.startsWith("TEST")) {
Serial.println("MANDANDO TEST");
this->enviarTodosUDPClientes("TEST");
}
return;
}
void InterfaceWifi::generarClaveCliente(ClienteConectado* cliente) {
int intCant = sizeof(cliente->strClave);
char charTmp;
randomSeed(millis());
for (int i=0; i<intCant; i++) {
//charTmp = random(48,90-7);
charTmp = random(48,122-7-6);
if (charTmp>=58) {
charTmp+=7;
}
if (charTmp>=91) {
charTmp+=6;
}
cliente->strClave[i] = charTmp;
}
cliente->strClave[intCant-1]='\0';
}
int InterfaceWifi::chequearClaveCliente(String data, int intIni) {
int intPos2=data.indexOf(';',intIni);
if (intPos2>=0 && data.length()>intIni && data.length()>intPos2+1) {
int tmpIntID = data.substring(intIni,intPos2).toInt();
return tmpIntID;
String strClave = data.substring(intPos2+1);
if (tmpIntID>=0 && tmpIntID<MAX_CLIENTES_UDP && strClave.compareTo(this->arrClientesConectados[tmpIntID].strClave)==0) {
return tmpIntID;
}
else {
return -1;
}
}
else {
return -2;
}
}
int InterfaceWifi::chequearIPCliente(String data, int intIni, IPAddress ipCliente) {
int intPos2=data.indexOf(';',intIni);
if (intPos2>=0 && data.length()>intIni && data.length()>intPos2) {
int tmpIntID = data.substring(intIni,intPos2).toInt();
//return tmpIntID;
if (tmpIntID>=0 && tmpIntID<MAX_CLIENTES_UDP && this->arrClientesConectados[tmpIntID].ip==ipCliente) {
return tmpIntID;
}
else {
return -1;
}
}
else {
return -2;
}
}
void InterfaceWifi::buscarConexionesCaidas() {
//Serial.print(".");
//return;
if ((millis() - this->lastCheckKeepAlive > this->timeoutCheckKeepAlive)) {
this->lastCheckKeepAlive = millis();
this->intCantClienteUDP = 0;
bool blDesactivo = false;
Serial.println("Buscando conexiones caidas...");
for (int i=0;i<MAX_CLIENTES_UDP;i++) {
if(this->arrClientesConectados[i].blActivo) {
//TODO
if(this->arrClientesConectados[i].intKeepAlive>this->maxRetryCheckKeepAlive) {
blDesactivo = true;
this->arrClientesConectados[i].ip = IPAddress(0,0,0,0);
this->arrClientesConectados[i].blActivo = false;
this->arrClientesConectados[i].intKeepAlive = 0;
Serial.print("POS: ");
Serial.print(i);
Serial.print(" -> ");
Serial.print("***");
Serial.println();
}
else {
this->arrClientesConectados[i].intKeepAlive++;
this->intCantClienteUDP++;
Serial.print("POS: ");
Serial.print(i);
Serial.print(" -> ");
Serial.print(this->arrClientesConectados[i].ip);
Serial.print(" (");
Serial.print(this->arrClientesConectados[i].intKeepAlive-1);
Serial.print(")");
Serial.println();
}
}
else {
Serial.print("POS: ");
Serial.print(i);
Serial.print(" -> ");
Serial.println();
}
}
if (blDesactivo) {
this->buscarProxPosClienteUDPDisponible();
}
Serial.print("Cliente proximo disponible: ");
Serial.println(this->intPosProxClienteUDPDisponible);
Serial.print("Conexiones activas: ");
Serial.println(this->intCantClienteUDP);
}
}
int InterfaceWifi::getCantClientes() {
return this->intCantClienteUDP;
}
void InterfaceWifi::enviarTodosUDPClientes(String data) {
for (int i=0;i<MAX_CLIENTES_UDP;i++) {
if (this->arrClientesConectados[i].blActivo) {
this->enviarUDPCliente(data,this->arrClientesConectados[i].ip);
}
}
}
void InterfaceWifi::enviarUDPCliente(String data, IPAddress ip) {
//Despacha los ping pendientes, sino los pierde
this->recibirUDP();
//Envia la info
this->enviarUDP(data,ip,this->puertoClienteUDPComandos);
}
void InterfaceWifi::enviarUDP(String data, IPAddress ip, unsigned int port) {
this->sktUDPDatos->beginPacket(ip, port);
this->sktUDPDatos->write(data.c_str());
this->sktUDPDatos->endPacket();
}
void InterfaceWifi::imprimirEstado() {
if ((millis() - this->lastViewState > this->timeoutViewState)) {
this->lastViewState = millis();
Serial.print("Estado actual: ");
if (this->isStartedRadar()) {
Serial.print(this->intEstado-1);
}
else {
Serial.print("0");
}
Serial.print(" (0=stop;1=automatico;2=manual)");
Serial.println();
Serial.print("Cantidad clientes activos: ");
Serial.print(this->getCantClientes());
Serial.println();
return;
Serial.print("Clientes activos: ");
for (int i=0;i<MAX_CLIENTES_UDP;i++) {
if (this->arrClientesConectados[i].blActivo) {
Serial.print(this->arrClientesConectados[i].ip);
Serial.print(",");
}
}
Serial.println();
}
}
String InterfaceWifi::getModeString() {
if(this->intEstado==3) {
return "2";
}
else if(this->intEstado==2) {
return "2";
}
else {
return "1";
}
}
int InterfaceWifi::setModeAutomaticRadar() {
if(this->intEstado==3) {
this->intEstado=2;
return 0;
}
return -1;
}
int InterfaceWifi::setModeManualRadar() {
if(this->intEstado==2) {
this->intEstado=3;
return 0;
}
return -1;
}
void InterfaceWifi::setStartRadar() {
if (intEstado==0) {
if (this->intEstadoAnterior==0) {
this->intEstado = 2;
}
else {
this->intEstado = this->intEstadoAnterior;
}
this->intEstadoAnterior = 0;
}
}
void InterfaceWifi::setStopRadar() {
if (intEstado>=2) {
this->intEstadoAnterior = this->intEstado;
this->intEstado = 0;
}
}
bool InterfaceWifi::isModeAutomaticRadar(){
return this->intEstado==2;
}
bool InterfaceWifi::isModeManualRadar(){
return this->intEstado==3;
}
bool InterfaceWifi::isStartedRadar() {
return this->intEstado>1;
}
bool InterfaceWifi::isConfiguringRadar() {
return this->intEstado==1;
}
void InterfaceWifi::setTimeoutCheckKeepAlive(unsigned long t) {
this->timeoutCheckKeepAlive = t;
this->lastCheckKeepAlive = millis();
}
void InterfaceWifi::setMaxRetryKeepAlive(int m) {
this->maxRetryCheckKeepAlive=m;
}
void InterfaceWifi::setTimeouViewState(unsigned long t) {
this->timeoutViewState = t;
this->lastViewState = millis();
}
void InterfaceWifi::printWifiStatus() {
// print your WiFi shield's IP address:
Serial.print("MAC Address: ");
Serial.println(this->myMacAddress);
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
void InterfaceWifi::listNetworks() {
// scan for nearby networks
int numSsid = WiFi.scanNetworks();
if (numSsid == -1) {
Serial.println("Couldn't get a wifi connection");
while (true);
}
// print the list of networks seen
Serial.print("Number of available networks:");
Serial.println(numSsid);
// print the network number and name for each network found
for (int thisNet = 0; thisNet < numSsid; thisNet++) {
Serial.print(thisNet);
Serial.print(") ");
Serial.print(WiFi.SSID(thisNet));
Serial.print("\tSignal: ");
Serial.print(WiFi.RSSI(thisNet));
Serial.print(" dBm");
Serial.print("\tEncryption: ");
printEncryptionType(WiFi.encryptionType(thisNet));
}
}
void InterfaceWifi::printEncryptionType(int thisType) {
// read the encryption type and print out the name
switch (thisType) {
case ENC_TYPE_WEP:
Serial.print("WEP");
break;
case ENC_TYPE_WPA_PSK:
Serial.print("WPA_PSK");
break;
case ENC_TYPE_WPA2_PSK:
Serial.print("WPA2_PSK");
break;
case ENC_TYPE_WPA_WPA2_PSK:
Serial.print("WPA_WPA2_PSK");
break;
case ENC_TYPE_NONE:
Serial.print("None");
break;
}
Serial.println();
}
String InterfaceWifi::getStringMacAddress() {
char mac[25];
uint8_t* macInt=new uint8_t[WL_MAC_ADDR_LENGTH];
WiFi.macAddress(macInt);
sprintf(mac,"%x\:%x\:%x\:%x\:%x\:%x",macInt[5],macInt[4],macInt[3],macInt[2],macInt[1],macInt[0]);
return String(mac);
}
|
c669362a4fa4a0af765024ae1e05218021c4605a
|
[
"C++"
] | 3 |
C++
|
gpibarra/UNLaM_SOA_TP_Arduino
|
ab7c97923f2c5468fe0e33759fb7690ed78808ac
|
66ddbb871f1f671c54a1cc7383e28c9df3cfc724
|
refs/heads/main
|
<repo_name>MarkoGlamocak/JavaFXCheckers<file_sep>/JavaFXCheckersGame/src/main/java/App.java
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
/**
* JavaFX App
*/
public class App extends Application {
private HashMap<String, Scene> sceneMap;
private GameBoardTile[][] gameBoardMatrix;
private Checker[][] checkerMatrix;
private int whichPlayer = 1;
private int lastPlayerToMove = 1;
private int[] checkerLocation;
private Checker lastChecker;
private boolean checkerIsSelected = false;
private boolean canMoveAgain = true;
private int numRed = 12;
private int numBlue = 12;
private PauseTransition pause;
private Timer timer;
private TimerTask timeTask;
// Welcome Scene Data Members
private Button singlePlayer;
private Button multiPlayer;
private Button howToPlay;
private Button exitButton1;
// Single Game Scene Data Members
private GridPane gameBoard;
private Label turnTracker;
private Button endTurn;
private Label timerLabel;
private Button startGameButton;
// How To Play Scene Data Members
private Button goBackButton;
// Result Scene Data Members
private Button exitButton2;
private Label resultLabel;
public static void main(String[] args) {
launch();
}
@Override
public void start(Stage stage) {
sceneMap = new HashMap<>();
sceneMap.put("welcome", welcomeScene());
sceneMap.put("single", singleGameScene());
sceneMap.put("howTo", howToPlayScene());
sceneMap.put("result", resultScene());
singlePlayer.setOnAction(e -> stage.setScene(sceneMap.get("single")));
timer = new Timer();
timeTask = new TimerTask() {
@Override
public void run() {
if (lastChecker != null && lastChecker.isSelected()) {
lastChecker.unselectChecker();
}
checkerIsSelected = false;
canMoveAgain = true;
if (lastChecker.getColor() == 1) {
whichPlayer = 2;
turnTracker.setText("Blue's Turn");
turnTracker.setStyle("-fx-background-color: blue");
} else {
whichPlayer = 1;
turnTracker.setText("Red's Turn");
turnTracker.setStyle("-fx-background-color: red");
}
}
};
pause = new PauseTransition(Duration.seconds(2));
pause.setOnFinished(e -> { stage.setScene(sceneMap.get("result"));
resultLabel.setText("Player " + lastChecker.getColor() + " Won!");
});
startGameButton.setOnAction(e -> {
startGameButton.setVisible(false);
startGameButton.setDisable(true);
});
exitButton1.setOnAction(e -> {
Platform.exit();
System.exit(0);
});
exitButton2.setOnAction(e -> {
Platform.exit();
System.exit(0);
});
howToPlay.setOnAction(e -> stage.setScene(sceneMap.get("howTo")));
goBackButton.setOnAction(e -> stage.setScene(sceneMap.get("welcome")));
endTurn.setOnAction(e -> { lastChecker.unselectChecker();
checkerIsSelected = false;
canMoveAgain = true;
if (lastChecker.getColor() == 1) {
whichPlayer = 2;
turnTracker.setText("Blue's Turn");
turnTracker.setStyle("-fx-background-color: blue");
} else {
whichPlayer = 1;
turnTracker.setText("Red's Turn");
turnTracker.setStyle("-fx-background-color: red");
}
});
stage.setScene(sceneMap.get("welcome"));
stage.show();
}
public Scene welcomeScene() {
Label welcomeLabel = new Label("The Game of Checkers");
welcomeLabel.setFont(Font.font("Times New Roman", 70));
singlePlayer = new Button("Single Player");
singlePlayer.setFont(Font.font("Times New Roman", 30));
multiPlayer = new Button("Multi Player");
multiPlayer.setFont(Font.font("Times New Roman", 30));
howToPlay = new Button("How To Play");
howToPlay.setFont(Font.font("Times New Roman", 30));
exitButton1 = new Button("Exit");
exitButton1.setFont(Font.font("Times New Roman", 30));
VBox root = new VBox(welcomeLabel, singlePlayer, multiPlayer, howToPlay, exitButton1);
root.setAlignment(Pos.CENTER);
root.setSpacing(15);
root.setStyle("-fx-background-image: url(checkered-board-game.jpg);" + "-fx-background-repeat: stretch;" + "-fx-background-size: 900 900;" + "-fx-background-position: center center;");
return new Scene(root, 900, 900);
}
public Scene singleGameScene() {
gameBoardMatrix = new GameBoardTile[8][8];
checkerMatrix = new Checker[8][8];
checkerLocation = new int[2];
gameBoard = new GridPane();
addGrid(gameBoard);
timerLabel = new Label("5:00");
turnTracker = new Label("Red's Turn");
turnTracker.setStyle("-fx-background-color: red");
endTurn = new Button("End Turn");
startGameButton = new Button("Start");
startGameButton.setFont(Font.font("Times New Roman", 70));
VBox root1 = new VBox(timerLabel, turnTracker, endTurn);
root1.setAlignment(Pos.CENTER);
root1.setPrefSize(200, 50);
root1.setSpacing(15);
HBox root2 = new HBox(root1, gameBoard);
root2.setAlignment(Pos.CENTER);
StackPane root = new StackPane(root2, startGameButton);
root.setAlignment(Pos.CENTER);
return new Scene(root, 800, 800);
}
public Scene howToPlayScene() {
Label titleHowTo = new Label("How To Play");
Label instructions = new Label("Instructions");
goBackButton = new Button("Go Back");
VBox root = new VBox(titleHowTo, instructions, goBackButton);
return new Scene(root, 700, 700);
}
public Scene resultScene() {
resultLabel = new Label();
resultLabel.setAlignment(Pos.CENTER);
Button playAgainButton = new Button("Play Again");
playAgainButton.setAlignment(Pos.CENTER);
exitButton2 = new Button("Exit");
VBox root = new VBox(resultLabel, playAgainButton, exitButton2);
root.setAlignment(Pos.CENTER);
root.setSpacing(15);
root.setStyle("-fx-background-image: url(checkered-board-game.jpg);" + "-fx-background-repeat: stretch;" + "-fx-background-size: 700 700;" + "-fx-background-position: center center;");
return new Scene(root, 700, 700);
}
// This function adds game buttons to the GridPane layout and attaches event handlers to each button, so that they are intractable with.
public void addGrid(GridPane grid) {
int color = 0;
for (int i = 0; i < 8; i++) {
if (color == 0) {
color = 1;
} else {
color = 0;
}
for (int j = 0; j < 8; j++) {
GameBoardTile gb = new GameBoardTile(j, i, color);
Checker checker = new Checker(j, i, 0);
if (color == 0) {
color = 1;
gb.getChildren().add(checker);
gb.setAlignment(Pos.CENTER);
if (j < 3) {
gb.setTakenBy(1);
checker.setColor(1);
} else if (j > 4) {
gb.setTakenBy(2);
checker.setColor(2);
} else {
checker.setColor(0);
}
} else {
color = 0;
}
checker.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
if (checker.isValid(whichPlayer)) {
if (whichPlayer == 1) {
lastPlayerToMove = 1;
whichPlayer = 0;
checkerLocation[0] = checker.getRow();
checkerLocation[1] = checker.getColumn();
lastChecker = checker;
checker.selectChecker();
} else if (whichPlayer == 2) {
lastPlayerToMove = 2;
whichPlayer = 0;
checkerLocation[0] = checker.getRow();
checkerLocation[1] = checker.getColumn();
lastChecker = checker;
checker.selectChecker();
} else {
if (lastPlayerToMove == 1 && checker.getColor() == 1 && !checkerIsSelected) {
checkerLocation[0] = checker.getRow();
checkerLocation[1] = checker.getColumn();
lastChecker.unselectChecker();
lastChecker = checker;
checker.selectChecker();
} else if (lastPlayerToMove == 2 && checker.getColor() == 2 && !checkerIsSelected) {
checkerLocation[0] = checker.getRow();
checkerLocation[1] = checker.getColumn();
lastChecker.unselectChecker();
lastChecker = checker;
checker.selectChecker();
} else if (lastPlayerToMove == 1 && checker.getColor() == 0) {
if (checker.getRow() == lastChecker.getRow() + 1 && Math.abs(checker.getColumn() - lastChecker.getColumn()) == 1 && !checkerIsSelected) {
checker.setColor(1);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
lastChecker = checker;
}
if (checker.getRow() == lastChecker.getRow() - 1 && Math.abs(checker.getColumn() - lastChecker.getColumn()) == 1 && !checkerIsSelected && lastChecker.isKing()) {
checker.setColor(1);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
lastChecker = checker;
}
if (lastChecker.getRow() + 2 <= 7 && lastChecker.getColumn() - 2 >= 0 && canMoveAgain) {
if (checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() - 1].getColor() == 2 && checkerMatrix[lastChecker.getRow() + 2][lastChecker.getColumn() - 2] == checker) {
checker.setColor(1);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
canMoveAgain = false;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() - 1].setColor(0);
checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() - 1].destroyKing();
numBlue--;
lastChecker = checker;
}
}
if (lastChecker.getRow() + 2 <= 7 && lastChecker.getColumn() + 2 <= 7 && canMoveAgain) {
if (checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() + 1].getColor() == 2 && checkerMatrix[lastChecker.getRow() + 2][lastChecker.getColumn() + 2] == checker) {
checker.setColor(1);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() + 1].setColor(0);
checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() + 1].destroyKing();
numBlue--;
lastChecker = checker;
}
}
if (lastChecker.getRow() - 2 >= 0 && lastChecker.getColumn() - 2 >= 0 && canMoveAgain && lastChecker.isKing()) {
if (checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() - 1].getColor() == 2 && checkerMatrix[lastChecker.getRow() - 2][lastChecker.getColumn() - 2] == checker) {
checker.setColor(1);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
canMoveAgain = false;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() - 1].setColor(0);
checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() - 1].destroyKing();
numBlue--;
lastChecker = checker;
}
}
if (lastChecker.getRow() - 2 >= 0 && lastChecker.getColumn() + 2 <= 7 && canMoveAgain && lastChecker.isKing()) {
if (checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() + 1].getColor() == 2 && checkerMatrix[lastChecker.getRow() - 2][lastChecker.getColumn() + 2] == checker) {
checker.setColor(1);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
canMoveAgain = false;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() + 1].setColor(0);
checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() + 1].destroyKing();
numBlue--;
lastChecker = checker;
}
}
} else if (lastPlayerToMove == 2 && checker.getColor() == 0) {
if (checker.getRow() == lastChecker.getRow() - 1 && Math.abs(checker.getColumn() - lastChecker.getColumn()) == 1 && !checkerIsSelected) {
checker.setColor(2);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
canMoveAgain = false;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
lastChecker = checker;
}
if (checker.getRow() == lastChecker.getRow() + 1 && Math.abs(checker.getColumn() - lastChecker.getColumn()) == 1 && !checkerIsSelected && lastChecker.isKing()) {
checker.setColor(2);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
canMoveAgain = false;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
lastChecker = checker;
}
if (lastChecker.getRow() - 2 >= 0 && lastChecker.getColumn() - 2 >= 0 && canMoveAgain) {
if (checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() - 1].getColor() == 1 && checkerMatrix[lastChecker.getRow() - 2][lastChecker.getColumn() - 2] == checker) {
checker.setColor(2);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() - 1].setColor(0);
checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() - 1].destroyKing();
numRed--;
lastChecker = checker;
}
}
if (lastChecker.getRow() - 2 >= 0 && lastChecker.getColumn() + 2 <= 7 && canMoveAgain) {
if (checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() + 1].getColor() == 1 && checkerMatrix[lastChecker.getRow() - 2][lastChecker.getColumn() + 2] == checker) {
checker.setColor(2);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() + 1].setColor(0);
checkerMatrix[lastChecker.getRow() - 1][lastChecker.getColumn() + 1].destroyKing();
numRed--;
lastChecker = checker;
}
}
if (lastChecker.getRow() + 2 <= 7 && lastChecker.getColumn() - 2 >= 0 && canMoveAgain && lastChecker.isKing()) {
if (checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() - 1].getColor() == 1 && checkerMatrix[lastChecker.getRow() + 2][lastChecker.getColumn() - 2] == checker) {
checker.setColor(2);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() - 1].setColor(0);
checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() - 1].destroyKing();
numRed--;
lastChecker = checker;
}
}
if (lastChecker.getRow() + 2 <= 7 && lastChecker.getColumn() + 2 <= 7 && canMoveAgain && lastChecker.isKing()) {
if (checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() + 1].getColor() == 1 && checkerMatrix[lastChecker.getRow() + 2][lastChecker.getColumn() + 2] == checker) {
checker.setColor(2);
checker.selectChecker();
checker.makeKing(lastChecker);
checkerIsSelected = true;
lastChecker.setColor(0);
lastChecker.unselectChecker();
lastChecker.destroyKing();
checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() + 1].setColor(0);
checkerMatrix[lastChecker.getRow() + 1][lastChecker.getColumn() + 1].destroyKing();
numRed--;
lastChecker = checker;
}
}
}
}
}
if (isWin1()) {
pause.play();
}
}
});
grid.add(gb, i, j); // Adds GameButton to GridPane
gameBoardMatrix[j][i] = gb; // Adds GameButton to 2D Matrix Data Structure
checkerMatrix[j][i] = checker; // Adds Checker to 2D Matrix Data Structure
}
}
}
boolean isWin1() {
/////
///// ALSOOOOOOO Check if a player can't move. If they can't then they lose.
/////
if (numRed == 0 || numBlue == 0) {
return true;
}
return false;
}
/*
boolean isWin2() {
for (Checker[] a : checkerMatrix) {
for (Checker e : a) {
if (e.getRow() + 1 <= 7 && ) {
}
}
}
return true;
}
*/
}
<file_sep>/JavaFXCheckersGame/src/main/java/GameBoardTile.java
import javafx.scene.layout.VBox;
public class GameBoardTile extends VBox {
private int row;
private int column;
private int color; // color = 0 means the tile is white, color = 1 means the tile is black.
private int takenBy; // takenBy = 0 means the tile is not takenBy anyone, takenBy = 1 means the tile is taken by player 1, takenBy = 2 means the tile is taken by player 2.
// GameButton Constructor
public GameBoardTile(int x, int y, int z) {
this.row = x;
this.column = y;
this.takenBy = 0;
this.setColor(z);
this.setPrefSize(100,100);
}
// Returns the row the VBox is in the gridpane
public int getRow() {
return this.row;
}
// Returns the column the VBox is in the gridpane
public int getColumn() {
return this.column;
}
public void setColor(int val) {
this.color = val;
if(val == 0) {
this.setStyle("-fx-background-color: black");
} else {
this.setStyle("-fx-background-color: white");
}
}
void setTakenBy(int val) {
this.takenBy = val;
}
}
<file_sep>/JavaFXCheckersGame/src/main/java/Checker.java
import javafx.scene.control.Button;
import javafx.scene.shape.Circle;
public class Checker extends Button {
private int row;
private int column;
private int color; // color = 0 means the checker is white, color = 1 means the checker is red, color = 2 means the tile is blue.
private boolean king;
private boolean selected;
final double r = 30;
Checker(int x, int y, int z) {
this.row = x;
this.column = y;
this.color = z;
this.setShape(new Circle(r));
this.setMinSize(2*r, 2*r);
this.setMaxSize(2*r, 2*r);
}
void setColor(int val) {
this.color = val;
if (val == 0) {
this.setStyle("-fx-background-color: black");
} else if (val == 1) {
this.setStyle("-fx-background-color: red");
} else {
this.setStyle("-fx-background-color: blue");
}
}
void selectChecker() {
this.setMinSize((2*r) + 10, (2*r) + 10);
this.setMaxSize((2*r) + 10, (2*r) + 10);
this.selected = true;
}
void unselectChecker() {
this.setMinSize(2*r, 2*r);
this.setMaxSize(2*r, 2*r);
this.selected = false;
}
boolean isValid(int val) {
if (val == 0) {
return true;
}
if (color == val) {
return true;
}
return false;
}
void makeKing(Checker lastChecker) {
if (lastChecker.isKing()) {
this.setText("K");
this.king = true;
} else if (this.color == 1 && this.row == 7) {
this.setText("K");
this.king = true;
} else if (this.color == 2 && this.row == 0) {
this.setText("K");
this.king = true;
}
}
void destroyKing() {
this.setText("");
this.king = false;
}
boolean isKing() {
return this.king;
}
boolean isSelected() { return this.selected; }
// Returns the row the Checker is in the gridpane
public int getRow() {
return this.row;
}
// Returns the column the Checker is in the gridpane
public int getColumn() {
return this.column;
}
// Returns the Checker Color, this is how we can identify the who the checker belongs to
public int getColor() {
return this.color;
}
}
|
b1b7b9d02480922d639a4e7071c8d542ac327339
|
[
"Java"
] | 3 |
Java
|
MarkoGlamocak/JavaFXCheckers
|
bf5717054d7fc47e244ed135e40ae55f4ab42710
|
1f35c9d89ea190a5bdf9325e9fcc8f80b84c91a9
|
refs/heads/master
|
<file_sep>/**
* Created by msxiehui on 2017/8/17.
* Date:2017/8/17
* Time:15:12
* Email:<EMAIL>
* VERSION: 0.1
*北京耀启网络科技有限公司
*北京百孚思传实网络营销机构
*
*/
var yaoqi = yaoqi || {};
yaoqi.uploadfile = function () {
this.isPost = false;
this.ok = false;
this.taget = null;
this.params = {};
this.types = "";
this.fd = "";
this.xhr = "";
this.files = "";
return this;
}
yaoqi.uploadfile.prototype.init = function (id, params) {
this.taget = document.getElementById(id);
var defaults = {
size: 1024 * 1024 * 2,
imgType: "jpeg,png",
auto: false,
lrz: false,
maxHeight: 1000,
maxWidth: 1000,
lrzType: "width",
url: "http://cc.cc.com",
urlParams: {},
callback: function (data) {
}
}
params = params || {};
for (var def in defaults) {
if (typeof params[def] === 'undefined') {
params[def] = defaults[def];
} else if (typeof params[def] === 'object') {
for (var deepDef in defaults[def]) {
if (typeof params[def][deepDef] === 'undefined') {
params[def][deepDef] = defaults[def][deepDef];
}
}
}
}
this.params = params;
var types = this.params.imgType.split(",");
if (types.length > 0) {
for (var i = 0; i < types.length; i++) {
this.types += "image/" + types[i] + ",";
}
this.types = this.types.slice(0, this.types.length - 1);
} else {
this.types = "image/jpeg,image/png"
}
this.taget.setAttribute("accept", this.types);
this.ok = true;
var self = this;
console.log("init");
this.taget.addEventListener("change", function (event) {
self.isPost = false;
self.files = event.target.files[0];
if (self.params.auto == true) {
self.upload();
}
});
return this;
}
yaoqi.uploadfile.prototype.upload = function () {
console.log("执行upload");
if (!this.ok) {
console.log("先初始化!");
return;
}
if (this.isPost) {
return;
}
if (!this.files) {
var data = {
result: 4001,
error_message: "没有文件信息"
}
this.params.callback(data);
return;
}
if (this.files.size > this.params.size) {
var data = {
result: 4002,
error_message: "文件超过限制大小"
}
this.params.callback(data);
return;
}
if (this.types.indexOf(this.files.type) == -1) {
var data = {
result: 4003,
error_message: "文件类型超出限制"
}
this.params.callback(data);
return;
}
if(this.params.lrz==true){
var self=this;
var data={};
if(this.params.lrzType=="height"){
data["height"]=this.params.maxHeight;
}else{
data["width"]=this.params.maxWidth;
}
if(typeof(lrz)=="undefined") {
var data = {
result: 4000,
error_message: "请加载压缩插件(lrz.mobile.min.js)"
}
self.params.callback(data);
return;
}
//开始压缩并上传。
lrz(this.files,data, function(results) {
var blob = dataURLtoBlob(results.base64);
self.files=blob;
self.send();
});
}else{
this.send();
}
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
}
}
yaoqi.uploadfile.prototype.send=function () {
this.isPost = true;
this.fd = new FormData();
this.fd.append("file", this.files);
for (var val in this.params.urlParams) {
this.fd.append(val, this.params.urlParams[val]);
}
this.xhr = new XMLHttpRequest();
this.xhr.addEventListener("load", uploadComplete, true);
this.xhr.addEventListener("error", uploadFailed, false);
this.xhr.open("POST", this.params.url);
this.xhr.send(this.fd);
var self = this;
function uploadComplete(evt) {
self.isPost = false;
if (evt.currentTarget.status == 200) {
var return_body = evt.currentTarget.responseText;
var data = JSON.parse(return_body);
self.params.callback(data);
} else if (evt.currentTarget.status == 404) {
var data = {
result: 4004,
error_message: evt.currentTarget.responseText
}
self.params.callback(data);
} else {
var data = {
result: 4005,
status: evt.currentTarget.status,
error_message: evt.currentTarget.responseText
}
self.params.callback(data);
}
}
function uploadFailed(evt) {
self.isPost = false;
var data = {
result: 4006,
message: evt.responseText
}
self.params.callback(data);
}
}
yaoqi.upload = new yaoqi.uploadfile();
<file_sep># yaoqi
[<EMAIL>](mail://<EMAIL>)<br>
北京耀启网络科技有责任公司
# 列表
1、图片上传插件 yaoqi.uploadfile.js <br>
压缩依赖 lrz.mobile.min.js (3.0版) [最新localResizeIMG 4.09 已停止维护](https://github.com/think2011/localResizeIMG)
# 使用方式
### 1、上传插件
### html:
<input id="fileupload" type="file" name="file" value="" />
<!--如需压缩图片时(主要为移动端)-->
<script src="lrz.mobile.min.js"></script>
<!--插件主文件-->
<script src="yaoqi.uploadfile.js"></script>
### javascript:
默认暴露 yaoqi.upload
初始化 yaoqi.upload.init(选择框的ID,参数);
yaoqi.upload("fileupload",{
size: 1024 * 1024 * 2, //上传大小限制 单位字节 默认为 2M
imgType: "jpeg,png", //上传格式限制 默认为 jpg、png
auto: false, //是否自动上传(选择文件后,自动执行上传) 默认为 false
lrz: false, //是否启用图片压缩(需加载插件 lrz.mobile.min.js) 默认为 false
maxHeight: 500, //启用图片压缩时有效,压缩图片的高度(小于此值会放大) 默认为 500
maxWidth: 500, //启用图片压缩时有效,压缩图片的宽度(小于此值会放大) 默认为 500
lrzType: "width",//启用图片压缩时有效,压缩图片的方式 height/width 默认width
url: "", // 图片上传的链接 默认为空
urlParams: {}, // 图片上传时的其他参数 默认为空
callback: function (data) {
//data 上传图片正确时,此data 返回信息为 后台返回信息。
//上传错误时,data.result 为错误代码
//data.error_message 为错误信息。
if(data.result!=200){
alert(data.error_message);
}else{
alert("上传成功!");
}
} // 回调函数
}
如果 **auto** 参数为 **flase** 时
通过 yaoqi.upload.start() 执行上传操作。
$("#btn").click(function(){
yaoqi.upload.start();
})
|
46dcb72d1d9e7291ccada30490dd92e7e11ce377
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
jooner888/yaoqi
|
41b59f95efb7ee2942ecd4d43588891375703424
|
aace63d506da63bf199c5053114cfca8b6362718
|
refs/heads/master
|
<file_sep>import React from 'react'
import { Link } from 'react-router'
import Timer from '../components/timer'
export default class Home extends React.Component {
constructor(props){
super(props);
this.state = {
number :0
};
this.handleClick = this.handleClick.bind(this);
}
componentWillMount(){
console.log("Component will mounted")
}
componentDidMount(){
console.log("Component mounted")
}
handleClick(event) {
console.log('Click Handler', event);
this.setState({number: 10});
}
render() {
return (
<div className="container home">
<div className="row">
<div className="col-lg-12">
<h2>Happy St Patrick's Day !!!</h2>
<Link to="/deck">Go to twitter deck.{this.state.number}</Link>
<button onClick={this.handleClick} >Click</button>
</div>
</div>
</div>
)
}
}<file_sep>import React from 'react'
import DeckList from "./deck-list"
export default class DeckListWrap extends React.Component {
constructor(props) {
super(props)
}
render() {
let tweets = [{name: 'Krunal'},{name: 'Krunal1'},{name: 'Krunal2'}];
return (
<div className="deck-wrap clearfix">
<DeckList tweets={tweets} />
<DeckList />
<DeckList />
</div>
)
}
}<file_sep>import React from 'react'
import NavigationBar from '../components/navbar'
import Footer from '../components/footer'
export default class App extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="app">
<div className="page-wrap">
<NavigationBar />
{
this.props.children
}
</div>
<Footer />
</div>
)
}
}
<file_sep>import ReactDOM from 'react-dom'
import React from 'react'
import { Router, Route, browserHistory, IndexRoute } from 'react-router'
import App from 'pages/app'
import Home from 'pages/home'
import Deck from 'pages/deck'
import Timer from 'components/timer'
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="home" component={Home}/>
<Route path="deck" component={Deck}/>
<Route path="timer" component={Timer}/>
</Route>
</Router>
, document.querySelector('#root')
);<file_sep># react-basic-bootcamp
Code repo for react basic bootcamp with very minimal tooling
# Brunch + React + React-router + Babel/ES6
## Installation
Clone this repo.
## Getting started
* Install (if you don't have them):
* [Node.js](http://nodejs.org): `brew install node` on OS X
* [Brunch](http://brunch.io): `npm install -g brunch`
* `cd` into this repo and Brunch plugins and app dependencies: `npm install`
* Run:
* `npm run start` or `brunch watch --server` — watches the project with continuous rebuild. This will also launch HTTP server with [pushState](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history).
* `npm run prod` or `brunch build --production` — builds minified project for production
* Learn:
* `public/` dir is fully auto-generated and served by HTTP server. Write your code in `app/` dir.
* Place static files you want to be copied from `app/assets/` to `public/`.
<file_sep>import React from 'react'
import DeckListWrap from '../components/deck/deck-list-wrap'
export default class Deck extends React.Component {
render() {
return (
<div className="container deck-page">
<div className="deck-wrap clearfix">
<DeckListWrap />
</div>
</div>
)
}
}
|
72ce110e5a0d51216b9cc226aad32a0519a2afa3
|
[
"JavaScript",
"Markdown"
] | 6 |
JavaScript
|
krupatel/react-basic-bootcamp
|
f9dc9adbd075bbe4f1826823797b3e83f878bbd3
|
1c354959109026349850a700a86d5fa8666e7719
|
refs/heads/main
|
<repo_name>kishenkumar345/Authentication_And_Access_Control_System<file_sep>/LoginSystem.cpp
#include "md5.h"
#include "LoginSystem.h"
#include <fstream>
#include <string>
#include <iostream>
LoginSystem::LoginSystem(){}
int LoginSystem::getUserClearance(){return user_clearance;}
void LoginSystem::setUserClearance(int userclearance){user_clearance = userclearance;}
std::string LoginSystem::getUsername(){return username;}
void LoginSystem::setUsername(std::string user_name){username = user_name;}
int LoginSystem::retrieve_info(){
std::fstream load_file;
std::string user_name;
std::string pass_word;
std::string file_user;
std::string file_salt;
std::string shadow_file_user;
std::string shadow_file_hash;
std::string shadow_file_clearance;
MD5 md5;
char* hash;
bool user_name_confirm = false;
bool shadow_user_name_confirm = false;
load_file.open("salt.txt");
std::cout << "Enter Username: " << std::endl;
std::cin >> user_name;
std::cout << "Enter Password: " << std::endl;
std::cin >> <PASSWORD>;
while(std::getline(load_file, file_user, ':')){
std::getline(load_file, file_salt);
if(user_name == file_user){ //if the user is found in the salt.txt file, send message and break the loop
user_name_confirm = true;
std::cout << user_name << " found in salt.txt\n" << "salt retrieved: " << file_salt << std::endl;
break;
}
}
if(user_name_confirm == false){//if the user is not found, send error and return -1
load_file.close();
std::cerr << "The Username Does Not Exist, Please Create User.\nExiting System...." << std::endl;
return -1;
}
load_file.close();
load_file.open("shadow.txt");
while(std::getline(load_file, shadow_file_user, ':')){
std::getline(load_file, shadow_file_hash, ':');
std::getline(load_file, shadow_file_clearance);
if(user_name == shadow_file_user){ //if username is found in the shadow file, start password hashing.
shadow_user_name_confirm = true;
std::cout << "Hashing..." << std::endl;
pass_word += file_salt;
hash = &*pass_word.begin();
if(md5.digestString(hash) == shadow_file_hash){ //if the hash of the password enterd matches with hashed password in shadow file, then user is authenticated
std::cout << "Authentication For User " << user_name << " Complete.\n" << "The Clearance for " <<
user_name << " is " << shadow_file_clearance << std::endl;
setUsername(user_name);
setUserClearance(std::stoi(shadow_file_clearance));
break;
} else { //if hash doesn't match with hash in shadow file, send error
load_file.close();
std::cerr << "Password Mismatch. Exiting System..." << std::endl;
return -1;
}
}
}
if(shadow_user_name_confirm == false){ //if the username was not found in the shadowfile, send error and return -1
load_file.close();
std::cerr << "The Username Does Not Exist, Please Create User.\nExiting System...." << std::endl;
return -1;
}
load_file.close();
}
void LoginSystem::options_menu(){
std::ifstream files_store;
std::ofstream files_store_input;
char option;
char shutdown;
std::string filename;
std::string file_store_user;
std::string files_store_filename;
std::string files_store_classification;
std::string filename_storage[20];
int file_counter = 0;
bool login_system_exit = false;
bool file_exist = false;
bool correct_option = false;
bool shutdown_option = false;
do {
files_store.open("Files.store");
files_store_input.open("Files.store",std::ios::app);
if(!files_store){//if Files.store doesn't exist for input, send error
std::cerr << "Files.txt doesn't exit" << std::endl;
}
if(!files_store_input){//if Files.store doesn't exist for output, send error
std::cerr << "Files.txt doesn't exit" << std::endl;
}
std::cout << "Options: (C)reate, (A)ppend, (R)ead, (W)rite, (L)ist, (S)ave, (E)xit." << std::endl;
std::cin >> option;
if(option == 'C'){//if correct option input, set correct option to true
correct_option = true;
} else if(option == 'A'){
correct_option = true;
} else if(option == 'R'){
correct_option = true;
} else if(option == 'W'){
correct_option = true;
} else if(option == 'L'){
correct_option = true;
} else if(option == 'S'){
correct_option = true;
} else if(option == 'E'){
correct_option = true;
}
while(correct_option == false){ //if correct option not input, loop till correct option is input.
std::cerr << "Only Options Are: C, A, R, W, L, S, E\nOptions: (C)reate, (A)ppend, (R)ead, (W)rite, (L)ist, (S)ave, (E)xit." << std::endl;
std::cin >> option;
if(option == 'C'){
correct_option = true;
} else if(option == 'A'){
correct_option = true;
} else if(option == 'R'){
correct_option = true;
} else if(option == 'W'){
correct_option = true;
} else if(option == 'L'){
correct_option = true;
} else if(option == 'S'){
correct_option = true;
} else if(option == 'E'){
correct_option = true;
}
}
if(option == 'C'){//Create file
std::cout << "Enter Filename: " << std::endl;
std::cin >> filename;
while(std::getline(files_store, files_store_filename, ':')){
std::getline(files_store, file_store_user, ':');
std::getline(files_store, files_store_classification);
if(filename == files_store_filename){//if the filename already exist then go back to menu(1)
file_exist = true;
std::cerr << "This File Name Already Exists." << std::endl;
}
}
if(file_exist == false){//if the file name doesn't exist, send message regarding filename, file owner and classification.
std::cout << "File: " << filename << "\nOwner: " << getUsername() << "\nClassification: " << getUserClearance() <<
"\nPlease use the save option to store your created file."<< std::endl;
filename_storage[file_counter] = filename; //store file name in string array at position file_counter, for saving later
file_counter++;
}
} else if(option == 'A'){
std::cout << "Enter Filename: " << std::endl;
std::cin >> filename;
while(std::getline(files_store, files_store_filename, ':')){
std::getline(files_store, file_store_user, ':');
std::getline(files_store, files_store_classification);
if(filename == files_store_filename){
file_exist = true;
break;
}
}
if(file_exist == true){//if file exists, check user clearance. Write up and read down principle.
std::cout << "This File Exists." << std::endl;
if(getUserClearance() <= std::stoi(files_store_classification)){
if(getUserClearance() == 0){//clearance of 0 can't do anything except create files.
std::cerr << "Failure Writing To File. Clearance is 0." << std::endl;
} else {
std::cout << "Success Appending From File. Correct Clearance" << std::endl;
}
} else {
std::cerr << "Failure Appending From File. Lower Clearance Required." << std::endl;
}
}
if(file_exist == false){
std::cout << "File Does Not Exist." << std::endl;
}
} else if(option == 'R'){
std::cout << "Enter Filename: " << std::endl;
std::cin >> filename;
while(std::getline(files_store, files_store_filename, ':')){
std::getline(files_store, file_store_user, ':');
std::getline(files_store, files_store_classification);
if(filename == files_store_filename){
file_exist = true;
break;
}
}
if(file_exist == true){
std::cout << "This File Exists." << std::endl;
if(getUserClearance() >= std::stoi(files_store_classification)){//if file exists, check user clearance. Write up and read down principle.
if(getUserClearance() == 0){
std::cerr << "Failure Writing To File. Clearance is 0." << std::endl;
}else{
std::cout << "Success Reading From File. Correct Clearance" << std::endl;
}
} else {
std::cerr << "Failure Reading From File. Higher Clearance Required." << std::endl;
}
}
if(file_exist == false){
std::cerr << "File Does Not Exist." << std::endl;
}
} else if(option == 'W'){
std::cout << "Enter Filename: " << std::endl;
std::cin >> filename;
while(std::getline(files_store, files_store_filename, ':')){
std::getline(files_store, file_store_user, ':');
std::getline(files_store, files_store_classification);
if(filename == files_store_filename){
file_exist = true;
break;
}
}
if(file_exist == true){
std::cout << "This File Exists." << std::endl;
if(getUserClearance() == std::stoi(files_store_classification)){//if file exists, check user clearance. Write up and read down principle.
if(getUserClearance() == 0){
std::cerr << "Failure Writing To File. Clearance is 0." << std::endl;
} else {
std::cout << "Success Writing To File. Correct Clearance" << std::endl;
}
} else {
std::cerr << "Failure Writing To File. Clearance & Classification Not Equal." << std::endl;
}
}
if(file_exist == false){
std::cerr << "File Does Not Exist." << std::endl;
}
} else if(option == 'L'){//Show data from Files.store file.
while(std::getline(files_store, files_store_filename, ':')){
std::getline(files_store, file_store_user, ':');
std::getline(files_store, files_store_classification);
std::cout << files_store_filename << std::endl;
}
} else if(option == 'S'){//Save all created files to Files.store.
for(int i = 0; i < file_counter; i++){
files_store_input << filename_storage[i] << ":" << getUsername() << ":" << getUserClearance() << std::endl;
std::cout << filename_storage[i] << " File Saved." << std::endl;
}
} else if(option == 'E'){//Exit option
std::cout << "Shut Down The FileSystem? (Y)es (N)o" << std::endl;
std::cin >> shutdown;
if(shutdown == 'Y'){ //check if correct option picked and if so set login_system_exit to true.
shutdown_option = true;
login_system_exit = true;
} else if (shutdown == 'N'){//check if correct option picked and if so set login_system_exit to false.
shutdown_option = true;
login_system_exit = false;
}
while(shutdown_option == false){ //if correct option not inputed, loop until correct option inputted.
std::cout << "Only Options Are: Y, N\nShut Down The FileSystem? (Y)es (N)o" << std::endl;
std::cin >> shutdown;
if(shutdown == 'Y'){
shutdown_option = true;
login_system_exit = true;
} else if (shutdown == 'N'){
shutdown_option = true;
login_system_exit = false;
}
}
}
files_store_input.close();
files_store.close();
} while(login_system_exit == false);
std::cout << "Exiting System..." << std::endl;
}
<file_sep>/LoginSystem.h
#ifndef LOGIN_SYSTEM
#define LOGIN_SYSTEM
#pragma once
#include <fstream>
class LoginSystem {
public:
LoginSystem();
int retrieve_info();
void options_menu();
int getUserClearance();
void setUserClearance(int);
std::string getUsername();
void setUsername(std::string);
private:
int user_clearance;
std::string username;
};
#endif /* end of include guard: */
<file_sep>/Readme.txt
1. All files must be together in a single folder. Files salt.txt, shadow.txt, Files.store must be in the folder. If not, create these files.
2. To compile enter: g++ *.cpp -o filesystem
3. To create a new user enter: ./filesystem -i
4. To login as an existing user enter: ./filesystem
<file_sep>/CreationSystem.cpp
#include "md5.h"
#include "CreationSystem.h"
#include <iostream>
#include <fstream>
#include <random>
CreationSystem::CreationSystem(){}
std::string CreationSystem::getUsername(){return username;}
std::string CreationSystem::getPassword(){return password;}
int CreationSystem::getUserClearance(){return user_clearance;}
void CreationSystem::setUsername(std::string user_name){username = user_name;}
void CreationSystem::setPassword(std::string pass_word){password = <PASSWORD>;}
void CreationSystem::setUserClearance(int userclearance){user_clearance = userclearance;}
void CreationSystem::store_user(){
bool digit_true;
std::string user_name;
std::string pass_word;
std::string confirm_password;
int userclearance = 0;
int salt_random = 0;
int counter = 0;
std::string salt = "";
char* salt_point;
std::fstream salt_shadow;
srand(time(0));
std::cout << "Enter Username: " << std::endl;
std::cin >> user_name;
setUsername(user_name);
std::cout << "Password Should Be Minimum 8 Characters Long, \nMix Of Digits And Letters,\nEnter A Password: " << std::endl;
std::cin >> pass_word;
for(char &character : pass_word){//check every character to see if at least one is a digit
if(isdigit(character) != 0){
digit_true = true;
break;
} else {
digit_true = false;
}
}
while(digit_true == false) {//if no digit, loop until password has digit in it
std::cerr << "Password does not have any digits, Please Re-enter Password: " << std::endl;
std::cin >> pass_word;
for(char &character : pass_word){//if password has digit, break the loop
if(isdigit(character) == true){
digit_true = true;
break;
}
}
}
if(pass_word.find('0') != std::string::npos ||
pass_word.find('1') != std::string::npos ||
pass_word.find('2') != std::string::npos ||
pass_word.find('3') != std::string::npos ||
pass_word.find('4') != std::string::npos ||
pass_word.find('5') != std::string::npos ||
pass_word.find('6') != std::string::npos ||
pass_word.find('7') != std::string::npos ||
pass_word.find('8') != std::string::npos ||
pass_word.find('9') != std::string::npos) {
std::cout << "Confirm Password: " << std::endl;
std::cin >> confirm_password;
while(pass_word != confirm_password){
std::cout << "Password Mismatch, Re-enter Confirmation: " << std::endl;
std::cin >> confirm_password;
}
if(pass_word == confirm_password){
setPassword(confirm_password);
}
}
std::cout << "Enter User Clearance (0 or 1 or 2 or 3): " << std::endl;
std::cin >> userclearance;
while(userclearance < 0 || userclearance > 3){
std::cerr << "User Clearance Must Be Between 0 and 3 Inclusive" << std::endl;
std::cin >> userclearance;
}
setUserClearance(userclearance);
size_t salt_size = 8;
for(int a = 0; a < 8; a++){
if(salt.length() == salt_size){ //if salt length is 8, stop creating random numbers and adding to salt string.
break;
}
salt_random = rand() % (10 + 1);
salt += std::to_string(salt_random);
}
std::string pass_salt;
pass_salt += getPassword(); //concat password into string
pass_salt += salt; //concat salt into string
salt_shadow.open("salt.txt", std::ios::app);
salt_shadow << getUsername() << ":" << salt << std::endl;
salt_shadow.close();
MD5 md5;
salt_point = &*pass_salt.begin(); //changing string to char* for hashing
salt_shadow.open("shadow.txt", std::ios::app);
salt_shadow << getUsername() << ":" << md5.digestString(salt_point) << ":" << getUserClearance() << std::endl; //Write to file username, hashed password and salt, and user clearance.
salt_shadow.close();
}
<file_sep>/CreationSystem.h
#ifndef CREATION_SYSTEM
#define CREATION_SYSTEM
#pragma once
#include<string>
class CreationSystem {
public:
CreationSystem();
void store_user();
std::string getUsername();
void setUsername(std::string);
std::string getPassword();
void setPassword(std::string);
int getUserClearance();
void setUserClearance(int);
private:
std::string username;
std::string password;
int user_clearance = 0;
};
#endif /* end of include guard: */
<file_sep>/FileSystem.cpp
#include <iostream>
#include "md5.h"
#include "CreationSystem.h"
#include "LoginSystem.h"
int main(int argc, char *argv[]){
MD5 test_md5;
std::cout << "Test MD5: " << test_md5.digestString("This is a test") << std::endl;
int retrieve_func_int = 0;
if(argc > 1){
std::string start_creation(argv[1]);
if(start_creation == "-i"){
std::cout << "Argument Valid" << std::endl;
CreationSystem create_user;
create_user.store_user();
} else {
std::cerr << "Incorrect Arguments" << std::endl;
}
} else {
LoginSystem retrieve_user;
retrieve_func_int = retrieve_user.retrieve_info();
if(retrieve_func_int == -1){
return 0;
}
retrieve_user.options_menu();
}
return 0;
}
|
6601e2e7a0507ed7493e5ca3d9e1b590bcea56fd
|
[
"Text",
"C++"
] | 6 |
C++
|
kishenkumar345/Authentication_And_Access_Control_System
|
238bc564eb1129e614cce0fac7d18cd31e2af67b
|
7e4ff1be9a3cd7a383a850ee8fb08a9cfb119a55
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Title -->
<title>Mingo - Responsive HTML5 Blog Site Template</title>
<!-- Favicon -->
<link rel="shortcut icon" type="image/ico" href="assets/images/favicon.ico">
<!-- gulp:css -->
<link rel="stylesheet" href="assets/css/app.min.css">
<!-- endgulp -->
</head>
<body>
<!-- ==================== PRELOADER HERE ===================================== -->
<div class="preloader-wrapper">
<div class="lds-spinner">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<!-- ==================== PRELOADER END ===================================== -->
<!-- ======================== START HEADER AREA HERE ====================================== -->
<header class="themeix-header clearfix">
<div class="container">
<div class="row">
<div class="col-lg-9">
<div class="themeix-logo float-left">
<a class="themeix-brand" href="index.html"><img src="assets/images/logo.png" alt="Header Logo"></a>
</div>
<div class="header-container highlight">
<nav class="themeix-menu float-left">
<ul id="navigation-menu" class="slimmenu">
<li class="has-submenu">
<a href="index.html">Home</a>
<ul>
<li><a href="index.html">Home V1</a></li>
<li><a href="index-v2.html">Home V2</a></li>
<li><a href="index-v3.html">Home V3</a></li>
</ul>
</li>
<li><a href="about.html">About</a></li>
<li class="has-submenu">
<a href="#">Page</a>
<ul>
<li><a href="authors.html">Authors</a></li>
<li><a href="tags.html">Tags</a></li>
<li><a href="404.html">404</a></li>
</ul>
</li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
</div>
</div>
<div class="col-lg-3">
<form action="/search" id="search-form" method="get" target="_top">
<input id="search-text" name="q" placeholder="Search Here" type="text" />
<button id="search-button" type="submit">
<span><i class="fa fa-search"></i></span>
</button>
</form>
</div>
</div>
</div>
</header>
<!-- =================== START MAIN CONTENT AREA HERE ========================-->
<main class="main-content-area section-pb clearfix">
<div class="mingo-blog-thumb section-pb-60">
<img src="assets/images/Blog-Post.jpg" alt="Blog-Post-thumb" />
</div>
<div class="container">
<div class="row">
<div class="col-md-10 mx-auto">
<div class="post-entry-content">
<div class="mingo-blog-title text-center pb-4 mb-4">
<h1>This Is A Standard Format Post</h1>
<div class="mingo-tag">
<p><i class="fa fa-tag" aria-hidden="true"></i><a href="tag.html">Lifestyle</a></p>
<p><i class="fa fa-clock-o" aria-hidden="true"></i>08 Min Read</p>
</div>
</div>
<p>Duis ex ad cupidatat tempor Excepteur cillum cupidatat fugiat nostrud cupidatat dolor sunt sint sit nisi est eu exercitation incididunt adipisicing veniam velit id fugiat enim mollit amet anim veniam dolor dolor irure velit commodo cillum sit nulla ullamco magna amet magna cupidatat qui labore cillum sit in tempor veniam consequat non laborum adipisicing aliqua ea nisi sint ut quis proident ullamco ut dolore culpa occaecat ut laboris in sit minim cupidatat ut dolor voluptate enim veniam consequat occaecat fugiat in adipisicing in amet Ut nulla nisi non ut enim aliqua laborum mollit quis nostrud sed sed.
</p>
<h2>Heading 2 Text Example</h2>
<p>Amet sed arcu morbi, arcu libero rutrum, quisque aenean hendrerit. Eum libero libero, purus sapien mollis nisl magna, diamlorem in sed eu velit. Id purus felis luctus fermentum, ut unde tristique sit nec. Eget massa leo eget ut, aliquet bibendum eget a duis, quis sapien porttitor metus, sapien nulla. Ultricies euismod, sodales tellus mattis interdum, vel vel turpis, aut id </p>
<blockquote>
<p>Fuctus quisque erat aliquet morbi euismodsit fblandit. Sodin eu pede fermentum ac sed vel arcu, eu praesent lectus hac nun commodo dictum</p>
</blockquote>
<p>Hendrerit quis suscipit pellentesque quis nullam id. Turpis justo vestibulum convallis vitae, quam et et, tincidunt quis tortor odio sit parturient sit, maecenas praesent lacus integer mauris mi, nulla est orci morbi. Non ornare pede pede lacinia nunc accumsan, id neque neque risus risus rutrum</p>
<h3>Heading 3 Text</h3>
<p>Amet sed arcu morbi, arcu libero rutrum, quisque aenean hendrerit. Eum libero libero, purus sapien mollis nisl magna, diamlorem in sed eu velit. Id purus felis luctus fermentum, ut unde tristique sit nec. Eget massa leo eget ut, aliquet bibendum eget a duis, quis sapien porttitor metus, sapien nulla. Ultricies euismod, sodales tellus mattis interdum, vel vel turpis, aut id </p>
<figure class="m-small-img my-4">
<img src="assets/images/small-img.jpg" alt="small-img" />
<figcaption>Image Caption Test </figcaption>
</figure>
<p>Duis ultricies ornare, fusce sit vitae vehicula aute, ante dui, risus suspendisse vitae leInteger mi, lobortis felis praesent elit. Posuere porro, elementum et, urna risus erat, auctor aenean rerum luctus et, sollicitudin amet a id vivamus metus. Nunc pretium integer, moscelerisque ipsum justo neque bibendum donec, pede enim nonummy justo. Nuncmperdiet sit urna, commodo cum tellus, pretium lorem numquam, ornare eros wisi euismod natoque nibh. Lacinia at orci sollicitudin arcu sapien nulla. Dolore natoque rhoncus lorem</p>
<!-- <figure class="fluid-image my-4">
<img src="assets/images/fluid-image.jpg" alt="eofe" />
</figure> -->
<p>Libero a sed ultricies eu, dui morbi est sollicitudin felis, proin nisl lacinia mattis ut, ultrices pellentesque libero massa, molestie luctus dui semper mauris. Consectetuer condimentum vestibulu Platea ligula faucibus sed mauris venenatis. Mi viverra, ipsum natoque sed. Sed lacinia vitae aliquam, nullam quisque iaculis iaculis at adipiscing. Vulputate etiam consectetuer ante, orci commodo eu quis vestibulum auctor laoreet. Vehicula tenetur leo wisi, ultricies esse cursus, molest</p>
<ul>
<li>Suspendisse vitae leo. Integer</li>
<li>Quisque egestas nulla volutpat</li>
<li>Vehicula et scelerisque erat</li>
<li>Quisque egestas nulla volutpat</li>
</ul>
<p>Libero a sed ultricies eu, dui morbi est sollicitudin felis, proin nisl lacinia mattis ut, ultrices pellentesque libero massa, molestie luctus dui semper mauris. Consectetuer condimentum vestibulu Platea ligula faucibus sed mauris venenatis. Mi viverra, ipsum natoque sed. Sed lacinia vitae aliquam, nullam quisque iaculis iaculis at adipiscing. Vulputate etiam consectetuer ante, orci commodo eu quis vestibulum auctor laoreet. Vehicula tenetur leo wisi, ultricies esse cursus, molest</p>
<h3>Gallery Example</h3>
<div class="image-gallery">
<div class="row">
<div class="col-md-4">
<div class="gallery-img">
<a href="assets/images/g-img-01.jpg" data-lightbox="gallery-popup"><img src="assets/images/g-img-01.jpg" alt="gallery" /></a>
</div>
</div>
<div class="col-md-4">
<div class="gallery-img">
<a href="assets/images/g-img-02.jpg" data-lightbox="gallery-popup"><img src="assets/images/g-img-02.jpg" alt="gallery" /></a>
</div>
</div>
<div class="col-md-4">
<div class="gallery-img">
<a href="assets/images/g-img-03.jpg" data-lightbox="gallery-popup"><img src="assets/images/g-img-03.jpg" alt="gallery" /></a>
</div>
</div>
<div class="col-md-4">
<div class="gallery-img">
<a href="assets/images/g-img-04.jpg" data-lightbox="gallery-popup"><img src="assets/images/g-img-04.jpg" alt="gallery" /></a>
</div>
</div>
<div class="col-md-4">
<div class="gallery-img">
<a href="assets/images/g-img-05.jpg" data-lightbox="gallery-popup"><img src="assets/images/g-img-05.jpg" alt="gallery" /></a>
</div>
</div>
<div class="col-md-4">
<div class="gallery-img">
<a href="assets/images/g-img-06.jpg" data-lightbox="gallery-popup"><img src="assets/images/g-img-06.jpg" alt="gallery" /></a>
</div>
</div>
</div>
</div>
<p>Amet sed arcu morbi, arcu libero rutrum, quisque aenean hendrerit. Eum libero libero, purus sapien mollis nisl magna, diamlorem in sed eu velit. Id purus felis luctus fermentum, ut unde tristique sit nec. Eget massa leo eget ut, aliquet bibendum eget a duis, quis sapien porttitor metus, sapien nulla. Ultricies euismod, sodales tellus mattis interdum, vel vel turpis, aut id </p>
<p class="m-0">Molestie sodales, ac purus maecenas, nunc ridiculus id eget sit vivamus felis. Ac porttitor tincidunt, felis molestie risus id, penatibus ac wisi netus suscipit fermentum sollicitudin, pede augue ipsum</p>
</div>
<div class="tags-social-meta my-4">
<div class="row">
<div class="col-md-8">
<div class="tags">
<ul class="list-inline display-all-tags">
<li class="list-inline-item"><i class="fa fa-tag" aria-hidden="true"></i> Tags:</li>
<li class="list-inline-item"><a href="tag.html">Education <span class="tag-sep">,</span></a></li>
<li class="list-inline-item"><a href="tag.html">Design<span class="tag-sep">,</span></a></li>
<li class="list-inline-item"><a href="tag.html">Travel<span class="tag-sep">,</span></a></li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class="social-meta float-md-right">
<ul class="list-inline float-left">
<li class="list-inline-item">Share:</li>
<li class="list-inline-item"><a href="#" data-toggle="tooltip" title="Pinterest"><i class="fa fa-pinterest"></i></a></li>
<li class="list-inline-item"><a href="#" data-toggle="tooltip" title="Twitter"><i class="fa fa-twitter"></i></a></li>
<li class="list-inline-item"><a href="#" data-toggle="tooltip" title="Dribble"><i class="fa fa-dribbble" aria-hidden="true"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="author-bio-details white-bg my-4">
<div class="meta-info p-5">
<div class="author-pic pb-2">
<a href="author.html"><img src="assets/images/post-author.png" alt="post-author" /></a>
</div>
<div class="a-title mt-2 mb-3">
<p><a href="author.html"><strong><NAME></strong></a><span>Themeix</span></p>
</div>
<p class="m-0">Quisque egestas nulla volutpat, odio ipsum, dolor elit, urna consequat ad sem ipsum, orci fermentum enim luctus, quisque vitae, litora eget enim in lacus tincidunt in. Feugiat sodales, maecenas nulla ut,</p>
</div>
</div>
<div class="white-box my-4">
<div class="inner-title mb-4">
<h4 class="heading-4">03 Comments</h4>
</div>
<div class="themeix-comments">
<div class="comments-details">
<div class="author-image">
<a href="author.html"><img src="assets/images/comenter-1.png" alt="" /></a>
</div>
<div class="comment-text pb-4">
<div class="c-title">
<p><a href="author.html"><NAME></a> <span class="ml-1">18 May, 2019</span></p>
<p class="float-right reply-btn"><a href="#">Reply</a></p>
</div>
<div class="c-content">
<p>Circumstances and owing to the claims of duty or the obligations dislike men who are so beguiled and demoralized by the charms of pleasure they cannot</p>
</div>
</div>
</div>
<div class="comments-details">
<div class="reply-comment ml-5">
<div class="author-image">
<a href="author.html"><img src="assets/images/comenter-2.png" alt="" /></a>
</div>
<div class="comment-text pb-4">
<div class="c-title">
<p><a href="author.html"><NAME></a> <span class="ml-1">18 May, 2019</span></p>
<p class="float-right reply-btn"><a href="#">Reply</a></p>
</div>
<div class="c-content">
<p>Circumstances and owing to the claims of duty or the obligations dislike men who are so beguiled and demoralized by the charms of pleasure they cannot</p>
</div>
</div>
</div>
</div>
<div class="comments-details">
<div class="author-image">
<a href="author.html"><img src="assets/images/comenter-3.png" alt="" /></a>
</div>
<div class="comment-text">
<div class="c-title">
<p><a href="author.html"><NAME></a><span class="ml-1">18 May, 2019</span></p>
<p class="float-right reply-btn"><a href="#">Reply</a></p>
</div>
<div class="c-content">
<p class="m-0">Circumstances and owing to the claims of duty or the obligations dislike men who are so beguiled and demoralized by the charms of pleasure they cannot</p>
</div>
</div>
</div>
</div>
</div>
<div class="white-box">
<div class="inner-title mb-4">
<h4 class="heading-4">Post a Comment</h4>
</div>
<form class="comment-form">
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" class="form-control" placeholder="Your Name">
</div>
<div class="col-md-6 form-group">
<input class="form-control" type="text" placeholder="Your Email">
</div>
</div>
<div class="form-row">
<div class="col-md-12 form-group">
<textarea class="form-control" rows="4" placeholder="Type Comment"></textarea>
</div>
</div>
<button type="submit" class="btn-submit">Post Comment</button>
</form>
</div>
</div>
</div>
</div>
</main>
<!-- ======================== END MAIN CONTENT AREA HERE ========================-->
<!-- ==================== START FOOTER AREA ===================================== -->
<footer class="footer-area section-pt">
<div class="container">
<div class="footer-border"></div>
<div class="row">
<div class="col-lg-8">
<div class="inner-title section-pb-70">
<h4 class="heading-4">Popular Posts</h4>
</div>
<div class="row">
<div class="col-md-6">
<div class="mingo-footer-widget">
<div class="mingo-widget-details">
<div class="mingo-populer-post">
<div class="mingo-p-thumb">
<a href="blog-details.html"><img src="assets/images/popular-post-thumb-1.jpg" alt="popular-post-thumb" /></a>
</div>
<div class="mingo-meta">
<div class="mingo-post-title">
<h6><a href="blog-details.html">More people are eating organic</a></h6>
</div>
<div class="mingo-tag">
<p><i class="fa fa-tag" aria-hidden="true"></i><a href="tag.html">Lifestyle</a></p>
</div>
</div>
</div>
<div class="mingo-populer-post">
<div class="mingo-p-thumb">
<a href="blog-details.html"><img src="assets/images/popular-post-thumb-2.jpg" alt="popular-post-thumb" /></a>
</div>
<div class="mingo-meta">
<div class="mingo-post-title">
<h6><a href="blog-details.html">Organic Produce: Myth vs. Reality</a></h6>
</div>
<div class="mingo-tag">
<p><i class="fa fa-tag" aria-hidden="true"></i><a href="tag.html">Lifestyle</a></p>
</div>
</div>
</div>
<div class="mingo-populer-post">
<div class="mingo-p-thumb">
<a href="blog-details.html"><img src="assets/images/popular-post-thumb-3.jpg" alt="popular-post-thumb" /></a>
</div>
<div class="mingo-meta">
<div class="mingo-post-title">
<h6><a href="blog-details.html">The natural beauty workshop</a></h6>
</div>
<div class="mingo-tag">
<p><i class="fa fa-tag" aria-hidden="true"></i><a href="tag.html">Lifestyle</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="mingo-footer-widget">
<div class="mingo-footer-widget float-md-right">
<div class="mingo-widget-details">
<div class="mingo-populer-post">
<div class="mingo-p-thumb">
<a href="blog-details.html"><img src="assets/images/popular-post-thumb-4.jpg" alt="popular-post-thumb" /></a>
</div>
<div class="mingo-meta">
<div class="mingo-post-title">
<h6><a href="blog-details.html">How to make neroli whipped body butter</a></h6>
</div>
<div class="mingo-tag">
<p><i class="fa fa-tag" aria-hidden="true"></i><a href="tag.html">Lifestyle</a></p>
</div>
</div>
</div>
<div class="mingo-populer-post">
<div class="mingo-p-thumb">
<a href="blog-details.html"><img src="assets/images/popular-post-thumb-5.jpg" alt="popular-post-thumb" /></a>
</div>
<div class="mingo-meta">
<div class="mingo-post-title">
<h6><a href="blog-details.html">The mom adrienne writes about real food </a></h6>
</div>
<div class="mingo-tag">
<p><i class="fa fa-tag" aria-hidden="true"></i><a href="tag.html">Lifestyle</a></p>
</div>
</div>
</div>
<div class="mingo-populer-post">
<div class="mingo-p-thumb">
<a href="blog-details.html"><img src="assets/images/popular-post-thumb-6.jpg" alt="popular-post-thumb" /></a>
</div>
<div class="mingo-meta">
<div class="mingo-post-title">
<h6><a href="blog-details.html">How to start cosmetic business at home</a></h6>
</div>
<div class="mingo-tag">
<p><i class="fa fa-tag" aria-hidden="true"></i><a href="tag.html">Lifestyle</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-2 col-sm-6">
<div class="inner-title section-pb-70">
<h4 class="heading-4">Tags Cloud
</h4>
</div>
<div class="mingo-footer-widget">
<div class="mingo-widget-details mingo-tags">
<ul class="list-inline">
<li><a href="tag.html">Travel</a></li>
<li><a href="tag.html">Clean</a></li>
<li><a href="tag.html">Web</a></li>
<li><a href="tag.html">Design</a></li>
<li><a href="tag.html">Html</a></li>
<li><a href="tag.html">Video</a></li>
</ul>
</div>
</div>
</div>
<div class="col-lg-2 col-sm-6">
<div class="inner-title section-pb-70">
<h4 class="heading-4">Useful Link
</h4>
</div>
<div class="mingo-widget-details">
<div class="mingo-widget-link">
<ul class="list-inline">
<li><a href="tags.html">Our Category</a></li>
<li><a href="contact.html">Contact Us</a></li>
<li><a href="about.html">About Us</a></li>
<li><a href="tag.html">Tag</a></li>
<li><a href="authors.html">Authors</a></li>
<li><a href="404.html">404</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="mingo-footer-bottom text-center pt-3 pb-3">
<p>© Copyright - Mingo - Designed by <a href="https://themeix.com/">Themeix</a></p>
</div>
</div>
</div>
</div>
</footer>
<!-- ==================== END FOOTER AREA HERE ===================================== -->
<!-- gulp:js -->
<script src="assets/js/build.min.js"></script>
<!-- endgulp -->
</body>
</html><file_sep>(function($) {
"use strict";
if ('.top-carousel'.length > 0) {
$(".top-slider").owlCarousel({
autoplay: true,
dots: true,
nav: true,
loop: true,
margin: 30,
lazyLoad: true,
center: true,
responsive: {
0: {
items: 2
},
768: {
items: 3
},
1200: {
items: 3
}
}
});
}
/* slimmenu */
$('.slimmenu').slimmenu({
resizeWidth: '991',
animSpeed: 'medium',
indentChildren: true,
});
/* scrollUp */
jQuery.scrollUp({
scrollName: 'scrollUp', // Element ID
topDistance: '300', // Distance from top before showing element (px)
topSpeed: 4000, // Speed back to top (ms)
animation: 'fade', // Fade, slide, none
animationInSpeed: 1000, // Animation in speed (ms)
animationOutSpeed: 1000, // Animation out speed (ms)
scrollText: '<i class="fa fa-angle-up" aria-hidden="true"></i>', // Text for element
activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF'
});
$(window).on('load', function() {
/* Preloader js*/
var preLoder = $(".preloader-wrapper");
preLoder.fadeOut(1000);
/*Isotope */
var $grid = $('.grid').isotope({
itemSelector: '.grid-item',
percentPosition: true,
masonry: {
columnWidth: 2,
}
});
});
}(jQuery));
|
a3fc3631cd1f32959b0d43b619df31a9987e3210
|
[
"JavaScript",
"HTML"
] | 2 |
HTML
|
jesmin001/mingo
|
2654b78451ed70ee19d28c3376a7901d164a590b
|
fe6a647a85d156f539d32dd890cb1f080eb6cb7c
|
refs/heads/master
|
<repo_name>e-yi/hairstyle_generation<file_sep>/note.md
## 参考资料
### 1. [FaceApp](https://www.reddit.com/r/MachineLearning/comments/67umwt/d_how_does_faceapp_work/)
> I managed to produce [a few failure cases](https://imgur.com/a/itQp1) which gives away some information. You can see that they pick a square around the face and process only that part and then putting it back into the original photo. Secondly, in the last picture you can see that in some cases they do apply hand crafted textures onto the image, which becomes obvious when they fail to correctly get the orientation of the head.
### 2. [smile vector](https://twitter.com/smilevector)
一个推特账号
### 3. [OpenCV](https://www.learnopencv.com/facial-landmark-detection/)
蒙版
目标:类似[edge2cat](https://affinelayer.com/pixsrv/)可以输入线条,输出发型。
- step1:使用自动边缘检测器,生成人脸边缘,跑pix2pix
- step2:输入任何人的头像,输出光头版(???<file_sep>/data/makeData.py
import os
import cv2
import sys
import argparse
import numpy as np
from PIL import Image
def dfsFile(path,func):
"""
给定根目录,dfs寻找其下所有文件进行统一操作
"""
for file in os.listdir(path):
fullPath = os.path.join(path,file)
if os.path.isdir(fullPath):
dfsFile(fullPath,func)
else:
func(file,fullPath)
def resize(im):
new_width = new_height = 256
width, height = im.size # Get dimensions
left = (width - new_width)/2
top = (height - new_height)/2
right = (width + new_width)/2
bottom = (height + new_height)/2
return im.crop((left, top, right, bottom))
def edge(im,output_dir,k=(11,11),lb=50,ub=90):
img = np.array(im)
gaussian = cv2.GaussianBlur(src=img, ksize=k, sigmaX=0, sigmaY=0)
canny = cv2.Canny(gaussian, lb, ub)
cv2.imwrite(output_dir,canny) # save img
def process(file,output_resize,output_canny,output_concat):
im = Image.open(file)
im = resize(im)
im.save(output_resize)
edge(im,output_canny)
list_im = [output_resize, output_canny]
imgs = [ Image.open(i).convert('RGB') for i in list_im ]
assert imgs[0].size == imgs[1].size
imgs_comb = np.hstack( (np.asarray(i) for i in imgs ) )
imgs_comb = Image.fromarray( imgs_comb)
imgs_comb.save(output_concat)
def batchProcess(input_dir, output_dir):
output_resize = os.path.join(output_dir,'resize')
output_canny = os.path.join(output_dir,'canny')
output_concat = os.path.join(output_dir,'concat')
os.makedirs(output_resize,exist_ok=True)
os.makedirs(output_canny,exist_ok=True)
os.makedirs(output_concat,exist_ok=True)
def f(file,fullPath):
r = os.path.join(output_resize,file)
ca = os.path.join(output_canny,file)
co = os.path.join(output_concat,file)
return process(fullPath,r,ca,co)
dfsFile(input_dir, f)
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataroot', help='path to images')
parser.add_argument('--output_dir', help='path to store processed images')
args = parser.parse_args()
batchProcess(args.dataroot,args.output_dir)
<file_sep>/README_zh.md
# 发型生成
#### 介绍
生成发型!!!!
|
95497b642e73556f3342e586260e1219bf023256
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
e-yi/hairstyle_generation
|
8955ec658ecfc9847c80133f9738c24906db677f
|
88f1b5b795be72884702254db70d0e47bfd147b2
|
refs/heads/master
|
<file_sep>#!/bin/bash
################################################################################
#
# /opt/castnow_scripts/castnow_scripts.cfg (openhab:openhab, 644)
#
# In this file you can define some values that will be used
# by the different castnow scripts.
#
# Copy or rename this file to 'castnow_scripts.cfg'
#
# It is recommended to specify the IP address of your Chromecast
#
# by <NAME>
# 2015-11-27
#
################################################################################
# Castnow will use the first Chromecast device it finds.
# You can define a specific device by using its name.
CASTNAME=""
# Castnow searches for devices via mDNS.
# You can define the IP address of your device to skip the searching process.
# This is the recommended method.
CASTIP=""
# Define a name for the screen that will be created
SCREENNAME="castnow_screen"
# Path to castnow binary
CASTNOW="/usr/bin/castnow"
# File to store the screen output temporarily
HARDCOPYFILE="/tmp/hardcopy_$SCREENNAME"
# User to execute screen command
# Use the same user that runs openhab
USER="openhab"
# Enable debug mode
DEBUG="no"
#
# Generate some commands based on the above defined values
#
# Creating the parameters using when starting castnow
if [ "$CASTIP" != "" ]
then
# Use IP to find Chromecast
CASTNOWPARAM="--address $CASTIP"
else
if [ "$CASTNAME" != "" ]
then
# Use Chromecast name if no IP is defined
CASTNOWPARAM="--device $CASTNAME"
else
# Use first found Chromecast if nothing is defined
CASTNOWPARAM=""
fi
fi
# Command to execute other conmmands as the defined user
if [ "$USER" == "`whoami`" ]
then
SUDOCMD=""
else
SUDOCMD="sudo -u $USER"
fi
<file_sep># castnow_control
Some scripts to integrate and control castnow via openHAB.
# Requirements
Install `screen` via your pakage manager. (e.g. `sudo apt-get install screen`)
Get `castnow` from GitHub: https://github.com/xat/castnow
Here is how it is done on Rasbian Jessie on RaspberryPi.
Add the repository for `nodejs`
```
curl -sL https://deb.nodesource.com/setup | sudo bash -
```
Install `nodejs` and `screen`.
```
sudo apt-get install nodejs screen
```
Install castnow
```
sudo npm install castnow -g
```
# Install
Clone this repository or copy the files to your system (e.g. `/opt/castnow_control`)
Copy or rename the default configuration from `castnow_scripts.cfg.default`to `castnow_scripts.cfg`and define your own values.
Chown the folder and files to the same user that will run the scripts. (e.g. `openhab`)
```
cd /opt
sudo git clone https://github.com/CWempe/castnow_control.git
cd castnow_control
cp castnow_scripts.cfg.default castnow_scripts.cfg
chown -R openhab:openhab /opt/castnow_control
```
Create a cronjob for `castnow_watchdog.sh`or execute it via `watch`.
Let the watchdog run every few seconds (depending on the available performance of your system).
# Integrating in openHAB
## exec binding
Install the exec binding.
On rasbian:
```
sudo apt-get install openhab-addon-binding-exec
```
## chromecast.items
```
String CastState "Status [%s]" { exec="<[/opt/castnow_control/castnow_get_state.sh state:1000:]" }
String CastSource "Title [%s]" { exec="<[/opt/castnow_control/castnow_get_state.sh source:1000:]" }
String CastDown "Volume -" {exec=">[TOGGLE:/opt/castnow_control/castnow_send_command.sh down]", "autoupdate"="false"}
String CastUp "Volume +" {exec=">[TOGGLE:/opt/castnow_control/castnow_send_command.sh up]", "autoupdate"="false"}
String CastMute "Mute" {exec=">[TOGGLE:/opt/castnow_control/castnow_send_command.sh mute]", "autoupdate"="false"}
String CastPause "Pause" {exec=">[TOGGLE:/opt/castnow_control/castnow_send_command.sh pause]", "autoupdate"="false"}
String CastStop "Stop" {exec=">[TOGGLE:/opt/castnow_control/castnow_send_command.sh stop]", "autoupdate"="false"}
String CastLeft "Seek backwards" {exec=">[TOGGLE:/opt/castnow_control/castnow_send_command.sh left]", "autoupdate"="false"}
String CastRight "Seek forward" {exec=">[TOGGLE:/opt/castnow_control/castnow_send_command.sh right]", "autoupdate"="false"}
String CastQuit "Quit" {exec=">[TOGGLE:/opt/castnow_control/castnow_send_command.sh quit]", "autoupdate"="false"}
```
## chromecast.sitemap
```
sitemap chromecast label="Chromecast"
{
Frame label="State" {
Text item=CastState
Text item=CastSource
}
Frame label="Control" {
Switch item=CastDown
Switch item=CastUp
Switch item=CastMute
Switch item=CastPause
Switch item=CastStop
Switch item=CastLeft
Switch item=CastRight
Switch item=CastQuit
}
}
```
# What do the scripts do?
## castnow_get_state.sh
This script reads the output from castnow and returns the `Status` and/or the `Source` (e.g. title of video).
## castnow_send_command.sh
This script send commands (e.g. play/pause, mute, stop, Vol+, ...) to castnow.
## castnow_watchdog.sh
This script (re)starts castnow if it is not running or lost connection to your Chromecast device.
# How it works
Because castnow only runs in the foreground in the command line we need a way to put it back in the background and let it run as some kind of deamon.
That is way these scripts use `screen`.
To get the current state we take a `hardcopy`of the screen/castnow output, save it to a file and parse it.
We use the `-X stuff`function of `screen`to send keypresses to castnow.
# Limitations/to-do
- open/start streams via castnow
- support multiple Chromecast devices at the same time
- push buttons do not work correctly in HABdroid and iOS app
see: https://community.openhab.org/t/habdroid-not-supporting-push-buttons-toggle/4604
<file_sep>#!/bin/bash
################################################################################
#
# /opt/castnow_scripts/castnow_get_state.sh (openhab:openhab, 744)
#
# This script gets the state of the chromecast and the source that is playing.
# In this case "source" means title.
# (e.g. title of a YouTube video, or "Artist - Title" of a song)
#
# by <NAME>
# 2015-11-27
#
################################################################################
# define base directory for castnow_scripts
BASEDIR="$(dirname "$0")"
# Import configuration
if [ -f "$BASEDIR/castnow_scripts.cfg" ]
then
source $BASEDIR/castnow_scripts.cfg
else
if [ -f "$BASEDIR/castnow_scripts.cfg.default" ]
then
source $BASEDIR/castnow_scripts.cfg.default
else
echo "Cannot find configuration file ($BASEDIR/castnow_scripts.cfg[.default])!"
exit 1
fi
fi
# write the current screen output to file
$SUDOCMD screen -d -R -S $SCREENNAME -p0 -X hardcopy $HARDCOPYFILE
# Read screen output from file with 'cat'
# Use 'echo' to get rid of blank spaces at the beginning and end of each line
# 'cut' to remove "State:" and "Source:"
# Remove dots with 'tr'
CASTSTATE="`echo \`cat $HARDCOPYFILE | grep State | cut -d : -f 2-\` | tr -d '.'`"
CASTSOURCE="`echo \`cat $HARDCOPYFILE | grep Source | cut -d : -f 2-\``"
# check how many parameter are set
if [ "$#" -gt "0" ]
then
# check if the first parameter is "state"
if [ "$1" == "state" ]
then
echo -E "$CASTSTATE"
else
# check if the first parameter is "source"
if [ "$1" == "source" ]
then
echo -E "$CASTSOURCE"
else
echo "Unkwnown parameter: $1"
exit 1
fi
fi
else
# Print both values if there are more or less than one parameter passed to this script
echo "State: $CASTSTATE"
echo "Source: $CASTSOURCE"
fi
#EOF<file_sep>#!/bin/bash
################################################################################
#
# /opt/castnow_scripts/castnow_send_command.sh (openhab:openhab, 744)
#
# This script sends commands to the running castnow screen to control
# the connected Chromecast device.
#
# Use: ./castnow_send_command.sh <command>
#
# by <NAME>
# 2015-11-27
#
################################################################################
# define base directory for castnow_scripts
BASEDIR="$(dirname "$0")"
# Import configuration
#source $BASEDIR/castnow_scripts.cfg
# Import configuration
if [ -f "$BASEDIR/castnow_scripts.cfg" ]
then
source $BASEDIR/castnow_scripts.cfg
else
if [ -f "$BASEDIR/castnow_scripts.cfg.default" ]
then
source $BASEDIR/castnow_scripts.cfg.default
else
echo "Cannot find configuration file ($BASEDIR/castnow_scripts.cfg[.default])!"
exit 1
fi
fi
# command to send the defined input to the screen
SCREENCMD="$SUDOCMD screen -S $SCREENNAME -X stuff"
####echo "$SCREENCMD"
# print erro if the amount of passed parameters is not 1
if [ "$#" -ne "1" ]
then
echo "Specify one command!"
echo "Supported: pause, play, stop, mute, unmute, up, down, right, left, quit"
exit 1
else
COMMAND="$1"
fi
case $COMMAND in
# control playback
pause|play)
$SCREENCMD " "
;;
stop)
$SCREENCMD "s"
;;
# Volume (un)mute
mute|unmute)
$SCREENCMD "m"
;;
# Volume up/down
up)
$SCREENCMD "^[^[[A"
;;
down)
$SCREENCMD "^[^[[B"
;;
# Seek forward
right)
$SCREENCMD "^[^[[C"
;;
# Seek backward
left)
$SCREENCMD "^[^[[D"
;;
# Next in playlist
# does not work
next)
# $SCREENCMD "n"
echo "'next' does not work!"
;;
# Quit castnow
quit)
$SCREENCMD "quit"
;;
*)
echo "Unkwnown parameter: $1"
;;
esac
#EOF<file_sep>#!/bin/bash
################################################################################
#
# /opt/castnow_scripts/castnow_watchdog.sh (openhab:openhab, 744)
#
# This script checks the connection of a running castnow screen
# and restarts or starts the program if necessary.
#
# To periodically running this script, define it in cron or execute it via watch
#
# by <NAME>
# 2015-11-27
#
################################################################################
# define base directory for castnow_scripts
BASEDIR="$(dirname "$0")"
# Import configuration
#source $BASEDIR/castnow_scripts.cfg
# Import configuration
if [ -f "$BASEDIR/castnow_scripts.cfg" ]
then
source $BASEDIR/castnow_scripts.cfg
else
if [ -f "$BASEDIR/castnow_scripts.cfg.default" ]
then
source $BASEDIR/castnow_scripts.cfg.default
else
echo "Cannot find configuration file ($BASEDIR/castnow_scripts.cfg[.default])!"
exit 1
fi
fi
# check if castnow is still running
# ps all | grep -v "grep" | grep -q "node $CASTNOW"
$SUDOCMD screen -ls | grep -q "$SCREENNAME"
if [ "`echo $?`" -ne "0" ]
then
if [ "$DEBUG" = "yes" ]
then
echo "castnow is not running anymore!"
echo ""
echo "Restarting castnow..."
fi
$SUDOCMD screen -d -m -S $SCREENNAME $CASTNOW $CASTNOWPARAM
else
if [ "$DEBUG" = "yes" ]
then
echo "castnow is still running"
fi
# check current state
$BASEDIR/castnow_get_state.sh | grep -q "Closed"
# if state is closed, quit screen
# screen will be started next run automatically
if [ "`echo $?`" -eq "0" ]
then
if [ "$DEBUG" = "yes" ]
then
echo "State is closed. Quit screen..."
echo "$SUDOCMD screen -X -S $SCREENNAME quit"
fi
$SUDOCMD screen -X -S $SCREENNAME quit
fi
fi
#EOF
|
867a0ed88125d6df2ddbaf03dce6ff775cb12dac
|
[
"Markdown",
"Shell"
] | 5 |
Shell
|
CWempe/castnow_control
|
e74bdf1043f6f9b22d5899813836674bc31be7ba
|
25b1d7f46c3d381c6d433365eb09d642a7ddf57a
|
refs/heads/master
|
<file_sep><?php defined('WWW_ROOT') OR exit('No direct access allowed!');
class MySQL
{
var $pdo = null;
var $connected = false;
var $lastErrorMsg = null;
var $lastErrorCode = null;
// connect();
// connect($config);
// connect($host, $port, $username, $password, $dbname, $unixsocket);
function connect() {
$host = '';
$port = '';
$username = '';
$password = '';
$dbname = '';
$unixsocket = '';
$args = func_get_args();
if(count($args) == 0) {
global $config;
return $this->connect($config);
} elseif(count($args) == 1 && is_array($args[0])) {
return $this->connect(
$args[0]['mysql']['hostname'],
$args[0]['mysql']['hostport'],
$args[0]['mysql']['username'],
$args[0]['mysql']['password'],
$args[0]['mysql']['database'],
$args[0]['mysql']['unixsock']);
} elseif(count($args) >= 5) {
$host = $args[0];
$port = $args[1];
$username = $args[2];
$password = $args[3];
$dbname = $args[4];
if(count($args) == 6) {
$unixsocket = $args[5];
}
$flags = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$init = "mysql:host=$host;port=$port;dbname=$dbname";
if(!empty($unixsocket)) {
$init = "mysql:unix_socket=$unixsocket;dbname=$dbname";
}
try {
$this->pdo = new PDO($init, $username, $password, $flags);
$this->connected = true;
} catch (PDOException $e) {
$this->set_error($e->getMessage());
$this->connected = false;
}
return $this->connected;
}
return false;
}
function alias_query($query, $aliases = array()) {
try {
$s = $this->pdo->prepare($query);
if(count($aliases) > 0) {
$s->execute($aliases);
} else {
$s->execute();
}
return $s;
} catch (PDOException $e) {
$this->set_error($e->getMessage());
return false;
}
}
//$r = $this->sql->insert('fansubbers', array('name' => 'Commie'));
function insert($table, $valuesArray) {
if(empty($valuesArray) || !is_array($valuesArray)) {
$this->set_error("MySQL::insert: Invalid Parameters");
return false;
}
$fields = array();
$values = array();
$qmarks = array();
foreach($valuesArray as $id => $value) {
$fields[] = '`' . $id . '`';
$values[] = $value;
$qmarks[] = '?';
}
$fields = implode(',', $fields);
$qmarks = implode(',', $qmarks);
$qstr = "INSERT INTO $table ($fields) VALUES ($qmarks)";
$s = $this->alias_query($qstr, $values);
return ($s !== false);
}
//$r = $this->sql->select("SELECT * FROM fansubbers WHERE name LIKE ?", array('%Co%'));
function select($query, $aliases = array()) {
$s = $this->alias_query($query, $aliases);
return ($s !== false) ? $s->fetch(PDO::FETCH_ASSOC) : false;
}
//$r = $this->sql->selectAll("SELECT * FROM fansubbers WHERE name LIKE ?", array('%Co%'));
function selectAll($query, $aliases = array()) {
$s = $this->alias_query($query, $aliases);
return ($s !== false) ? $s->fetchAll() : false;
}
//$r = $this->sql->delete('DELETE FROM genre_tags WHERE animeid=?', array(678));
function delete($query, $aliases = array()) {
$s = $this->alias_query($query, $aliases);
return ($s !== false) ? $s->rowCount() : false;
}
// Note to self: This should be a lot better, easier and use normal aliases. I don't know why I did it this way.
//$r = $this->sql->update('UPDATE genre_tags SET animeid=:animeid WHERE animeid=:search', array('animeid' => 678, 'search' => 123));
function update($query, $valuesArray) {
if(empty($valuesArray) || !is_array($valuesArray)) {
$this->set_error("MySQL::update: Invalid Parameters");
return false;
}
try {
$s = $this->pdo->prepare($query);
foreach($valuesArray as $id => $value) {
$s->bindValue(":$id", $value, ((is_numeric($value) ? PDO::PARAM_INT : PDO::PARAM_STR)));
}
$s->execute();
} catch (PDOException $e) {
$s = false;
}
return ($s !== false) ? $s->rowCount() : false;
}
function set_error($msg) {
$this->lastErrorMsg = $msg;
}
function get_error() {
return $this->lastErrorMsg;
}
function close() {
$this->pdo = null;
}
};
?><file_sep><?php
class Octo_Put
{
var $loader = null;
function __construct($loader) {
$this->loader = $loader;
}
function web($path) {
global $config;
echo(APP_DIR . '/' . WEBROOT_DIR . '/' . $path);
}
function arg($name) {
echo($this->loader->viewArgs[$name]);
}
function config($group, $name) {
global $config;
if(!isset($config[$group])) return;
if(!isset($config[$group][$name])) return;
echo($config[$group][$name]);
}
};
?><file_sep><?php defined('WWW_ROOT') OR exit("No direct access allowed!\n");
require_once('Octo_Base.php');
require_once('Octo_Model.php');
require_once('Octo_RainTPL.php');
require_once('Octo_Controller.php');
class Octo extends Octo_Base
{
var $controller = null;
var $controller_class = '';
var $controller_func = null;
var $tpl = null;
function main() {
global $config;
parent::main(); // Loads configuration and loader
$this->initialize_raintpl();
$this->parse_controller_data();
}
function initialize_raintpl() {
global $config;
raintpl::configure('tpl_dir', ROOT . DS . APP_DIR . DS . 'view' . DS);
raintpl::configure('cache_dir', ROOT . DS . APP_DIR . DS . 'cache' . DS);
raintpl::configure('base_url', $config['base']['webpath']);
raintpl::configure('tpl_ext', 'tpl.html');
raintpl::configure('path_replace', false);
$this->tpl = new RainTPL();
}
function parse_controller_data() {
global $config;
$controllerPath = ROOT . DS . APP_DIR . DS . 'controller' . DS;
if(isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !== NULL) {
$pathdata = explode('/', $_SERVER['PATH_INFO']);
$controller_data = array();
if(count($pathdata) > 1 && isset($pathdata[1]) && !empty($pathdata[1])) {
array_shift($pathdata); // Remove first bit
if(empty($pathdata[count($pathdata) - 1])) {
array_pop($pathdata);
}
$directoryResolvedIndex = 0;
for(; $directoryResolvedIndex < count($pathdata); $directoryResolvedIndex++) {
if(!is_dir($controllerPath . implode(array_slice($pathdata, 0, $directoryResolvedIndex + 1), DS))) {
break;
}
}
// Check if controller file exists for action
$selectedDirectory = $controllerPath . implode(array_slice($pathdata, 0, $directoryResolvedIndex), DS) . DS;
$actiondata = array_splice($pathdata, $directoryResolvedIndex, count($pathdata) - $directoryResolvedIndex);
// If the controller file exists, use that, if not, base
$controller = 'base.php';
$this->controller_class = $pathdata[$directoryResolvedIndex - 1] . '_Controller'; // Default controller classname is the directory it is in
if(!empty($actiondata)) {
if(file_exists($selectedDirectory . $actiondata[0] . '.php')) {
$controller = $actiondata[0] . '.php';
$this->controller_class = $actiondata[0] . '_Controller';
array_shift($actiondata); // remove controller from action, these are params now
}
}
require_once($selectedDirectory . $controller);
if(!class_exists($this->controller_class)) {
throw new Exception("You must include a controller class in your controller file [{$this->controller_class}]");
}
$this->controller = new $this->controller_class($this);
// and now we decide what is a parameter or not
$this->controller_func = 'index';
if(!empty($actiondata)) {
if(method_exists($this->controller, $actiondata[0])) {
$this->controller_func = $actiondata[0];
array_shift($actiondata);
}
}
// call function and pass arguments
$this->controller->{$this->controller_func}($actiondata);
}
} else {
$controllerFile = $config['base']['default_page'];
$this->controller_class = $controllerFile . '_Controller';
$this->controller_func = 'index';
$controllerFile = $controllerPath . $controllerFile . DS . 'base.php';
if(file_exists($controllerFile)) {
require_once($controllerFile);
$this->controller = new $this->controller_class($this);
if(method_exists($this->controller, 'index')) {
$this->controller->index(array());
} else {
throw new Exception("Default controller missing 'index' function");
}
} else {
throw new Exception("Default controller file misconfiguration");
}
}
}
};
?>
<file_sep><?php defined('WWW_ROOT') OR exit("No direct access allowed!\n");
require_once('Octo_Base.php');
class Console extends Octo_Base
{
var $loader = null;
var $start_time = 0;
var $applet = null;
var $parameters = array();
function __construct($arguments) {
$this->applet = $arguments[1];
$this->parameters = array_slice($arguments, 2);
}
function main() {
global $config;
parent::main();
$conPath = $config['console']['app_path'];
$appPath = $conPath . $this->applet . '/';
if(is_dir($conPath) && is_dir($appPath) && file_exists($appPath . 'base.php')) {
require($appPath . 'base.php');
$consoleClassMake = new $this->applet($this);
$consoleClassMake->main($this->parameters);
} else {
throw new Exception("Console application [$appPath] does not exist or the console directory has been removed");
}
}
};
?>
<file_sep><?php
// Delivery of JS and CSS
?>
<file_sep><?php
define('APP_DIR', 'app');
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__FILE__));
define('WEBROOT_DIR', 'webroot');
define('WWW_ROOT', ROOT . DS . APP_DIR . DS . WEBROOT_DIR . DS);
// We're going to see if we have any command line arguments here
// If we do, we're going to go straight to console mode
if(isset($argv) && isset($argv[1]) && !empty($argv[1])) {
require_once(ROOT . DS . APP_DIR . DS . 'core' . DS . 'Console.php');
$console = new Console($argv);
$console->main();
exit();
} elseif(isset($argv) && isset($argv[0])) {
echo("Invalid command line parameters.\n");
exit();
}
require_once(ROOT . DS . APP_DIR . DS . 'core' . DS . 'Octo.php');
$octo = new Octo();
$octo->main();
?>
<file_sep><?php
class Octo_Controller {
var $base = null;
var $actionable = true;
function __construct($base) {
$this->base = $base;
$this->loader = $base->loader; // Ease of access
}
};
?><file_sep><?php defined('WWW_ROOT') OR exit("No direct access allowed!\n");
class Octo_Loader
{
var $lastError = null;
var $main = null;
var $arguments = array();
function __construct($main) {
$this->main = $main;
}
function load_if_exists($file) {
$file = ROOT . DS . APP_DIR . DS . $file;
$r = file_exists($file);
if($r) {
include($file);
} else {
$this->lastError = ('load_if_exists: No such file for path [' . $file . ']');
}
return $r;
}
function class_load_if_exists($dir, $class, $bit = '', $construct = null) {
$fullpath = $dir . DS . $class . '.php';
$fullclass = $class . $bit;
$l = $this->load_if_exists($fullpath);
if(class_exists($fullclass)) {
if($construct === null) {
return new $fullclass();
} else {
return new $fullclass($construct);
}
} else {
$this->lastError = ('class_load_if_exists: No such class exists for plugin [' . $fullpath . '][' . $fullclass . ']');
}
return null;
}
function plugin($name, $sub = '') {
if(class_exists($name)) { // We don't need to reload this
return new $name();
}
return $this->class_load_if_exists('plugin' . ((!empty($sub)) ? (DS . $sub) : ''), $name);
}
function model($name, $args = array()) {
$fullClass = $name . '_Model';
if(class_exists($fullClass)) { // We don't need to reload this
return new $fullClass($args);
}
return $this->class_load_if_exists('model', $name, '_Model', $args);
}
function assign($name, $value) {
$this->arguments[$name] = $value;
}
function view($name, $args = array()) {
$this->main->tpl->assign($this->arguments);
$this->main->tpl->assign($args);
$this->main->tpl->draw($name);
unset($this->arguments);
$this->arguments = array();
return true;
}
};
?>
<file_sep><?php
class Octo_ViewContainer
{
var $loader = null;
function __construct($loader) {
$this->loader = $loader;
}
function render_view($type, $name, $args) {
return $loader->load_if_exists('view' . DS . $type . DS . $name . '.php');
}
function web($path) {
global $config;
echo(APP_DIR . '/' . WEBROOT_DIR . '/' . $path);
}
function arg($name) {
echo($this->loader->viewArgs[$name]);
}
function conf($name, $group = '') {
global $config;
if(!empty($group)) {
echo($config[$group][$name]);
return;
}
echo($config[$name]);
}
};
?><file_sep><?php defined('WWW_ROOT') OR exit('No direct access allowed!');
class BasicHTTP
{
var $ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0 Firefox/17.0';
function set_ua($ua) {
$this->ua = $ua;
}
function get($url, $content = 'text/plain') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: ' . $content));
curl_setopt($ch, CURLOPT_USERAGENT, $this->ua);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
$e = curl_exec($ch);
curl_close($ch);
return $e;
}
function post($url, $post, $content = 'text/plain') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: ' . $content));
curl_setopt($ch, CURLOPT_USERAGENT, $this->ua);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
$e = curl_exec($ch);
curl_close($ch);
return $e;
}
};
?><file_sep><?php defined('WWW_ROOT') OR exit("No direct access allowed!\n");
require_once('Octo_Loader.php');
class Octo_Base
{
var $loader = null;
var $start_time = 0;
function main() {
global $config;
$this->start_time = microtime();
$this->load_configs();
$this->load_loader();
}
function load_loader() {
$this->loader = new Octo_Loader($this); // The loader class will load models, views and plugins
}
function load_configs() {
global $config;
$iterator = new \DirectoryIterator(ROOT . DS . APP_DIR . DS . 'config' . DS);
foreach ( $iterator as $info ) {
if($info->isFile() && !$info->isDot() && $info->getExtension() == 'json') {
$fileContents = file_get_contents(ROOT . DS . APP_DIR . DS . 'config' . DS . $info->getFilename());
if($fileContents !== FALSE) {
$decoded = json_decode($fileContents, true);
if($decoded !== FALSE && $decoded !== NULL) {
$base = $info->getBasename('.json');
$config[$base] = $decoded[$base];
} else {
throw new Exception("Failed to decode {$info->getFilename()}");
}
} else {
throw new Exception("Failed to load {$info->getFilename()}");
}
}
}
}
};
?>
<file_sep><?php
class Octo_Model
{
var $args = array();
function __construct($args) {
$this->args = $args;
}
};
?><file_sep>octo
====
Simplistic PHP MVC core powering Haruhichan v3
<file_sep><?php defined('WWW_ROOT') OR exit("No direct access allowed!\n");
class Applet
{
var $con = null;
function __construct($console) {
$this->con = $console;
}
function main($args) {
print_r($args);
}
};
?>
<file_sep><?php defined('WWW_ROOT') OR exit("No direct access allowed!\n");
class FrontPage_Controller extends Octo_Controller {
// If you want things to be loaded for this controller across all actions, do this
function __construct($base) {
parent::__construct($base);
}
function index($args) {
global $config;
echo('hello world');
}
function testaction1($args) {
var_dump($args);
echo('<br />action1');
}
};
?>
<file_sep><?php
class TestAction2_Controller
{
function __construct($base) {
parent::__construct($base);
}
function index($args) {
//
}
};
?>
|
7bf27b0d1df43173c19c11de9324fd4f5e8b35b9
|
[
"Markdown",
"PHP"
] | 16 |
PHP
|
haruhichan/octo
|
1dbf35f9230121cea52fc62efedf15b7bfb074a8
|
5f25fed60515c8ff129e68f5c2b2c672de52ce8d
|
refs/heads/master
|
<repo_name>contrepoint/ruby-array-explorer<file_sep>/data.js
var explorerDataEn = {
'add': {
'end': {
'name': 'push',
'link_name': 'push',
'desc': 'Adds element(s) to the end of an array. Returns the modified array',
'text': "nums = [2, 3, 5] #=> [2, 3, 5]<br>nums << 8 #=> [2, 3, 5, 8]<br>nums.push(13, 21) #=> [2, 3, 5, 8, 13, 21]<br>nums.push(37) #=> [2, 3, 5, 8, 13, 21, 37]"
},
'start': {
'name': 'unshift',
'link_name': 'unshift',
'desc': 'Adds element(s) to the front of an array. Returns the modified array',
'text': 'nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.unshift(3) #=> [3, 4, 5, 6]<br>nums.unshift(1, 2) #=> [1, 2, 3, 4, 5, 6]'
},
'insert': {
'name': 'insert',
'link_name': 'insert',
'desc': 'Inserts the given element(s) before the element with the given index. Returns the modified array',
'text': "nums = [3, 4, 5, 6] #=> [4, 5, 6]<br>nums.insert(2, 9) #=> [3, 4, 9, 6]<br>nums.insert(2, 'one', 1) #=>[3, 4, \"one\", 1, 9, 6]"
},
'concat': {
'name': '+',
'link_name': '2B',
'desc': 'Returns a new array built by adding (concatenating) two arrays together',
'text': "nums = [4, 5, 6] #=> [4, 5, 6]<br>more_nums = nums + [1, 2] #=> [4, 5, 6, 1, 2]<br>nums #=> [4, 5, 6]<br><br>[4, 5, 6] + [1, 2] #=> [4, 5, 6, 1, 2]"
}
},
'rm': {
'end': {
'name': 'pop',
'link_name': 'pop',
'desc': 'Removes the last n elements from the array and returns it. Returns nil if the array is empty',
'text': "nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.pop #=> 6<br>nums #=> [4, 5]<br><br>nums.pop(2) #=> [4, 5]<br>nums #=> []<br><br>nums.pop #=> nil<br>nums #=> []"
},
'start': {
'name': 'shift',
'link_name': 'shift',
'desc': 'Adds the last n elements to the array and returns it. Returns nil if the array is empty',
'text': 'nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.shift #=> 4<br>nums #=> [5, 6]<br><br>nums.shift(2) #=> [5, 6]<br>nums #=> []<br><br>nums.shift #=> nil<br>nums #=> []'
},
'delete_at': {
'name': 'delete_at',
'link_name': 'delete_at',
'desc': 'Deletes the element at the given index and returns that element. Returns nil if the index is out of range',
'text': "nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.delete_at(1) #=> 5<br>nums #=> [4, 6]<br><br>nums.delete_at(99) #=> nil"
},
'delete': {
'name': 'delete',
'link_name': 'delete',
'desc': 'Delete all items from the array that are equal to the given element. Returns the last deleted item or nil if no matching item is found',
'text': "nums = [4, 5, 5, 6] #=> [4, 5, 5, 6]<br>nums.delete(2) #=> nil<br>nums #=> [4, 5, 5, 6]<br><br>nums.delete(5) #=> 5<br>nums #=> [4, 6]"
},
'compact': {
'name': 'compact',
'link_name': 'compact',
'desc': 'Returns a copy of the original array with all nil elements removed.',
'text': "items = [nil, 4, nil, 6, nil, nil] #=> [nil, 4, nil, 6, nil, nil]<br>items.compact #=> [4, 6]<br>items #=> [nil, 4, nil, 6, nil, nil]"
},
'uniq': {
'name': 'uniq',
'link_name': 'uniq',
'desc': 'Returns a copy of the original array with all duplicate elements removed.',
'text': "nums = [5, 4, 5, 1, 7, 5, 1] #=> [5, 4, 5, 6, 7, 5, 1]<br>nums.uniq #=> [4, 7]<br>nums #=> [5, 4, 5, 6, 7, 5, 1]"
}
},
'find': {
'specific': {
'name': '[]',
'link_name': '5B-5D',
'desc': 'Returns the element at the specified index(es)',
'text': "nums = [1, 2, [3, 3.5]] #=> [1, 2, [3, 3.5]]<br>nums[0]#=> 1<br>nums[2, 1] #=> 3.5"
},
'match': {
'name': 'select',
'link_name': 'select',
'desc': 'Returns a new array containing all elements of the original array for which the given block returns a true value',
'text': 'nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.select { |num| num.even? } #=> [4, 6]'
},
'include': {
'name': 'include',
'link_name': 'include-3F',
'desc': 'Returns true if the given object is in the array. otherwise, returns false',
'text': 'nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.include?(3) #=> false<br>nums.include?(4) #=> true'
},
'bsearch': {
'name': 'bsearch',
'link_name': 'bsearch',
'desc': 'Uses binary search to find a value in a sorted array that meets a given condition. Returns nil if not found',
'text': "nums = [0, 4, 7, 10, 12]<br>nums.bsearch {|x| x >= 4 } #=> 4<br>nums.bsearch {|x| x >= 6 } #=> 7<br>nums.bsearch {|x| x >= -1 } #=> 0<br>nums.bsearch {|x| x >= 100 } #=> nil<br>nums.bsearch{|x| x == 7 } => 7<br>nums.bsearch {|x| x == 6 } #=> nil"
}
},
'iter': {
'each': {
'name': 'each',
'link_name': 'each',
'desc': 'calls the given block once for each element in the array. Returns the original array',
'text': "nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.each{|x| print x+1} #=> [4, 5, 6]<br>#the command above prints '567' and returns [4, 5, 6]"
},
'map': {
'name': 'map',
'link_name': 'map',
'desc': 'calls the given block once for each element in the array. Returns the original array, whose values have been replaced by the values returned by the block',
'text': 'nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.each{|x| x+10} #=> [14, 15, 16]'
}
},
'sort': {
'reverse': {
'name': 'reverse',
'link_name': 'reverse',
'desc': "Returns a new array containing the original array's elements in reverse order. <br><br><code>reverse</code> does not modify the original array. <code>reverse!</code> modifies the original array",
'text': "nums = [5, 4, 6] #=> [5, 4, 6]<br>nums.reverse #=> [6, 4, 5]<br>nums #=> [5, 4, 6]<br><br>nums.reverse! #=> [6, 4, 5]<br>nums #=> [6, 4, 5]"
},
'sort': {
'name': 'sort',
'link_name': 'sort',
'desc': 'Returns a new array created by sorting the original array.<br><code>sort</code> does not modify the original array. <code>sort!</code> modifies the original array',
'text': "nums = [5, 4, 6] #=> [5, 4, 6]<br>nums.sort #=> [4, 5, 6]<br><br>nums #=> [5, 4, 6]<br>nums.sort! #=> [4, 5, 6]<br>nums #=> [4, 5, 6]<br>"
}
},
'other': {
'length': {
'name': 'length',
'link_name': 'length',
'desc': 'Returns the length of an array. Length may be 0.',
'text': "nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.length #=> 3"
},
'empty': {
'name': 'empty',
'link_name': 'empty-3F',
'desc': 'Returns true if the array has no elements. otherwise, returns false',
'text': 'nums = [4, 5, 6] #=> [4, 5, 6]<br>nums.empty? #=> false<br><br>nums = [] #=> []<br>nums.empty? #=> true'
}
}
};
var explorerData = {
'en': explorerDataEn
}
<file_sep>/readme.md
# [Ruby Array Explorer](https://contrepoint.github.io/ruby-array-explorer/)
* Ruby is my first programming language. When learning it, I spent a lot of time looking up documentation and googling. I was inspired by <NAME>'s [Javascript Array Explorer](https://sdras.github.io/array-explorer) and ported it to Ruby.
* To quote Sarah, "please keep in mind that this is not meant to be as comprehensive or a replacement for full documentation". Each method also links to the Ruby docs.
* I based the examples and longer descriptions off the Ruby docs, altering as needed to make it more beginner-friendly.
## Notes:
* Ruby commands always return something.
* At the prompt of [irb](http://ruby-doc.org/stdlib-2.0.0/libdoc/irb/rdoc/IRB.html), a Ruby shell, typing in `nums = [4, 5, 6]` and pressing enter results in `=> [4, 5, 6]`.
* Similarly, the code in [Ruby Array Explorer]((https://contrepoint.github.io/ruby-array-explorer/) shows you what is returned at the end of every command.
* Thus, `nums = [4, 5, 6] #=> [4, 5, 6]` means that `nums = [4, 5, 6]` returns `[4, 5, 6]`
* Syntax highlighted with [highlight.js](https://highlightjs.org/)
<file_sep>/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ruby Array Explorer</title>
<!-- Google Tag Manager -->
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-T4M78QN');
</script>
<!-- End Google Tag Manager -->
<link rel="stylesheet" href="index.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript" src="data.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/gruvbox-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script>
hljs.initHighlightingOnLoad();
hljs.configure({useBR: true});
</script>
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-T4M78QN"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<div id='octocat'>
<a href="https://github.com/contrepoint/ruby-array-explorer" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill: #f55e41; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</div>
<div id='language'>Language:
<select id='sel-language'>
<option value='en'>English</option>
</select>
</div>
<div id='content'>
<div id='left'>
<h1 id='left-title'>Ruby Array Explorer</h1>
<h2 id='left-description'>Find the array method you need without digging through the docs</h2>
<div id='left-content'>
<div>
I have an array. I would like to:
<select id='first-selector'>
<option value='default'>...</option>
<option value="add">add elements or other arrays</option>
<option value="rm">remove elements</option>
<option value="find">find elements</option>
<option value="iter">iterate over elements</option>
<option value='sort'>order the array</option>
<option value='other'>do something else</option>
</select>
</div>
<div id='second-selector'>
<div id='add'>I need to add:
<select id='sel-add'>
<option value='default'>...</option>
<option value='start'>element(s) to the front of an array</option>
<option value='end'>element(s) to the end of an array</option>
<option value="insert">element(s) at a specific array location</option>
<option value='concat'>this array to other array(s)</option>
</select>
</div>
<div id='rm'>I need to remove:
<select id='sel-rm'>
<option>...</option>
<option value='start'>element(s) from the start of the array</option>
<option value="end">element(s) from the end of an array</option>
<option value="delete_at">element(s) at a specific location</option>
<option value="delete">all occurences of a specific element</option>
<option value="compact">nil elements</option>
<option value="uniq">duplicate elements</option>
</select>
</div>
<div id='find'>I need to find:
<select id='sel-find'>
<option>...</option>
<option value='specific'>an element at a specific position</option>
<option value="match">elements that match a condition I create</option>
<option value='include'>whether a certain element exists</option>
<option value="bsearch">an element that matches a condition in a sorted array</option>
</select>
</div>
<div id='iter'>I need to iterate by:
<select id='sel-iter'>
<option>...</option>
<option value='each'>executing a function I will create for each element</option>
<option value="map">creating a new array from each element with a function I create</option>
</select>
</div>
<div id='sort'>I need to:
<select id='sel-sort'>
<option>...</option>
<option value='reverse'>reverse the array</option>
<option value="sort">sort the array's elements</option>
</select>
</div>
<div id='other'>I need to:
<select id='sel-other'>
<option>...</option>
<option value='length'>find an array's length</option>
<option value="empty">check whether an array is empty</option>
</select>
</div>
</div>
<div id='documentation'>
<h2 id='doc-title'>Create an Array</h2>
<div>
A new array can be created by using the literal constructor [].<br>
Arrays can contain different types of objects.
</div>
<a href='https://ruby-doc.org/core-2.5.0/Array.html#class-Array-label-Creating+Arrays' id='doc-link' target='_blank'>see the docs →</a>
</div>
</div>
</div>
<div id='right'>
<h2 id='right-title'>Code</h2>
<div id='right-content'>
<div>
<pre id='codeblock'>
<code id='code' class='ruby'> # Create an array<br>numbers = [1, 2, 3] #=> [1, 2, 3]</code>
</pre>
</div>
</div>
</div>
</div>
<footer class='footer'>
inspired by <a href='https://sdras.github.io/array-explorer/'>Javascript Array Explorer
</footer>
</body>
</html>
<file_sep>/index.js
$(document).ready(function(){
initHide();
function initHide() {
hideSecondSelectorChildren();
hideDocumentation();
}
function hideDocumentation() {
$("#documentation").hide();
}
$("#first-selector").change(function() {
resetFirstSelector(this.value);
});
function resetFirstSelector(selectedVal) {
hideSecondSelectorChildren();
hideDocumentation();
$("#second-selector #" + selectedVal ).show();
$("#code").html(" # Create an array<br>numbers = [1, 2, 3] #=> [1, 2, 3]");
highlightCode();
}
function highlightCode() {
$('pre code').each(function(i, e) {hljs.highlightBlock(e);});
}
function hideSecondSelectorChildren() {
$("#second-selector").children().hide();
}
// when #second-selector children change
$("#sel-add").change(function() {
updateInfo('add', this.value);
});
$("#sel-rm").change(function() {
updateInfo('rm', this.value);
});
$("#sel-find").change(function() {
updateInfo('find', this.value);
});
$("#sel-iter").change(function() {
updateInfo('iter', this.value);
});
$("#sel-sort").change(function() {
updateInfo('sort', this.value);
});
$("#sel-other").change(function() {
updateInfo('other', this.value);
});
function updateInfo(category, itemName) {
updateCode(category, itemName);
showDocumentation();
highlightCode();
updateDocumentation(category, itemName);
}
function updateCode(category, itemName) {
$("#code").html(explorerData['en'][category][itemName]['text']);
}
function showDocumentation(){
$("#documentation").show();
}
function updateDocumentation(category, itemName) {
var selectedItem = explorerData['en'][category][itemName];
var elem = [];
elem[0] = "<h2 id='doc-title'>Array." + selectedItem['name'] + '</h2>';
elem[1] = '<div>' + selectedItem['desc'] + '</div>';
elem[2] = "<a href='https://ruby-doc.org/core-2.5.0/Array.html#method-i-" + selectedItem['link_name'] + "' id='doc-link' target='_blank'>see the docs →</a>";
var text = elem.join('');
$('#documentation').html(text);
}
});
|
4f3e8cc8d6ade29b6190873a90041fc5bf6bac7f
|
[
"JavaScript",
"HTML",
"Markdown"
] | 4 |
JavaScript
|
contrepoint/ruby-array-explorer
|
c94db83e532f48529476fa83de2eeb352f64550c
|
31a7d1499d3fdcb653ea9a3ff33190c5108c5606
|
refs/heads/master
|
<file_sep>import React from 'react';
import profilePicture from "../../../static/assets/images/bio/Koy-portfolio.png";
export default function() {
return (
<div className="about content-page-wrapper">
<div className="left-column">
<img src={profilePicture}></img>
</div>
<div className="right-column">
Hi my name is <NAME>, I am a web developer. I have a passion for success and a creative mind, I love to create and think up new things. Outside the box is a very common place to me. There has to be a more efficient way, there always is. I hope you enjoy taking a look at what skills I have and what I have to offer you and your company.
</div>
</div>
)
}
|
b956763003fad24fda41bba8f6dde843fb89bdda
|
[
"JavaScript"
] | 1 |
JavaScript
|
herrickoy/koy-herrick-porfolio
|
08d3282d91a94b0e79056cfb8cda417afb79cc21
|
e2a779108841374e2f1fe99943f5471748d4f528
|
refs/heads/master
|
<file_sep>#shamelessly taken from threebarber's alertme project on gh
# requires requests, oauth2 and python-twitter packages
# -*- coding: utf-8 -*-
import time
import requests
import smtplib
from timeit import default_timer as timer
import oauth2 as oauth
#loading keys from another file
#safe to comment out the next 3 lines if you want to declare the key variable strings in this file
import sys
sys.path.append('/Users/Demian/Documents/projects/')
from twitterkeys import *
import twitter
api = twitter.Api(consumer_key=my_consumer_key,
consumer_secret=my_consumer_secret,
access_token_key=my_access_token_key,
access_token_secret=my_access_token_secret)
start = timer()
# notification functions
def post_tweet(subject, body):
status = api.PostUpdate(subject + ' ' + body)
print(status.text)
def send_email(user, pwd, recipient, subject, body): #snippet courtesy of david / email sending function
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587) #start smtp server on port 587
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd) #login to gmail server
server.sendmail(FROM, TO, message) #actually perform sending of mail
server.close() #end server
print 'successfully sent the mail' #alert user mail was sent
except Exception, e: #else tell user it failed and why (exception e)
print "failed to send mail, " +str(e)
def main(): #main function
with requests.Session() as c:
url = 'http://alexotoro.wordpress.com'
wait_time = 45 #customizable time to wait to check for changes IE every 5 secs
page1 = c.get(url) #base page that will be compared against
time.sleep(wait_time) #wait inbeetween initial retrieval and comparison actions
page2 = c.get(url) #page to be compared against page1 / the base page
if page1.content == page2.content: #if else statement to check if content of page remained same
end = timer()
if ((end-start)) >= 60:
timeMinutes = (end-start) / 60
print "[-]No Change Detected @ " +str(url)+ "\n[-]Elapsed Time: " +str(timeMinutes)+ " minutes"
else:
print '[-]No Change Detected @ ' +str(url)+ "\n[+]Elapsed Time: " +str((end-start))+ " seconds"
else:
end = timer()
if int((end-start)) >= 60:
timeMinutes = (end-start) / 60
print '[+]Change Detected - \n[+]Elapsed Time: ' +str(timeMinutes)+ " minutes" #if anything was changed - it sends an email alerting the user
else:
print '[+]Change Detected - \n[+]Elapsed Time: ' +str((end-start))+ " seconds" #if anything was changed - it sends an email alerting the user
#pick the notification type here
#send_email(user, pwd, recipient, subject, body) #send notification email
post_tweet(subject, body)
page2 = None #clear page2 variable before looping through main function again
#time.sleep(wait_time) optional wait beetween starting again
main() #super simple easy loop method
if __name__ == "__main__": #start main function
main()
<file_sep># alertme
Script to monitor for changes in websites and send an email when one is detected
|
99aceb98b0752ee6f6611aef721b29cdea9a9d6c
|
[
"Markdown",
"Python"
] | 2 |
Python
|
alpacarodeo/alertme
|
23adbe8f05a332dfadc4f08452403c9a8d6e44de
|
3799f7ab671ddd20083f88aa3de8abf021c88ef2
|
refs/heads/master
|
<repo_name>mingyaulee/TestAdapterIssue<file_sep>/src/TestAdapterCore/TestMethodAttribute.cs
using System;
namespace TestAdapterCore
{
/// <summary>Use this attribute to mark a method as a test method.</summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class TestMethodAttribute : Attribute
{
/// <summary>Use this attribute to mark a method as a test method.</summary>
public TestMethodAttribute()
{
}
/// <summary>Use this attribute to mark a method as a test method.</summary>
/// <param name="displayName">The display name for this test.</param>
public TestMethodAttribute(string displayName)
{
DisplayName = displayName;
}
/// <summary>The display name for this test.</summary>
public string DisplayName { get; set; }
}
}
<file_sep>/src/TestAdapterCore/TestAssemblyAttribute.cs
using System;
using System.Reflection;
namespace TestAdapterCore
{
/// <summary>Use this attribute to specify the test assembly.</summary>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
public class TestAssemblyAttribute : Attribute
{
public TestAssemblyAttribute(Type typeInAssembly)
{
Assembly = typeInAssembly.Assembly;
}
public Assembly Assembly { get; }
}
}
<file_sep>/src/VS.TestAdapter/TestExecutor.cs
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using System;
using System.Collections.Generic;
namespace VS.TestAdapter
{
[ExtensionUri(ExecutorUri)]
public class TestExecutor : ITestExecutor
{
public const string ExecutorUri = "executor://MyTestExecutor";
public void Cancel()
{
throw new NotImplementedException();
}
public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle)
{
// Just simulating all passing test result
foreach (var testCase in tests)
{
var testResult = new TestResult(testCase)
{
Outcome = TestOutcome.Passed
};
frameworkHandle.RecordResult(testResult);
}
}
public void RunTests(IEnumerable<string> sources, IRunContext runContext, IFrameworkHandle frameworkHandle)
{
// Look for test cases in assemblies
var testCases = new TestDiscoverer().FindTestCases(sources);
// Just simulating all passing test result
foreach (var testCase in testCases)
{
var testResult = new TestResult(testCase)
{
Outcome = TestOutcome.Passed
};
frameworkHandle.RecordResult(testResult);
}
}
}
}
<file_sep>/src/TestAdapterCore/Infrastructure/TestAssemblyLoader.cs
using System;
using System.IO;
using System.Reflection;
namespace TestAdapterCore.Infrastructure
{
public class TestAssemblyLoader : IDisposable
{
private TestAssemblyLoadContext testAssemblyLoadContext;
private bool disposedValue;
public Assembly LoadAssembly(string assemblyPath)
{
testAssemblyLoadContext = new TestAssemblyLoadContext(assemblyPath);
return testAssemblyLoadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(assemblyPath)));
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing && testAssemblyLoadContext is not null && testAssemblyLoadContext.IsCollectible)
{
testAssemblyLoadContext.Unload();
testAssemblyLoadContext = null;
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
<file_sep>/src/VS.TestAdapter/TestDiscoverer.cs
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using TestAdapterCore;
using TestAdapterCore.Infrastructure;
namespace VS.TestAdapter
{
[FileExtension(".dll")]
[DefaultExecutorUri(TestExecutor.ExecutorUri)]
public class TestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
var testCases = FindTestCases(sources);
foreach (var testCase in testCases)
{
discoverySink.SendTestCase(testCase);
}
}
public IEnumerable<TestCase> FindTestCases(IEnumerable<string> sources)
{
var testCases = new List<TestCase>();
using var testAssemblyLoader = new TestAssemblyLoader();
foreach (var source in sources)
{
// Load the assembly and find the assembly attribute which specifies which referenced assembly to search for tests
var assembly = testAssemblyLoader.LoadAssembly(source);
var testAssemblyAttribute = assembly.GetCustomAttributes(typeof(TestAssemblyAttribute), false).SingleOrDefault() as TestAssemblyAttribute;
if (testAssemblyAttribute is null)
{
continue;
}
// Now that the test assembly is found, look for methods which has the TestMethodAttribute
var testAssembly = testAssemblyAttribute.Assembly;
testCases.AddRange(FindTestsInAssembly(testAssembly));
}
return testCases;
}
private IEnumerable<TestCase> FindTestsInAssembly(Assembly assembly)
{
foreach (var exportedType in assembly.GetExportedTypes())
{
var publicMethods = exportedType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (var publicMethod in publicMethods)
{
if (publicMethod.IsDefined(typeof(TestMethodAttribute), true))
{
var integrationTestAttribute = publicMethod.GetCustomAttribute<TestMethodAttribute>();
yield return new TestCase()
{
DisplayName = integrationTestAttribute.DisplayName ?? publicMethod.Name,
ExecutorUri = new Uri(TestExecutor.ExecutorUri),
FullyQualifiedName = $"{exportedType.FullName}.{publicMethod.Name}",
Source = assembly.Location
};
}
}
}
}
}
}
<file_sep>/test/AProjectWithTests/Tests/MyTestClass.cs
using TestAdapterCore;
namespace AProjectWithTests.Tests
{
public class MyTestClass
{
[TestMethod("custom test name")]
public void MyTestMethod()
{
}
}
}
<file_sep>/test/ActualTestProject/IntegrationSpec.cs
[assembly: TestAdapterCore.TestAssembly(typeof(AProjectWithTests.Program))]<file_sep>/src/TestAdapterCore/Infrastructure/TestAssemblyLoadContext.cs
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace TestAdapterCore.Infrastructure
{
public class TestAssemblyLoadContext : AssemblyLoadContext
{
private readonly AssemblyDependencyResolver resolver;
public TestAssemblyLoadContext(string pluginPath) : base(pluginPath, true)
{
resolver = new AssemblyDependencyResolver(pluginPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
var loadedAssembly = Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == assemblyName.Name);
if (loadedAssembly is not null)
{
return loadedAssembly;
}
string assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);
if (assemblyPath != null)
{
return LoadFromAssemblyPath(assemblyPath);
}
return null;
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string libraryPath = resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
if (libraryPath != null)
{
return LoadUnmanagedDllFromPath(libraryPath);
}
return IntPtr.Zero;
}
}
}
|
693439a87ce141565126934ee7aa20fd741c03ab
|
[
"C#"
] | 8 |
C#
|
mingyaulee/TestAdapterIssue
|
f5a8dc83e47da616f50ca1eb21decdc8679f3ade
|
999ae9f75bd900a43302c9e0fbb1e6d77dfa8a41
|
refs/heads/master
|
<file_sep># Working with DoD CACs
## Preparation
On OSX, make sure you have [brew](https://brew.sh) installed and
that you've installed the following formulas ...
* go
* nss
* openssl
On RHEL, make sure you have the following packages installed ...
* nss-util
* openssl
* go-toolset
## Running
There are two scripts that do all the work.
* `pull-the-certs.sh` populates an NSS database with the DoD root
and intermediate CAs
* `run-simple-server.sh` runs a simple go server listening on port
8443 with mutual TLS and all of the CAs necessary to support CAC
cards. This script writes a `client.pem` file which contains the
received client certificate in DER format.
## Verify certificate chain
Running both of the above scripts enables you to print the `client.pem`
certificate chain using the following command ...
certutil -A -n client -d nssdb -t u,u,u -i client.pem
certutil -O -n client -d nssdb
<file_sep>#!/usr/bin/env bash
IFS=$'\n'
for cert in $(certutil -L -d nssdb | grep -i dod | rev | awk '{$1="";print $0}' | rev | sed 's/ *$//g')
do
echo "************************************************************************"
echo Validating $cert ...
echo
certutil -O -d nssdb -n "$cert"
echo
done
<file_sep>package main
import (
"crypto/tls"
"crypto/x509"
"io"
"io/ioutil"
"log"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
// Write "Hello, world!" to the response body
io.WriteString(w, "Hello, world!\n")
ioutil.WriteFile("client.pem", r.TLS.PeerCertificates[0].Raw, 0644)
}
func main() {
// Set up a /hello resource handler
http.HandleFunc("/hello", helloHandler)
// Create a CA certificate pool and add CAs to it
caList := []string{"AllCerts.pem", "RootCert2.pem", "RootCert3.pem", "RootCert4.pem", "RootCert5.pem", "ca.cert.pem", "intermediate.cert.pem"}
caCertPool := x509.NewCertPool()
for _, ca := range caList {
caCert, err := ioutil.ReadFile("CAs/" + ca)
if err != nil {
log.Fatal(err)
}
caCertPool.AppendCertsFromPEM(caCert)
}
// Create the TLS Config with the CA pool and enable Client certificate validation
tlsConfig := &tls.Config{
ClientCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
}
tlsConfig.BuildNameToCertificate()
// Create a Server instance to listen on port 8443 with the TLS config
server := &http.Server{
Addr: ":8443",
TLSConfig: tlsConfig,
}
// Listen to HTTPS connections with the server certificate and wait
log.Fatal(server.ListenAndServeTLS("certs/server.pem", "certs/server.key"))
}
<file_sep>#!/usr/bin/env bash
# work in current script directory
WORKDIR=$(pushd $(dirname $0) &> /dev/null && pwd && popd &> /dev/null)
pushd $WORKDIR &> /dev/null
rm -fr certs CAs
mkdir certs CAs
echo
echo "Get DoD root and intermediate CAs ... "
# pull the DoD root and intermediate CAs
for bundle in AllCerts.p7b RootCert2.cer RootCert3.cer RootCert4.cer RootCert5.cer
do
curl -sLO https://militarycac.com/maccerts/$bundle
done
# import the DoD root CAs
for bundle in RootCert2 RootCert3 RootCert4 RootCert5
do
openssl x509 -in $bundle.cer -inform DER -out CAs/$bundle.pem -outform PEM
rm $bundle.cer
done
# import the DoD intermediate CAs
openssl pkcs7 -print_certs -inform der -in AllCerts.p7b -out CAs/AllCerts.pem
rm AllCerts.p7b
if [[ ! -e intranet-test-certs/server.p12 ]]
then
echo Create temporary root CA, intermediate CA, and server cert and key ...
rm -fr intranet-test-certs
git clone https://github.com/rlucente-se-jboss/intranet-test-certs.git \
&> /dev/null
pushd intranet-test-certs &> /dev/null
./02-create-root-pair.sh &> /dev/null
./03-create-intermediate-pair.sh &> /dev/null
./04-create-server-pair.sh &> /dev/null
./05-create-client-pair.sh &> /dev/null
./06-export-certs.sh &> /dev/null
else
pushd intranet-test-certs &> /dev/null
fi
# set temporary import/export password
echo '<PASSWORD>!' > password.txt
openssl pkcs12 -in server.p12 -nodes -nocerts \
-password file:password.txt 2> /dev/null | \
openssl rsa -out server.key &> /dev/null
openssl pkcs12 -in server.p12 -out server.pem -nokeys \
-password file:password.txt &> /dev/null
rm -f password.txt
cp ca.cert.pem ../CAs
cp intermediate.cert.pem ../CAs
mv server.key server.pem ../certs
popd &> /dev/null
IPADDR=localhost
if [[ "$(uname -s)" = "Darwin" ]]
then
IPADDR=$(ifconfig | grep 'inet [0-9]' | grep -v 127.0.0.1 | awk '{print $2; exit}')
elif [[ "$(uname -s)" = "Linux" ]]
then
IPADDR=$(ip a s | grep 'inet [0-9]' | grep -v 127.0.0.1 | awk '{print $2; exit}' | cut -d/ -f1)
sudo firewall-cmd --add-port=8443/tcp
fi
echo
echo Server running at https://$IPADDR:8443/hello
echo Stop the server using CTRL-C
echo
go run server.go
popd &> /dev/null
<file_sep>#!/usr/bin/env bash
for bundle in AllCerts.p7b RootCert2.cer RootCert3.cer RootCert4.cer RootCert5.cer
do
curl -sLO https://militarycac.com/maccerts/$bundle
done
WORKDIR=$(pushd $(dirname $0) &> /dev/null && pwd && popd &> /dev/null)
NSSDB=$WORKDIR/nssdb
# initialize the NSS database
rm -fr $NSSDB
mkdir $NSSDB
certutil -N -d $NSSDB --empty-password
# set temporary import/export password
echo '<PASSWORD>1redhat!' > password.txt
# import the root CAs
for bundle in RootCert2 RootCert3 RootCert4 RootCert5
do
openssl x509 -in $bundle.cer -inform DER -out $bundle.pem -outform PEM
openssl pkcs12 -export -nokeys -in $bundle.pem -out $bundle.p12 -password file:password.txt
pk12util -d $NSSDB -i $bundle.p12 -w password.txt
done
# import the intermediate CAs
openssl pkcs7 -print_certs -inform der -in AllCerts.p7b -out AllCerts.pem
openssl pkcs12 -export -nokeys -in AllCerts.pem -out AllCerts.p12 -password file:password.txt
pk12util -d $NSSDB -i AllCerts.p12 -w password.txt
# update the trust attributes to CT,C,C for all the certs
IFS=$'\n'
for cert in $(certutil -L -d $NSSDB -h all | grep Government | sed 's/\(Government\).*/\1/g')
do
certutil -M -n "$cert" -d $NSSDB -t CT,C,C
done
# dump the certificates
certutil -L -d $NSSDB -h all
# delete the temporary files
ls password.txt *.cer *.p7b *.pem *.p12 | grep -v client.pem | xargs rm -f
|
82b20648249e1a7b334c46dcf384792d3957543c
|
[
"Markdown",
"Go",
"Shell"
] | 5 |
Markdown
|
rlucente-se-jboss/dod-cac-certs
|
e42a3253b8e2b1272ad543debd571dc64fcc96e9
|
c41d677702d01434255b06442b71837e3b107b07
|
refs/heads/master
|
<repo_name>lazaryo/sorrow-bot<file_sep>/commands/dictionary.js
exports.run = (bot, message, args, serverSorrows, about, guildConf, rn, botUptime, banned, safe, checkID, checkWord, convertTime, displayWords, singleWord) => {
message.author.send({
"embed": {
color: 0x23BDE7,
title: 'Dictionary',
description: `There are currently \`${serverSorrows.length}\` Obscure Sorrows in the dictionary.\n\nUse ${bot.user} \`word (word)\` for a specific word's information. See the full list below.`,
footer: {
icon_url: bot.user.avatarURL,
text: bot.user.username
}
}
}).catch(error => console.log(error));
// Send the list of words in a separate message because the dictionary can be large.
message.author.send({
"embed": {
color: 0x23BDE7,
title: 'Full List',
description: `${displayWords(serverSorrows)}`,
footer: {
icon_url: bot.user.avatarURL,
text: bot.user.username
}
}
}).catch(error => console.log(error));
message.reply('Please check your DMs :eyes:');
}
<file_sep>/commands/setconf.js
exports.run = (bot, message, args, serverSorrows, about, guildConf) => {
const adminRole = message.guild.roles.find("name", guildConf.adminRole);
if(!adminRole) return message.reply("Administrator Role Not Found");
// if the user is not admin
if(!message.member.roles.has(adminRole.id)) return message.reply("You're not an admin, sorry!")
// Let's get our key and value from the arguments. This is array destructuring, by the way.
const [key, ...value] = args;
// Example:
// key: "prefix"
// value: ["+"]
// (yes it's an array, we join it further down!)
// check if the key exists in the config
if(!bot.settings.has(message.guild.id, key)) return message.reply("This key is not in the configuration.");
// Set the prefix value back to it's default value if empty
// need to reset each key if something similar happens
if (value.join(" ") == "" && key == 'prefix') return bot.settings.set(message.guild.id, `${bot.user}`, key);
bot.settings.set(message.guild.id, value.join(" "), key);
message.channel.send(`Guild configuration item ${key} has been changed to:\n\`${value.join(" ")}\``);
}
<file_sep>/README.md
# sorrow-bot
Discord Bot to provide you with Obscure Sorrows. If there is a video associated with the word, you will recieve that too.
## Getting Started
Use **help** to show all of the available commands.
<file_sep>/commands/showconf.js
exports.run = (bot, message, args, serverSorrows, about, guildConf) => {
let configKeys = "";
Object.keys(guildConf).forEach(key => {
configKeys += `${key} : ${guildConf[key]}\n`;
});
message.channel.send(`The following are the server's current configuration: \`\`\`${configKeys}\`\`\``);
}
<file_sep>/commands/list.js
exports.run = (bot, message, args, serverSorrows, about, guildConf, rn, botUptime, banned, safe, checkID, checkWord, convertTime) => {
const currentGuild = message.guild;
const currentGuildID = message.guild.id;
const currentChannelID = message.channel.id;
if (message.author.id !== "<PASSWORD>") {
return message.channel.send('You don\'t have permission you :chicken:!');
}
if (currentGuildID != '299853081578045440') {
return message.channel.send('Not in this server!');
}
if (currentChannelID != '300143870056857600') {
return message.channel.send('Use this command in the Admin Channel!');
}
function theList() {
var parts = [];
let i = 1;
for (let n of bot.guilds) {
let criticalInfo = {
"name": n[1].name,
"id": n[1].id,
"ownerID": n[1].ownerID,
"memberCount": n[1].members.size,
"botCount": n[1].members.filter(m => m.user.bot).size,
"humanCount": n[1].members.filter(m => !m.user.bot).size,
"joined": convertTime(n[1].joinedTimestamp)
}
let server = {
name: criticalInfo.name,
value: `Server ID: ${criticalInfo.id}\nOwner ID: ${criticalInfo.ownerID}\nHuman Size: ${criticalInfo.humanCount}\nBot Size: ${criticalInfo.botCount}\nJoined: ${criticalInfo.joined}`,
inline: false
};
parts.push(server);
i++
}
return parts;
}
message.channel.send({
"embed": {
color: 0x23BDE7,
title: 'Guild List',
description: `Retrieve information regarding all guilds ${bot.user} has joined.`,
fields: theList(),
timestamp: new Date(),
footer: {
icon_url: bot.user.avatarURL,
text: bot.user.username
}
}
}).catch(error => console.log(error));
}
<file_sep>/commands/reload.js
exports.run = (bot, message, args) => {
if (message.author.id !== "3<PASSWORD>") {
return message.channel.send('You don\'t have permission you :chicken:!');
}
if(!args || args.size < 1) return message.channel.send(`You must provide a command name to reload.`);
// the path is relative to the *current folder*, so just ./filename.js
delete require.cache[require.resolve(`./${args[0]}.js`)];
message.channel.send(`The command \`${args[0]}\` has been reloaded.`);
};<file_sep>/commands/leave.js
exports.run = (bot, message) => {
const currentGuild = message.guild;
const currentGuildID = message.guild.id;
const messageCount = message.content.split(` `).length;
let serverID = message.content.split(` `)[2];
if (message.author.id !== "3<PASSWORD>") {
return message.channel.send('You don\'t have permission you :chicken:!');
}
if (currentGuildID != '299853081578045440') {
return message.channel.send('Not in this server!');
}
if (messageCount != 3) {
return message.channel.send('Brother man, you need to add a Guild ID for me to leave.');
} else {
for (let guild of bot.guilds) {
if (guild.includes(serverID)) {
message.channel.send(`I have left the guild: \`${guild[1].name}\``);
return guild[1].leave();
}
}
}
}
|
faaaeeded6d3484d6102223f910cbd72602614b2
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
lazaryo/sorrow-bot
|
205d1552c187aff9287a50340eb7c62eff3c91a0
|
d7c2fce5c2a7f9e31052245a2a1269ceb7bcf722
|
refs/heads/master
|
<file_sep><?php
// Rock Lobstah!<file_sep>=== Lobsterfonterizer ===
Contributors: iamrobertv, weswilson, warmwaffles, vluther
Site: http://iamrobertv.com
Tags: fonts, lobster, design foul
Requires at least: 3.0
Tested up to: 3.4
Stable tag: 0.6
License: WTFPL
== Description ==
This plugin does all the hard work of choosings fonts for you. It just uses Lobster for everything.
== Installation ==
1. Upload the plugin to your site and activate it.
2. Navigate to Appearance > Lobsterfonterize.
3. Enable Lobsterfonterification.
4. Bask in the Lobster-ness.
== Frequently Asked Questions ==
= Why? =
Because let's be honest... everyone just wants to use Lobster anyway.
= Will my site designer hate me if I use this plugin? =
Of course not. Designers LOVE this font.
== Future Versions ==
I plan on adding a menu to select other awesome fonts. Your designer will love you for saving him/her from having to spend time carefully choosing a font.
== Changelog ==
= 0.6 =
* Added admin menu with option to enable/disable Lobsterfonterification while plugin is active.
= 0.5 =
* This is the intial release.<file_sep><?php
/*
Plugin Name: Lobsterfonterizer
Plugin URI: http://iamrobertv.com
Description: This plugin does all the hard work of choosings fonts for you. It just uses Lobster for everything.
Version: 0.6
Author: <NAME>
Author URI: http://iamrobertv.com
License: WTFPL
*/
/*
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 3.Robert (Because I Can), August 2012
Copyright (C) 2012 <NAME> <<EMAIL>>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
*/
// Include a few things
include('lobsterfonterizer-admin.php');
// Grab plugin options from options table
$lobsterfonterizer_options = get_option('lobsterfonterizer_settings');
// The code below does the damn thing.
function lobsterfonterizer () {
global $lobsterfonterizer_options;
if($lobsterfonterizer_options[enabled]){
wp_enqueue_style('lobsterfonterizer', plugin_dir_url( __FILE__ ) . 'lobsterfonterizer.css');
}
}
add_action('wp_enqueue_scripts', 'lobsterfonterizer');<file_sep><?php
// Admin Page Content
function lobsterfonterizer_admin() {
// Globalize options
global $lobsterfonterizer_options;
ob_start(); ?>
<div class="wrap">
<div id="icon-options-general" class="icon32"><br /></div>
<h2>Lobsterfonterizer Options</h2>
<form method="post" action="options.php">
<?php settings_fields('lobsterfonterizer_settings_group'); ?>
<h4><?php _e('Enable / Disable The Lobsterfonterification', 'lobsterfonterizer_domain'); ?></h4>
<p>
<input id="lobsterfonterizer_settings[enabled]" name="lobsterfonterizer_settings[enabled]" type="checkbox" value="1" <?php checked($lobsterfonterizer_options['enabled'], 1); ?> />
<label class="description" for="lobsterfonterizer_settings[enabled]"><?php _e('Lobsterfonterize', 'lobsterfonterizer_domain'); ?></label>
</p>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Lobster Me!', 'lobsterfonterizer_domain'); ?>" />
</p>
</form>
</div>
<?php echo ob_get_clean();
}
// Admin Menu Creation
function lobsterfonterizer_add_menu() {
add_options_page('Lobsterfonterizer', 'Lobsterfonterizer', 'manage_options', 'lobsterfonterizer', 'lobsterfonterizer_admin');
}
add_action('admin_menu', 'lobsterfonterizer_add_menu');
// Register Plugin Settings
function lobsterfonterizer_register_settings() {
register_setting('lobsterfonterizer_settings_group', 'lobsterfonterizer_settings');
}
add_action('admin_init', 'lobsterfonterizer_register_settings');
|
4f4f4883f9926036522c88ebe9bc0ddc150b979c
|
[
"Text",
"PHP"
] | 4 |
PHP
|
iamrobertv/lobsterfonterizer
|
5f7f5c0b432641b09286a0302a400c8772cfcda4
|
0f11fd77ff2f03ba3ad81e7fbdab5eec53b85a4e
|
refs/heads/master
|
<repo_name>sayali1998/ReactSense<file_sep>/gui.py
from tkinter import*
#from PIL import Image,ImageTk
top= Tk()
top.title("REACTSENSE")
top.geometry("1300x1300")
title=Label(top,text="REACTSENSE")
title.config(font="Verdana 40 bold")
title.place(relx=0.5,rely=0.4,anchor=CENTER)
def openLoginPage():
top.destroy()
loginpage = Tk()
loginpage.title("REACTSENSE")
loginpage.geometry("1300x1300")
login_title=Label(loginpage,text="REACTSENSE")
instruction=Label(loginpage,text="Please enter your credentials")
instruction.config(font="Verdana 25")
#instruction.grid(row=1,column=1,sticky=E)
instruction.place(relx=0.5,rely=0.3,anchor=CENTER)
user_id= Entry(loginpage, width=20)
usernameLabel = Label(loginpage,text='Username')
usernameLabel.config(font="Verdana 20",padx=2)
#usernameLabel.grid(row=3,column = 5,sticky=W,pady=30)
usernameLabel.pack()
usernameLabel.place(relx=0.4,rely=0.4,anchor=CENTER)
#user_id.grid(row=3,column = 4)
user_id.pack()
user_id.place(relx=0.5,rely=0.4,anchor=CENTER)
#usernameLabel.pack(padx=10,pady=10,expand=True)
#user_id.pack(padx=10,pady=10,expand=True)
password= Entry(loginpage,width=20,show = '*')
passwordLabel = Label(loginpage,text='password')
passwordLabel.config(font="Verdana 20")
passwordLabel.pack()
passwordLabel.place(relx=0.4,rely=0.45,anchor=CENTER)
#passwordLabel.grid(row=4,column=5,sticky=W)
#password.grid(row=4,column=4)
password.pack()
password.place(relx=0.5,rely=0.45,anchor=CENTER)
def callvideos():
loginpage.destroy()
videos()
submit_btn=Button(loginpage,text="Submit",width = 20,height=4,command=callvideos)
#submit_btn.grid(row=5,column=5,pady=10)
submit_btn.pack()
submit_btn.place(relx=0.5,rely=0.5,anchor=CENTER)
loginpage.pack()
def videos():
#loginpage.destroy()
v = Tk()
v.title("REACTSENSE")
#image=Image.open('image.png')
v.geometry("1300x1300")
photo = PhotoImage(file = 'image.png',master = v)
b1=Button(v,image=photo)
b1.config(width="250",height="200",padx=5,pady=5)
#b1.grid(row=1,column=1)
b1.pack()
b1.place(relx=0.2,rely=0.3,anchor=W)
b1_label=Label(v,text="Video 1")
b1_label.config(font="Verdana 20",padx=5,pady=5)
#b1_label.grid(row=2,column=1)
b1_label.pack()
b1_label.place(relx=0.3,rely=0.4,anchor=CENTER)
b2=Button(v,image=photo)
b2.config(width="250",height="200",padx=5,pady=5)
#b2.grid(row=1,column=2,padx=30)
b2.pack()
b2.place(relx=0.8,rely=0.3,anchor=E)
b2_label=Label(v,text="Video 2")
b2_label.config(font="Verdana 20",padx=2,pady=5)
#b2_label.grid(row=2,column=2)
b2_label.pack()
b2_label.place(relx=0.7,rely=0.4,anchor=CENTER)
b3=Button(v,image=photo)
b3.config(width="250",height="200",padx=5,pady=5)
#b3.grid(row=3,column=1)
b3.pack()
b3.place(relx=0.2,rely=0.6,anchor=W)
b3_label=Label(v,text="Video 3")
b3_label.config(font="Verdana 20",padx=5,pady=5)
#b3_label.grid(row=4,column=1)
b3_label.pack()
b3_label.place(relx=0.3,rely=0.7,anchor=CENTER)
b4=Button(v,image=photo)
b4.config(width="250",height="200",padx=5,pady=5)
#b4.grid(row=3,column=2,padx=30)
b4.pack()
b4.place(relx=0.8,rely=0.6,anchor=E)
b4_label=Label(v,text="Video 4")
b4_label.config(font="Verdana 20",padx=2,pady=5)
#b4_label.grid(row=4,column=2)
b4_label.pack()
b4_label.place(relx=0.7,rely=0.7,anchor=CENTER)
v.pack()
#title.grid(row = 1)
login_btn = Button(top, text ="Login",command = openLoginPage)
login_btn.config( height ="5", width ="15",padx=2)
signup_btn=Button(top,text="Sign up")
signup_btn.config( height = "5", width = "15",padx=2)
login_btn.place(relx=0.4,rely=0.5,anchor=W)
signup_btn.place(relx=0.6,rely=0.5,anchor=E)
#login_btn.grid(row=2,column = 10,pady = 10,padx = (245,10))
#signup_btn.grid(row=2,column = 11)
top.mainloop()
|
4541af3587e6712d94ff85649fcd1886cfe6f32b
|
[
"Python"
] | 1 |
Python
|
sayali1998/ReactSense
|
9f525e7f3a54dce97a0a562b0ef2b3c350f45643
|
ff5e5649e53c471a58317d92706fb4791ab853fe
|
refs/heads/master
|
<repo_name>bryantaoli/MSCKF-NOROS<file_sep>/build/Makefile
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.5
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/mso/Downloads/Project/VIO/MSCKF/MSCKF-NOROS
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/mso/Downloads/Project/VIO/MSCKF/MSCKF-NOROS/build
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /home/mso/Downloads/Project/VIO/MSCKF/MSCKF-NOROS/build/CMakeFiles /home/mso/Downloads/Project/VIO/MSCKF/MSCKF-NOROS/build/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /home/mso/Downloads/Project/VIO/MSCKF/MSCKF-NOROS/build/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named msckf_noros
# Build rule for target.
msckf_noros: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 msckf_noros
.PHONY : msckf_noros
# fast build rule for target.
msckf_noros/fast:
$(MAKE) -f CMakeFiles/msckf_noros.dir/build.make CMakeFiles/msckf_noros.dir/build
.PHONY : msckf_noros/fast
#=============================================================================
# Target rules for targets named MSCKF_NOROS
# Build rule for target.
MSCKF_NOROS: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 MSCKF_NOROS
.PHONY : MSCKF_NOROS
# fast build rule for target.
MSCKF_NOROS/fast:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/build
.PHONY : MSCKF_NOROS/fast
src/image_processor.o: src/image_processor.cpp.o
.PHONY : src/image_processor.o
# target to build an object file
src/image_processor.cpp.o:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/image_processor.cpp.o
.PHONY : src/image_processor.cpp.o
src/image_processor.i: src/image_processor.cpp.i
.PHONY : src/image_processor.i
# target to preprocess a source file
src/image_processor.cpp.i:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/image_processor.cpp.i
.PHONY : src/image_processor.cpp.i
src/image_processor.s: src/image_processor.cpp.s
.PHONY : src/image_processor.s
# target to generate assembly for a file
src/image_processor.cpp.s:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/image_processor.cpp.s
.PHONY : src/image_processor.cpp.s
src/main.o: src/main.cpp.o
.PHONY : src/main.o
# target to build an object file
src/main.cpp.o:
$(MAKE) -f CMakeFiles/msckf_noros.dir/build.make CMakeFiles/msckf_noros.dir/src/main.cpp.o
.PHONY : src/main.cpp.o
src/main.i: src/main.cpp.i
.PHONY : src/main.i
# target to preprocess a source file
src/main.cpp.i:
$(MAKE) -f CMakeFiles/msckf_noros.dir/build.make CMakeFiles/msckf_noros.dir/src/main.cpp.i
.PHONY : src/main.cpp.i
src/main.s: src/main.cpp.s
.PHONY : src/main.s
# target to generate assembly for a file
src/main.cpp.s:
$(MAKE) -f CMakeFiles/msckf_noros.dir/build.make CMakeFiles/msckf_noros.dir/src/main.cpp.s
.PHONY : src/main.cpp.s
src/msckf_vio.o: src/msckf_vio.cpp.o
.PHONY : src/msckf_vio.o
# target to build an object file
src/msckf_vio.cpp.o:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/msckf_vio.cpp.o
.PHONY : src/msckf_vio.cpp.o
src/msckf_vio.i: src/msckf_vio.cpp.i
.PHONY : src/msckf_vio.i
# target to preprocess a source file
src/msckf_vio.cpp.i:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/msckf_vio.cpp.i
.PHONY : src/msckf_vio.cpp.i
src/msckf_vio.s: src/msckf_vio.cpp.s
.PHONY : src/msckf_vio.s
# target to generate assembly for a file
src/msckf_vio.cpp.s:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/msckf_vio.cpp.s
.PHONY : src/msckf_vio.cpp.s
src/random_numbers.o: src/random_numbers.cpp.o
.PHONY : src/random_numbers.o
# target to build an object file
src/random_numbers.cpp.o:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/random_numbers.cpp.o
.PHONY : src/random_numbers.cpp.o
src/random_numbers.i: src/random_numbers.cpp.i
.PHONY : src/random_numbers.i
# target to preprocess a source file
src/random_numbers.cpp.i:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/random_numbers.cpp.i
.PHONY : src/random_numbers.cpp.i
src/random_numbers.s: src/random_numbers.cpp.s
.PHONY : src/random_numbers.s
# target to generate assembly for a file
src/random_numbers.cpp.s:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/random_numbers.cpp.s
.PHONY : src/random_numbers.cpp.s
src/utils.o: src/utils.cpp.o
.PHONY : src/utils.o
# target to build an object file
src/utils.cpp.o:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/utils.cpp.o
.PHONY : src/utils.cpp.o
src/utils.i: src/utils.cpp.i
.PHONY : src/utils.i
# target to preprocess a source file
src/utils.cpp.i:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/utils.cpp.i
.PHONY : src/utils.cpp.i
src/utils.s: src/utils.cpp.s
.PHONY : src/utils.s
# target to generate assembly for a file
src/utils.cpp.s:
$(MAKE) -f CMakeFiles/MSCKF_NOROS.dir/build.make CMakeFiles/MSCKF_NOROS.dir/src/utils.cpp.s
.PHONY : src/utils.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... edit_cache"
@echo "... msckf_noros"
@echo "... rebuild_cache"
@echo "... MSCKF_NOROS"
@echo "... src/image_processor.o"
@echo "... src/image_processor.i"
@echo "... src/image_processor.s"
@echo "... src/main.o"
@echo "... src/main.i"
@echo "... src/main.s"
@echo "... src/msckf_vio.o"
@echo "... src/msckf_vio.i"
@echo "... src/msckf_vio.s"
@echo "... src/random_numbers.o"
@echo "... src/random_numbers.i"
@echo "... src/random_numbers.s"
@echo "... src/utils.o"
@echo "... src/utils.i"
@echo "... src/utils.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>/README.MD
S-MSCKF去除ROS版本
在ubuntu系统下可运行,需要提前安装此系统;
使用了boost,eigen, opencv库,方便交叉编译,故需要提前安装这些库。
一 运行
1、修改main中euroc数据集路径,如果使用其他的数据集,修改getFiles()
2、如果使用其他数据集修改loadParameters()中相机参数
二 要点
1.去除ROS环境
2.增加了相机和IMU的数据同步,
3.去除了SuiteSparse(交叉编译起来很麻烦)
4.注意typedef long long int FeatureIDType类型,arm下编译会有问题
<file_sep>/src/main.cpp
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <glob.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <string>
#include <stdio.h>
#include <map>
#include <Eigen/Dense>
#include "msckf_vio/image_processor.h"
#include "msckf_vio/msckf_vio.h"
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
queue<pair<double,vector<Eigen::Vector3d>> > IMU;
queue<pair<double,vector<cv::Mat>> > IMAGE;
std::mutex m_buf;
double current_time = -1;
std::condition_variable con;
msckf_vio::ImageProcessor vio_msckf_frontend_;
msckf_vio::MsckfVio vio_msckf_backend_;
//数据集的图像名字是时间戳(ns).png
//从小到大排序得到文件名称中的num
vector<double> getFiles(char* dirc){
vector<string> files;
//dirent,LINUX系统下的一个头文件,在这个目录下/usr/include,为了获取某文件夹目录内容,所使用的结构体
struct dirent *ptr;
DIR *dir;
dir = opendir(dirc);
if(dir == NULL)
{
perror("open dir error ...");
exit(1);
}
while((ptr = readdir(dir)) != NULL){
if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///当前目录或当前的父目录
continue;
if(ptr->d_type == 8)//it;s file
{
files.push_back(ptr->d_name);
}
else if(ptr->d_type == 10)//link file
continue;
else if(ptr->d_type == 4) //dir
{
files.push_back(ptr->d_name);
}
}
closedir(dir);
vector<double> result;
for(int i=0; i < files.size(); i++)
{
result.push_back(atof(files[i].c_str()));
}
sort(result.begin(), result.end());
return result;
}
Eigen::Vector3d PreprocessAccelerator(const Eigen::Vector3d &inacc)
{
static Eigen::Vector3d last_output = Eigen::Vector3d::Zero();
static int num[3] = {0,0,0};
static double k[3] = {0.03,0.03,0.03};
static bool old_flag[3] = {false,false,false};
bool new_flag[3];
Eigen::Vector3d new_output;
if(last_output.norm() < 1)
{
last_output = inacc;
return last_output;
}
for(int i=0;i<2;i++)
{
new_flag[i] = inacc[i] > last_output[i];
if(new_flag[i] == old_flag[i])
{
if(fabs(inacc[i] - last_output[i]) > 2)
num[i]++;
if(num[i] > 5)
k[i] += 0.1;
}
else
{
num[i] = 0;
k[i] = 0.03;
}
if(k[i] > 0.5) k[i] = 0.5;
new_output[i] = k[i] * inacc[i] + (1 - k[i]) * last_output[i];
old_flag[i] = new_flag[i];
}
for(int i=2;i<3;i++)
{
new_flag[i] = inacc[i] > last_output[i];
if(new_flag[i] == old_flag[i])
{
if(fabs(inacc[i] - last_output[i]) > 2)
num[i]++;
if(num[i] > 5)
k[i] += 0.01;
}
else
{
num[i] = 0;
k[i] = 0.01;
}
if(k[i] > 0.1) k[i] = 0.1;
new_output[i] = k[i] * inacc[i] + (1 - k[i]) * last_output[i];
old_flag[i] = new_flag[i];
}
// new_output = inacc;
return new_output;
}
void InputIMU( const double timestamp, const Eigen::Vector3d& accl, const Eigen::Vector3d& gyro)
{
m_buf.lock();
vector<Eigen::Vector3d> IMUTEMP;
IMUTEMP.push_back(accl);
IMUTEMP.push_back(gyro);
IMU.push(make_pair(timestamp,IMUTEMP));
m_buf.unlock();
con.notify_one();
}
void InputIMAGE(const cv::Mat& cam0_img,
const cv::Mat& cam1_img,
double time)
{
m_buf.lock();
vector<cv::Mat> IMAGETEMP;
IMAGETEMP.push_back(cam0_img);
IMAGETEMP.push_back(cam1_img);
IMAGE.push(make_pair(time,IMAGETEMP));
m_buf.unlock();
con.notify_one();
}
std::vector<std::pair<vector<pair<double,vector<Eigen::Vector3d>> >, vector<pair<double,vector<cv::Mat>> > >>
getMeasurements()
{
std::vector<std::pair<vector<pair<double,vector<Eigen::Vector3d>> >, vector<pair<double,vector<cv::Mat>> > >> measurements;
while (true)
{
if(IMAGE.empty()||IMU.empty())
{
//cout<<"wait for data"<<endl;
return measurements;
}
if (!(IMU.back().first > IMAGE.front().first))
{
cout<<"wait for imu, only should happen at the beginning";
return measurements;
}
if (!(IMU.front().first < IMAGE.front().first))
{
cout<<"throw img, only should happen at the beginning";
IMAGE.pop();
continue;
}
vector<pair<double,vector<Eigen::Vector3d>> > IMUs;
while (IMU.front().first < IMAGE.front().first)
{
IMUs.emplace_back(IMU.front());
IMU.pop();
}
IMUs.emplace_back(IMU.front());
if (IMUs.empty())
cout<<"no imu between two image";
vector<pair<double,vector<cv::Mat>> > IMAGES;
IMAGES.push_back(IMAGE.front());
IMAGE.pop();
measurements.push_back(make_pair(IMUs,IMAGES));
}
cout<<measurements.size()<<endl;
return measurements;
}
void process()
{
while (true)
{
//vector<pair<double,vector<Eigen::Vector3d>>>, vector<pair<double,vector<cv::Mat>
//
std::vector<std::pair<vector<pair<double,vector<Eigen::Vector3d>> >, vector<pair<double,vector<cv::Mat>> > >> measurements;
//一个用于多线程的锁
std::unique_lock<std::mutex> lk(m_buf);
con.wait(lk, [&]
{
return (measurements = getMeasurements()).size() != 0;
});
lk.unlock();
//measurement 是 std::pair<vector<pair<double,vector<Eigen::Vector3d>>>, vector<pair<double,vector<cv::Mat>>> >
for (auto &measurement : measurements)
{
//measurement.second是vector<pair<double,vector<cv::Mat>>
//measurement.second.front()是pair<double,vector<cv::Mat>
auto img = measurement.second.front();
double dx = 0, dy = 0, dz = 0, rx = 0, ry = 0, rz = 0;
//measurement.first是vector<pair<double,vector<Eigen::Vector3d>>>
//imu_msg是vector<pair<double,vector<Eigen::Vector3d>>>的元素
for (auto &imu_msg : measurement.first)
{
double t = imu_msg.first;
double img_t = img.first;
if (t <= img_t)
{
if (current_time < 0)
current_time = t;
double dt = t - current_time;
current_time = t;
//imu_msg.second是vector<Eigen::Vector3d>
//vector<Eigen::Vector3d>就包括两个元素,front是加速度计的,back是陀螺仪的
dx = imu_msg.second.front()[0];
dy = imu_msg.second.front()[1];
dz = imu_msg.second.front()[2];
rx = imu_msg.second.back()[0];
ry = imu_msg.second.back()[1];
rz = imu_msg.second.back()[2];
vio_msckf_frontend_.imuCallback(current_time,Eigen::Vector3d(dx, dy, dz), Eigen::Vector3d(rx, ry, rz));
vio_msckf_backend_.imuCallback(current_time,Eigen::Vector3d(dx, dy, dz), Eigen::Vector3d(rx, ry, rz));
//std::cout.setf(std::ios::fixed, std::ios::floatfield);
//std::cout.precision(6);
//cout<<"imu:"<<current_time<<endl;
}
else
{
double dt_1 = img_t - current_time;
double dt_2 = t - img_t;
current_time = img_t;
//w1和w2分别是两个权重 做插值
double w1 = dt_2 / (dt_1 + dt_2);
double w2 = dt_1 / (dt_1 + dt_2);
dx = w1 * dx + w2 * imu_msg.second.front()[0];
dy = w1 * dy + w2 * imu_msg.second.front()[1];
dz = w1 * dz + w2 * imu_msg.second.front()[2];
rx = w1 * rx + w2 * imu_msg.second.back()[0];
ry = w1 * ry + w2 * imu_msg.second.back()[1];
rz = w1 * rz + w2 * imu_msg.second.back()[2];
//图像处理的(前端):imuCallback
vio_msckf_frontend_.imuCallback(current_time,Eigen::Vector3d(dx, dy, dz), Eigen::Vector3d(rx, ry, rz));
//MsckfVio的(后端):imuCallback
vio_msckf_backend_.imuCallback(current_time,Eigen::Vector3d(dx, dy, dz), Eigen::Vector3d(rx, ry, rz));
}
}
//cv::imshow("1",img.second.front());
//cv::waitKey(1);
//std::cout.precision(6);
//cout<<"imagetime"<<img.first<<endl;
vector<pair<double, std::vector<Eigen::Matrix<double, 5, 1>>> > tempmsckf_feature;
//图像处理的(前端):imgCallback
tempmsckf_feature=vio_msckf_frontend_.stereoCallback(img.second.front(),img.second.back(),img.first);
vio_msckf_backend_.featureCallback(tempmsckf_feature);
}
}
}
int main(int argc, char** argv)
{
//处理线程
std::thread measurement_process{process};
//下面是文件读取
//左目.右目和imu的路径
char* left_image_path = argv[1];
char* right_image_path = argv[2];
char* imu_path = argv[3];
//char* left_image_path = "/home/mso/Downloads/Dataset/Euroc/V1_01_easy/mav0/cam0/data";
//char* right_image_path = "/home/mso/Downloads/Dataset/Euroc/V1_01_easy/mav0/cam1/data";
//char* imu_path = "/home/mso/Downloads/Dataset/Euroc/V1_01_easy/mav0/imu0/data.csv";
char buf[1024];
vector<double> left_image_index = getFiles(left_image_path);// ..
vector<double> right_image_index = getFiles(right_image_path);
FILE *fp;
fp = fopen(imu_path,"r");
//imu第一行是头,跳过
fgets(buf, sizeof(buf), fp);
double imu_time,last_imu_time;
double acceleration[3],angular_v[3];
double time_count_left, time_count_right;
int imu_seq = 1; //..
std::map<int,int> imu_big_interval;
int fscanf_return;
//读取imu,一行是7个double的数据
fscanf_return = fscanf(fp,"%lf,%lf,%lf,%lf,%lf,%lf,%lf,",
&imu_time,angular_v,angular_v+1,angular_v+2,acceleration,acceleration+1,acceleration+2);
imu_time=imu_time*0.000000001;
last_imu_time = imu_time;
std::cout<<imu_time<<std::endl;
if (fscanf_return != 7)
{
std::cout << "1fscanf error " << std::endl;
fclose(fp);
return -1;
}
for(size_t i = 10; (i < left_image_index.size()-10)&&(i < right_image_index.size()-10) ;++i)
{
if (feof(fp))
break;
ostringstream stringStream;
//double转long long,把左图像名转成长整型
unsigned long long left_image_index_=left_image_index[i];
std::string left_filename = string(left_image_path)+"/"+ to_string(left_image_index_) + string(".png");///构造文件名
//cout<<left_filename<<endl;
cv::Mat left_image = cv::imread(left_filename,CV_LOAD_IMAGE_GRAYSCALE);
time_count_left = left_image_index[i]*0.000000001;//图名是ns,转成s
//double转long long,把右图像名转成长整型
unsigned long long right_image_index_=right_image_index[i];
std::string right_filename = string(right_image_path)+"/" + to_string(right_image_index_) + ".png";
cv::Mat right_image = cv::imread(right_filename,CV_LOAD_IMAGE_GRAYSCALE);
if(left_image_index.empty() || right_image_index.empty())
{
std::cout << "right image empty\n";
fclose(fp);
return -1;
}
time_count_right = right_image_index[i]*0.000000001;//图名是ns,转成s
if(time_count_left != time_count_right)
{
std::cout << "left image time != right image time .............." << std::endl;
fclose(fp);
return -1;
}
//当imu时间戳一直比左图时间戳小时,就一直读imu
while (imu_time < left_image_index[i+1]*0.000000001)
{
if(last_imu_time > imu_time)
{
std::cout << "imu time disorder!!!!!!!!!!!" << std::endl;
return -1;
}
if ( imu_time - last_imu_time > 8)
{
imu_big_interval[imu_seq] = imu_time - last_imu_time;
std::cout<<"imu time to long!!!!!!!!!!!";
//return -1;
}
//线加速度
Eigen::Vector3d acc0(acceleration[0],acceleration[1],acceleration[2]);
Eigen::Vector3d acc1 = PreprocessAccelerator(acc0);
Eigen::Vector3d gyro(angular_v[0],angular_v[1],angular_v[2]);
if(imu_time > last_imu_time)
{
//把imu数据放入IMU这个queue里去
InputIMU(double(imu_time),acc0,gyro);
//std::cout.setf(std::ios::fixed, std::ios::floatfield);
//std::cout.precision(6);
//std::cout << "imu_time: " << imu_time << std::endl;
}
last_imu_time = imu_time;
fscanf_return = fscanf(fp,"%lf,%lf,%lf,%lf,%lf,%lf,%lf,",
&imu_time,angular_v,angular_v+1,angular_v+2,acceleration,acceleration+1,acceleration+2);
imu_time=imu_time*0.000000001;
if (fscanf_return != 7)
{
std::cout << "3fscanf error: " << fscanf_return << std::endl;
std::cout << "imu_time: " << imu_time << std::endl << "image_time: " << time_count_left << std::endl;
fclose(fp);
std::map<int,int>::iterator it1 ;
for(it1 = imu_big_interval.begin();it1 != imu_big_interval.end();it1++)
{
cout << "total: " << imu_big_interval.size() << " imu_seq: " << it1->first << " interval: " << it1->second << endl;
}
return -1;
}
}
cv::Mat IMAGELEFT=left_image.clone();
cv::Mat IMAGERIGHT=right_image.clone();
//把图像放到IMAGE这个queque中
InputIMAGE(IMAGELEFT, IMAGERIGHT, time_count_left);
//std::cout.setf(std::ios::fixed, std::ios::floatfield);
//std::cout.precision(6);
//std::cout << "result image stamp: " << time_count_left << std::endl;
//睡眠一会,等待process处理
usleep(2000);
}
fclose(fp);
return 0;
}
<file_sep>/build/startmsckf_noros
#!/usr/bin/python3
import tkinter as tk
from tkinter import filedialog
import os
root = tk.Tk()
root.withdraw()
print('请选择mav0/cam0/data文件夹')
Folderpathcam0 = filedialog.askdirectory()
print('请选择mav0/cam1/data文件夹')
Folderpathcam1 = filedialog.askdirectory()
print('请选择mav0/imu0/data.csv文件')
Filepathimu0 = filedialog.askopenfilename()
#print('Folderpath:',Folderpath)
#print('Filepath:',Filepath)
command = 'rm msckfvio.txt'
os.system(command)
command = './msckf_noros ' + Folderpathcam0 + ' ' + Folderpathcam1 + ' ' + Filepathimu0
os.system(command)
<file_sep>/src/random_numbers.cpp
#include "msckf_vio/random_numbers.h"
#include <boost/random/lagged_fibonacci.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/scoped_ptr.hpp>
static boost::uint32_t first_seed_ = 0;
/// Compute the first seed to be used; this function should be called only once
//计算要使用的第一个种子;这个函数应该只调用一次
static boost::uint32_t firstSeed(void)
{
boost::scoped_ptr<int> mem(new int());
first_seed_ = (boost::uint32_t)(
(boost::posix_time::microsec_clock::universal_time() - boost::posix_time::ptime(boost::date_time::min_date_time))
.total_microseconds() +
(unsigned long long)(mem.get()));
return first_seed_;
}
/// We use a different random number generator for the seeds of the
/// Other random generators. The root seed is from the number of
/// nano-seconds in the current time.
//我们对其他随机生成器的种子使用不同的随机数生成器。根种子来自当前时间中的纳米秒数。
static boost::uint32_t nextSeed(void)
{
static boost::mutex rngMutex;
boost::mutex::scoped_lock slock(rngMutex);
static boost::lagged_fibonacci607 sGen(firstSeed());
static boost::uniform_int<> sDist(1, 1000000000);
static boost::variate_generator<boost::lagged_fibonacci607&, boost::uniform_int<> > s(sGen, sDist);
boost::uint32_t v = s();
return v;
}
random_numbers::RandomNumberGenerator::RandomNumberGenerator(void)
: generator_(nextSeed())
, uniDist_(0, 1)
, normalDist_(0, 1)
, uni_(generator_, uniDist_)
, normal_(generator_, normalDist_)
{
}
random_numbers::RandomNumberGenerator::RandomNumberGenerator(boost::uint32_t seed)
: generator_(seed), uniDist_(0, 1), normalDist_(0, 1), uni_(generator_, uniDist_), normal_(generator_, normalDist_)
{
/// Because we manually specified a seed, we need to save it ourselves
//因为我们手动指定了一个种子,所以我们需要自己保存它
first_seed_ = seed;
}
// From: "Uniform Random Rotations", <NAME>, Graphics Gems III, pg. 124-132
void random_numbers::RandomNumberGenerator::quaternion(double value[4])
{
double x0 = uni_();
double r1 = sqrt(1.0 - x0), r2 = sqrt(x0);
double t1 = 2.0 * boost::math::constants::pi<double>() * uni_(),
t2 = 2.0 * boost::math::constants::pi<double>() * uni_();
double c1 = cos(t1), s1 = sin(t1);
double c2 = cos(t2), s2 = sin(t2);
value[0] = s1 * r1;
value[1] = c1 * r1;
value[2] = s2 * r2;
value[3] = c2 * r2;
}
boost::uint32_t random_numbers::RandomNumberGenerator::getFirstSeed()
{
return first_seed_;
}
<file_sep>/src/msckf_vio.cpp
#include <iostream>
#include <iomanip>
#include <cmath>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <Eigen/SVD>
#include <Eigen/QR>
#include <Eigen/SparseCore>
//#include <Eigen/SPQRSupport>
#include "boost/math/distributions/chi_squared.hpp"
#include <msckf_vio/msckf_vio.h>
#include <msckf_vio/math_utils.hpp>
#include <msckf_vio/utils.h>
using namespace Eigen;
namespace msckf_vio{
// Static member variables in IMUState class.
StateIDType IMUState::next_id = 0;
double IMUState::gyro_noise = 0;
double IMUState::acc_noise = 0;
double IMUState::gyro_bias_noise = 0;
double IMUState::acc_bias_noise = 0;
Vector3d IMUState::gravity = Vector3d(0, 0, -GRAVITY_ACCELERATION);
Isometry3d IMUState::T_imu_body = Isometry3d::Identity();
// Static member variables in CAMState class.
Isometry3d CAMState::T_cam0_cam1 = Isometry3d::Identity();
// Static member variables in Feature class.
FeatureIDType Feature::next_id = 0;
double Feature::observation_noise = 0.01;
Feature::OptimizationConfig Feature::optimization_config;
map<int, double> MsckfVio::chi_squared_test_table;
//DEBUG HAN
string MSCKF_RESULT_PATH="./msckfvio.txt";
MsckfVio::MsckfVio():
is_gravity_set(false),
is_first_img(true)
{
initialize();
return;
}
bool MsckfVio::loadParameters() {
// Frame id
//
position_std_threshold=8.0;
rotation_threshold=0.2618;
translation_threshold=0.4;
tracking_rate_threshold=0.5;
// Feature optimization parameters
Feature::optimization_config.translation_threshold=-0.1;
// Noise related parameters
//改噪声
IMUState::gyro_noise=0.005;
IMUState::acc_noise=0.05;
IMUState::gyro_bias_noise= 0.001;
IMUState::acc_bias_noise= 0.01;
Feature::observation_noise=0.035;
// Use variance instead of standard deviation.
IMUState::gyro_noise *= IMUState::gyro_noise;
IMUState::acc_noise *= IMUState::acc_noise;
IMUState::gyro_bias_noise *= IMUState::gyro_bias_noise;
IMUState::acc_bias_noise *= IMUState::acc_bias_noise;
Feature::observation_noise *= Feature::observation_noise;
// Set the initial IMU state.
// The intial orientation and position will be set to the origin
// implicitly. But the initial velocity and bias can be
// set by parameters.
// TODO: is it reasonable to set the initial bias to 0?
state_server.imu_state.velocity(0)= 0.0;
state_server.imu_state.velocity(1)= 0.0;
state_server.imu_state.velocity(2)= 0.0;
// The initial covariance of orientation and position can be
// set to 0. But for velocity, bias and extrinsic parameters,
// there should be nontrivial uncertainty.
double gyro_bias_cov, acc_bias_cov, velocity_cov;
velocity_cov=0.25;
gyro_bias_cov=0.01;
acc_bias_cov= 0.01;
double extrinsic_rotation_cov, extrinsic_translation_cov;
extrinsic_rotation_cov=0.000305;
extrinsic_translation_cov=0.000025;
state_server.state_cov = MatrixXd::Zero(21, 21);
for (int i = 3; i < 6; ++i)
state_server.state_cov(i, i) = gyro_bias_cov;
for (int i = 6; i < 9; ++i)
state_server.state_cov(i, i) = velocity_cov;
for (int i = 9; i < 12; ++i)
state_server.state_cov(i, i) = acc_bias_cov;
for (int i = 15; i < 18; ++i)
state_server.state_cov(i, i) = extrinsic_rotation_cov;
for (int i = 18; i < 21; ++i)
state_server.state_cov(i, i) = extrinsic_translation_cov;
// Transformation offsets between the frames involved.
//改从imu到相机0的变换矩阵
Eigen::Matrix3d R3;
R3 << 0.014865542981794, 0.999557249008346, -0.025774436697440,
-0.999880929698575, 0.014967213324719, 0.003756188357967,
0.004140296794224, 0.025715529947966, 0.999660727177902;
Eigen::Vector3d T3;
T3 << 0.065222909535531, -0.020706385492719, -0.008054602460030;
Isometry3d T_imu_cam0=Isometry3d::Identity();
T_imu_cam0.prerotate(R3);
T_imu_cam0.pretranslate(T3);
Isometry3d T_cam0_imu = T_imu_cam0.inverse();
state_server.imu_state.R_imu_cam0 = T_cam0_imu.linear().transpose();
state_server.imu_state.t_cam0_imu = T_cam0_imu.translation();
//改从相机0到相机1的变换矩阵
Eigen::Matrix4d T4;
T4 << 0.999997256477881, 0.002312067192424, 0.000376008102415, -0.110073808127187,
-0.002317135723281, 0.999898048506644, 0.014089835846648, 0.000399121547014,
-0.000343393120525, -0.014090668452714, 0.999900662637729, -0.000853702503357,
0, 0, 0, 1.000000000000000;
CAMState::T_cam0_cam1 =T4;
Eigen::Matrix4d T5;
T5 << 1.0000, 0.0000, 0.0000, 0.0000,
0.0000, 1.0000, 0.0000, 0.0000,
0.0000, 0.0000, 1.0000, 0.0000,
0.0000, 0.0000, 0.0000, 1.0000;
IMUState::T_imu_body =
T5.inverse();
// Maximum number of camera states to be stored
max_cam_state_size=20;
std::cout<<"R_imu_cam0"<<state_server.imu_state.R_imu_cam0<<std::endl;
std::cout<<"t_cam0_imu"<<state_server.imu_state.t_cam0_imu[0]<<state_server.imu_state.t_cam0_imu[1]<<
state_server.imu_state.t_cam0_imu[2]<<std::endl;
// std::cout<<"T_cam0_cam1"<<CAMState::T_cam0_cam1<<std::endl;
return true;
}
bool MsckfVio::initialize() {
if (!loadParameters()) return false;
std::cout<<"Finish loading parameters..."<<std::endl;
// Initialize state server
state_server.continuous_noise_cov =
Matrix<double, 12, 12>::Zero();
state_server.continuous_noise_cov.block<3, 3>(0, 0) =
Matrix3d::Identity()*IMUState::gyro_noise;
state_server.continuous_noise_cov.block<3, 3>(3, 3) =
Matrix3d::Identity()*IMUState::gyro_bias_noise;
state_server.continuous_noise_cov.block<3, 3>(6, 6) =
Matrix3d::Identity()*IMUState::acc_noise;
state_server.continuous_noise_cov.block<3, 3>(9, 9) =
Matrix3d::Identity()*IMUState::acc_bias_noise;
// Initialize the chi squared test table with confidence
// level 0.95.
for (int i = 1; i < 100; ++i) {
boost::math::chi_squared chi_squared_dist(i);
chi_squared_test_table[i] =
boost::math::quantile(chi_squared_dist, 0.05);
}
return true;
}
void MsckfVio::imuCallback(
const double timestamp, const Eigen::Vector3d& accl, const Eigen::Vector3d& gyro) {
/// IMU msgs are pushed backed into a buffer instead of being processed immediately. The IMU msgs are processed
/// when the next image is available, in which way, we can easily handle the transfer delay.
///IMU消息被推回缓冲区,而不是立即处理。在有下一张图像时处理IMU消息,这样可以很容易地处理传输延迟。
Eigen::Matrix<double, 6, 1> tempimu;
tempimu<<accl[0],accl[1],accl[2],gyro[0],gyro[1],gyro[2];
imubuffer.push_back(make_pair(timestamp,tempimu));
if (!is_gravity_set) {
//至少静止200个imu数据才能很好的进行重力初始化
if (imubuffer.size() < 200) return;
std::cout<<"initial g"<<std::endl;
initializeGravityAndBias();
is_gravity_set = true;
}
return;
}
//静止时候初始化重力方向,陀螺仪偏值,从重力坐标系到IMU坐标系
void MsckfVio::initializeGravityAndBias() {
// Initialize gravity and gyro bias.初始化重力和陀螺偏差。
Vector3d sum_angular_vel = Vector3d::Zero();
Vector3d sum_linear_acc = Vector3d::Zero();
for (const auto& imu_msg : imubuffer) {
Vector3d angular_vel = Vector3d::Zero();
Vector3d linear_acc = Vector3d::Zero();
linear_acc << imu_msg.second[0],imu_msg.second[1],imu_msg.second[2];
angular_vel << imu_msg.second[3],imu_msg.second[4],imu_msg.second[5];
sum_angular_vel += angular_vel;
sum_linear_acc += linear_acc;
}
state_server.imu_state.gyro_bias =
sum_angular_vel / imubuffer.size();
//IMUState::gravity =
// -sum_linear_acc / imu_msg_buffer.size();
// This is the gravity in the IMU frame.
Vector3d gravity_imu =
sum_linear_acc / imubuffer.size();
// Initialize the initial orientation, so that the estimation
// is consistent with the inertial frame.
////初始化初始方向,使估计值与惯性坐标系一致。
double gravity_norm = gravity_imu.norm();
IMUState::gravity = Vector3d(0.0, 0.0, -gravity_norm);
//FromTwoVectors()是从第一个向量转到第二个向量
//即是从imu坐标系到重力坐标系
Quaterniond q0_i_w = Quaterniond::FromTwoVectors(
gravity_imu, -IMUState::gravity);
state_server.imu_state.orientation =
rotationToQuaternion(q0_i_w.toRotationMatrix().transpose());
return;
}
void MsckfVio::featureCallback(
const vector<pair<double, std::vector<Eigen::Matrix<double, 5, 1>>> > & msg) {
// Return if the gravity vector has not been set.
//如果重力向量没有设置,则返回。
if (!is_gravity_set) return;
cout << "==================================" << endl;
cout << "start new state estimate" << endl;
cout << "==================================" << endl;
// Start the system if the first image is received.
// The frame where the first image is received will be the origin.
////如果接收到第一个图像,则启动系统。接收到第一张图像的帧将是原点。
if (is_first_img) {
is_first_img = false;
state_server.imu_state.time = msg[0].first;
}
TicToc t_whole ;
// Propogate the IMU state that are received before the image msg.
//传播img消息收到前的imu状态
batchImuProcessing(msg[0].first);
// Augment the state vector. 状态扩维
stateAugmentation(msg[0].first);
/// Add new observations for existing features or new features in the map server.
//为现有特性或地图服务器中的新特性添加新的观察结果
addFeatureObservations(msg);
/// Perform measurement update if necessary.
//进行测量更新。 里面调用了measurementUpdate
removeLostFeatures();
//如果相机状态超过30个,则剔除两个相机状态
pruneCamStateBuffer();
// Publish the odometry.
publish(msg[0].first);
std::cout<<"whole time for state estimate:"<<t_whole.toc()<<std::endl;
// Reset the system if necessary.
return;
}
//得到图像帧时间间隔内的imu数据
void MsckfVio::batchImuProcessing(const double& time_bound) {
// Counter how many IMU msgs in the buffer are used.
int used_imu_msg_cntr = 0;
//std::cout<<imubuffer.size()<<std::endl;
for (const auto& imu_msg : imubuffer) {
double imu_time = imu_msg.first;
if (imu_time < state_server.imu_state.time) {
++used_imu_msg_cntr;
continue;
}
if (imu_time > time_bound) break;
// Convert the msgs.
Vector3d m_gyro, m_acc;
m_gyro<<imu_msg.second[3],imu_msg.second[4],imu_msg.second[5];
m_acc<<imu_msg.second[0],imu_msg.second[1],imu_msg.second[2];
// Execute process model.
processModel(imu_time, m_gyro, m_acc);
++used_imu_msg_cntr;
}
//std::cout<<"propoimu"<<used_imu_msg_cntr<<std::endl;
// Set the state ID for the new IMU state.
state_server.imu_state.id = IMUState::next_id++;
// Remove all used IMU msgs.
imubuffer.erase(imubuffer.begin(),
imubuffer.begin()+used_imu_msg_cntr);
return;
}
void MsckfVio::processModel(const double& time,
const Vector3d& m_gyro,
const Vector3d& m_acc) {
// Remove the bias from the measured gyro and acceleration
//1.将加速度和陀螺仪减去他们的偏值
IMUState& imu_state = state_server.imu_state;
Vector3d gyro = m_gyro - imu_state.gyro_bias;
Vector3d acc = m_acc - imu_state.acc_bias;
double dtime = time - imu_state.time;
// Compute discrete transition and noise covariance matrix
//2.计算IMU状态量的倒数的雅可比和协方差
Matrix<double, 21, 21> F = Matrix<double, 21, 21>::Zero();
Matrix<double, 21, 12> G = Matrix<double, 21, 12>::Zero();
F.block<3, 3>(0, 0) = -skewSymmetric(gyro);
F.block<3, 3>(0, 3) = -Matrix3d::Identity();
F.block<3, 3>(6, 0) = -quaternionToRotation(
imu_state.orientation).transpose()*skewSymmetric(acc);
F.block<3, 3>(6, 9) = -quaternionToRotation(
imu_state.orientation).transpose();
F.block<3, 3>(12, 6) = Matrix3d::Identity();
G.block<3, 3>(0, 0) = -Matrix3d::Identity();
G.block<3, 3>(3, 3) = Matrix3d::Identity();
G.block<3, 3>(6, 6) = -quaternionToRotation(
imu_state.orientation).transpose();
G.block<3, 3>(9, 9) = Matrix3d::Identity();
// Approximate matrix exponential to the 3rd order,
// which can be considered to be accurate enough assuming
// dtime is within 0.01s.
//3.状态方程的离散化(3阶,vins是1阶)
Matrix<double, 21, 21> Fdt = F * dtime;
Matrix<double, 21, 21> Fdt_square = Fdt * Fdt;
Matrix<double, 21, 21> Fdt_cube = Fdt_square * Fdt;
Matrix<double, 21, 21> Phi = Matrix<double, 21, 21>::Identity() +
Fdt + 0.5*Fdt_square + (1.0/6.0)*Fdt_cube;
// Propogate the state using 4th order Runge-Kutta
//4.RK4积分p,v,q
predictNewState(dtime, gyro, acc);
// Modify the transition matrix
//5.改进状态转移矩阵Phi
//???
Matrix3d R_kk_1 = quaternionToRotation(imu_state.orientation_null);
Phi.block<3, 3>(0, 0) =
quaternionToRotation(imu_state.orientation) * R_kk_1.transpose();
Vector3d u = R_kk_1 * IMUState::gravity;
RowVector3d s = (u.transpose()*u).inverse() * u.transpose();
Matrix3d A1 = Phi.block<3, 3>(6, 0);
Vector3d w1 = skewSymmetric(
imu_state.velocity_null-imu_state.velocity) * IMUState::gravity;
Phi.block<3, 3>(6, 0) = A1 - (A1*u-w1)*s;
Matrix3d A2 = Phi.block<3, 3>(12, 0);
Vector3d w2 = skewSymmetric(
dtime*imu_state.velocity_null+imu_state.position_null-
imu_state.position) * IMUState::gravity;
Phi.block<3, 3>(12, 0) = A2 - (A2*u-w2)*s;
// Propogate the state covariance matrix.
//6.协方差更新
//IMU状态协方差更新
Matrix<double, 21, 21> Q = Phi*G*state_server.continuous_noise_cov*
G.transpose()*Phi.transpose()*dtime;
state_server.state_cov.block<21, 21>(0, 0) =
Phi*state_server.state_cov.block<21, 21>(0, 0)*Phi.transpose() + Q;
//相机状态协方差更新
if (state_server.cam_states.size() > 0) {
state_server.state_cov.block(
0, 21, 21, state_server.state_cov.cols()-21) =
Phi * state_server.state_cov.block(
0, 21, 21, state_server.state_cov.cols()-21);
state_server.state_cov.block(
21, 0, state_server.state_cov.rows()-21, 21) =
state_server.state_cov.block(
21, 0, state_server.state_cov.rows()-21, 21) * Phi.transpose();
}
//7.保证协方差的对称性
MatrixXd state_cov_fixed = (state_server.state_cov +
state_server.state_cov.transpose()) / 2.0;
state_server.state_cov = state_cov_fixed;
// Update the state correspondes to null space.
imu_state.orientation_null = imu_state.orientation;
imu_state.position_null = imu_state.position;
imu_state.velocity_null = imu_state.velocity;
// Update the state info
state_server.imu_state.time = time;
return;
}
void MsckfVio::predictNewState(const double& dt,
const Vector3d& gyro,
const Vector3d& acc) {
// TODO: Will performing the forward integration using
// the inverse of the quaternion give better accuracy?
double gyro_norm = gyro.norm();
Matrix4d Omega = Matrix4d::Zero();
Omega.block<3, 3>(0, 0) = -skewSymmetric(gyro);
Omega.block<3, 1>(0, 3) = gyro;
Omega.block<1, 3>(3, 0) = -gyro;
Vector4d& q = state_server.imu_state.orientation;
Vector3d& v = state_server.imu_state.velocity;
Vector3d& p = state_server.imu_state.position;
// Some pre-calculation
Vector4d dq_dt, dq_dt2;
if (gyro_norm > 1e-5) {
dq_dt = (cos(gyro_norm*dt*0.5)*Matrix4d::Identity() +
1/gyro_norm*sin(gyro_norm*dt*0.5)*Omega) * q;
dq_dt2 = (cos(gyro_norm*dt*0.25)*Matrix4d::Identity() +
1/gyro_norm*sin(gyro_norm*dt*0.25)*Omega) * q;
}
//值很小的时候,cos(gyro_norm*dt*0.25)=1貌似可以忽略
else {
dq_dt = (Matrix4d::Identity()+0.5*dt*Omega) *
cos(gyro_norm*dt*0.5) * q;
dq_dt2 = (Matrix4d::Identity()+0.25*dt*Omega) *
cos(gyro_norm*dt*0.25) * q;
}
Matrix3d dR_dt_transpose = quaternionToRotation(dq_dt).transpose();
Matrix3d dR_dt2_transpose = quaternionToRotation(dq_dt2).transpose();
// k1 = f(tn, yn)
Vector3d k1_v_dot = quaternionToRotation(q).transpose()*acc +
IMUState::gravity;
Vector3d k1_p_dot = v;
// k2 = f(tn+dt/2, yn+k1*dt/2)
Vector3d k1_v = v + k1_v_dot*dt/2;
Vector3d k2_v_dot = dR_dt2_transpose*acc +
IMUState::gravity;
Vector3d k2_p_dot = k1_v;
// k3 = f(tn+dt/2, yn+k2*dt/2)
Vector3d k2_v = v + k2_v_dot*dt/2;
Vector3d k3_v_dot = dR_dt2_transpose*acc +
IMUState::gravity;
Vector3d k3_p_dot = k2_v;
// k4 = f(tn+dt, yn+k3*dt)
Vector3d k3_v = v + k3_v_dot*dt;
Vector3d k4_v_dot = dR_dt_transpose*acc +
IMUState::gravity;
Vector3d k4_p_dot = k3_v;
// yn+1 = yn + dt/6*(k1+2*k2+2*k3+k4)
q = dq_dt;
quaternionNormalize(q);
v = v + dt/6*(k1_v_dot+2*k2_v_dot+2*k3_v_dot+k4_v_dot);
p = p + dt/6*(k1_p_dot+2*k2_p_dot+2*k3_p_dot+k4_p_dot);
return;
}
void MsckfVio::stateAugmentation(const double& time) {
const Matrix3d& R_i_c = state_server.imu_state.R_imu_cam0;
const Vector3d& t_c_i = state_server.imu_state.t_cam0_imu;
// Add a new camera state to the state server.
//1.由上一步得到的IMU状态计算当前相机状态
Matrix3d R_w_i = quaternionToRotation(
state_server.imu_state.orientation);
Matrix3d R_w_c = R_i_c * R_w_i;
Vector3d t_c_w = state_server.imu_state.position +
R_w_i.transpose()*t_c_i;
//2.相机状态的增广
state_server.cam_states[state_server.imu_state.id] =
CAMState(state_server.imu_state.id);
CAMState& cam_state = state_server.cam_states[
state_server.imu_state.id];
cam_state.time = time;
cam_state.orientation = rotationToQuaternion(R_w_c);
cam_state.position = t_c_w;
cam_state.orientation_null = cam_state.orientation;
cam_state.position_null = cam_state.position;
// Update the covariance matrix of the state.
// To simplify computation, the matrix J below is the nontrivial block
// in Equation (16) in "A Multi-State Constraint Kalman Filter for Vision
// -aided Inertial Navigation".
//3.计算相对于以前状态向量的雅可比
//???
Matrix<double, 6, 21> J = Matrix<double, 6, 21>::Zero();
J.block<3, 3>(0, 0) = R_i_c;
J.block<3, 3>(0, 15) = Matrix3d::Identity(); //???
J.block<3, 3>(3, 0) = -skewSymmetric(R_w_i.transpose()*t_c_i); //???为了简化计算,使用了msckfmono中的J
//J.block<3, 3>(3, 0) = -R_w_i.transpose()*skewSymmetric(t_c_i); //???
J.block<3, 3>(3, 12) = Matrix3d::Identity();
J.block<3, 3>(3, 18) = Matrix3d::Identity(); //???
// Resize the state covariance matrix.
//4.协方差的增广
int old_rows = state_server.state_cov.rows();
int old_cols = state_server.state_cov.cols();
state_server.state_cov.conservativeResize(old_rows+6, old_cols+6);
// Rename some matrix blocks for convenience.
const Matrix<double, 21, 21>& P11 =
state_server.state_cov.block<21, 21>(0, 0);
const MatrixXd& P12 =
state_server.state_cov.block(0, 21, 21, old_cols-21);
// Fill in the augmented state covariance.
//
state_server.state_cov.block(old_rows, 0, 6, old_cols) << J*P11, J*P12;
state_server.state_cov.block(0, old_cols, old_rows, 6) =
state_server.state_cov.block(old_rows, 0, 6, old_cols).transpose();
state_server.state_cov.block<6, 6>(old_rows, old_cols) =
J * P11 * J.transpose();
// Fix the covariance to be symmetric
//5.保证协方差的对称性(A+A^T)/2
MatrixXd state_cov_fixed = (state_server.state_cov +
state_server.state_cov.transpose()) / 2.0;
state_server.state_cov = state_cov_fixed;
return;
}
//增加当前帧观测到的点到特征点地图中
void MsckfVio::addFeatureObservations(
const vector<pair<double, std::vector<Eigen::Matrix<double, 5, 1>>> > & msg) {
StateIDType state_id = state_server.imu_state.id;
int curr_feature_num = map_server.size();
int tracked_feature_num = 0;
// Add new observations for existing features or new
// features in the map server.
for (const auto& feature : msg.begin()->second) {
if (map_server.find(feature[0]) == map_server.end()) {
// This is a new feature.
map_server[feature[0]] = Feature(feature[0]);
map_server[feature[0]].observations[state_id] =
Vector4d(feature[1], feature[2],
feature[3], feature[4]);
} else {
// This is an old feature.
map_server[feature[0]].observations[state_id] =
Vector4d(feature[1], feature[2],
feature[3], feature[4]);
++tracked_feature_num;
}
}
tracking_rate =
static_cast<double>(tracked_feature_num) /
static_cast<double>(curr_feature_num);
return;
}
//计算每一个特征点对单个相机状态和单个特征点的雅可比
void MsckfVio::measurementJacobian(
const StateIDType& cam_state_id,
const FeatureIDType& feature_id,
Matrix<double, 4, 6>& H_x, Matrix<double, 4, 3>& H_f, Vector4d& r) {
// Prepare all the required data.
const CAMState& cam_state = state_server.cam_states[cam_state_id];
const Feature& feature = map_server[feature_id];
// Cam0 pose.
Matrix3d R_w_c0 = quaternionToRotation(cam_state.orientation);
const Vector3d& t_c0_w = cam_state.position;
// Cam1 pose.
Matrix3d R_c0_c1 = CAMState::T_cam0_cam1.linear();
Matrix3d R_w_c1 = CAMState::T_cam0_cam1.linear() * R_w_c0;
Vector3d t_c1_w = t_c0_w - R_w_c1.transpose()*CAMState::T_cam0_cam1.translation();
// 3d feature position in the world frame.
// And its observation with the stereo cameras.
const Vector3d& p_w = feature.position;
const Vector4d& z = feature.observations.find(cam_state_id)->second;
// Convert the feature position from the world frame to
// the cam0 and cam1 frame.
//1.将世界坐标系下的特征点转到相机坐标系
Vector3d p_c0 = R_w_c0 * (p_w-t_c0_w);
Vector3d p_c1 = R_w_c1 * (p_w-t_c1_w);
// Compute the Jacobians.
//2.计算雅可比
Matrix<double, 4, 3> dz_dpc0 = Matrix<double, 4, 3>::Zero();
dz_dpc0(0, 0) = 1 / p_c0(2);
dz_dpc0(1, 1) = 1 / p_c0(2);
dz_dpc0(0, 2) = -p_c0(0) / (p_c0(2)*p_c0(2));
dz_dpc0(1, 2) = -p_c0(1) / (p_c0(2)*p_c0(2));
Matrix<double, 4, 3> dz_dpc1 = Matrix<double, 4, 3>::Zero();
dz_dpc1(2, 0) = 1 / p_c1(2);
dz_dpc1(3, 1) = 1 / p_c1(2);
dz_dpc1(2, 2) = -p_c1(0) / (p_c1(2)*p_c1(2));
dz_dpc1(3, 2) = -p_c1(1) / (p_c1(2)*p_c1(2));
Matrix<double, 3, 6> dpc0_dxc = Matrix<double, 3, 6>::Zero();
dpc0_dxc.leftCols(3) = skewSymmetric(p_c0);
dpc0_dxc.rightCols(3) = -R_w_c0;
Matrix<double, 3, 6> dpc1_dxc = Matrix<double, 3, 6>::Zero();
dpc1_dxc.leftCols(3) = R_c0_c1 * skewSymmetric(p_c0);
dpc1_dxc.rightCols(3) = -R_w_c1;
Matrix3d dpc0_dpg = R_w_c0;
Matrix3d dpc1_dpg = R_w_c1;
H_x = dz_dpc0*dpc0_dxc + dz_dpc1*dpc1_dxc;
H_f = dz_dpc0*dpc0_dpg + dz_dpc1*dpc1_dpg;
// Modifty the measurement Jacobian to ensure
// observability constrain.
//3.改进雅可比,为了能观
//???
Matrix<double, 4, 6> A = H_x;
Matrix<double, 6, 1> u = Matrix<double, 6, 1>::Zero();
u.block<3, 1>(0, 0) = quaternionToRotation(
cam_state.orientation_null) * IMUState::gravity;
u.block<3, 1>(3, 0) = skewSymmetric(
p_w-cam_state.position_null) * IMUState::gravity;
H_x = A - A*u*(u.transpose()*u).inverse()*u.transpose();
H_f = -H_x.block<4, 3>(0, 3);
// Compute the residual.
//4.计算残差
r = z - Vector4d(p_c0(0)/p_c0(2), p_c0(1)/p_c0(2),
p_c1(0)/p_c1(2), p_c1(1)/p_c1(2));
return;
}
//计算每一个特征点的雅可比,且映射到左零空间
void MsckfVio::featureJacobian(
const FeatureIDType& feature_id,
const std::vector<StateIDType>& cam_state_ids,
MatrixXd& H_x, VectorXd& r) {
const auto& feature = map_server[feature_id];
// Check how many camera states in the provided camera
// id camera has actually seen this feature.
//1.检测每个特征点在多少个相机状态中检测到
vector<StateIDType> valid_cam_state_ids(0);
for (const auto& cam_id : cam_state_ids) {
if (feature.observations.find(cam_id) ==
feature.observations.end()) continue;
valid_cam_state_ids.push_back(cam_id);
}
int jacobian_row_size = 0;
jacobian_row_size = 4 * valid_cam_state_ids.size();
//H_xj(4M,21+6N)
//H_fj(4M,3)
//r_j(4M,1)
MatrixXd H_xj = MatrixXd::Zero(jacobian_row_size,
21+state_server.cam_states.size()*6);
MatrixXd H_fj = MatrixXd::Zero(jacobian_row_size, 3);
VectorXd r_j = VectorXd::Zero(jacobian_row_size);
int stack_cntr = 0;
//2.计算每个特征点的对应的所有相机状态的雅可比
for (const auto& cam_id : valid_cam_state_ids) {
//H_xi(4,6)
//H_fi(4,3)
//r_i(4,1)
Matrix<double, 4, 6> H_xi = Matrix<double, 4, 6>::Zero();
Matrix<double, 4, 3> H_fi = Matrix<double, 4, 3>::Zero();
Vector4d r_i = Vector4d::Zero();
measurementJacobian(cam_id, feature.id, H_xi, H_fi, r_i);
auto cam_state_iter = state_server.cam_states.find(cam_id);
int cam_state_cntr = std::distance(
state_server.cam_states.begin(), cam_state_iter);
// Stack the Jacobians.
H_xj.block<4, 6>(stack_cntr, 21+6*cam_state_cntr) = H_xi;
H_fj.block<4, 3>(stack_cntr, 0) = H_fi;
r_j.segment<4>(stack_cntr) = r_i;
stack_cntr += 4;
}
// Project the residual and Jacobians onto the nullspace
// of H_fj.
//3.映射到左零空间中
//???
//ComputeFullU意味着U是方的(4m,4m)的
JacobiSVD<MatrixXd> svd_helper(H_fj, ComputeFullU | ComputeThinV);
//A(4m,4m-3)
MatrixXd A = svd_helper.matrixU().rightCols(
jacobian_row_size - 3);
//H_x(4m-3,21+6n)
//r(4m-3,1)
H_x = A.transpose() * H_xj;
r = A.transpose() * r_j;
return;
}
void MsckfVio::measurementUpdate(
const MatrixXd& H, const VectorXd& r) {
if (H.rows() == 0 || r.rows() == 0) return;
// Decompose the final Jacobian matrix to reduce computational complexity
// 分解最终雅可比矩阵,降低计算复杂度
//H(l*(4M-3),21+6N)
//r(l*(4M-3),21+6N)
//1.QR分解
MatrixXd H_thin;
VectorXd r_thin;
if (H.rows() > H.cols()) {
/* // Convert H to a sparse matrix.
SparseMatrix<double> H_sparse = H.sparseView();
// Perform QR decompostion on H_sparse.
SPQR<SparseMatrix<double> > spqr_helper;
spqr_helper.setSPQROrdering(SPQR_ORDERING_NATURAL);
spqr_helper.compute(H_sparse);
MatrixXd H_temp;
VectorXd r_temp;
(spqr_helper.matrixQ().transpose() * H).evalTo(H_temp);
(spqr_helper.matrixQ().transpose() * r).evalTo(r_temp);
//H_thin(21+6n,21+6n)
//r_thin(21+6n,1)
H_thin = H_temp.topRows(21+state_server.cam_states.size()*6);
r_thin = r_temp.head(21+state_server.cam_states.size()*6);
*/
HouseholderQR<MatrixXd> qr_helper(H);
MatrixXd Q = qr_helper.householderQ();
MatrixXd Q1 = Q.leftCols(21+state_server.cam_states.size()*6);
H_thin = Q1.transpose() * H;
r_thin = Q1.transpose() * r;
} else {
H_thin = H;
r_thin = r;
}
// Compute the Kalman gain.
//2.计算卡尔曼增益
//最终视觉的噪声协方差变成(Q^T*R*Q),由于Q是正交矩阵,R是视觉噪声乘以单位阵
const MatrixXd& P = state_server.state_cov;
MatrixXd S = H_thin*P*H_thin.transpose() +
Feature::observation_noise*MatrixXd::Identity(
H_thin.rows(), H_thin.rows());
//MatrixXd K_transpose = S.fullPivHouseholderQr().solve(H_thin*P);
MatrixXd K_transpose = S.ldlt().solve(H_thin*P);
MatrixXd K = K_transpose.transpose();
// Compute the error of the state.
//3.计算状态误差增量
VectorXd delta_x = K * r_thin;
// Update the IMU state.
//4.更新IMU的误差状态
const VectorXd& delta_x_imu = delta_x.head<21>();
if (//delta_x_imu.segment<3>(0).norm() > 0.15 ||
//delta_x_imu.segment<3>(3).norm() > 0.15 ||
delta_x_imu.segment<3>(6).norm() > 0.5 ||
//delta_x_imu.segment<3>(9).norm() > 0.5 ||
delta_x_imu.segment<3>(12).norm() > 1.0) {
printf("delta velocity: %f\n", delta_x_imu.segment<3>(6).norm());
printf("delta position: %f\n", delta_x_imu.segment<3>(12).norm());
std::cout<<"Update change is too large."<<endl;
//return;
}
//
const Vector4d dq_imu =
smallAngleQuaternion(delta_x_imu.head<3>());
state_server.imu_state.orientation = quaternionMultiplication(
dq_imu, state_server.imu_state.orientation);
state_server.imu_state.gyro_bias += delta_x_imu.segment<3>(3);
state_server.imu_state.velocity += delta_x_imu.segment<3>(6);
state_server.imu_state.acc_bias += delta_x_imu.segment<3>(9);
state_server.imu_state.position += delta_x_imu.segment<3>(12);
const Vector4d dq_extrinsic =
smallAngleQuaternion(delta_x_imu.segment<3>(15));
state_server.imu_state.R_imu_cam0 = quaternionToRotation(
dq_extrinsic) * state_server.imu_state.R_imu_cam0;
state_server.imu_state.t_cam0_imu += delta_x_imu.segment<3>(18);
// Update the camera states.
// 更新相机状态。
auto cam_state_iter = state_server.cam_states.begin();
for (int i = 0; i < state_server.cam_states.size();
++i, ++cam_state_iter) {
const VectorXd& delta_x_cam = delta_x.segment<6>(21+i*6);
const Vector4d dq_cam = smallAngleQuaternion(delta_x_cam.head<3>());
cam_state_iter->second.orientation = quaternionMultiplication(
dq_cam, cam_state_iter->second.orientation);
cam_state_iter->second.position += delta_x_cam.tail<3>();
}
// Update state covariance.
//5.更新协方差矩阵
MatrixXd I_KH = MatrixXd::Identity(K.rows(), H_thin.cols()) - K*H_thin;
//state_server.state_cov = I_KH*state_server.state_cov*I_KH.transpose() +
// K*K.transpose()*Feature::observation_noise;
state_server.state_cov = I_KH*state_server.state_cov;
// Fix the covariance to be symmetric
// 确保协方差是对称的
MatrixXd state_cov_fixed = (state_server.state_cov +
state_server.state_cov.transpose()) / 2.0;
state_server.state_cov = state_cov_fixed;
return;
}
bool MsckfVio::gatingTest(
const MatrixXd& H, const VectorXd& r, const int& dof) {
MatrixXd P1 = H * state_server.state_cov * H.transpose();
MatrixXd P2 = Feature::observation_noise *
MatrixXd::Identity(H.rows(), H.rows());
double gamma = r.transpose() * (P1+P2).ldlt().solve(r);
//cout << dof << " " << gamma << " " <<
// chi_squared_test_table[dof] << " ";
if (gamma < chi_squared_test_table[dof]) {
//cout << "passed" << endl;
return true;
} else {
// cout << "failed" << endl;
return false;
}
}
void MsckfVio::removeLostFeatures() {
// Remove the features that lost track.
// BTW, find the size the final Jacobian matrix and residual vector.
// 删除丢失的特征点,顺便求出最终雅可比矩阵和残差向量的大小
int jacobian_row_size = 0;
vector<FeatureIDType> invalid_feature_ids(0);
vector<FeatureIDType> processed_feature_ids(0);
for (auto iter = map_server.begin();
iter != map_server.end(); ++iter) {
// Rename the feature to be checked.重命名要检查的特征点。
auto& feature = iter->second;
//1.找到追踪不上的点,且剔除尺寸小于3的点
// Pass the features that are still being tracked.
//剔除在当前帧的点
if (feature.observations.find(state_server.imu_state.id) !=
feature.observations.end()) continue;
//剔除尺寸小于3个的
if (feature.observations.size() < 3) {
invalid_feature_ids.push_back(feature.id);
continue;
}
// Check if the feature can be initialized if it has not been.
//检查未被初始化的特征点是否可被初始化
if (!feature.is_initialized) {
if (!feature.checkMotion(state_server.cam_states)) {
invalid_feature_ids.push_back(feature.id);
continue;
} else {
if(!feature.initializePosition(state_server.cam_states)) {
invalid_feature_ids.push_back(feature.id);
continue;
}
}
}
jacobian_row_size += 4*feature.observations.size() - 3;
processed_feature_ids.push_back(feature.id);
}
// Remove the features that do not have enough measurements.
// 删除没有足够测量的特征点。
for (const auto& feature_id : invalid_feature_ids)
map_server.erase(feature_id);
// Return if there is no lost feature to be processed.
if (processed_feature_ids.size() == 0) return;
//左零空间
//H_x=(l*(4M-3),21+6N),l是特征点的个数,M是每个特征点对应的相机状态个数,N是所有相机状态个数
//r=(l*(4M-3),1)
MatrixXd H_x = MatrixXd::Zero(jacobian_row_size,
21+6*state_server.cam_states.size());
VectorXd r = VectorXd::Zero(jacobian_row_size);
int stack_cntr = 0;
// Process the features which lose track.
//2.计算所有特征点的雅可比
for (const auto& feature_id : processed_feature_ids) {
auto& feature = map_server[feature_id];
vector<StateIDType> cam_state_ids(0);
for (const auto& measurement : feature.observations)
cam_state_ids.push_back(measurement.first);
MatrixXd H_xj;
VectorXd r_j;
//H_xj(4m-3,21+6n)
//r_j(4m-3,1)
featureJacobian(feature.id, cam_state_ids, H_xj, r_j);
if (gatingTest(H_xj, r_j, cam_state_ids.size()-1)) {
H_x.block(stack_cntr, 0, H_xj.rows(), H_xj.cols()) = H_xj;
r.segment(stack_cntr, r_j.rows()) = r_j;
stack_cntr += H_xj.rows();
}
// Put an upper bound on the row size of measurement Jacobian,
// which helps guarantee the executation time.
if (stack_cntr > 1500) break;
}
H_x.conservativeResize(stack_cntr, H_x.cols());
r.conservativeResize(stack_cntr);
// Perform the measurement update step.
//3.视觉更新
measurementUpdate(H_x, r);
// Remove all processed features from the map.
for (const auto& feature_id : processed_feature_ids)
map_server.erase(feature_id);
return;
}
//选择要剔除的哪两个相机状态
void MsckfVio::findRedundantCamStates(
vector<StateIDType>& rm_cam_state_ids) {
// Move the iterator to the key position.
auto key_cam_state_iter = state_server.cam_states.end();//最新帧
for (int i = 0; i < 4; ++i)
--key_cam_state_iter;
auto cam_state_iter = key_cam_state_iter;//第5最新帧
++cam_state_iter;//第四最新帧
auto first_cam_state_iter = state_server.cam_states.begin();//最老帧
// Pose of the key camera state.
const Vector3d key_position =
key_cam_state_iter->second.position;
const Matrix3d key_rotation = quaternionToRotation(
key_cam_state_iter->second.orientation);
// Mark the camera states to be removed based on the
// motion between states.
//清除两个相机状态
//1.如果第五帧与第四帧之间的角度,平移小于阈值以及追踪率大于阈值,则剔除第四帧
//2.否则就剔除最老帧
for (int i = 0; i < 2; ++i) {
const Vector3d position =
cam_state_iter->second.position;
const Matrix3d rotation = quaternionToRotation(
cam_state_iter->second.orientation);
double distance = (position-key_position).norm();
double angle = AngleAxisd(
rotation*key_rotation.transpose()).angle();
if (angle < rotation_threshold &&
distance < translation_threshold &&
tracking_rate > tracking_rate_threshold) {
rm_cam_state_ids.push_back(cam_state_iter->first);
++cam_state_iter;
} else {
rm_cam_state_ids.push_back(first_cam_state_iter->first);
++first_cam_state_iter;
}
}
// Sort the elements in the output vector.
sort(rm_cam_state_ids.begin(), rm_cam_state_ids.end());
return;
}
//如果相机状态超过30个,则剔除两个相机状态
void MsckfVio::pruneCamStateBuffer() {
if (state_server.cam_states.size() < max_cam_state_size)
return;
// Find two camera states to be removed.
//1.选择要被剔除的两个相机状态
vector<StateIDType> rm_cam_state_ids(0);
findRedundantCamStates(rm_cam_state_ids);
// Find the size of the Jacobian matrix.
// 求雅可比矩阵的大小
int jacobian_row_size = 0;
for (auto& item : map_server) {
auto& feature = item.second;
// Check how many camera states to be removed are associated with this feature.
//检查这个点中有几个将要被移除的相机状态
vector<StateIDType> involved_cam_state_ids(0);
for (const auto& cam_id : rm_cam_state_ids) {
if (feature.observations.find(cam_id) !=
feature.observations.end())
involved_cam_state_ids.push_back(cam_id);
}
//如果该特征点只检测到一个相机状态,直接剔除该特征点
if (involved_cam_state_ids.size() == 0) continue;
if (involved_cam_state_ids.size() == 1) {
feature.observations.erase(involved_cam_state_ids[0]);
continue;
}
//如果特征点没有三角化,则也直接剔除
if (!feature.is_initialized) {
// Check if the feature can be initialize.
// 检查特征点是否可以初始化。
if (!feature.checkMotion(state_server.cam_states)) {
// If the feature cannot be initialized, just remove the observations associated with the camera states to be removed.
// 如果特征点不能初始化,只需删除与相机状态相关的观测即可。
for (const auto& cam_id : involved_cam_state_ids)
feature.observations.erase(cam_id);
continue;
} else {
if(!feature.initializePosition(state_server.cam_states)) {
for (const auto& cam_id : involved_cam_state_ids)
feature.observations.erase(cam_id);
continue;
}
}
}
jacobian_row_size += 4*involved_cam_state_ids.size() - 3;
}
// Compute the Jacobian and residual.
// 计算雅可比矩阵和残差。
MatrixXd H_x = MatrixXd::Zero(jacobian_row_size,
21+6*state_server.cam_states.size());
VectorXd r = VectorXd::Zero(jacobian_row_size);
int stack_cntr = 0;
for (auto& item : map_server) {
auto& feature = item.second;
// Check how many camera states to be removed are associated with this feature.
// 检查有多少相机状态要删除
vector<StateIDType> involved_cam_state_ids(0);
for (const auto& cam_id : rm_cam_state_ids) {
if (feature.observations.find(cam_id) !=
feature.observations.end())
involved_cam_state_ids.push_back(cam_id);
}
if (involved_cam_state_ids.size() == 0) continue;
MatrixXd H_xj;
VectorXd r_j;
featureJacobian(feature.id, involved_cam_state_ids, H_xj, r_j);
if (gatingTest(H_xj, r_j, involved_cam_state_ids.size())) {
H_x.block(stack_cntr, 0, H_xj.rows(), H_xj.cols()) = H_xj;
r.segment(stack_cntr, r_j.rows()) = r_j;
stack_cntr += H_xj.rows();
}
for (const auto& cam_id : involved_cam_state_ids)
feature.observations.erase(cam_id);
}
H_x.conservativeResize(stack_cntr, H_x.cols());
r.conservativeResize(stack_cntr);
// 执行测量更新。
measurementUpdate(H_x, r);
for (const auto& cam_id : rm_cam_state_ids) {
int cam_sequence = std::distance(state_server.cam_states.begin(),
state_server.cam_states.find(cam_id));
int cam_state_start = 21 + 6*cam_sequence;
int cam_state_end = cam_state_start + 6;
// Remove the corresponding rows and columns in the state covariance matrix.
// 删除状态协方差矩阵中对应的行和列。
if (cam_state_end < state_server.state_cov.rows()) {
state_server.state_cov.block(cam_state_start, 0,
state_server.state_cov.rows()-cam_state_end,
state_server.state_cov.cols()) =
state_server.state_cov.block(cam_state_end, 0,
state_server.state_cov.rows()-cam_state_end,
state_server.state_cov.cols());
state_server.state_cov.block(0, cam_state_start,
state_server.state_cov.rows(),
state_server.state_cov.cols()-cam_state_end) =
state_server.state_cov.block(0, cam_state_end,
state_server.state_cov.rows(),
state_server.state_cov.cols()-cam_state_end);
state_server.state_cov.conservativeResize(
state_server.state_cov.rows()-6, state_server.state_cov.cols()-6);
} else {
state_server.state_cov.conservativeResize(
state_server.state_cov.rows()-6, state_server.state_cov.cols()-6);
}
// Remove this camera state in the state vector.
// 在状态向量中移除这个摄像机状态。
state_server.cam_states.erase(cam_id);
}
return;
}
void MsckfVio::onlineReset() {
// Never perform online reset if position std threshold is non-positive.
// 如果位置std阈值是非正的,不要执行在线重置。
static long long int online_reset_counter = 0;
// Check the uncertainty of positions to determine if the system can be reset.
// 检查位置的不确定度,确定系统是否可以复位。
double position_x_std = std::sqrt(state_server.state_cov(12, 12));
double position_y_std = std::sqrt(state_server.state_cov(13, 13));
double position_z_std = std::sqrt(state_server.state_cov(14, 14));
/* if (position_x_std < position_std_threshold &&
position_y_std < position_std_threshold &&
position_z_std < position_std_threshold) return;
*/
// Remove all existing camera states. 删除所有现有的相机状态。
state_server.cam_states.clear();
// Clear all exsiting features in the map.
map_server.clear();
// Reset the state covariance.
double gyro_bias_cov, acc_bias_cov, velocity_cov;
velocity_cov=0.25;
gyro_bias_cov= 1e-4;
acc_bias_cov=1e-2;
double extrinsic_rotation_cov, extrinsic_translation_cov;
extrinsic_rotation_cov=3.0462e-4;
extrinsic_translation_cov= 1e-4;
state_server.state_cov = MatrixXd::Zero(21, 21);
for (int i = 3; i < 6; ++i)
state_server.state_cov(i, i) = gyro_bias_cov;
for (int i = 6; i < 9; ++i)
state_server.state_cov(i, i) = velocity_cov;
for (int i = 9; i < 12; ++i)
state_server.state_cov(i, i) = acc_bias_cov;
for (int i = 15; i < 18; ++i)
state_server.state_cov(i, i) = extrinsic_rotation_cov;
for (int i = 18; i < 21; ++i)
state_server.state_cov(i, i) = extrinsic_translation_cov;
std::cout<<"online reset"<<std::endl;
return;
}
void MsckfVio::publish(const double& time) {
const IMUState& imu_state = state_server.imu_state;
Eigen::Isometry3d T_i_w = Eigen::Isometry3d::Identity();
T_i_w.linear() = quaternionToRotation(
imu_state.orientation).transpose();
T_i_w.translation() = imu_state.position;
std::ofstream foutC(MSCKF_RESULT_PATH, std::ios::app);
foutC.setf(ios::fixed, ios::floatfield);
foutC.precision(6);
foutC << time << " ";
foutC.precision(5);
foutC << imu_state.position.x() << " "
<< imu_state.position.y() << " "
<< imu_state.position.z() << " "
<< Quaterniond(quaternionToRotation(imu_state.orientation).transpose()).x() << " "
<< Quaterniond(quaternionToRotation(imu_state.orientation).transpose()).y() << " "
<< Quaterniond(quaternionToRotation(imu_state.orientation).transpose()).z() << " "
<< Quaterniond(quaternionToRotation(imu_state.orientation).transpose()).w() //<< " "
//<< estimator.Vs[WINDOW_SIZE].x() << ","
//<< estimator.Vs[WINDOW_SIZE].y() << ","
//<< estimator.Vs[WINDOW_SIZE].z() << ","
<< endl;
foutC.close();
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(6);
std::cout<<"time="<<time<<" translation="<<imu_state.position.x() << " "
<< imu_state.position.y() << " "
<< imu_state.position.z() << " "
<<" rotation="
<< Quaterniond(quaternionToRotation(imu_state.orientation).transpose()).x() << " "
<< Quaterniond(quaternionToRotation(imu_state.orientation).transpose()).y() << " "
<< Quaterniond(quaternionToRotation(imu_state.orientation).transpose()).z() << " "
<< Quaterniond(quaternionToRotation(imu_state.orientation).transpose()).w()<<std::endl;
return;
}
} // namespace msckf_vio
<file_sep>/include/msckf_vio/random_numbers.h
#ifndef RANDOM_NUMBERS_RANDOM_NUMBERS_
#define RANDOM_NUMBERS_RANDOM_NUMBERS_
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/normal_distribution.hpp>
namespace random_numbers
{
/** \brief Random number generation (wrapper for boost). An instance of this class
cannot be used by multiple threads at once (member functions
are not const). However, the constructor is thread safe and
different instances can be used safely in any number of
threads. It is also guaranteed that all created instances will
have a "random" random seed. */
class RandomNumberGenerator
{
public:
/** \brief Constructor. Always sets a "random" random seed */
RandomNumberGenerator(void);
/** \brief Constructor. Allow a seed to be specified for deterministic behaviour */
RandomNumberGenerator(boost::uint32_t seed);
/** \brief Generate a random real between 0 and 1 */
double uniform01(void)
{
return uni_();
}
/**
* @brief Generate a random real within given bounds: [\e lower_bound, \e upper_bound)
* @param lower_bound The lower bound
* @param upper_bound The upper bound
*/
double uniformReal(double lower_bound, double upper_bound)
{
return (upper_bound - lower_bound) * uni_() + lower_bound;
}
/** \brief Generate a random real using a normal distribution with mean 0 and variance 1 */
double gaussian01(void)
{
return normal_();
}
/** \brief Generate a random real using a normal distribution with given mean and variance */
double gaussian(double mean, double stddev)
{
return normal_() * stddev + mean;
}
/** \brief Uniform random unit quaternion sampling. The computed value has the order (x,y,z,w)
* @param value[4] A four dimensional array in which the computed quaternion will be returned
*/
void quaternion(double value[4]);
/** \brief Generate an integer uniformly at random within a specified range (inclusive) */
int uniformInteger(int min, int max)
{
boost::uniform_int<> dis(min, max);
return dis(generator_);
}
/**
* \brief Allow the randomly generated seed to be saved so that experiments / benchmarks can be recreated in the future
*/
boost::uint32_t getFirstSeed();
private:
boost::mt19937 generator_;
boost::uniform_real<> uniDist_;
boost::normal_distribution<> normalDist_;
boost::variate_generator<boost::mt19937&, boost::uniform_real<> > uni_;
boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > normal_;
};
}
#endif
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(MSCKF_NOROS)
set(CMAKE_BUILD_TYPE "Release")
add_compile_options(-std=c++11)
find_package(Boost REQUIRED COMPONENTS math_c99 random)
find_package(Eigen3 REQUIRED)
find_package(OpenCV 3 REQUIRED)
include_directories(
include
${PROJECT_SOURCE_DIR}/include/msckf_vio
${EIGEN3_INCLUDE_DIR}
${Boost_INCLUDE_DIRS}
${OpenCV_INCLUDE_DIRS}
)
# Msckf Vio
add_library(${PROJECT_NAME} SHARED
src/msckf_vio.cpp
src/utils.cpp
src/image_processor.cpp
src/random_numbers.cpp
)
target_link_libraries(${PROJECT_NAME}
${OpenCV_LIBRARIES}
${Boost_LIBRARIES}
)
add_executable(msckf_noros src/main.cpp)
target_link_libraries(msckf_noros ${PROJECT_NAME} /usr/lib/x86_64-linux-gnu/libpthread.so )
<file_sep>/src/utils.cpp
#include <msckf_vio/utils.h>
#include <vector>
namespace msckf_vio {
namespace utils {
} // namespace utils
} // namespace msckf_vio
<file_sep>/include/msckf_vio/utils.h
#ifndef MSCKF_VIO_UTILS_H
#define MSCKF_VIO_UTILS_H
#include <string>
#include <opencv2/core/core.hpp>
#include <Eigen/Geometry>
#include <ctime>
#include <cstdlib>
#include <chrono>
namespace msckf_vio {
/*
* @brief utilities for msckf_vio
*/
class TicToc
{
public:
TicToc()
{
tic();
}
void tic()
{
start = std::chrono::system_clock::now();
}
double toc()
{
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
return elapsed_seconds.count() * 1000;
}
private:
std::chrono::time_point<std::chrono::system_clock> start, end;
};
}
#endif
|
cd880f7a5a3deb22a7a865179cb4d96e31b7037e
|
[
"CMake",
"Markdown",
"Makefile",
"Python",
"C++"
] | 10 |
Makefile
|
bryantaoli/MSCKF-NOROS
|
8c6399fb06e6272b8da69ae1c259dfecd67ff63e
|
14b4aa9ea1a45ac61a71ce3436c6d5edd7e385c2
|
refs/heads/master
|
<file_sep>d3.fbo = function() {
var fbo = {},
nodeHeight = 24,
nodePadding = 8,
size = [1, 1],
real_size = [1, 1],
nodes = [],
links = [],
groups = [];
fbo.nodeHeight = function(_) {
if (!arguments.length) return nodeHeight;
nodeHeight = +_;
return fbo;
};
fbo.nodePadding = function(_) {
if (!arguments.length) return nodePadding;
nodePadding = +_;
return fbo;
};
fbo.nodes = function(_) {
if (!arguments.length) return nodes;
nodes = _;
return fbo;
};
fbo.links = function(_) {
if (!arguments.length) return links;
links = _;
return fbo;
};
fbo.groups = function(_) {
if (!arguments.length) return groups;
groups = _;
return fbo;
};
fbo.size = function(_) {
if (!arguments.length) return real_size;
real_size = _;
size[0] = real_size[0] - nodePadding;
size[1] = real_size[1] - nodePadding;
return fbo;
};
fbo.layout = function(iterations) {
computeNodeLinks();
computeNodeValues();
computeNodeBreadths();
computeNodeDepths(iterations);
computeLinkDepths();
return fbo;
};
fbo.relayout = function() {
computeLinkDepths();
return fbo;
};
fbo.link = function() {
var curvature = .5;
function link(d) {
var y0 = d.source.y + d.source.dy,
y1 = d.target.y,
yi = d3.interpolateNumber(y0, y1),
y2 = yi(curvature),
y3 = yi(1 - curvature),
x0 = d.source.x + d.sx + d.source.dx / 2,
x1 = d.target.x + d.tx + d.target.dx / 2;
return "M" + x0 + "," + y0
+ "C" + x0 + "," + y2
+ " " + x1 + "," + y3
+ " " + x1 + "," + y1;
}
link.curvature = function(_) {
if (!arguments.length) return curvature;
curvature = +_;
return link;
};
return link;
};
// Populate the sourceLinks and targetLinks for each node.
// Also, if the source and target are not objects, assume they are indices.
function computeNodeLinks() {
nodes.forEach(function(node) {
node.sourceLinks = [];
node.targetLinks = [];
});
links.forEach(function(link) {
var source = link.source,
target = link.target;
if (typeof source === "number") source = link.source = nodes[link.source];
if (typeof target === "number") target = link.target = nodes[link.target];
source.sourceLinks.push(link);
target.targetLinks.push(link);
});
}
// Compute the value (size) of each node by summing the associated links.
function computeNodeValues() {
nodes.forEach(function(node) {
node.value = node.columns;
//console.log("Node columns: " + node.columns);
});
links.forEach(function(link) {
link.value = link.source.columns;
});
}
// Iteratively assign the breadth (x-position) for each node.
// Nodes are assigned the maximum breadth of incoming neighbors plus one;
// nodes with no incoming links are assigned breadth zero, while
// nodes with no outgoing links are assigned the maximum breadth.
function computeNodeBreadths() {
get_group_order = function(arr, a_group){
arr.forEach(function(group){
if (group.name == a_group)
return group.order;
});
};
var group_map = d3.nest()
.key(function(d) { return d.name; })
.entries(groups);
var nodesByGroup = d3.nest()
.key(function(d) { return d.group; })
.sortKeys(function(a, b) {
return get_group_order(groups, b) < get_group_order(groups, a) ? -1 : get_group_order(groups, b) > get_group_order(groups, a) ? 1 : 0;
})
.entries(nodes);
var y = 0;
var last_group_y = 0;
nodesByGroup.forEach(function(pair) {
console.log("Node nodes2: " + pair.key);
var remainingNodes = pair.values,
nextNodes;
while (remainingNodes.length) {
nextNodes = [];
console.log("New iteration");
remainingNodes.forEach(function(node) {
node.y = y;
node.dy = nodeHeight;
console.log("Node name: " + node.name + ", group: " + node.group + ", y: " + node.y);
node.sourceLinks.forEach(function(link) {
if (link.target.group == pair.key){
nextNodes.push(link.target);
}
});
});
remainingNodes = nextNodes;
++y;
}
moveSinksRight(y, pair.key);
groups.forEach(function(group){
if (group.name == pair.key)
{
group.x = 0;
group.dx = width ;
group.y = last_group_y;
group.dy = y - last_group_y;
console.log("group name: " + group.name + ", group.x: " + group.x + ", group.dx: " + group.dx + ", group.y: " + group.y + ", group.dy: " + group.dy );
}
});
last_group_y = y;
});
scaleNodeBreadths((size[1] - nodeHeight) / (y - 1));
}
function moveSourcesRight() {
nodes.forEach(function(node) {
if (!node.targetLinks.length) {
node.y = d3.min(node.sourceLinks, function(d) { return d.target.y; }) - 1;
}
});
}
function moveSinksRight(y, phase) {
nodes
.filter(function(value, index, ar){
return (value.group == phase);
})
.forEach(function(node) {
if (!node.sourceLinks.length) {
node.y = y - 1;
}
});
}
function scaleNodeBreadths(ky) {
nodes.forEach(function(node) {
node.y *= ky;
node.y += nodePadding/2;
});
groups.forEach(function(group) {
group.y *= ky;
group.dy *= ky;
console.log("Group name: " + group.name + ", x: " + group.x + ", y: " + group.y + ", dx: " + group.dx + ", dy: " + group.dy);
});
}
function computeNodeDepths(iterations) {
var nodesByBreadth = d3.nest()
.key(function(d) { return d.y; })
.sortKeys(d3.ascending)
.entries(nodes)
.map(function(d) { return d.values; });
//
initializeNodeDepth();
resolveCollisions();
for (var alpha = 1; iterations > 0; --iterations) {
relaxRightToLeft(alpha *= .99);
resolveCollisions();
relaxLeftToRight(alpha);
resolveCollisions();
}
function initializeNodeDepth() {
var kx = d3.min(nodesByBreadth, function(nodes) {
return (size[0] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
});
nodesByBreadth.forEach(function(nodes) {
nodes.forEach(function(node, i) {
node.x = i;
node.dx = node.value * kx;
});
});
links.forEach(function(link) {
link.dx = link.value * kx;
});
}
function relaxLeftToRight(alpha) {
nodesByBreadth.forEach(function(nodes, breadth) {
nodes.forEach(function(node) {
if (node.targetLinks.length) {
var x = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
node.x += (x - center(node)) * alpha;
}
});
});
function weightedSource(link) {
return center(link.source) * link.value;
}
}
function relaxRightToLeft(alpha) {
nodesByBreadth.slice().reverse().forEach(function(nodes) {
nodes.forEach(function(node) {
if (node.sourceLinks.length) {
var x = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
node.x += (x - center(node)) * alpha;
}
});
});
function weightedTarget(link) {
return center(link.target) * link.value;
}
}
function resolveCollisions() {
nodesByBreadth.forEach(function(nodes) {
var node,
dx,
x0 = 0,
n = nodes.length,
i;
// Push any overlapping nodes down.
nodes.sort(ascendingDepth);
for (i = 0; i < n; ++i) {
node = nodes[i];
dx = x0 - node.x;
if (dx > 0) node.x += dx;
x0 = node.x + node.dx + nodePadding;
}
// If the bottommost node goes outside the bounds, push it back up.
dx = x0 - nodePadding - size[0];
if (dx > 0) {
x0 = node.x -= dx;
// Push any overlapping nodes back up.
for (i = n - 2; i >= 0; --i) {
node = nodes[i];
dx = node.x + node.dx + nodePadding - x0;
if (dx > 0) node.x -= dx;
x0 = node.x;
}
}
});
}
function ascendingDepth(a, b) {
return a.x - b.x;
}
}
function computeLinkDepths() {
nodes.forEach(function(node) {
node.sourceLinks.sort(ascendingTargetDepth);
node.targetLinks.sort(ascendingSourceDepth);
});
nodes.forEach(function(node) {
var sx = 0, tx = 0;
node.sourceLinks.forEach(function(link) {
link.sx = sx;
//sy += link.dy;
});
node.targetLinks.forEach(function(link) {
link.tx = tx;
//ty += link.dy;
});
});
function ascendingSourceDepth(a, b) {
return a.source.x - b.source.x;
}
function ascendingTargetDepth(a, b) {
return a.target.x - b.target.x;
}
}
function center(node) {
return node.x + node.dx / 2;
}
function value(link) {
return link.value;
}
return fbo;
};
|
ceb1a0548d775cd762ff7e94b13efe382c471799
|
[
"JavaScript"
] | 1 |
JavaScript
|
bourgeof/LrDoc
|
7212167d4e89f6319fe985a3762142d788862d60
|
a56860bafecf1a3c8dd6b912757dd0ded6a0f48f
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <math.h>
#include <iostream>
#include <chrono>
#include <cstdlib>
#include <unistd.h>
#include "TNT/tnt.h"
#include "JAMA/jama_eig.h"
#include "Eigen/Eigenvalues"
#include "../Eigen/Eigen/Dense"
typedef Eigen::Matrix<float, 10, 10, Eigen::RowMajor> MagCalM10x10;
typedef Eigen::Matrix<float, 6, 4, Eigen::RowMajor> MagCalM6x4;
typedef Eigen::Matrix<float, 4, 4, Eigen::RowMajor> MagCalM4x4;
typedef Eigen::Matrix<float, 4, 6, Eigen::RowMajor> MagCalM4x6;
typedef Eigen::Matrix<float, 3, 3, Eigen::RowMajor> MagCalM3x3;
typedef Eigen::VectorXcf MagCalVc;
typedef Eigen::Vector3f MagCalV3;
typedef Eigen::Matrix<float, 6, 6, Eigen::RowMajor> MagCalM6x6;
typedef Eigen::VectorXf MagCalV;
typedef Eigen::ArrayXf MagCalA;
typedef Eigen::MatrixXf MagCalM;
typedef Eigen::MatrixXcf MagCalMc;
MagCalM6x6 AE;
MagCalMc VE(6, 6);
MagCalA lambda6E(6);
Eigen::EigenSolver<MagCalM> ES;
typedef float f_t;
namespace TNT
{
Array1D<f_t> get_col(int col, Array2D<f_t>& array)
{
int size = array.dim1();
Array1D<f_t> out(size);
for (int i = 0; i < size; i++)
{
out[i] = array[i][col];
}
return out;
}
float get_max_coeff(int* index, Array1D<f_t>& array)
{
*index = 0;
double max_e_value = array[0];
for (int i = 1; i < array.dim1(); i++)
{
if (array[i] > max_e_value)
{
*index = i;
max_e_value = array[i];
}
}
return max_e_value;
}
void conv_to_c_arr(f_t* c_arr, const Array1D<f_t>& tnt_arr, int len)
{
int i = 0;
while (i < len)
{
*(c_arr+i) = tnt_arr[i++];
}
}
void conv_to_2DTNT(const f_t* c_arr, Array2D<f_t>& tnt_arr, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
tnt_arr[i][j] = c_arr[i*rows + j];
}
}
}
void find_largest_eigen_vector(float* S11, float *v, float* max_eval)
{
Array1D<f_t> evalues(6);
Array2D<f_t> evectors(6, 6);
Array2D<f_t> mat(6, 6);
conv_to_2DTNT(S11, mat, 6, 6);
JAMA::Eigenvalue<f_t> es_tnt(mat);
es_tnt.getRealEigenvalues(evalues);
es_tnt.getV(evectors);
int ii;
get_max_coeff(&ii, evalues);
*max_eval = evalues[ii];
Array1D<f_t> max_tnt_evec = get_col(ii, evectors);
conv_to_c_arr(v, max_tnt_evec, 6);
}
}
int compare_eigen_TNT_largest_eigenvalue_calc()
{
float S11[36];
float v_eigen[6];
float v_TNT[6];
// Initialize Matrix
std::cout << "[";
for (int i = 0; i < 6; i++)
{
std::cout << "\n [";
for (int j = 0; j < 6; j++)
{
// S11[i+6*j] = (double)(rand())/double(RAND_MAX)*2.-1.; // this one almost always gives bogus results
// S11[i+6*j] = (double)(rand())/double(RAND_MAX); // this one sometimes flips the e-vector
S11[i+6*j] = (double)(rand())/double(RAND_MAX)-0.5; // This one sometimes gives bogus results
if (i == j)
S11[i+6*j] += 10.;
std::cout << S11[i+6*j] << ", ";
}
std::cout << "],";
}
std::cout << "\n]" << std::endl;
// Eigen Code
AE = Eigen::Map<MagCalM6x6>(S11, 6, 6);
ES.compute(AE);
lambda6E = ES.eigenvalues().real();
VE = ES.eigenvectors();
int ii;
lambda6E.maxCoeff(&ii);
float e_max_eval = lambda6E[ii];
MagCalV::Map(v_eigen, 6) = VE.col(ii).real();
// TNT Version
float TNT_max_eval;
TNT::find_largest_eigen_vector(S11, v_TNT, &TNT_max_eval);
// Check equivalence
std::cout << "eigen\tTNT\n";
bool success = true;
float v_TNT_flipped[6];
for (int i = 0; i < 6; i++)
{
v_TNT_flipped[i] = v_TNT[i] * -1.0;
}
for (int i = 0; i < 6; i++)
{
std::cout << v_eigen[i] << "\t" << v_TNT[i] << "\n";
if (std::fabs(v_eigen[i] - v_TNT[i]) > 1e-4
&& std::fabs(v_eigen[i] - v_TNT_flipped[i]) > 1e-4 )
{
success = false;
}
}
std::cout << std::endl;
if (!success)
std::cout << "FAILED\n\n";
else
std::cout << "PASSED\n\n";
}
int main()
{
for (int i = 0; i < 10; i++)
{
compare_eigen_TNT_largest_eigenvalue_calc();
}
}
<file_sep>cmake_minimum_required(VERSION 2.8.3)
project(matrix_math_comparison)
set (CMAKE_CXX_STANDARD 11)
#find_package(GSL)
include_directories(include
lib/Eigen
lib/TNT
lib/TNT/TNT
lib/TNT/JAMA
lib/GSL
)
#add_executable(matrix_test
#src/main.cpp
#)
add_executable(eigen_decomp
src/eigen_decomp.cpp
)
#target_link_libraries(matrix_test gsl gslcblas)
<file_sep>#!/usr/env/python
import matplotlib.pyplot as plt
import csv
def plot_results(filename):
size = []
TNT = []
GSL = []
Eigen = []
csvfile = open(filename, 'rb')
reader = csv.reader(csvfile, delimiter
=',')
for i, row in enumerate(reader):
if i == 0:
continue
size.append(float(row[0]))
Eigen.append(float(row[1]))
TNT.append(float(row[2]))
GSL.append(float(row[3]))
plt.figure(1)
plt.title("Asymmetric Eigenvalue Decomposition")
ax = plt.subplot(111)
plt.plot(size, TNT, label="TNT")
plt.plot(size, GSL, label="GSL")
plt.plot(size, Eigen, label="Eigen")
plt.legend()
ax.set_yscale("log")
plt.ylabel('$\mu$s')
plt.xlabel('matrix size')
plt.figure(2)
plt.title("Asymmetric Eigenvalue Decomposition (Small matrices)")
ax = plt.subplot(111)
plt.plot(size[:25], TNT[:25], label="TNT")
plt.plot(size[:25], GSL[:25], label="GSL")
plt.plot(size[:25], Eigen[:25], label="Eigen")
plt.legend()
ax.set_yscale("log")
plt.ylabel('$\mu$s')
plt.xlabel('matrix size')
plt.show()
if __name__ == '__main__':
plot_results('../build/csv_symm_results.csv')
plot_results('../build/csv_asymm_results.csv')
<file_sep>#include <stdio.h>
#include <chrono>
#include <cstdlib>
#include "TNT/tnt.h"
#include "JAMA/jama_eig.h"
#include "Eigen/Eigenvalues"
#include "gsl/gsl_eigen.h"
#include "gsl/gsl_math.h"
double run_TNT_symm(int size, double alpha)
{
TNT::Array2D<double> pei(size, size, (double)1.0);
TNT::Array2D<double> id(size, size, (double)0);
for (int i = 0; i < size; i++)
id[i][i] = 1.;
pei += id;
TNT::Array2D<double> evalues(size, size);
TNT::Array2D<double> evectors(size, size);
double avg_sum = 0.0;
for (int i = 0; i < 25; i++)
{
auto start = std::chrono::steady_clock::now();
JAMA::Eigenvalue<double> es(pei);
es.getD(evalues);
es.getV(evectors);
avg_sum += std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
}
return avg_sum/25.0;
}
double run_Eigen_symm(int size, double alpha)
{
Eigen::MatrixXd eigen_pei(size, size);
eigen_pei.setOnes();
eigen_pei += Eigen::MatrixXd::Identity(size, size);
Eigen::EigenSolver<Eigen::MatrixXd> es;
double avg_sum = 0.0;
for (int j = 0; j < 25; j++)
{
auto start = std::chrono::steady_clock::now();
es.compute(eigen_pei, true);
Eigen::MatrixXcd evectors = es.eigenvectors();
Eigen::MatrixXcd evalues = es.eigenvalues();
avg_sum += std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
}
return avg_sum/25.0;
}
double run_GSL_symm(int size, double alpha)
{
double data[size*size];
for (int i = 0; i < size*size; i++)
{
data[i] = 1.0;
}
for (int i = 0; i < size; i++)
{
data[i + i*size] += alpha;
}
double avg_sum = 0.0;
gsl_matrix_view gsl_pei = gsl_matrix_view_array(data, size, size);
gsl_vector *eval = gsl_vector_alloc(size);
gsl_matrix *evec = gsl_matrix_alloc(size, size);
gsl_eigen_symmv_workspace *wspace = gsl_eigen_symmv_alloc(size);
for (int j = 0; j < 25; j++)
{
auto start = std::chrono::steady_clock::now();
gsl_eigen_symmv (&gsl_pei.matrix, eval, evec, wspace);
avg_sum += std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
}
gsl_eigen_symmv_free (wspace);
return avg_sum/25.0;
}
double run_TNT_asymm(int size)
{
TNT::Array2D<double> evalues(size, size);
TNT::Array2D<double> evectors(size, size);
double avg_sum = 0.0;
for (int i = 0; i < 25; i++)
{
TNT::Array2D<double> pei(size, size);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
pei[i][j] = (double)(rand())/double(RAND_MAX);
}
}
TNT::Array2D<double> id(size, size, (double)0);
for (int i = 0; i < size; i++)
id[i][i] = 1.;
pei += id;
auto start = std::chrono::steady_clock::now();
JAMA::Eigenvalue<double> es(pei);
es.getD(evalues);
es.getV(evectors);
avg_sum += std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
}
return avg_sum/25.0;
}
double run_Eigen_asymm(int size)
{
Eigen::EigenSolver<Eigen::MatrixXd> es;
double avg_sum = 0.0;
for (int j = 0; j < 25; j++)
{
Eigen::MatrixXd mat(size, size);
mat.setRandom();
mat += Eigen::MatrixXd::Identity(size, size);
auto start = std::chrono::steady_clock::now();
es.compute(mat, true);
volatile Eigen::MatrixXcd evectors = es.eigenvectors();
volatile Eigen::MatrixXcd evalues = es.eigenvalues();
avg_sum += std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
}
return avg_sum/25.0;
}
double run_GSL_asymm(int size)
{
double data[size*size];
double avg_sum = 0.0;
gsl_vector_complex *eval = gsl_vector_complex_alloc(size);
gsl_matrix_complex *evec = gsl_matrix_complex_alloc(size, size);
gsl_eigen_nonsymmv_workspace *wspace = gsl_eigen_nonsymmv_alloc(size);
for (int j = 0; j < 25; j++)
{
for (int i = 0; i < size*size; i++)
{
data[i] = (double)(rand()/(double)(RAND_MAX));
}
for (int i = 0; i < size; i++)
{
data[i + i*size] += 1.0;
}
gsl_matrix_view gsl_pei = gsl_matrix_view_array(data, size, size);
auto start = std::chrono::steady_clock::now();
gsl_eigen_nonsymmv (&gsl_pei.matrix, eval, evec, wspace);
avg_sum += std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start).count();
}
gsl_eigen_nonsymmv_free (wspace);
return avg_sum/25.0;
}
int main()
{
FILE *symm_fp = fopen("csv_symm_results.csv", "w");
printf("size,\tEigen,\tTNT\n");
fprintf(symm_fp, "size,\tEigen,\tTNT\n");
for (int size = 5; size < 200; size += 1)
{
double tnt_time = run_TNT_symm(size, 0.4);
double eigen_time = run_Eigen_symm(size, 0.4);
double gsl_time = run_GSL_symm(size, 0.4);
printf("%*d,%*.2f,%*.2f,%*.2f\n",7, size, 12, eigen_time, 12, tnt_time, 12, gsl_time);
fprintf(symm_fp, "%*d,%*.2f,%*.2f,%*.2f\n",7, size, 12, eigen_time, 12, tnt_time, 12, gsl_time);
}
fclose(symm_fp);
FILE* asymm_fp = fopen("csv_asymm_results.csv", "w");
printf("size,\tEigen,\tTNT\n");
fprintf(asymm_fp, "size,\tEigen,\tTNT\n");
for (int size = 5; size < 200; size += 1)
{
double tnt_time = run_TNT_asymm(size);
double eigen_time = run_Eigen_asymm(size);
double gsl_time = run_GSL_asymm(size);
printf("%*d,%*.2f,%*.2f,%*.2f\n",7, size, 12, eigen_time, 12, tnt_time, 12, gsl_time);
fprintf(asymm_fp, "%*d,%*.2f,%*.2f,%*.2f\n",7, size, 12, eigen_time, 12, tnt_time, 12, gsl_time);
}
fclose(asymm_fp);
}
<file_sep># Matrix Comparison Code
A short C++ program to compare the performance of GSL, TNT and Eigen, and a python script to plot it.
## Installation
TNT and Eigen are header-only, so no installation is required. GSL, on the other hand, is not, and therefore requires installation. I'm using the [AMPL CMake-enabled version](https://github.com/ampl/gsl/tree/644e768630841bd085cb7121085a688c4ff424d0) of GSL, which is included as a submodule.
To install, perform the following operations
```bash
git clone https://github.com/superjax/matrix_comparison.git
cd matrix_comparison
git submodule update --init --recursive
cd lib/GSL
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j4 -l4
sudo make install
```
To run the examples
```bash
cd matrix_comparison
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j4 -l4
./matrix_test
```
To plot the comparison
``` bash
cd python
python plot_results.py
```
|
46c8130fa61ed8536bec95084c8c31ae96d8d636
|
[
"Markdown",
"Python",
"CMake",
"C++"
] | 5 |
C++
|
superjax/matrix_comparison
|
0bd9ed7982b92a4c74eb400fd25a49a915a8d436
|
935949ce4ed3f2e96aab6c8a7a921d2cbc0c2049
|
refs/heads/master
|
<repo_name>dooman87/go-intro<file_sep>/interfaces.go
package intro
type Greeter interface {
Greet() string
}
type MachoMan struct {
Age int
}
func (mr *MachoMan) Greet() string {
return "Aloha!"
}
<file_sep>/README.md
# Introduction to Go
This repo contains a demo that I prepared for my talk on GDG Melbourne:
https://plus.google.com/events/cahdv4rtr3gbunmbjobtarbsvb0
# Installation
```
$ go get github.com/dooman87/go-intro
```
# Running in Docker
```
$ docker build -t go-intro .
$ docker run -it --rm -p 8080:8080 -v `pwd`:/go/src/github.com/dooman87/go-intro go-intro
```
# Description
All demos run from `cmd/main.go`.
Demos include:
```
* Package manager - showing go get
* Hello World & Compilation - main.go
* Static Types & Type Inference - types.go
* Slices - slices.go
* Maps - maps.go
* Structs - interfaces.go
* Interfaces - interfaces.go
* Closures - closures.go
* Go routines - goroutines.go
* Channels - channels.go
* Standard library - http.go
* Tools - show go-vet, go-test, go-lint, go-replace, ...
```<file_sep>/goroutines.go
package intro
import (
"fmt"
"time"
)
func Go(num int, howFast time.Duration) {
for i:=0; i < 5; i++ {
fmt.Printf("Number %d\n", num)
time.Sleep(howFast * time.Millisecond)
}
fmt.Printf("Number %d FINISH!\n", num)
}
<file_sep>/channels.go
package intro
import (
"fmt"
"math/rand"
"time"
)
func Casino(ch chan int) {
var casino, gambler int
for {
casino = rand.Intn(6)
gambler = <- ch
if casino > gambler {
fmt.Printf("Casino won! (%d:%d)\n", casino, gambler)
} else if casino < gambler {
fmt.Printf("Gambler won! (%d:%d)\n", casino, gambler)
} else {
fmt.Printf("Draw (%d:%d)\n", casino, gambler)
}
}
}
func Gambler(ch chan int) {
var myScore int
for {
myScore = rand.Intn(6)
ch <- myScore
time.Sleep(1 * time.Second)
}
}<file_sep>/closures.go
package intro
func Sum(a func() int, b func() int) int {
return a() + b()
}
<file_sep>/slices.go
package intro
import "fmt"
func Slices() {
slice := make([]int, 0)
slice = append(slice, 9, 8, 7, 6, 5, 4, 3, 2, 1)
fmt.Printf("%v\n", slice[8])
fmt.Printf("%v\n", slice[3:5])
fmt.Printf("%v\n", slice[7:])
//Delete 2nd element
slice = append(slice[:1], slice[2:]...)
fmt.Printf("%v\n", slice)
fmt.Printf("len = %d, cap = %d\n", len(slice), cap(slice))
//fmt.Printf("%v\n", slice[100])
}
<file_sep>/types.go
package intro
var greeting string
func init() {
greeting = "Hello Go!\n---------\n"
}
func GetGreeting() string {
return greeting
}
func GetInferredGreeting() string {
newGreeting := "Well Well Well\n"
return newGreeting
}
<file_sep>/entrypoint.sh
#!/bin/bash
cd /go/src/github.com/dooman87/go-intro/cmd
go run main.go<file_sep>/maps.go
package intro
import "fmt"
func Maps() {
m := make(map[int]string, 0)
m[1] = "one"
m[2] = "two"
m[3] = "three"
fmt.Printf("%v\n", m)
for k, v := range m {
fmt.Printf("Key: %d, Value: %s\n", k, v)
}
delete(m, 2)
fmt.Printf("%v\n", m)
}
<file_sep>/http.go
package intro
import (
"net/http"
"html/template"
"log"
)
const (
page = `
<h1>
Hello
{{if .name}}
{{.name}}
{{else}}
Anonymous
{{end}}
</h1>
`
)
func RunServer() {
templ, err := template.New("hello").Parse(page)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/hello", func (w http.ResponseWriter, req *http.Request) {
templ.Execute(w, req.URL.Query())
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
<file_sep>/cmd/main.go
package main
import (
"fmt"
"github.com/dooman87/go-intro"
"time"
)
func main() {
fmt.Println("Hello world!\n")
//Types
fmt.Println(intro.GetGreeting())
fmt.Println(intro.GetInferredGreeting())
//Interfaces
fmt.Println(greetingFactory().Greet())
//Closures
n := 3
getNumber := func() int {
return n
}
n = 4
fmt.Printf("Sum: %d", intro.Sum(getNumber, getNumber))
//Collections
intro.Slices()
intro.Maps()
//Go routines
go intro.Go(1, 1000)
go intro.Go(2, 500)
time.Sleep(10 * time.Second)
//Channels
ch := make(chan int)
go intro.Casino(ch)
go intro.Gambler(ch)
time.Sleep(10 * time.Second)
//Standard library
intro.RunServer()
}
func greetingFactory() intro.Greeter {
return new(intro.MachoMan)
}
|
d0dd46a4a745468046b5b3244bf9f62c2291099b
|
[
"Markdown",
"Go",
"Shell"
] | 11 |
Go
|
dooman87/go-intro
|
6d61f98eb7646b9d24d15780bcbf741350fc2559
|
c8d3e1de1217fd334f78e32d5569f8047663ac1e
|
refs/heads/master
|
<repo_name>10XL/C-Test<file_sep>/c5/module2-solution/scripts/app.js
(function(){
'use strict';
angular.module('ShoppingListCheckOff', [])
.service('ShoppingListCheckOffService', function() {
var toBuy = [
{name:"orange", qty:4},
{name:"lemon", qty:2},
{name:"carrot", qty:3},
{name:"apple", qty:6},
{name:"banana", qty:6},
];
var alreadyBought = [];
this.getAvailableItems = function() {
return toBuy;
};
this.getBoughtItems = function() {
return alreadyBought;
};
this.buyItem = function(name) {
var i = toBuy.map(function(s) { return s.name; }).indexOf(name);
var item = toBuy.splice(i, 1);
this.addItem(item[0]);
};
this.addItem = function(item) {
alreadyBought.push(item);
};
})
.controller('ToBuyShoppingController', ['$scope', '$filter', 'ShoppingListCheckOffService',
function($scope, $filter, ShoppingListCheckOffService) {
var shoppingService = ShoppingListCheckOffService;
$scope.items = shoppingService.getAvailableItems();
$scope.buyRequest = function(name) {
console.log("buy_controller: name is:", name);
shoppingService.buyItem(name);
};
}])
.controller('AlreadyBoughtShoppingController', ['$scope', 'ShoppingListCheckOffService',
function($scope, ShoppingListCheckOffService) {
var shoppingService = ShoppingListCheckOffService;
$scope.boughtItems = shoppingService.getBoughtItems();
}])
;
})();<file_sep>/c5/module1-solution/scripts/app.js
(function(){
'use strict';
angular.module('LunchCheck', [])
.controller('LunchCheckController', ['$scope', function($scope) {
$scope.message = "";
$scope.lunchItems = "";
$scope.tooManyItems = function(items) {
// var arr = items.trim().split(' ').filter(function(s){s !== "";});
var arr = items.trim().split(' ').filter(s => s !== ""); // ES6 arrow syntax
if (arr.length === 0) {$scope.message = "Please enter data first."; return null;}
if (arr.length <= 3 && arr.length > 0) $scope.message = "Enjoy!";
if (arr.length > 3) $scope.message = "Too much!";
};
}])
;
})();<file_sep>/c5/module3-solution/scripts/app.js
(function() {
'use strict';
angular.module('NarrowItDownApp', [])
.controller('NarrowItDownController', NarrowItDownController)
.service('MenuSearchService', MenuSearchService)
.directive('foundItems', FoundItemsDirective)
.constant('baseUrl', 'https://davids-restaurant.herokuapp.com/');
NarrowItDownController.inject = ['MenuSearchService'];
function NarrowItDownController(MenuSearchService) {
var nid = this;
var menuSvc = MenuSearchService;
nid.found = [];
nid.search = '';
nid.showError = false;
nid.getItems = function(search) {
if (search === '') return (nid.showError = true);
menuSvc.getMatchedMenuItems()
.then(items => nid.found = menuSvc.filterItems(search, items))
.then(items => items.length === 0 ? nid.showError = true : nid.showError = false)
};
nid.removeItem = function(id) {
nid.found.splice(id, 1);
};
}
MenuSearchService.inject = ['$http', 'baseUrl'];
function MenuSearchService($http, baseUrl) {
var menuSvc = this;
menuSvc.filterItems = function(searchTerm, array) {
return array.filter(s => s.description.toLowerCase().includes(searchTerm));
};
menuSvc.getMatchedMenuItems = function(searchTerm) {
return $http({
url: (baseUrl + "/menu_items.json")
}).then(res => res.data.menu_items);
};
}
function FoundItemsDirective() {
var ddo = {
templateUrl: 'templates/foundItems.html',
scope: {
items: '<',
onRemove: '&',
},
controller: NarrowItDownController,
controllerAs: 'list',
bindToController: true,
};
return ddo;
}
})();<file_sep>/c5/module4-solution/src/routes.js
(function() {
'use strict';
angular.module('MenuApp')
.config(RoutesConfig);
RoutesConfig.$inject = ['$stateProvider', '$urlRouterProvider', '$locationProvider'];
function RoutesConfig($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$stateProvider
.state('home', {
url: '/',
templateUrl: 'src/templates/home.html'
})
.state('categories', {
url: '/categories',
templateUrl: 'src/templates/categories.html',
controller: 'CategoryListController as categoryCtrl',
resolve: {
items: ['MenuDataService', function(MenuDataService) {
return MenuDataService.getAllCategories();
}]
}
})
.state('items', {
url: '/items/{shortName}',
templateUrl: 'src/templates/items.html',
controller: 'ItemCategoryController as itemCategoryCtrl',
resolve: {
items: ['$stateParams', 'MenuDataService',
function($stateParams, MenuDataService) {
return MenuDataService.getItemsForCategory($stateParams.shortName);
}]
}
});
}
})();
|
56fbb48711eeacf9ac76b71a6d7701787df10df0
|
[
"JavaScript"
] | 4 |
JavaScript
|
10XL/C-Test
|
9748232916d49ff8dd716cb31890d3467ec5144b
|
7ce359ec6a348a13e53bfbb3409c234cbfd8b0e4
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqToSQL
{
public class DwieKolumny
{
public string Kolor;
public string Styl;
public DwieKolumny(string styl, string kolor)
{
Kolor = kolor;
Styl = styl;
}
}
class Program
{
static void Main(string[] args)
{
TSQLV4DataContext dc = new TSQLV4DataContext();
Console.WriteLine("Co chcesz wykonać?");
Console.WriteLine("1 : zwracanie danych z tabeli Product");
Console.WriteLine("2 : cena większa od 300");
Console.WriteLine("3 : Własny typ");
Console.WriteLine("4 : Anonimowy typ");
Console.WriteLine("5 : Dane z dwóch tabel");
Console.WriteLine("6 : Dane z dwóch polączonych tabel");
Console.WriteLine("7 : Dane z dwóch polączonych tabel (entityRef)");
Console.WriteLine("8 : Update");
Console.WriteLine("9 : INSERT");
Console.WriteLine("10 : DELETE");
int liczba = Convert.ToInt32(Console.ReadLine());
switch (liczba)
{
case 1:
daneZTabeli(dc);
break;
case 2:
daneZTabeliWhere(dc);
break;
case 3:
daneZTabeliDwieKolumntWłasnyTyp(dc);
break;
case 4:
daneZTabeliNieokreślonyTyp(dc);
break;
case 5:
przeszukiwanieDwochTabel(dc);
break;
case 6:
przeszukiwanieDwochPolaczonychTabel(dc);
break;
case 7:
entityRef(dc);
break;
case 8:
UPDATE(dc);
break;
case 9:
INSERT(dc);
break;
case 10:
DELETE(dc);
break;
default:
break;
}
}
static void daneZTabeli(TSQLV4DataContext dc)
{
var data = from p in dc.Product
select p;
var firstFive = data.Take(5);
foreach (var item in firstFive)
{
Console.WriteLine("Id: {0}, Numer: {1}, Nazwa: {2}", item.ProductID, item.ProductNumber, item.Name);
}
Console.ReadKey();
}
static void daneZTabeliWhere(TSQLV4DataContext dc)
{
var data = from p in dc.Product
where p.ListPrice > 300
select p;
foreach (var item in data)
{
Console.WriteLine("Id: {0}, Nazwa: {1}, Cena: {2}", item.ProductID, item.Name, item.ListPrice);
}
Console.ReadKey();
}
static void daneZTabeliDwieKolumntWłasnyTyp(TSQLV4DataContext dc)
{
var data = from p in dc.Product
where p.ListPrice > 250
select new DwieKolumny(p.Style, p.Color);
foreach(DwieKolumny item in data)
{
Console.WriteLine($"Styl: {item.Styl}, Kolor: {item.Kolor}");
}
Console.ReadKey();
}
static void daneZTabeliNieokreślonyTyp(TSQLV4DataContext dc)
{
var data = from p in dc.Product
where p.ListPrice > 500
select new { nazwa_produktu = p.Name, linia_produktu = p.ProductLine };
foreach (var item in data)
{
Console.WriteLine($"Nazwa produktu: {item.nazwa_produktu}, Linia produktu: {item.linia_produktu}");
}
Console.ReadKey();
}
static void przeszukiwanieDwochTabel(TSQLV4DataContext dc)
{
int ilosc = 0;
var data = from p in dc.Product
from pc in dc.ProductCategory
where p.ListPrice > 300 && pc.Name == "Clothing"
select new { nazwa_produktu = p.Name, nazwa_kategorii = pc.Name };
foreach (var item in data)
{
ilosc++;
Console.WriteLine($"Nazwa produktu: {item.nazwa_produktu}, Nazwa kategorii: {item.nazwa_kategorii} policz ilosc:{ilosc}");
}
Console.ReadKey();
}
static void przeszukiwanieDwochPolaczonychTabel(TSQLV4DataContext dc)
{
int ilosc = 0;
var data = from p in dc.Product
from psc in dc.ProductSubcategory
where p.ProductSubcategoryID == psc.ProductSubcategoryID
select new {p.ProductID, p.ProductSubcategoryID, psc.Name };
foreach (var item in data)
{
ilosc++;
Console.WriteLine("Id: {0}, Id Subkategorii: {1}, Nazwa: {2}, ilosc {3}", item.ProductID, item.ProductSubcategoryID, item.Name, ilosc);
}
Console.ReadKey();
}
static void entityRef (TSQLV4DataContext dc)
{
var data = from p in dc.Product
select new
{
SubcategoryName = p.ProductSubcategory.Name,
ProductName = p.Name,
ProducktId = p.ProductID
};
foreach(var item in data)
{
Console.WriteLine($"Nazwa produktu {item.ProductName}, Id produktu {item.ProducktId}, Nazwa podkategorii {item.SubcategoryName}");
}
Console.ReadKey();
}
static void UPDATE(TSQLV4DataContext dc)
{
var update = from p in dc.Product
where p.Name.Contains("Tube")
select p;
int i = 0;
foreach(var item in update)
{
item.Name = "Tuuube" + i.ToString();
i++;
}
dc.SubmitChanges();
var poUpdate = from p in dc.Product
where p.Name.Contains("Tuuube")
select p;
foreach(var item in poUpdate)
{
Console.WriteLine("Id: {0}, Nazwa: {1}", item.ProductID, item.Name);
}
Console.ReadKey();
}
static void INSERT(TSQLV4DataContext dc)
{
ProductCategory prod = new ProductCategory();
prod.Name = "Test";
prod.ModifiedDate = System.DateTime.Now;
dc.ProductCategory.InsertOnSubmit(prod);
dc.SubmitChanges();
var lastrow = (from p in dc.ProductCategory
orderby p.ProductCategoryID descending
select p).First();
Console.WriteLine("Id: {0}, Nazwa: {1}", lastrow.ProductCategoryID, lastrow.Name);
Console.ReadKey();
}
static void DELETE(TSQLV4DataContext dc)
{
var delete = from p in dc.ProductCategory
where p.Name.Contains("Test")
select p;
dc.ProductCategory.DeleteAllOnSubmit(delete);
dc.SubmitChanges();
var afterChanges = from p in dc.ProductCategory
select p;
foreach (var item in afterChanges)
{
Console.WriteLine("Id: {0}, Nazwa: {1}", item.ProductCategoryID, item.Name);
}
Console.ReadKey();
}
}
}
|
c5da5ebe2116ae136a9833c179c4c4dfdb5e7603
|
[
"C#"
] | 1 |
C#
|
Fenrirus/LinqToSQL
|
a19da439db4bc3b26423a40aeb9b2f24d0e88780
|
ebc26dd679b5ecc94afa82f9c3cbcbf51eb0b001
|
refs/heads/master
|
<repo_name>scopemedia/feedr<file_sep>/main.js
/**
* Project 2: Feedr
* ====
*
* See the README.md for instructions
*/
(function() {
var container = document.querySelector('#container')
var state = {loading: true}
// Loader State
function renderLoading(data, into) {
into.innerHTML = `
<div id="pop-up" class="loader">
</div>
`
}
// States
// - Leading state
// - Defatult state
// Call loader
renderLoading(state, container)
// console.log(state.loading);
// if (state.loading === true) {
// renderLoading(state, container)
// } else {
// // renderArticles(data, container)
// console.log('time to render');
// }
// Function takes in Reddit json and returns an object with values
function redditDataProcessor(dataAsJson) {
var i = -1
var articleData = dataAsJson.data.children.map((item) => {
i++;
return {
articleTitle: item.data.title,
articleDescription: item.title,
articleCategory: item.data.subreddit,
articleCount: item.data.ups,
articleLink: item.data.url,
articleImage: item.data.thumbnail,
dataID: i
}
})
return articleData
}
// Function takes in Mashable json and returns an object with values
function mashableDataProcessor(dataAsJson) {
var i = -1
var articleData = dataAsJson.hot.map((item) => {
i++;
return {
articleTitle: item.title,
articleDescription: item.content.plain ,
articleCategory: item.channel,
articleCount: item.shares.total,
articleLink: item.link,
articleImage: item.image,
dataID: i
}
})
return articleData
}
// Function takes in Mashable json and returns an object with values
function nytDataProcessor(dataAsJson) {
var i = -1
var articleData = dataAsJson.results.map((item) => {
i++;
return {
articleTitle: item.title,
articleDescription: item.abstract,
articleCategory: item.abstract,
articleCount: '',
articleLink: 'image',
articleImage: 'http://placehold.it/200x200',
dataID: i
}
})
return articleData
}
//function takes in json and returns
function loadRSS(url, dataProcessor) {
fetch(url).then((response) => {
renderLoading(state, container)
return response.json()
}).then((dataAsJson) => {
// update state
state = {loading: false}
// Render Article Template
var processedData = dataProcessor(dataAsJson)
// Create function to render Section around articles
// - Function takes 2 parameters
// 1 - The Processed Data from the feed (Which contains an object with the key value pairs)
// 2 - The location to render into
function renderArticleList(data, into) {
into.innerHTML = `
<section id="main" class="wrapper">
${data.map((item) => {
return `
<article class="article">
${renderArticle(item)}
<div class="clearfix"></div>
</article>
`
}).join('')}
</section>
`
// Create Function to render articles
// - Returns article content with processedDate values
function renderArticle(item) {
return `
<section class="featured-image">
<img src="${item.articleImage}" alt="" />
</section>
<section class="article-content">
<a href="#0" data-id="${item.dataID}"><h3>${item.articleTitle}</h3></a>
<h6>${item.articleCategory}</h6>
</section>
<section class="impressions">
${item.articleCount}
</section>
<div class="clearfix"></div>
`
}
// Add listener to the article link which pops up the article modal
// - Creates a variable for the link
// - Add the listener whcih calls the trigger on popup
var popupLink = document.querySelectorAll('.article-content a')
for (var i = 0; i < popupLink.length; i++) {
popupLink[i].addEventListener("click", popUpTrigger, false);
}
function popUpTrigger() {
var popupID = this.getAttribute('data-id')
popUp(processedData[popupID], articlepopup);
}
}
// Call function to render Article List
// - Function takes 2 parameters
// 1 - The Processed Data from the feed (Which contains an object with the key value pairs)
// 2 - The location to render into
renderArticleList(processedData, container);
// Create function to Render Popup
// - Takes in 2 parameters
// 1 - The article data - Needs to be the correct data
// 2 - Container in whcih to inject the html
function popUp(data, into) {
into.innerHTML = `
<div id="pop-up">
<a href="#" class="close-pop-up">X</a>
<div class="wrapper">
<h1>${data.articleTitle}</h1>
<p>
${data.articleDescription}
</p>
<a href="${data.articleLink}" class="pop-up-action" target="_blank">Read more from source</a>
</div>
</div>
`
// Create function to close popup modal
// - Create a variable for close icon
// - Add event listener to button
// - When button is clicked call the popUpClose function which clears the html
// content f
var popupCloseBtn = document.querySelector('.close-pop-up')
popupCloseBtn.addEventListener("click", popUpClose, false);
// Close Popup by injecting empty html into the articlepopup conatiner
function popUpClose() {
into.innerHTML = `
`
}
}
}).catch(function(err) {
console.log('Error', err);
alert('Error fetching the RSS feed. Please try again or choose one of the other feeds.')
});
};
// listener for click
// render state
// pop-up
var switcher = document.querySelectorAll('nav li ul li a');
switcherName = document.querySelector('nav ul li a span');
for (var i = 0; i < switcher.length; i++) {
// Function that checks text content of link and loads matching RSS feed
function clickMe() {
if (this.textContent === 'Reddit') {
updateName('Reddit')
loadRSS('https://www.reddit.com/top.json', redditDataProcessor)
} else if (this.textContent === 'Mashable') {
updateName('Mashable')
loadRSS('https://crossorigin.me/http://mashable.com/stories.json', mashableDataProcessor)
} else if (this.textContent === 'The New York Times') {
updateName('The New York Times')
loadRSS('https://api.nytimes.com/svc/topstories/v2/home.json?api-key=<KEY>', nytDataProcessor)
}
}
// Function to update Feed name in switcher
function updateName(name) {
switcherName.innerHTML = name;
}
// Listens for clicks on links and calls function to switch RSS feed
switcher[i].addEventListener("click", clickMe, false);
}
//
// Logo reset
// - On click of the logo load the default feed.
// Cache the logo variable
var logo = document.querySelector('h1');
// Listen for click on logo
logo.addEventListener("click", tester, false);
// Trigger function to reset feed
function tester() {
loadRSS('https://www.reddit.com/top.json', redditDataProcessor)
updateName('Reddit')
}
// Default state for Feedr
// - Calls the RSS function with a feed url
// - Updates the feed name in the selector
loadRSS('https://www.reddit.com/top.json', redditDataProcessor)
updateName('Reddit')
})()
|
51e133af7022f9c64be3651468ccf8cd0678afff
|
[
"JavaScript"
] | 1 |
JavaScript
|
scopemedia/feedr
|
e98285ab31d023e5ff064c752d2d244c2aab9eb2
|
6367005b8da07ba34ea61ea51abe3ba676365d82
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'PatchLion'
from flask import Flask, send_file
app = Flask(__name__, static_folder="static")
@app.route("/")
def index():
return "Bootstrap3 test"
@app.route("/<html>")
def html(html):
return send_file("templates/"+html)
|
70e8a3419dbf93de6fe57b9316ede837348a80fe
|
[
"Python"
] | 1 |
Python
|
PatchLion/bootstrap3_learn
|
b3860087dd0e1ebc1074f5ece88bb356d47f0182
|
3192c210474e5698942fe9c83a2bc86870f90a9f
|
refs/heads/master
|
<repo_name>dojo-react-workshop/heather_latham<file_sep>/coding_challenges/stock-gains.js
'use strict'
//APPLE
// Can't buy and sell in same time slots
//return best profit could have made from one purchase and one sale
//for this one, buy low at 5 and sell high at 11
// function maxProfit(arr) {
// var buyIndex = 0;
// var sellIndex = 1;
// var maxProfit = arr[sellIndex] - arr[buyIndex];
// for(let i=0; i<arr.length; i++) {
// for(let x=i+1; x<arr.length; x++) {
// if((arr[x]-arr[i]) > maxProfit) {
// buyIndex = i;
// sellIndex = x;
// maxProfit = arr[x]-arr[i];
// }
// }
// }
// return({buyIndex:buyIndex, sellIndex:sellIndex, maxProfit:maxProfit});
// }
// console.log(maxProfit(applePricesYesterday));
//use this one to only loop once (this is hte concept of the greedy solution, means
//keeping the best solution so far and throwing away the rest)
function maxProfit(arr) {
if(arr.length < 2){
throw new Error('Must provide at least 2 prices.');
}
let buy = arr[0];
let maxProfit = arr[1] - arr[0];
for(let i=1; i<arr.length; i++) {
if((arr[i]-buy) > maxProfit){
maxProfit = arr[i]-buy;
}
if(arr[i] < buy){
buy = arr[i];
}
}
return maxProfit;
}
var arr=[2,3,5,7,13,9]
const applePricesYesterday = [10,7,5,8,11,9]
var arr_2 = [1,-3]
console.log(maxProfit(arr))
console.log(maxProfit(arr_2))
console.log(maxProfit(applePricesYesterday))
<file_sep>/coding_challenges/binaryStringExpansion.js
function binaryStringExp(str, base='', results=[]){
if(str.length===0){
results.push(base);
}else{
if(str[0] ==='?'){
binaryStringExp(str.slice(1), base + '0', results)
binaryStringExp(str.slice(1), base + '1', results)
}else{
binaryStringExp(str.slice(1), base+str[0],results)
}
}
return results;
}
console.log(binaryStringExp('10?11?'))<file_sep>/node_and_apis/math_module/math.js
const myObj = {
add: function (a,b){
var ans = a+b;
return ans;
},
multiply: function (a,b){
var ans = a * b;
return ans;
},
square: function (a){
var ans = a * a;
return ans;
},
random: function (a,b){
var ans = Math.floor(Math.random()*(b-a+1))+a;
return ans;
}
};
module.exports = myObj;
<file_sep>/reactcode/memory_game/src/index.js
// import Underscore from 'underscore';
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
memoryArr: ['','','','','','','','','','','',''],
guessArr: ['','','','','','','','','','','',''],
board: 1,
counter: 3
};
}
startGameClick = () => {
this.setState({
memoryArr: ['','','','','','','','','','','',''],
guessArr: ['','','','','','','','','','','',''],
counter: 3,
board: 2
})
this.interval = setInterval(() => {
console.log(this.state.counter)
this.setState({
counter: this.state.counter-1
})
if (this.state.counter === 0){
clearInterval(this.interval)
this.setState({
memoryArr: ['Y','','Y','Y','','Y','','','','','',''],
board: 3
})
setTimeout(() => {
this.setState({
board: 4
})
}, 1000)
setTimeout(() => {
this.setState({
board: 5
})
}, 3000)
}}
, 3000)
}
render() {
const styleApp = {
width: '750px',
marginLeft: 'auto',
marginRight: 'auto'
}
return (
<div style={styleApp}>
<h1 style={{textAlign: 'center'}}>Memory Game</h1>
<GameBoard buildboard={this.state.board} memboard={this.state.memoryArr} personboard={this.state.guessArr}/>
<Footer startGameClick={this.startGameClick} board={this.state.board} counter={this.state.counter}/>
</div>
)
}
}
class GameBoard extends React.Component {
boardSquareClick = (value) => {
let tempSquaresArr = Object.assign(this.props.personboard)
tempSquaresArr[value] = 'Y'
this.setState({
guessArr: tempSquaresArr
})
}
render() {
const styleRow = {
display: 'block',
width: '610px',
marginLeft: 'auto',
marginRight: 'auto'
}
if ( this.props.buildboard === 1 || this.props.buildboard === 2 ) {
return (
<div style={styleRow}>
<Square styleColor={'white'} boardSquareClick={()=>{}} value={0} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={2} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={3} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={4} /><br/>
<Square styleColor={'white'} boardSquareClick={()=>{}} value={5} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={6} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={7} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={8} /><br/>
<Square styleColor={'white'} boardSquareClick={()=>{}} value={9} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={10} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={11} /><Square styleColor={'white'} boardSquareClick={()=>{}} value={12} /><br/>
</div>
)
} else if (this.props.buildboard === 3) {
let htmlString = []
for (let i = 0; i < this.props.memboard.length; i++){
if (this.props.memboard[i] === 'Y' ){
htmlString.push(<Square styleColor={'blue'} boardSquareClick={()=>{}} value={i}/>)
} else {
htmlString.push(<Square styleColor={'white'} boardSquareClick={()=>{}} value={i}/>)
}
if (i === 3 || i === 7 || i === 11) {
htmlString.push(<br/>)
}
}
return (
<div style={styleRow}>
{ htmlString }
</div>
)
} else if (this.props.buildboard === 4) {
let htmlString = []
for (let i = 0; i < this.props.personboard.length; i++){
if (this.props.personboard[i] === 'Y' ){
htmlString.push(<Square styleColor={'blue'} boardSquareClick={this.boardSquareClick} value={i}/>)
} else {
htmlString.push(<Square styleColor={'white'} boardSquareClick={this.boardSquareClick} value={i}/>)
}
if (i === 3 || i === 7 || i === 11) {
htmlString.push(<br/>)
}
}
return (
<div style={styleRow}>
{ htmlString }
</div>
)
} else if (this.props.buildboard === 5) {
let htmlString = []
for (let i = 0; i < this.props.memboard.length; i++){
if (this.props.memboard[i] === 'Y' & this.props.personboard[i] === 'Y'){
htmlString.push(<Square styleColor={'green'} boardSquareClick={()=>{}} value={i}/>)
} else if (this.props.memboard[i] === 'Y' && this.props.personboard[i] === '') {
htmlString.push(<Square styleColor={'yellow'} boardSquareClick={()=>{}} value={i}/>)
} else if (this.props.memboard[i] === '' && this.props.personboard[i] === 'Y') {
htmlString.push(<Square styleColor={'red'} boardSquareClick={()=>{}} value={i}/>)
} else {
htmlString.push(<Square styleColor={'white'} boardSquareClick={()=>{}} value={i}/>)
}
if (i === 3 || i === 7 || i === 11) {
htmlString.push(<br/>)
}
}
return (
<div style={styleRow}>
{ htmlString }
</div>
)
}
}
}
class Square extends React.Component {
selectCell = () => {
this.props.boardSquareClick(this.props.value)
}
render() {
let {styleColor} = this.props;
const styleSquare = {
width: '150px',
height: '150px',
border: 'thin solid black',
display: 'inline-block',
backgroundColor: styleColor
}
return (
<div style={styleSquare} onClick={this.selectCell}>
</div>
)
}
}
class Footer extends React.Component {
showCountDownFooter = () => {
this.props.startGameClick()
}
render() {
const styleRow = {
display: 'block',
width: '610px',
marginLeft: 'auto',
marginRight: 'auto'
}
if (this.props.board === 1) {
return (
<div style={styleRow}>
<button onClick={this.showCountDownFooter}>Start Game</button>
</div>
)
} else if (this.props.board === 2) {
return (
<div style={styleRow}>
<p>Get Ready To Memorize Cells in {this.props.counter} ... </p>
</div>
)
} else if (this.props.board === 3) {
return (
<div style={styleRow}>
</div>
)
} else if (this.props.board === 4) {
return (
<div style={styleRow}>
<p>Guess the correct cells!</p>
</div>
)
} else if (this.props.board === 5) {
return (
<div style={styleRow}>
<button onClick={this.showCountDownFooter}>Play Again</button>
</div>
)
}
}
}
ReactDOM.render(<App />, document.getElementById('root'));<file_sep>/node_and_apis/math_module/readnodetxt.js
var fs = require("fs") // this is a synchronous blocking operation
// console.log(fs.readFileSync("node.txt", "utf8")); // this way, this code has to finsih before we console log unrelated runs
fs.readFile('node.txt', 'utf8', (err, data) => { // this one takes a callback so the rest of the code can keep processing, now asynchronous
if (err) throw err;
console.log(data.toUpperCase());
});
console.log("Do completely unrelated stuff...."); //this is synchronous<file_sep>/coding_challenges/filter.js
//the filter function (accept a callback, builds us a new array with the items in that we want to keep, true keeps in array, false leaves out of array)
const filteredArr = a.filter(function(value){
return (value%2===0); //keeps even numbers
});
console.log(filteredArr);
// this is what the filter function does behind the scenes
Array.prototype.filter = function(callback){
const newArray = [];
for (let i = 0; i < this.length; i += 1){
if (callback(this[i])) {
newArray.push(this[i]);
}
}
return newArray;
};
const a = [1,2,3];
console.log(a.filter(function(value, index) {
return (value%2 === 0);
}));<file_sep>/node_and_apis/filteredls.js
'use strict'
var fs = require("fs");
var path = require("path");
var dirPath = process.argv[2];
var fileType = "." + process.argv[3];
fs.readdir(dirPath, (err, files) => { // this one takes a callback so the rest of the code can keep processing, now asynchronous
if (err) throw err;
var arr = files;
for (var i = 0; i < arr.length; i++){
if (path.extname(arr[i]) === fileType)
console.log(arr[i]);
}
});
// solution from program
// var fs = require('fs')
// var path = require('path')
// var folder = process.argv[2]
// var ext = '.' + process.argv[3]
// fs.readdir(folder, function (err, files) {
// if (err) return console.error(err)
// files.forEach(function (file) {
// if (path.extname(file) === ext) {
// console.log(file)
// }
// })
// })
<file_sep>/coding_challenges/validParens.js
'use strict'
// given a string, return a boolean whether it is valid with the number of open and closed
// parens '(sdhdf(fdsdf)sdfsd)' == true or '(sdfsdf(sdfsdfsdf)' = false
function validParens(str){
let counter = 0;
for (let i = 0; i < str.length; i++){
if (str[i] === '('){
counter++;
} else if (str[i] == ')'){
counter--;
}
if (counter < 0){
return false;
}
}
if (counter === 0) {
return true;
} else {
return false;
}
}
const str = '(sdhdf(fdsdf)sdfsd)';
console.log(validParens(str));
<file_sep>/oop/vehicleConstr3.js
function VehicleConstructor(name, wheels, passengers, speed){
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
this.name = name;
this.wheels = wheels;
this.passengers = passengers;
this.speed = speed;
this.distance_travelled = 0;
this.vin = createVin();
function createVin(){
var vin = '';
for (var i = 0; i< 17; i+=1){
vin += chars[Math.floor(Math.random()*35)];
}
return vin;
}
}
VehicleConstructor.prototype.makeNoise = function() {
console.log('I make noise');
return this;
};
VehicleConstructor.prototype.updateDistanceTravelled= function(){
this.distance_travelled += this.speed;
return this;
};
VehicleConstructor.prototype.move = function(){
this.updateDistanceTravelled();
this.makeNoise();
return this;
};
VehicleConstructor.prototype.checkMiles = function(){
console.log(this.distance_travelled);
};
var bike = new VehicleConstructor("Bike", 2, 1, 5);
bike.makeNoise = function(){
console.log("ring ring");
return this;
};
var sedan = new VehicleConstructor("Sedan", 4, 5, 60);
sedan.makeNoise = function(){
console.log("Honk Honk!");
return this;
};
var bus = new VehicleConstructor("Bus", 6, 10, 55);
bus.addPassenger = function(count) {
this.passengers += count;
return this;
};
bus.addPassenger(5);
console.log(bus);
<file_sep>/reactcode/tic_tac_toe/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
player: 1,
arrSquares: ['','','','','','','','','']
};
}
winnerCheck = () => {
const {arrSquares} = this.state
if ( arrSquares[0] === arrSquares[1] && arrSquares[0] !== '' ) {
if (arrSquares[1] === arrSquares[2]) {
return true
}
}
if ( arrSquares[3] === arrSquares[4] && arrSquares[3] !== '') {
if (arrSquares[4] === arrSquares[5]) {
return true
}
}
if ( arrSquares[6] === arrSquares[7] && arrSquares[6] !== '') {
if (arrSquares[7] === arrSquares[8]) {
return true
}
}
if ( arrSquares[0] === arrSquares[3] && arrSquares[3] !== '') {
if (arrSquares[3] === arrSquares[6]) {
return true
}
}
if ( arrSquares[1] === arrSquares[4] && arrSquares[4] !== '') {
if (arrSquares[4] === arrSquares[7]) {
return true
}
}
if ( arrSquares[2] === arrSquares[5] && arrSquares[2] !== '') {
if (arrSquares[5] === arrSquares[8]) {
return true
}
}
if ( arrSquares[0] === arrSquares[4] && arrSquares[0] !== '') {
if (arrSquares[4] === arrSquares[8]) {
return true
}
}
if ( arrSquares[2] === arrSquares[4] && arrSquares[2] !== '') {
if (arrSquares[4] === arrSquares[6]) {
return true
}
}
return false
}
boardSquareClick = (value) => {
const tempSquaresArr = Object.assign(this.state.arrSquares)
if (this.state.player === 1){
tempSquaresArr[value] = 'X'
this.setState({
player: 2,
arrSquares: tempSquaresArr
})
} else {
tempSquaresArr[value] = 'O'
this.setState({
player: 1,
arrSquares: tempSquaresArr
})
}
}
reset = () => {
this.setState ( {
player: 1,
arrSquares: ['','','','','','','','','']
})
}
render() {
const gameState= this.winnerCheck()
if (gameState) {
return(
<div>
<h1>You Win!</h1>
<Square boardSquareClick={()=>{}} value={0} text={this.state.arrSquares[0]}/><Square boardSquareClick={()=>{}} value={1} text={this.state.arrSquares[1]}/><Square boardSquareClick={()=>{}} value={2} text={this.state.arrSquares[2]}/><br/>
<Square boardSquareClick={()=>{}} value={3} text={this.state.arrSquares[3]}/><Square boardSquareClick={()=>{}} value={4} text={this.state.arrSquares[4]}/><Square boardSquareClick={()=>{}} value={5} text={this.state.arrSquares[5]}/><br/>
<Square boardSquareClick={()=>{}} value={6} text={this.state.arrSquares[6]}/><Square boardSquareClick={()=>{}} value={7} text={this.state.arrSquares[7]}/><Square boardSquareClick={()=>{}} value={8} text={this.state.arrSquares[8]}/><br/>
<button onClick={this.reset}>Start a New Game</button>
</div>
)
} else {
return (
<div>
<h1>It's player {this.state.player}'s turn!</h1>
<Square boardSquareClick={this.boardSquareClick} value={0} text={this.state.arrSquares[0]}/><Square boardSquareClick={this.boardSquareClick} value={1} text={this.state.arrSquares[1]}/><Square boardSquareClick={this.boardSquareClick} value={2} text={this.state.arrSquares[2]}/><br/>
<Square boardSquareClick={this.boardSquareClick} value={3} text={this.state.arrSquares[3]}/><Square boardSquareClick={this.boardSquareClick} value={4} text={this.state.arrSquares[4]}/><Square boardSquareClick={this.boardSquareClick} value={5} text={this.state.arrSquares[5]}/><br/>
<Square boardSquareClick={this.boardSquareClick} value={6} text={this.state.arrSquares[6]}/><Square boardSquareClick={this.boardSquareClick} value={7} text={this.state.arrSquares[7]}/><Square boardSquareClick={this.boardSquareClick} value={8} text={this.state.arrSquares[8]}/><br/>
<button onClick={this.reset}>Start a New Game</button>
</div>
)
}
}
}
class Square extends React.Component {
squareOnClick = () => {
if (this.props.text === '') {
this.props.boardSquareClick(this.props.value)
}
}
render() {
const styleSquare = {
border: 'thin solid black',
width: '150px',
height: '150px',
display: 'inline-block'
}
return (
<div style={styleSquare} onClick={this.squareOnClick} >
<p> {this.props.value} {this.props.text} </p>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<file_sep>/coding_challenges/mergeMeetings.js
function mergeMeetings(meetingTimeRanges) {
meetingTimeRanges.sort((a, b) => a.startTime - b.startTime);
return meetingTimeRanges.reduce((mergedMeetings, currentMeeting) => {
if (mergedMeetings.length === 0) {
mergedMeetings.push(currentMeeting);
return mergedMeetings;
}
const lastMergedMeeting = mergedMeetings[mergedMeetings.length - 1];
if (lastMergedMeeting.endTime >= currentMeeting.startTime) {
lastMergedMeeting.endTime = Math.max(lastMergedMeeting.endTime, currentMeeting.endTime);
// lastMergedMeeting.endTime = (lastMergedMeeting.endTime > currentMeeting.endTime) ? lastMergedMeeting.endTime : currentMeeting.endTime;
} else {
mergedMeetings.push(currentMeeting);
}
return mergedMeetings;
}, []);
}<file_sep>/reactcode/voting_app_part2/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import img from './plus.png';
const App = () => {
const styleH = {
textAlign: 'center'
}
return (
<div>
<h1 style={styleH}>Vote Your JS Library!</h1>
<Container/>
</div>
)
}
class Container extends React.Component {
state = {
libraries: [
{
text: 'React',
count: 0
},
{
text: 'Vue',
count: 0
},
{
text: 'Angular',
count: 0
},
{
text: 'Ember',
count: 0
}
]
}
incCount = (text) => {
this.setState((oldState) => {
const newLibraries = oldState.libraries.map((alibrary) => {
if (alibrary.text !== text) {
return {...alibrary};
} else {
return {
...alibrary,
count: alibrary.count + 1
}
}
})
return {
libraries: newLibraries
}
})
}
render () {
let sortedlibraries = [...this.state.libraries]
sortedlibraries = sortedlibraries.sort((a, b) => {
if (a.count < b.count) return 1
if (a.count > b.count) return -1
return 0
})
const rectangles = sortedlibraries.map((recObj) => {
return <Rectangle key={recObj.text} recInfo={recObj} myFunc={this.incCount} />
})
return (
<div>
{rectangles}
</div>
)
}
}
const Rectangle = (props) => {
const styleDiv = {
height: '55px',
width: '275px',
display: 'block',
border: 'thin solid black',
marginLeft: 'auto',
marginRight: 'auto'
};
const styleText = {
width: '80px',
height: '45px',
margin: '0px',
verticalAlign: 'middle',
textAlign: 'center',
display: 'inline-block'
}
const styleCounter = {
textAlign: 'center',
border: '2px solid black',
borderRadius: '50px',
margin: '0px',
width: '40px',
height: '40px',
fontSize: '20px',
display: 'inline-block',
verticalAlign: 'middle'
};
const stylePic = {
width: '35px',
height: '35px',
display: 'inline-block',
verticalAlign: 'middle'
}
const { recInfo } = props;
const text = recInfo.text;
const counter = recInfo.count;
const click = () => {
props.myFunc(text)
}
return (
<div style={styleDiv}>
<p style={styleCounter}>{counter}</p>
<p style={styleText}>{text}</p>
<img style={stylePic} onClick={click} src={img} alt="pluspic"/>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
<file_sep>/promise-shop/rejectresolvepromise.js
var promise = new Promise(function (resolve, reject) {
resolve("I FIRED");
reject(new Error("I DID NOT FIRE"));
});
function onRejected (error) {
console.log(error.message);
}
promise.then(function(item){
console.log(item);
},
onRejected);<file_sep>/reactcode/counter_app/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
state = {
numofcountholders: 1
}
incCountHolder = () => {
this.setState({numofcountholders: this.state.numofcountholders+1})
}
render() {
return (
<div>
<button onClick={this.incCountHolder}>Add Counter</button>
<CounterHolder numofcountholders={this.state.numofcountholders}/>
</div>
)
}
}
const CounterHolder = (props) => {
let total = props.numofcountholders
console.log(total);
let htmlString = [];
for (let i = 1; i <= total; i++){
htmlString.push(<Counter/>)
}
return <div>{htmlString}</div>;
}
class Counter extends React.Component {
state = {
count: 0
}
incCount = () => {
this.setState({count: this.state.count+1})
}
decCount = () => {
this.setState({count: this.state.count-1})
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.incCount}>Increment</button>
<button onClick={this.decCount}>Decrement</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<file_sep>/coding_challenges/getProducts.js
'use strict'
var myArray = [5,1,3,8,2];
// var myNewArray = [48, 240, 80, 30, 120];
//no division, optimize for time -- read in an aray and find the product of
//all the numbers apart from the index you are on
function getProducts(arr) {
let afters = [];
let before = [];
let newArr = [];
let prod = 1;
for (let i = arr.length-1; i >=0; i--){
afters[i] = prod;
prod = prod * arr[i];
}
prod = 1;
for (let i = 0; i < arr.length; i++){
before[i] = prod;
prod = prod * arr[i];
}
for (let i = 0; i < arr.length; i++){
newArr[i] = before[i] * afters[i];
}
return newArr;
}
console.log(getProducts(myArray));
<file_sep>/node_and_apis/firstasyncio.js
'use strict'
var fs = require("fs");
var filePath = process.argv[2];
fs.readFile(filePath, 'utf8', (err, data) => { // this one takes a callback so the rest of the code can keep processing, now asynchronous
if (err) throw err;
var string = data.toString();
var count = 0;
for (var i = 0; i < string.length; i++){
if (string[i] === '\n')
count++;
}
console.log(count);
});
//answer from program
// var fs = require('fs')
// var file = process.argv[2]
// fs.readFile(file, function (err, contents) {
// if (err) {
// return console.log(err)
// }
// // fs.readFile(file, 'utf8', callback) can also be used
// var lines = contents.toString().split('\n').length - 1
// console.log(lines)
// })
<file_sep>/node_and_apis/landing_page/server.js
//ajacent to server js file, make an html file, when server is git with a request, the contents of that file are sent back to the browser
var fs = require("fs");
var http = require('http');
var server = http.createServer(function(request, response){
console.log(request.url);
var page = "";
if (request.url == '/'){
page = "./index.html";
} else if (request.url == '/ninjas'){
page = "./ninjas.html";
} else if (request.url == '/dojos/new'){
page = "./dojos.html";
}
if (page){
fs.readFile(page, 'utf8', function(err, fileContents){
response.end(fileContents);
});
} else {
response.end("<html><h2>URL Requested is not available</h2></html>");
}
});
server.listen(6789);
<file_sep>/javascript/fund3.js
var person = {};
function personConstructor(person, name){
person = {name: name, distance_traveled: 0};
return person;
}
person = personConstructor(person, "Heather");
function say_name(obj){
console.log(obj.name);
}
say_name(person);
function say_something(parm, obj){
console.log(obj.name + " says " + parm);
}
say_something("I am cool", person);
function walk(obj){
obj.distance_traveled += 3;
console.log(obj.name + " is walking");
}
walk(person);
function run(obj){
obj.distance_traveled += 10;
console.log(obj.name + " is running");
}
run(person);
function crawl(obj){
obj.distance_traveled += 1;
console.log(obj.name + " is crawling");
}
crawl(person);
console.log(person);
// ninja's
var ninja = {};
function ninjaConstructor(ninja, name, cohort){
ninja = {name: name, cohort: cohort, beltlevel: 'yellow-belt'};
return ninja;
}
function levelUp(ninja){
if (ninja.beltlevel === 'yellow-belt') {
ninja.beltlevel = 'orange-belt';
} else if (ninja.beltlevel === 'orange-belt') {
ninja.beltlevel = 'green-belt';
} else if (ninja.beltlevel === 'green-belt') {
ninja.beltlevel = 'purple-belt';
} else if (ninja.beltlevel === 'purple-belt') {
ninja.beltlevel = 'brown-belt';
} else if (ninja.beltlevel === 'brown-belt') {
ninja.beltlevel = 'red-belt';
} else if (ninja.beltlevel === 'red-belt') {
ninja.beltlevel = 'black-belt';
} else ;
return ninja;
}
ninja = ninjaConstructor(ninja, "Heather", "Rob");
console.log(ninja);
levelUp(ninja);
console.log(ninja);
levelUp(ninja);
console.log(ninja);
levelUp(ninja);
console.log(ninja);
<file_sep>/coding_challenges/terraces.js
'use strict'
// given an array of terrace hights, and it's raining, configure how much water is caught
// by each terrace
//[3,1,5,2,6,4,2,3] = volume = 6
// *
// * *
// * * *
// * * * * *
// * * * * * * *
// * * * * * * * *
function findMaxInd(arr){
let maxVal = arr[0];
let index = 0;
for (let i = 1; i < arr.length; i++){
if (arr[i] > maxVal){
maxVal = arr[i];
index = i;
}
}
return index;
}
function terraceHeights(arr){
let left = 0;
let max = findMaxInd(arr);
let count = 0;
for (let i = 1; i < max; i++){
if (arr[i] < arr[left]){
count += (arr[left]-arr[i]);
} else {
left = i;
}
}
let rt = arr.length-1;
for (let i = arr.length-2; i > max; i--){
if (arr[i] < arr[rt]){
count += (arr[rt]-arr[i]);
} else {
rt = i;
}
}
return count;
}
const arr = [1,3,5,4,1,6,3,4];
console.log(terraceHeights(arr));<file_sep>/coding_challenges/map.js
//the map function (accept a callback, build us a new array with whatever we return)
const a = [1,2,3,4,5,6];
const mappedArr = a.map(function(value){
return value * 2;
});
console.log(mappedArr);
// this is what the map function does behind the scenes
Array.prototype.map = function(callback){
const newArray = [];
this.forEach(function(value){
newArray.push(callback(value));
});
return newArray;
};
console.log(a.map(function(value, index) {
return value * 2;
}));<file_sep>/express work/surveyform_onepage/client/js/main.js
'use strict';
// Write code that stops form from submitting
$(document).ready( function(){
$('form').submit( function(event){
event.preventDefault();
const dataForServer = $(this).serialize();
$.ajax({
url: '/results',
method: 'post',
data: dataForServer,
success: function(responseFromServer){
const htmlTags = `
<div id='headerDiv'><h3>Submitted Information</h3></div>
<div id="infoDiv">
<table>
<tr>
<td>Name:</td>
<td>${responseFromServer.name}</td>
</tr>
<tr>
<td>Dojo Location:</td>
<td>${responseFromServer.location}</td>
</tr>
<tr>
<td>Favorite Language:</td>
<td>${responseFromServer.language}</td>
</tr>
<tr>
<td>Comment:</td>
<td>${responseFromServer.comment}</td>
</tr>
</table>
</div>
<div id='buttonDiv'>
<button>Go Back</button>
</div>
</div>
`;
$('.main-content').html(htmlTags);
}
});
});
});<file_sep>/coding_challenges/PaintRoom/main.js
'use strict'
const orderSupplies = (item, callback) => {
// The orderSupplies function first finds the item you requested
const warehouse = [
{ item: 'paint', action(){ return 'start mixing!' } },
{ item: 'brush', action(){ return 'start painting!' } }
];
const deliveryTime = Math.random()*3000 + 1000;
setTimeout( () => {
const foundItem = warehouse.find((obj) => obj.item === item);
if (foundItem) {
callback(foundItem);
}
}, deliveryTime );
};
// original calls
// orderSupplies('paint', (delivery) => console.log(`${delivery.item} delivered! Time to ${delivery.action()}`));
// orderSupplies('brush', (delivery) => console.log(`${delivery.item} delivered! Time to ${delivery.action()}`));
//changed to:
const printItem = (delivery) => console.log(`${delivery.item} delivered! Time to ${delivery.action()}`);
let paintReceived = false;
let brush = null;
orderSupplies('paint', function(item) {
printItem(item);
paintReceived = true;
if (brush){
printItem(brush);
}
});
orderSupplies('brush', function(item) {
if (paintReceived){
printItem(item);
} else {
brush = item;
}
});
//This can take up to the max time of 8 seconds
// orderSupplies('paint', (delivery) => {
// console.log(`${delivery.item} delivered! Time to ${delivery.action()}`)
// orderSupplies('brush', (delivery) => console.log(`${delivery.item} delivered! Time to ${delivery.action()}`));
// });
// const printItem = (delivery) => console.log(`${delivery.item} delivered! Time to ${delivery.action()}`);
//these can print out of order
// orderSupplies('paint', printItem);
// orderSupplies('brush', printItem);
//these can take up to the max time of 8 seconds
// orderSupplies('paint', (item) => {
// printItem(item);
// orderSupplies('brush', printItem);
// });
// let paintReceived = false;
// let brush = null;
// orderSupplies('paint', (item) => {
// printItem(item); //can print as we don't need to do anything else
// paintReceived = true;
// if (brush){ //if brush is waiting in the garage, print item brush
// printItem(brush);
// }
// });
// orderSupplies('brush', (item) => {
// if (paintReceived){
// printItem(item); //only if the paint has been delivered
// } else {
// brush = item; // otherwise put the brush in the garage and wait until paint arrives
// }
// });
<file_sep>/coding_challenges/reduce.js
const array = [1,2,3,4];
const sum = array.reduce((currentSum, currentVal) => {
return currentSum + currentVal;
}, 100); //100 is the initial starting value
console.log(sum);
// this is what the reduce function does behind the scenes
Array.prototype.reduce = function(callback, initialAcc){
var start;
var cAcc;
if (initialAcc === undefined){
cAcc = this[0];
start = 1;
} else {
cAcc = initialAcc;
start = 0;
}
for (var i = start; i < this.length; i++){
cAcc = callback(cAcc, this[i]);
}
return cAcc;
};
function callback(sum2, currentacc){
return sum2 + currentacc;
}
console.log(array.reduce(callback, 100)); // starts at 100<file_sep>/coding_challenges/strAnagram.js
//Given a string, return an array where each element is a string representing a diffrent anagram
//(a different sequence of the letters in that string.
function anaGram(str, base='', arr=[]){
if(str===''){
arr.push(base)
}
for(let i=0; i< str.length; i++){
let newBase = base+str.slice(i,i+1)
let newStr = str.slice(0,i) + str.slice(i+1)
anaGram(newStr, newBase, arr)
}
return arr
}
console.log(anaGram('tar'))
<file_sep>/node_and_apis/modular.js
'use strict'
var fs = require("fs");
var path = require("path");
const myModule = require('./modulefile.js');
var dirPath = process.argv[2];
var fileType = process.argv[3];
myModule(dirPath,fileType,function (err, arr){
if (err) {
return console.error('There was an error:', err);
}
for (var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
});<file_sep>/promise-shop/throwerror.js
function parsePromised (json) {
return new Promise(function (fulfill, reject) {
try {
fulfill(JSON.parse(json));
} catch (e) {
reject(e);
}
});
}
parsePromised(process.argv[2])
.then(null, console.log);
// Build a function called `parsePromised` that creates a promise,
// performs `JSON.parse` in a `try`/`catch` block,
// and fulfills or rejectsthe promise depending on whether an error is
// thrown.**Note:** your function should synchronously return the promise!<file_sep>/node_and_apis/first_server/server.js
//ajacent to server js file, make an html file, when server is git with a request, the contents of that file are sent back to the browser
var fs = require("fs");
var http = require('http');
var server = http.createServer(function(request, response){
fs.readFile('./index.html', 'utf8', function(err, fileContents){
response.end(fileContents);
//callback function that is supplied with the contents of the file when we are done reading it
});
});
server.listen(8000);
<file_sep>/express work/namelist_twopages/server/controllers/controller.js
var namelist = [];
module.exports = (() => {
return {
homepage: (req,res) => {
if(req.body.name){
namelist.push(req.body.name);
}
res.render('index',{names:namelist});
}
}
})();<file_sep>/coding_challenges/inOrderSubsets.js
'use strict'
const str = 'abc';
// answer arr = ['', 'c', 'b', 'a', 'ab', 'ac','bc,'abc']
//one way
function subsets(str=''){
if(str.length===0){
return [''];
}
let subs = subsets(str.slice(1));
let count = subs.length;
for(let i=0; i<count; i++){
subs.push(str.slice(0,1) + subs[i]);
}
return subs;
}
console.log(subsets(str));
//second way
<file_sep>/README.md
## Coding Challenges
* [filter](./coding_challenges/fiter.js)
* [map](./coding_challenges/map.js)
<file_sep>/node_and_apis/math_module/main.js
const myMathService = require('./math'); // code that pulls in your module from math.js
console.log(myMathService.add(2,3)); // 5
console.log(myMathService.multiply(2,3)); // 6
console.log(myMathService.square(2)); // 4
console.log(myMathService.random(2, 9)); // 7<file_sep>/express work/namelist_twopages/server/config/routes.js
var controller = require('./../controllers/controller.js');
module.exports = (app) => {
app.get('/', controller.homepage);
app.post('/', controller.homepage);
}<file_sep>/javascript/functions.js
function runningLogger (){
console.log('I am running!');
}
runningLogger();
function multiplyByTen(value){
return value*10;
}
console.log(multiplyByTen(10));
function stringReturnOne(){
return "Hello";
}
console.log(stringReturnOne());
function stringReturnTwo(){
return "World!";
}
console.log(stringReturnTwo());
function caller(func) {
if (typeof func === "function"){
func();
}
}
function myDoubleConsoleLog(func1, func2){
if (typeof func1 === "function" && typeof func2 === "function"){
console.log(func1());
console.log(func2());
}
}
myDoubleConsoleLog(stringReturnOne, stringReturnTwo);
function caller2(func3){
console.log("starting");
setTimeout (function(){
if (typeof func3 === "function"){
func3(stringReturnOne, stringReturnTwo);
}}, 2000);
console.log("ending");
return "interesting";
}
console.log(caller2(myDoubleConsoleLog));
<file_sep>/reactcode/validateforms/src/App.js
import React, { Component } from 'react';
import './styles/App.css';
var validator = require("email-validator");
class App extends Component {
state = {
nameVal: '',
nameErrMgs: '',
email: '',
emailErrMgs: '',
namePass: false,
emailPass: false,
btnDis: true,
display: 'form' //'form' or 'thanks'
}
handleChange = (event) => {
const { name, value} = event.target;
let nameError = this.state.nameErrMgs;
let emailError = this.state.emailErrMgs;
let namePassing = this.state.namePass;
let emailPassing = this.state.emailPass;
let displaySubmitBtn = this.state.btnDis;
if(name === 'nameVal' && value.length<8){
nameError = 'Name needs to be 8 chars or longer';
namePassing = false;
}
else if(name === 'nameVal' && value.length>=8){
nameError = '';
namePassing = true;
}
if(name === 'email' && !validator.validate(value)){
emailError = 'invalid email format';
emailPassing = false;
}
else if(name === 'email' && validator.validate(value)){
emailError = '';
emailPassing = true;
}
if(namePassing && emailPassing) {
displaySubmitBtn = false;
}
else{
displaySubmitBtn = true;
}
this.setState( {
[name]: value,
nameErrMgs: nameError,
emailErrMgs: emailError,
namePass: namePassing,
emailPass: <PASSWORD>,
btnDis: displaySubmitBtn
})
}
submitFormClick = () => {
let display = 'thanks'
this.setState({display: display})
}
render() {
if(this.state.display === 'form'){
return (
<div className="App">
<div>
<input type='text' name='nameVal' placeholder='name' onChange={this.handleChange} value={this.state.name}/>
<p>{this.state.nameErrMgs}</p>
</div>
<div>
<input type='text' name='email' placeholder='email' onChange={this.handleChange} value={this.state.email}/>
<p>{this.state.emailErrMgs}</p>
</div>
<button onClick={this.submitFormClick} disabled={this.state.btnDis}>Submit</button>
</div>
);
}
else{
return (
<div className="App">
Thanks!
</div>
);
}
}
}
export default App;
<file_sep>/oop/cards.js
function PlayerConstructor(name, hand){
var player = {};
player.name = name;
player.hand = hand;
return player;
}
function createCard (suit, value) {
var card = {};
card.suit = suit;
card.value = value;
return card;
}
function createDeck (){
var deck = [];
var cardArr = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"];
var suitArr = ["Spades", "Diamonds", "Hearts", "Clubs"];
for (var i = 0; i < cardArr.length; i++){
for (var j = 0; j < suitArr.length; j++){
card = new createCard(suitArr[j], cardArr[i]);
deck.push(card);
}
}
return deck;
}
function shuffle(deck) {
var m = deck.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = deck[m];
deck[m] = deck[i];
deck[i] = t;
}
return deck;
}
function reset(){
newdeck = createDeck();
}
function deal(deck){
var index = Math.trunc(Math.random() * deck.length);
var randomCard = deck[index];
deck = deck.splice(index, 1);
return randomCard;
}
function discard(playerhand, playerdiscard){
playerhand.pop();
// playerhand = playerhand.splice((playerdiscard-1), 1);
return playerhand;
}
var newdeck = [];
newdeck = createDeck();
shuffle(newdeck);
var Heather = PlayerConstructor("Heather", []);
Heather.hand.push(deal(newdeck));
Heather.hand.push(deal(newdeck));
Heather.hand.push(deal(newdeck));
console.log(Heather);
Heather.hand = discard(Heather.hand, 1);
console.log(Heather);
Heather.hand.push(deal(newdeck));
console.log(Heather);
console.log(newdeck);
<file_sep>/reactcode/thinking_in_react/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
class ProductCategoryRow extends React.Component {
render() {
return <tr><th colSpan="2">{this.props.category}</th></tr>;
}
}
ProductCategoryRow.propTypes = {
category: PropTypes.string.isRequired
}
class ProductRow extends React.Component {
render() {
var name = this.props.product.stocked ?
this.props.product.name :
<span style={{color: 'red'}}>
{this.props.product.name}
</span>;
return (
<tr>
<td>{name}</td>
<td>{this.props.product.price}</td>
</tr>
);
}
}
ProductRow.propTypes = {
product: PropTypes.object.isRequired
}
class ProductTable extends React.Component {
render() {
console.log(this.props.showInStock)
console.log(this.props.searchString)
var rows = [];
var lastCategory = null;
this.props.products.forEach((product) => {
if (product.category !== lastCategory) {
rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
}
if (this.props.showInStock && product.stocked) { //checked so only show instock
if (product.name.toLowerCase().indexOf(this.props.searchString.toLowerCase()) > -1 ) { // and search text is found
rows.push(<ProductRow product={product} key={product.name} />);
}
} else if (!this.props.showInStock) { // not checked so show everything
if (product.name.toLowerCase().indexOf(this.props.searchString.toLowerCase()) > -1 ) { //and search text is found
rows.push(<ProductRow product={product} key={product.name} />);
}
}
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
}
class SearchBar extends React.Component {
inStockClick = (e) => {
this.props.filterClick(e.currentTarget.checked)
}
searchText = (e) => {
this.props.searchInput(e.currentTarget.value)
}
render() {
return (
<form>
<input type="text" placeholder="Search..." onKeyUp={this.searchText}/>
<p>
<input type="checkbox" onClick={this.inStockClick}/>
{' '}
Only show products in stock
</p>
</form>
);
}
}
class FilterableProductTable extends React.Component {
constructor(props) {
super(props);
this.state = {
inStockOnly: false,
searchString: ''
};
}
productInStockClick = (value) => {
this.setState({inStockOnly: value})
}
searchText = (value) => {
this.setState({searchString: value})
}
render() {
return (
<div>
<SearchBar filterClick={this.productInStockClick} searchInput={this.searchText}/>
<ProductTable products={this.props.products} showInStock={this.state.inStockOnly} searchString={this.state.searchString} />
</div>
);
}
}
var PRODUCTS = [
{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
{category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
{category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
{category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
{category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
{category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];
ReactDOM.render(
<FilterableProductTable products={PRODUCTS} />,
document.getElementById('container')
);
<file_sep>/express work/surveyform_onepage_promises/client/js/main.js
'use strict';
const http = axios;
// Write code that stops form from submitting
$(document).ready( function(){
$('form').submit( function(event){
event.preventDefault();
const dataForServer = $(this).serialize();
var promise = http({
url: '/results',
method: 'post',
data: dataForServer
});
promise
.then(function(responseFromServer){
const data = responseFromServer.data;
const htmlTags = `
<div id='headerDiv'><h3>Submitted Information</h3></div>
<div id="infoDiv">
<table>
<tr>
<td>Name:</td>
<td>${data.name}</td>
</tr>
<tr>
<td>Dojo Location:</td>
<td>${data.location}</td>
</tr>
<tr>
<td>Favorite Language:</td>
<td>${data.language}</td>
</tr>
<tr>
<td>Comment:</td>
<td>${data.comment}</td>
</tr>
</table>
</div>
<div id='buttonDiv'>
<button>Go Back</button>
</div>
</div>
`
$('.main-content').html(htmlTags);
})
.catch(function(err){
$('.main-content').prepend("<p class='error'>There was a problem</p>");
});
});
});<file_sep>/coding_challenges/balancepoint.js
//given an array, see if there is a balance point
function bp(arr){
let sum1 = arr.reduce(function(accum, val){
return accum + val;
})
let sum2 = 0;
for (let i = 0; i < arr.length; i++){
if (sum1 === sum2) {return true;}
let current = arr[i];
sum2 += current;
sum1 -= current;
}
return false;
}
console.log(bp([20,-10,10]))<file_sep>/reactcode/validateforms/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './styles/index.css';
const Wrapper = () => {
return (
<div className="wrapper">
<h1>form validation</h1>
<App />
</div>
);
}
ReactDOM.render(<Wrapper />, document.getElementById('root'));
|
6ede88743d7da0c292ebbbdb19b2423b241c9bd0
|
[
"JavaScript",
"Markdown"
] | 39 |
JavaScript
|
dojo-react-workshop/heather_latham
|
5d1238800aea07311327391f9aa9adb4736b2b3d
|
45993bb073c0a756417a2881b02b48e26efa0d34
|
refs/heads/master
|
<file_sep>(function () {
$(".wrapper dl dd .sub-menu .menu-list").on("mouseenter",function (e) {
$(".wrapper dl dd .sub-menu .menu-list").removeClass("move");
$(this).addClass("move");
})
})();
<file_sep>(function () {
var jqueryObj = $(".content .content-list li");
var iconBgObj = $(".content .content-list li .bg .icon-bg");
var subIconBgObj = $(".content .content-list li .bg .sub-icon-bg");
var iconUrl = ["url('./images/icon1.png')",
"url('./images/icon2.png')",
"url('./images/icon3.png')"];
var subIconUrl = ["url('./images/value.png')",
"url('./images/attiude.png')",
"url('./images/style.png')"];
var iconHoverUrl = ["url('./images/icon1-hover.png')",
"url('./images/icon2-hover.png')",
"url('./images/icon3-hover.png')"];
var subIconHoverUrl = ["url('./images/value-hover.png')",
"url('./images/attiude-hover.png')",
"url('./images/style-hover.png')"];
jqueryObj.each(function (i) {
jqueryObj.eq(i).on("mouseenter", function () {
jqueryObj[i].style.backgroundColor = "#1262a9";
jqueryObj[i].style.color = "#fff";
iconBgObj[i].style.backgroundImage = iconHoverUrl[i];
subIconBgObj[i].style.backgroundImage = subIconHoverUrl[i];
iconBgObj[i].style.backgroundColor = "#fff";
});
jqueryObj.eq(i).on("mouseleave", function () {
jqueryObj[i].style.backgroundColor = "#fff";
jqueryObj[i].style.color = "#1f2d3d";
iconBgObj[i].style.backgroundImage = iconUrl[i];
subIconBgObj[i].style.backgroundImage = subIconUrl[i];
});
})
}());
window.onload = function () {
//轮播图代码
var bannerLi = $(".banner-list li");
var oNext = $(".banner .next");
var oPrev = $(".banner .prev");
var Oon = $(".banner .tab li");
var oBanner = $(".banner");
var index = 0;
var timer = null;
//自动轮播
function autoPlay(){
timer = setInterval(function () {
index ++;
index %= 3;
change(index);
},4000);
};
autoPlay();
//点击tab切换=
Oon.hover(function () {
index = $(this).index();
Oon.eq(index).addClass("active").siblings().removeClass("active");
bannerLi.eq(index).stop(true).fadeIn("linear").siblings().stop(true).fadeOut("linear");
})
//图片和tab变换效果
function change(index){
Oon.eq(index).addClass("active").siblings().removeClass("active");
bannerLi.eq(index).stop(true).fadeIn("linear").siblings().stop(true).fadeOut("linear");
}
//按钮显示隐藏
function btnShow(){
oNext.toggle();
oPrev.toggle();
}
//点击下一页按钮
oNext.on("click",function () {
index ++;
index %= 3;
change(index);
})
//点击上一页按钮
oPrev.on("click",function () {
index --;
index = index == -1 ? 2 : index % 3;
change(index);
})
//鼠标移入banner
oBanner.on("mouseenter",function () {
btnShow();
clearInterval(timer);
})
//鼠标移出banner
oBanner.on("mouseleave",function () {
btnShow();
autoPlay();
})
}
window.onresize = function () {
//浏览器窗口重置时重新计算banner的高度
var imgHeight = 0;
var percent = 560 / 1920;
var width = document.documentElement.clientWidth;
if (width < 1200) {
imgHeight = 1200 * percent;
} else {
imgHeight = width * percent;
}
$(".banner").css({
height: imgHeight + 'px'
})
}
|
80c351568660455e52305abaa4fe237fdaaf9562
|
[
"JavaScript"
] | 2 |
JavaScript
|
17702737083/ly
|
16e33cd2a98b1aca5c0744f4537f52eced97de0a
|
2805c7ed9a031324096c391d7d9442c9ae3e8caf
|
refs/heads/main
|
<repo_name>gauravmeena41/Clock<file_sep>/index.js
const hour = document.querySelector(".hour h1");
const minute = document.querySelector(".minute h1");
const second = document.querySelector(".second h1");
const Am = document.querySelector(".am h1");
let clock = () => {
let date = new Date();
let hrs = date.getHours();
let mins = date.getMinutes();
let secs = date.getSeconds();
let period = "AM";
if (hrs == 0) {
hrs = 12;
} else if (hrs > 12) {
hrs = hrs - 12;
period = "PM";
}
hour.innerHTML = hrs < 10 ? `0${hrs}` : hrs;
minute.innerHTML = mins < 10 ? `0${mins}` : mins;
second.innerHTML = secs < 10 ? `0${secs}` : secs;
Am.innerHTML = period;
};
setInterval(clock, 1000);
|
7980d0fff6954f12b55e2cc9a49f11ec04cade11
|
[
"JavaScript"
] | 1 |
JavaScript
|
gauravmeena41/Clock
|
5bb0f535454d797e75b9852ba53b124d76e42061
|
a32a5b65efa40ba546a6560059e5f5c72efee136
|
refs/heads/master
|
<repo_name>xavibj/comp<file_sep>/README.md
# comp
Python interactive expression evaluator using PLY
<file_sep>/int.py
# -*- coding: utf-8 -*-
import cmd
import ply.yacc as yacc
# Get the token map from the lexer. This is required.
from lexer import tokens
names = {}
def p_statement_assign(p):
'statement : IDENT IGUAL expression'
names[p[1]] = p[3]
def p_statement_expression(p):
'statement : expression'
p[0] = p[1]
def p_expression_plus(p):
'expression : expression PLUS term'
try:
p[0] = p[1] + p[3]
except:
print("Ahhhh")
def p_expression_minus(p):
'expression : expression MINUS term'
p[0] = p[1] - p[3]
def p_expression_term(p):
'expression : term'
p[0] = p[1]
def p_term_times(p):
'term : term TIMES factor'
p[0] = p[1] * p[3]
def p_term_div(p):
'term : term DIVIDE factor'
p[0] = p[1] / p[3]
def p_term_factor(p):
'term : factor'
p[0] = p[1]
def p_factor_num(p):
'factor : NUMBER'
p[0] = p[1]
def p_factor_ident(p):
'factor : IDENT'
try:
p[0] = names[p[1]]
except LookupError:
print("undefined name '%s'" % p[1])
#p[0] = 0
def p_factor_expr(p):
'factor : LPAREN expression RPAREN'
p[0] = p[2]
# Error rule for syntax errors
def p_error(p):
#print("Syntax error in input!")
print p
raise SyntaxError
# Build the parser
parser = yacc.yacc()
class int(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = "int >"
self.intro = "Hi !!"
self.__doc__ = "DOC"
def do_exit(self, args):
"""Exits from the console"""
return -1
def do_EOF(self, args):
"""Exit on system end of file character"""
print("Good bye!")
return self.do_exit(args)
def do_help(self, args):
print((self.__doc__))
def emptyline(self):
"""Do nothing on empty input line"""
pass
def default(self, line):
"""Called on an input line when the command prefix
is not recognized.
In that case we execute the line as Python code.
"""
try:
result = parser.parse(line)
except SyntaxError:
print("Syntax error!")
else:
names['last'] = result
print(result)
def do_names(self, args):
"""List names"""
print(names)
i = int()
i.cmdloop()<file_sep>/lexer.py
# -*- coding: utf-8 -*-
import ply.lex as lex
# List of token names. This is always required
tokens = [
'NUMBER',
'PLUS',
'MINUS',
'TIMES',
'DIVIDE',
'LPAREN',
'RPAREN',
'IGUALIGUAL',
'IGUAL',
'IDENT'
]
reserved = {
'if': 'IF',
'then': 'THEN',
'else': 'ELSE',
'while': 'WHILE',
'end': 'END'
}
tokens = tokens + list(reserved.values())
# Regular expression rules for simple tokens
t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_IGUALIGUAL = r'=='
t_IGUAL = r'='
#t_IDENT = r'[a-zA-Z_][a-zA-Z_0-9]*'
def t_IDENT(t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = reserved.get(t.value, 'IDENT') # Check for reserved words
return t
# A regular expression rule with some action code
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
# Define a rule so we can track line numbers
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
# A string containing ignored characters (spaces and tabs)
t_ignore = ' \t'
t_ignore_COMMENT = r'\#.*'
# Error handling rule
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
def main(argv):
pass
lexer = lex.lex()
if __name__ == '__main__':
import sys
main(sys.argv)
|
fb01bb17ab797e82a192719dc16b40166e84e263
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
xavibj/comp
|
532b56570fd9ea552f483e3457702a9639a44b79
|
7dc9ce3465d08191f2684faaf6e305888fdf35f3
|
refs/heads/master
|
<file_sep>package singleton;
public class BossTehdas implements AbstraktiTehdas {
private static BossTehdas INSTANCE = null;
private BossTehdas(){}
public static BossTehdas getInstance(){
if (INSTANCE == null){
INSTANCE = new BossTehdas();
}
return INSTANCE;
}
@Override
public Lippis createLippis() {
return new BossLippis();
}
@Override
public Paita createPaita() {
return new BossPaita();
}
@Override
public Housut createHousut() {
return new BossHousut();
}
@Override
public Kengat createKengat() {
return new BossKengat();
}
}<file_sep>package facade;
/**
*
* @author Tiina
*/
public class Memory {
public void load(long position, byte[] data) {
String ret = "";
for(int i = 0; i<data.length; i++) {
ret += data[i];
}
System.out.println("Loading data from position: " +position+ " Data: "+ret);
}
}
<file_sep>package memento;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Tiina
*/
public class Arvuuttaja {
public Object liityPeliin() {
int arvottuLuku = 1 + (int)(Math.random() * 10);
System.out.println("Oikea luku: " + arvottuLuku);
return new Memento(arvottuLuku);
}
public void vertaa(Object obj, int arvaus) {
Memento memento = (Memento)obj;
if (memento.getLuku() == arvaus) {
System.out.println("Jee! Oikea luku!");
}
}
}
<file_sep>package adapter;
/**
*
* @author Tiina
*/
public class ClothesStore {
String vaate1;
String vaate2;
String vaate3;
String vaate4;
public ClothesStore(String vaate1, String vaate2, String vaate3, String vaate4) {
this.vaate1 = vaate1;
this.vaate2 = vaate2;
this.vaate3 = vaate3;
this.vaate4 = vaate4;
}
public String getVaate1() {
return this.vaate1;
}
public String getVaate2() {
return this.vaate2;
}
public String getVaate3() {
return this.vaate3;
}
public String getVaate4() {
return this.vaate4;
}
}
<file_sep>package singleton;
public class BossLippis implements Lippis {
@Override
public void pueLippis() {
System.out.println("Bossin lippis");
}
}
<file_sep>package templatemethod;
import java.util.Scanner;
/**
*
* @author Tiina
*/
class NoppaArvaus extends AbstraktiGame {
private int arvattuLuku;
private int lukuMin;
private int lukuMax;
private Scanner scanner;
private int kohde;
void initializeGame() {
//alusta peli
scanner = new Scanner(System.in);
lukuMin = 1;
System.out.println("Anna maksimi arvo");
lukuMax = scanner.nextInt();
kohde = (lukuMin + (int)(Math.random()*lukuMax));
System.out.println("Peli alkaa");
}
void makePlay(int player) {
System.out.println("Pelaaja "+(player+1)+" arvaa numero "+lukuMin+" ja "+lukuMax+" väliltä, kiitoooooos:");
arvattuLuku = scanner.nextInt();
if(arvattuLuku < kohde){
System.out.println("Arvaa suurempi luku kiitoooooos");
} else if (arvattuLuku > kohde){
System.out.println("Arvaa pienempi luku");
} else {
System.out.println("Luvut täsmäävät");
}
}
boolean endOfGame() {
if (arvattuLuku == kohde){
return true;
} else {
return false;
}
}
void printWinner() {
System.out.println("Voitit jee");
}
/* Specific declarations for the Monopoly game. */
// ...
}
<file_sep># AMKF
Ohjelmistotuotantoprojekti 1
Ammattikorkeakoulu finder
Ohjelman tarkoituksena on tehdä kaikkea kivaa ja värikästä.
Juu kyllä näin on.
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package builder;
/**
*
* @author Tiina
*/
public class Waiter {
private BurgeriBuilder bb;
public void setBurgerBuilder(BurgeriBuilder bb) {
this.bb = bb;
}
public Burgeri getBurger() {
return bb.getBurger();
}
public void constructBurger() {
bb.createNewBurger();
bb.buildBurger();
}
}
<file_sep>package strategy;
import java.util.List;
/**
*
* @author Tiina
*/
public interface ListConverter {
public abstract String listToString(List lista);
}
<file_sep>package decorator;
/**
*
* @author Tiina
*/
public class Tomaattikastike extends PizzaOsa {
private double hinta = 0.40;
public Tomaattikastike(Pizza lisattavaTayte){
super(lisattavaTayte);
}
@Override
public double getHinta(){
hinta += super.getHinta();
return hinta;
}
@Override
public String getDescription(){
return super.getDescription()+"- Tomaattikastiketta \n";
}
}
<file_sep>
package composite;
/**
*
* @author Tiina
*/
public abstract class AbstractLaiteOsa implements Laiteosa {
int hinta = 0;
public void addOsa (Laiteosa osa){
throw new RuntimeException
("Cannot add children to simple components");
}
public int getHinta (){
return hinta;
}
}
<file_sep>
package composite;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Tiina
*/
public class Tietokone {
List<Laiteosa> osat = new ArrayList<Laiteosa>();
public void rakenna(){
Laiteosa kotelo = new Kotelo(50);
Laiteosa emolevy = new Emolevy(100);
Laiteosa muisti = new Muistipiiri(44);
Laiteosa näyttis = new Naytonohjain(400);
Laiteosa prossu = new Prosessori(356);
Laiteosa verkkokortti = new Verkkokortti(35);
Laiteosa varaprossu = new Prosessori(348);
emolevy.addOsa(muisti);
emolevy.addOsa(näyttis);
emolevy.addOsa(prossu);
emolevy.addOsa(verkkokortti);
kotelo.addOsa(emolevy);
osat.add(kotelo);
osat.add(varaprossu);
}
public String getOsat(){
String osaString = "";
for(Laiteosa o : osat){
osaString += o.toString() + " ";
}
return osaString;
}
public int kerroHinta(){
int koneenHinta = 0;
for (Laiteosa o : osat){
koneenHinta += o.getHinta();
}
return koneenHinta;
}
}
<file_sep>
package abstractmethod;
public class BossPaita implements Paita {
@Override
public void puePaita() {
System.out.println("Bossin paita");
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package builder;
/**
*
* @author Tiina
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Waiter waiter = new Waiter();
BurgeriBuilder md = new McDonalds();
BurgeriBuilder hese = new Hesburger();
waiter.setBurgerBuilder(md);
waiter.constructBurger();
Burgeri burger = waiter.getBurger();
System.out.println("~*~*~*~McDonalds~*~*~*~");
System.out.println(burger.getBurger());
System.out.println("~*~*~*~Hesburger~*~*~*~");
waiter.setBurgerBuilder(hese);
waiter.constructBurger();
burger = waiter.getBurger();
System.out.println(burger.getBurger());
}
}
<file_sep>package strategy;
import java.util.*;
/**
*
* @author Tiina
*/
public class StrategyC implements ListConverter{
private int x = 1;
public String listToString(List lista){
String merkkijono = "";
ListIterator listItr = lista.listIterator();
while(listItr.hasNext()){
if (x >= 3){
merkkijono += listItr.next()+ "\n";
x=0;
}else{
merkkijono += listItr.next()+ " ";
}
x++;
}
return merkkijono;
}
}
<file_sep>
package decorator;
/**
*
* @author Tiina
*/
public class Valkosipuli extends PizzaOsa {
private double hinta = 0.70;
public Valkosipuli (Pizza lisattavaTayte){
super(lisattavaTayte);
}
@Override
public double getHinta(){
hinta += super.getHinta();
return hinta;
}
@Override
public String getDescription(){
return super.getDescription()+"- Valkosipulia \n";
}
}<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package builder;
/**
*
* @author Tiina
*/
public class Hesburger extends BurgeriBuilder{
@Override
public void buildBurger() {
burger.setBurger("Hesburgerin tavallinen burgeri");
}
}
<file_sep>package proxy;
/**
*
* @author Tiina
*/
public class ProxyExampleMain {
/**
* Test method
*/
public static void main(final String[] arguments) {
final Image image1 = new ProxyImage("HiRes_10MB_Photo1");
final Image image2 = new ProxyImage("HiRes_10MB_Photo2");
final Image image3 = new ProxyImage("HiRes_10MB_Photo3");
final Image image4 = new ProxyImage("HiRes_10MB_Photo4");
final Image image5 = new ProxyImage("HiRes_10MB_Photo5");
Image[] images = new Image[5];
images[0] = image1;
images[1] = image2;
images[2] = image3;
images[3] = image4;
images[4] = image5;
images[0].showData();
images[1].showData();
images[2].showData();
images[3].showData();
images[4].showData();
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package memento;
/**
*
* @author Tiina
*/
public class Asiakas extends Thread{
private boolean arvattu = false;
private String nimi;
private int arvausKerrat = 0;
private Object obj;
public Asiakas(String nimi) {
this.nimi = nimi;
}
public String getNimi() {
return this.nimi;
}
public void pelinAvaus(Object obj) {
this.obj = obj;
}
public void arvaus(Arvuuttaja arvuuttaja) {
int luku = 1 + (int)(Math.random() * 10);
System.out.println("Asiakkaan randomilla arvottu arvaus: " + luku);
arvuuttaja.vertaa(obj, luku);
}
}
<file_sep>package strategy;
import java.util.*;
/**
*
* @author Tiina
*/
public class Main {
public static void main(String[] args) {
List<String> lista = new ArrayList();
String changed = "";
Converter changer = new Converter(new StrategyA());
lista.add("Seppo1");
lista.add("Seppo2");
lista.add("Seppo3");
lista.add("Seppo4");
lista.add("Seppo5");
lista.add("Seppo6");
lista.add("Seppo7");
lista.add("Seppo8");
lista.add("Seppo9");
lista.add("Seppo10");
lista.add("Seppo11");
lista.add("Seppo12");
lista.add("Seppo13");
lista.add("Seppo14");
changed = changer.convert(lista);
System.out.println(changed);
changer.setStrategy(new StrategyB());
changed = changer.convert(lista);
System.out.println(changed);
changer.setStrategy(new StrategyC());
changed = changer.convert(lista);
System.out.println(changed);
}
}
<file_sep>
package composite;
public class Naytonohjain extends AbstractLaiteOsa {
public Naytonohjain (int hinta){
this.hinta = hinta;
}
public String toString(){
return "näytönohjain";
}
}
<file_sep>package prototype;
/**
*
* @author Tiina
*/
public class Main {
public static void main(String[] args) {
Clock clock = new Clock(6,42);
Clock clockclone = clock.clone();
System.out.println("Alkuperäinen: "+clock);
System.out.println("Klooni: "+clockclone);
System.out.println("");
clock.changeTime(5, 25);
clockclone.changeTime(4, 12);
System.out.println("Alkuperäinen: "+clock);
System.out.println("Klooni: "+clockclone);
}
}
|
5fcca06ac10aa957fb6501e5e7c4f365f64037ca
|
[
"Markdown",
"Java"
] | 22 |
Java
|
tiinajor/suunnittelumallit
|
72c282ff532731fc43d5c5e1c0fd78dadbb68f23
|
4595c225d90ff337315c801a0bd7b273f14153ff
|
refs/heads/master
|
<repo_name>hinrikg/conan-mapbox-variant<file_sep>/conanfile.py
from conans import ConanFile
from conans.tools import get
class MapboxVariantConan(ConanFile):
name = 'mapbox-variant'
version = '1.1.2'
author = '<NAME> (<EMAIL>)'
url = 'http://github.com/hinrikg/conan-mapbox-variant'
license = 'MIT'
settings = None
generators = 'cmake'
def source(self):
get('https://github.com/mapbox/variant/archive/v1.1.2.zip')
def package(self):
self.copy('*.hpp', dst='include', src='variant-1.1.2/include', keep_path=True)
self.copy('LICENSE', dst='.', src='variant-1.1.2')
self.copy('LICENSE_1_0.txt', dst='.', src='variant-1.1.2')
<file_sep>/README.md
# mapbox::variant Conan Package
[Conan.io](https://conan.io) package for the [mapbox::variant](https://github.com/mapbox/variant) library.
[](http://www.conan.io/source/mapbox-variant/1.1.2/hinrikg/stable)
mapbox::variant is an alternative to boost::variant for C++11 and C++14
## Usage
$ conan install mapbox-variant/1.1.2@hinrikg/stable
or add the package as a dependency in your conanfile.txt
[requires]
mapbox-variant/1.1.2@hinrikg/stable
For further information on how to use Conan see [the Conan documentation](http://docs.conan.io/)
|
cbd37fabe670dcbab44356a26580b64643981560
|
[
"Markdown",
"Python"
] | 2 |
Python
|
hinrikg/conan-mapbox-variant
|
abc5291b3553667ca944450df7c57a9252be7a86
|
f7f48502027a85193d0b1926a69d081867083777
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// Hangman
//
// Created by <NAME> on 10/13/15.
// Copyright © 2015 cs198-ios. All rights reserved.
//
import UIKit
class HangmanViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{
@IBOutlet weak var picker: UIPickerView!
@IBOutlet weak var HangmanImage: UIImageView!
@IBOutlet weak var Guesses: UILabel!
@IBOutlet weak var KnownString: UILabel!
var pickerData: [String] = [String]()
var pickedItem: String = "A"
var numberOfIncorrectGuesses = 0
var gameOver = false
var initialKnownString = ""
var hangman: Hangman = Hangman()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
hangman.start()
initialKnownString = hangman.knownString!
// Connect data:
self.picker.delegate = self
self.picker.dataSource = self
pickerData = ["A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"]
updateViewAndCheckIfGameOver()
}
@IBAction func TappedNewGameButton(sender: AnyObject) {
numberOfIncorrectGuesses = 0
gameOver = false
hangman.start()
initialKnownString = hangman.knownString!
updateViewAndCheckIfGameOver()
}
@IBAction func TappedGuessButton(sender: AnyObject) {
print(pickedItem)
if (gameOver || hangman.guessedLetters?.containsObject(pickedItem) == true){
} else if (hangman.guessLetter(pickedItem) == false) {
numberOfIncorrectGuesses += 1
}
updateViewAndCheckIfGameOver()
}
@IBAction func TappedStartOverButton(sender: AnyObject) {
numberOfIncorrectGuesses = 0
gameOver = false
hangman.knownString = initialKnownString
hangman.guessedLetters = NSMutableArray()
updateViewAndCheckIfGameOver()
}
func updateViewAndCheckIfGameOver() {
switch (numberOfIncorrectGuesses){
case 0:
HangmanImage.image = UIImage(named: "hangman1.gif")
break
case 1:
HangmanImage.image = UIImage(named: "hangman2.gif")
break
case 2:
HangmanImage.image = UIImage(named: "hangman3.gif")
break
case 3:
HangmanImage.image = UIImage(named: "hangman4.gif")
break
case 4:
HangmanImage.image = UIImage(named: "hangman5.gif")
break
case 5:
HangmanImage.image = UIImage(named: "hangman6.gif")
break
default:
HangmanImage.image = UIImage(named: "hangman7.gif")
gameOver = true
showLoseAlertMessage()
break
}
self.Guesses.text = "Guesses: " + hangman.guesses()
self.KnownString.text = hangman.knownString
if (numberOfIncorrectGuesses < 6 && hangman.answer == hangman.knownString) {
gameOver = true
showWinAlertMessage()
}
}
func showWinAlertMessage() {
let alertController = UIAlertController(title: "Game Over", message: "You Win!", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
}
func showLoseAlertMessage() {
let alertController = UIAlertController(title: "Game Over", message: "You Lose!", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
// The data to return for the row and component (column) that's being passed in
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// This method is triggered whenever the user makes a change to the picker selection.
// The parameter named row and component represents what was selected.
print("called pickerview")
pickedItem = pickerData[row]
}
}
|
4f77ad223d2c5149bc00027a07e73f570b3fec1b
|
[
"Swift"
] | 1 |
Swift
|
choi7326/ios-decal-proj2
|
6921d8cc63f2f85f54cab2371371457924d8b87b
|
9b7cddddec882e9b0fab1cd9fec531d8b76a866b
|
refs/heads/master
|
<repo_name>dvhdez/LSIntroToJS<file_sep>/objects/ex4.js
let obj = {
b: 2,
a: 1,
c: 3,
};
let obj2 = Object.keys(obj);
obj2.forEach(key => console.log(obj[key]));<file_sep>/loopsiterating/ex2.js
/*function times(number1, number2) {
let result = number1 * number2;
console.log(result);
return result;
}
let oneFactorial = times(1, 1);
let twoFactorial = times(2, oneFactorial);
let threeFactorial = times(3, twoFactorial);
let fourFactorial = times(4, threeFactorial);
let fiveFactorial = times(5, fourFactorial);
*/
let weather = 'snowy';
switch (weather) {
case 'sunny':
console.log("It's a beautiful day!");
break;
case 'rainy':
console.log('Grab your umbrella');
break;
case 'snowy':
console.log('Put on your boots!');
break;
default:
console.log("Let's stay inside");
}<file_sep>/functions/multiply.js
/*
let rlSync = require('readline-sync');
let firstName = rlSync.question('What is your first name?\n');
let lastName = rlSync.question('What is your last name?\n');
console.log(`Hello, ${firstName} ${lastName}`);
*/
function multiply(left, right) {
return left * right
}
function getNumber(prompt) {
let rlSync = require('readline-sync');
return parseFloat(rlSync.question(prompt));
}
let left = getNumber('Enter the first number: ');
let right = getNumber('Enter the second number: ');
console.log(`${left} * ${right} = ${multiply (left, right)}`);
|
1513be6915ff0de0fee9685c3e97c3e341871529
|
[
"JavaScript"
] | 3 |
JavaScript
|
dvhdez/LSIntroToJS
|
6171ddb0963a1e560733bece99bbb71b63c2c054
|
7fc111688e7ca50d52372ae263a1b47731c260e2
|
refs/heads/master
|
<file_sep>/*=============================================================================================================================================
Authors: <NAME>, <NAME>, <NAME>
Course: Data Structures
Instructor: <NAME>
TA: <NAME>
Abstract: This program is meant to compare the efficiency of four different collision resolution algorithms (Linear, quadratic, doublehash probing,
and chaining. User enters the Hash Table size, the number of keys, and the load ratio. The user then has the choice to manually
enter the numbers into the hash table or to have the numbers randomly generated. Finally, the user is asked which resolution scheme
is to be used.
Preconditions: The user should follow the prompts. All inputs are numeric (excepting "help").
Postconditions: The average number of comparisons used by the chosen resolution scheme.
=============================================================================================================================================*/
#include <stdlib.h>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <time.h>
using namespace std;
int counter=0;
/*==============================================================Comparison Counter=============================================================*/
//This function, "Comparison Counter" (CC for short) counts up every time a comparison is made
bool CC(string i, string mode, string j){
//Increment counter
counter++;
//Check case
if(mode == "!="){
if (i != j) return true; else return false;
}
else if(mode == "=="){
if (i == j) return true; else return false;
}
else{
cout << "wrong input, user should not ever see this message, fix code" << endl;
counter--;
return false;
}
}
/*=================================================================Class Definition================================================================*/
class HashTable{
private:
// Data
int TableSize; //The range of elements selected within "BucketArray"
int Num_of_keys; // obvious
double LoadRatio; // also obvious
int TotalInsertions;
int TotalComparisons;
string collRes; // collision-resolution scheme
string BucketArray[2000]; //initialized at compile time for most practical ranges. User is unable to change this (due to arrays being static).
struct KeyNode{//An array of keys determined at run time
string value;
KeyNode* next;
} *head, *Key;//pointer to head node and pointer for traversing the array.
// Methods
void InitKeyArray(int Num_of_keys);
int HashFunc(string lekey); //Hash function given in assignment
void FillKeyArray(string choice); //
void PrintTable(); //obvious
void Key2Table(string KeyVal, string collRes);
void ResetTable(); //Resets the table to NULL values
//collision-resolution schemes
void LinearInsert(int index, string KeyVal);
void QuadraInsert(int index, string KeyVal);
void ChainInsert(int index, string KeyVal);
void DoubleHashing(int index, string KeyVal);
public:
// Constructor/Menu
HashTable(); //Constructor (does nothing).
void menu(); //User interactivity.
};
/*===================================================================Constructor===================================================================*/
HashTable::HashTable(){
TableSize = 0;
Num_of_keys = 0;
LoadRatio = 0;
TotalInsertions = 0;
TotalComparisons = 0;
collRes = "";
for(int i = 0; i < 2000; i++){
BucketArray[i] = "NULL";
}
head = NULL;
Key = NULL;
}
/*==================================================================Menu Function==================================================================*/
void HashTable::menu(){
string UserInput;//It's the user's input
//Set TableSize
cout << "To begin, enter a Hash Table size (make sure the number is prime): ";
while(1){
cin >> UserInput;
stringstream(UserInput)>>TableSize; //converts string to int. (returns 0 on failure... e.g. "Words")
if(TableSize > 0 && TableSize <= 2000)//Correct range
break;//exit loop on correct input
else//Incorrect input/range
cout << "Do not falter young padawon, you must enter a number greater than 0. (and <= 2000)\n";
}
//Set Num_of_keys
cout << "Now ";
while(1){
cout << "enter the number of keys: ";
cin >> UserInput;
stringstream(UserInput)>>Num_of_keys; //string to int.
if(Num_of_keys > 0)//no upper limit to number of keys... load ratio catches infinite numbers.
break;//exit loop on correct input
else//Incorrect input/range
cout << "Avast ye scurvy dawg, enter a number greater 'tan zero!\n";
}
//Set LoadRatio
cout << "Please enter a load ratio as a decimal.\nType \"help\" for an example of the correct format.\n";
while(1){
cin >> UserInput;
if(UserInput == "help")
cout << "An example of inputting a load ratio of 25% would be entering \"0.25\" (or \".25\")\n";
else{
stringstream(UserInput)>>LoadRatio;//string to double
if(LoadRatio > 0 && LoadRatio <= 1)//correct range
break;
else{
cout << "Please enter a valid range, input, or command (> 0 and <= 1)\n";
cout << "Try again (remember \"help\"): ";
}
}
}
//Initialize a list for keys
InitKeyArray(Num_of_keys);
//Fill list of keys
cout << "Now ";
while(1){
cout << "please select an option in order to create a table:\n"
<< "(1) Insert the numbers into the hash table manually.\n"
<< "(2) Randomly generate and insert the numbers.\n";
cin >> UserInput;
if(UserInput == "1"){
while(Num_of_keys > 50){
cout << "Are you sure you want to input them manually? You have more than 50 keys. (y/n)\n";
cin >> UserInput;
if(UserInput == "y")
break;
else if(UserInput == "n")
break;
else
cout << "Come on now... input \"y\" or \"n\" for yes or no\n";
}
if(UserInput == "n") continue; //If the user had more than 50 keys, and wanted to reconsider inputting them manually, reset.
FillKeyArray("Manual");
break;
}
else if (UserInput == "2"){
FillKeyArray("RNG");// "RNG" stands for "Random Number Generator"
break;
}
else
cout << "Please enter 1 or 2 to make a choice. (\"help\" is not available here)\n";
}
while(1){
cout<<"Choose a collision resolution scheme:"<<endl<<"1) linear probing"<<endl<<"2) quadratic probing"<<endl;
cout<<"3) double hashing"<<endl<<"4) chaining"<<endl<<"5) exit"<<endl;
cin>>collRes;
while(collRes!="1"&&collRes!="2"&&collRes!="3"&&collRes!="4"&&collRes!="5"){
cout<<"Please enter a number 1 through 5: ";
cin>>collRes;
}
if(collRes == "5") break;
Key = head;//Reset Key to beginning of array
for(int i = 0; (double)(i+1)/(double)TableSize<LoadRatio && i<Num_of_keys; i++){
Key2Table(Key->value, collRes);
Key = Key->next;
}
PrintTable();
ResetTable();
}
return;
}
/*=================================================================Init Key Array==================================================================*/
void HashTable::InitKeyArray(int Num_of_keys){
//first node
head = new KeyNode;
head->value = "NULL";
head->next = NULL;
KeyNode *PrevNode = head;
//the remaining nodes
for(int i = 0; i < Num_of_keys-1; i++){
//creation
KeyNode *NewNode = new KeyNode; //create new node
NewNode->value = "NULL"; //set data
NewNode->next = NULL; //set next to null
//pointers
PrevNode->next = NewNode; //Set PrevNode's pointer
PrevNode = NewNode; //Set PrevNode to current node
}
return;
}
/*==================================================================Hash Function==================================================================*/
int HashTable::HashFunc(string key){
int intkey=0;
stringstream(key)>>intkey;
return intkey % TableSize;
}
/*==================================================================Linear Insert==================================================================*/
void HashTable::LinearInsert(int index, string KeyVal){
int i=1;
while(CC(BucketArray[index+i],"!=","NULL")){
i++;
}
BucketArray[index+i]=KeyVal;
return;
}
/*==================================================================Quadra Insert==================================================================*/
void HashTable::QuadraInsert(int index, string KeyVal){
int i=1;
while(CC(BucketArray[(index+i*i)%TableSize],"!=","NULL")){
i++;
}
BucketArray[(index+i*i)%TableSize]=KeyVal;
return;
}
/*===================================================================Chain Insert==================================================================*/
void HashTable::ChainInsert(int index, string KeyVal){
BucketArray[index]=BucketArray[index]+" & "+KeyVal;
return;
}
/*==================================================================Double Hashing=================================================================*/
void HashTable::DoubleHashing(int index, string KeyVal){
int intkey;
stringstream(KeyVal)>>intkey;
int i=1;
while(CC(BucketArray[(index+i*(20-intkey%20))%TableSize],"!=","NULL")){
i++;
}
BucketArray[(index+i*(20-intkey%20))%TableSize]=KeyVal;
return;
}
/*===================================================================Key to Table==================================================================*/
void HashTable::Key2Table(string KeyVal, string collRes){
int index = HashFunc(KeyVal);
TotalInsertions++;
if(CC(BucketArray[index],"==","NULL")){
BucketArray[index]=KeyVal;
}
else if(collRes=="1"){
LinearInsert(index, KeyVal); //collision resolution method
}
else if(collRes=="2"){
QuadraInsert(index, KeyVal);
}
else if(collRes=="3"){
DoubleHashing(index, KeyVal);
}
else if(collRes=="4"){
ChainInsert(index, KeyVal);
}
return;
}
//void HashTable::ArrayInit(){
//return;
// }
/*==================================================================Fill Key Array=================================================================*/
void HashTable::FillKeyArray(string choice){
/*int counter=0;
int index;
string KeyVal;*/
Key = head;
if(choice == "Manual"){
for(int i = 0; i < Num_of_keys; i++){
cout << "input key #" << i+1 << ": ";
cin >> Key->value;
Key = Key->next;
}
}
else if(choice == "RNG"){
srand(time(NULL));
for(int i = 0; i < Num_of_keys; i++){
int RandNum;
stringstream ss;
RandNum = (rand()%100000+rand()%100000+rand()%100000+rand()%100000)/4; //average of 4 random numbers "to avoid statistical biasing"
ss << RandNum; Key->value = ss.str(); //convert type int to type string and store in Key->value.
Key = Key->next;//increment
}
}
//PrintTable();
return;
}
/*==================================================================Reset Table====================================================================*/
void HashTable::ResetTable(){
for(int i = 0; i < TableSize; i++){
BucketArray[i] = "NULL";
}
return;
}
/*==================================================================Print Table====================================================================*/
void HashTable::PrintTable(){
TotalComparisons = counter;
counter = 0;
if(TableSize<=50){
cout<<"[";
for(int k=0; k<TableSize-1; k++){
if(k%10 == 0 && k!=0)//formats the table to 10 elements per line
cout << "\n ";
cout<<BucketArray[k]<<",";
}
cout<< BucketArray[TableSize-1] << "]\n";
}
cout << "The average number of comparisons: " << fixed << setprecision(3) << (double)TotalComparisons/(double)TotalInsertions << endl;
TotalInsertions = 0;
return;
}
/*=======================================================================Main======================================================================*/
int main(){
HashTable HashBrowns;
HashBrowns.menu();
return 0;
}
<file_sep>
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include "unistd.h"
using namespace std;
int counter=0;
//==============================================================Comparison Counter=============================================================\\
//This function, "Comparison Counter" (CC for short) counts up every time a comparison is made
bool CC(int i, string mode, int j){
//Increment counter
counter++;
//Check case
if(mode == "<"){
if (i < j) return true; else return false;
}
else if(mode == "<="){
if (i <= j) return true; else return false;
}
else if(mode == ">"){
if (i > j) return true; else return false;
}
else if(mode == ">="){
if (i >= j) return true; else return false;
}
else if(mode == "=="){
if (i == j) return true; else return false;
}
else{
cout << "wrong input, user should not ever see this message, fix code" << endl;
counter--;
return false;
}
}
//================================================================Insertion Sort===============================================================\\
template <typename T>
//takes in a vector of any type and does insert sort:
void insertionSort(vector<T> &v){
unsigned int i = 0;
unsigned int j = 0;
T temp = 0;
for(i = 1; i < v.size(); i++){
j = i;
//when i goes up temp stores the value at array[j] and assigns the one before it to array[j] and then the [j-1] becomes the old [j] write it out if you wanna see
while(CC(j, ">", 0) && CC(v[j-1], ">", v[j])){
temp = v[j];
v[j] = v[j-1];
v[j-1] = temp;
j--;
}
}
}
//=================================================================Bubble Sort=================================================================\\
template <typename T>
void bubbleSort(vector<T> &v){
bool sorted = false;
while (!sorted) {
sorted = true;
for (int i = 0; i < v.size() - 1; i++) {
if (CC(v[i], ">", v[i + 1])){
sorted = false;
T tmp = v[i];
v[i] = v[i + 1];
v[i + 1] = tmp;
}
}
}
}
//==================================================================Merge Sort=================================================================\\
template<typename T>
void merge(vector<T> &a, vector<T> &b, vector<T> &ret){
unsigned int ai = 0;
unsigned int bi = 0;
//vector<int> ret;
while(ai < a.size() || bi < b.size()){ // pull numbers off!
if(CC(ai, "==", a.size())){ // a is done
ret.push_back(b[bi]);
bi++;
}else if(CC(bi, "==", b.size())){ // b is done
ret.push_back(a[ai]);
ai++;
}else if(CC(a[ai], "<", b[bi])){
ret.push_back(a[ai]);
ai++;
}else{
ret.push_back(b[bi]);
bi++;
}
}
}
template <typename T>
void mergeSort(vector<T> &v){ // In place!
// base case!
if(CC(v.size(), "<=", 1)){
return;
}
// cut list into two halves
unsigned int middle = v.size() / 2;
vector<T> left;
left.reserve(v.size());
vector<T> right;
right.reserve(v.size());
for(unsigned int i = 0; i < v.size() ;i++){
if(CC(i, "<", middle)){
left.push_back(v[i]);
}else{
right.push_back(v[i]);
}
}
mergeSort(left);
mergeSort(right);
// merge them together!
v.clear();
merge(left, right, v);
}
//==================================================================Quick Sort=================================================================\\
template <typename T>
void quickSort(vector<T> &v, int left, int right) {
int i = left, j = right;
T tmp;
T pivot = v[(left + right) / 2];
/* partition section */
while (CC(i, "<=", j)){
while (CC(v[i], "<", pivot))
i++;
while (CC(v[j], ">", pivot))
j--;
if (CC(i, "<=", j)){
tmp = v[i];
v[i] = v[j];
v[j] = tmp;
i++;
j--;
}
};
/* recursion section*/
if (CC(left, "<", j))
quickSort(v, left, j);
if (CC(i, "<", right))
quickSort(v, i, right);
}
//=================================================================Hybrid Sort=================================================================\\
//-------------------------------------------------------------Merge sort (hybrid)-------------------------------------------------------------\\
template <typename T>
void mergeHybridSort(vector<T> &v, string smaller,int threshold){ // In place!
// base case!
if(CC(v.size(), "<=", 1)){
return;
}
if(v.size() < threshold){
if(smaller == "0"){
bubbleSort(v);
return;
}
else if(smaller == "1"){
insertionSort(v);
return;
}
}
// cut list into two halves
unsigned int middle = v.size() / 2;
vector<T> left;
left.reserve(v.size());
vector<T> right;
right.reserve(v.size());
for(unsigned int i = 0; i < v.size() ;i++){
if(CC(i, "<", middle)){
left.push_back(v[i]);
}else{
right.push_back(v[i]);
}
}
mergeHybridSort(left, smaller, threshold);
mergeHybridSort(right, smaller, threshold);
// merge them together!
v.clear();
merge(left, right, v);
}
//-------------------------------------------------------------Quick Sort (hybrid)-------------------------------------------------------------\\
template <typename T>
void quickHybridSort(vector<T> &v, int left, int right, string smaller ,int threshold) {
if(right-left < threshold){//if less than threshold, do basic sort...
vector<T> CopyVec;
for(int i = left; i <= right; i++){
CopyVec.push_back(v[i]);
}
//"smaller" is the user's choice of basic sort
if(smaller == "0"){
bubbleSort(CopyVec);
}
else if(smaller == "1"){
insertionSort(CopyVec);
}
//copy the sorted elements back into the original vector in the correct order
for(int i = 0; i <= right-left; i++){
v[i+left] = CopyVec[i];
}
}
else{//...otherwise continue quicksort
int i = left, j = right;
T tmp;
T pivot = v[(left + right) / 2];
/* partition section */
while (CC(i, "<=", j)) {
while (CC(v[i], "<", pivot))
i++;
while (CC(v[j], ">", pivot))
j--;
if (CC(i, "<=", j)){
tmp = v[i];
v[i] = v[j];
v[j] = tmp;
i++;
j--;
}
}
/* recursion section*/
if (CC(left, "<", j))
quickHybridSort(v, left, j, smaller, threshold);
if (CC(i, "<", right))
quickHybridSort(v, i, right, smaller, threshold);
}
}
//-----------------------------------------------------------------Hybrid Sort-----------------------------------------------------------------\\
template <typename T>
void hybridSort(vector<T> &v, string larger, string smaller, int threshold){
if(v.size() > threshold){
//User picks Merge Sort
if(larger == "0"){
mergeHybridSort(v, smaller, threshold);
return;
}
//User picks Quick Sort
else if(larger == "1"){
quickHybridSort(v, 0, v.size()-1, smaller, threshold);
return;
}
}
else{
//User accidentally enters an invalid number for threshold.
cout << "Do not enter a threshold value greater than the size of the array!" << endl;
}
}
//=============================================================================================================================================\\
//<<===========================================================END SORT ALGORITHMS===========================================================>>\\
//<<=========================================================BEGIN PROGRAM FUNCTIONS=========================================================>>\\
//===========================================================================================================================================>>\\
//-----------------------------------------------------------------Display List----------------------------------------------------------------\\
template<typename T>
void displayList(vector<T> &v){
cout<<"[";
for(unsigned int k=0; k<v.size()-1; k++){
cout<<v[k]<<",";
}
cout<<v[v.size()-1]<<"]"<<endl;
return;
}
//----------------------------------------------------------------List Generator---------------------------------------------------------------\\
template<typename T>
vector<T> listGenerator(vector<T> &A, int elements){ //assigns values to the inputted array.
srand(time(0));
int number = 0;
for(int k=0; k<elements; k++){
number = rand() % 1000;
A.push_back(number);
}
return A;
}
//----------------------------------------------------------------Menu Function----------------------------------------------------------------\\
template <typename T>
void menuGenerator(){
cout<<"Authors: <NAME>, <NAME>, <NAME>."<<endl;
cout<<"Description: This program is meant to analyze and compare the effectiveness of various sorting algorithms against each other. ";
cout<<"The algorithms compared are Merge Sort, Quick Sort, Insertion Sort, and Bubble Sort. The user is asked to enter a threshold value ";
cout<<"which will determine how long each algorithm is given to sort the elements. The user will then be asked for the size of ";
cout<<"the vector to be sorted. Sizes of over 100 elements will be automatically generated, while if the user inputs a size less than ";
cout<<"or equal to 100 the user will be given the option to either insert a vector manually or to have one automatically generated. "<<endl;
cout<<"BEGIN"<<endl;
cout<<"Please enter the threshold value for hybrid sort: "; //Threshold value is length for use by hybrid
int threshold;
cin>>threshold; cout<<endl;
cout<<"Enter the quantity of elements to be sorted: ";
unsigned int elements;
cin>>elements; cout<<endl;
vector<T> templist;
vector<T> thelist;
if(elements <= 100){
bool makelist=false;
cout<<"Would you like to manually enter the list? (1 for 'yes', 0 for 'no'. If '0', the list will be generated for you): ";
cin>>makelist;
if(makelist){
cout<<"Please begin entering the list:" << endl;
T tempval;
for(unsigned int k=0; k<elements; k++){ // user must enter as many elements as they ask for.
cout<<k<<": ";
cin>>tempval;
thelist.push_back(tempval); // there is no check to make sure the entry is valid.
}
}
else if(!makelist){
thelist=listGenerator(templist, elements); //the user said no to manually made list. generate a list for them.
}
else{
cout<<"invalid response start over"<<endl;
return;
}
bool display=false;
cout<<"Would you like the list to be displayed? (1 for 'yes', 0 for 'no'): ";
cin>>display;
if(display){
displayList(thelist);
}
}
else{
thelist = listGenerator(templist, elements);
}
bool running = true;
do{
vector<T> copyvector = thelist;
int choice;
cout << "What sort do you want to do?:" << endl;
cout << "1) Bubble Sort" << endl;
cout << "2) Insert Sort" << endl;
cout << "3) Quick Sort" << endl;
cout << "4) Merge Sort" << endl;
cout << "5) Hybrid Sort" << endl;
cin >> choice;
if(choice == 1){
bubbleSort(copyvector);
if(elements <= 100){
displayList(copyvector);
}
}
else if(choice == 2){
insertionSort(copyvector);
if(elements <= 100){
displayList(copyvector);
}
}
else if(choice == 3){
quickSort(copyvector,0, thelist.size()-1);
if(elements <= 100){
displayList(copyvector);
}
}
else if(choice == 4){
mergeSort(copyvector);
if(elements <= 100){
displayList(copyvector);
}
}
else if(choice == 5){
string larger = "";
string smaller = "";
cout << "What do you want the sort to be if the list is larger than the threshold?" << endl;
cout << "0) Merge Sort" << endl;
cout << "1) Quick Sort" << endl;
cin >> larger;
if(larger != "0" && larger != "1"){
cout << "You seem to have not been able to enter 0 or 1 please restart." << endl;
continue;
}
cout << "What do you want the sort to be if the list is smaller than the threshold?" << endl;
cout << "0) Bubble Sort" << endl;
cout << "1) Insert Sort" << endl;
cin >> smaller;
if(smaller != "0" && smaller != "1"){
cout << "You seem to have not been able to enter 0 or 1 please restart." << endl;
continue;
}
hybridSort(copyvector,larger, smaller, threshold);
if(elements <= 100){
cout << "Original list: ";
displayList(thelist);
cout << endl;
cout << "Sorted list: ";
displayList(copyvector);
cout << endl;
}
}
cout<<"Number of comparisons: "<<counter<<endl;
cout << "Do you want to choose a sort again? Enter 1 if you want to and anything else if you do not.";
string runningbool = "boo";
cin >> runningbool;
if(runningbool == "1"){
running = true;
}
else{
running = false;
}
counter=0; //global variable counting number of comparisons.
}
while(running);
}
//---------------------------------------------------------------------Main--------------------------------------------------------------------\\
int main(){
menuGenerator<int>();
return 0;
}
<file_sep>//Author: <NAME>, <NAME>, <NAME>
//Course title: Data Structures
//Course Number: 20CS2028
//Abstract: This program finds the area and parimeter of the shape chosen. The polygons are all regular. Only special polygons are isoceles, equalateral triangles and squares and rectangles which are the only quadrilaterals calculated. We did not see a scalene triangle req. so dont try that. You must choose from the list the program gives you.
//Preconditions: Follow the prompts. Enter the name exactly as it appears or else.
//Postconditions: Answer printed out. Or a giant pikachu will appear and eat you.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
//every class is derived from this polygon class
class Polygon{
public:
virtual float area()= 0;
virtual int perimeter()=0;
protected:
float area_poly;
int perimeter_poly;
};
//there are also types of triangles hence the use of more inheritance
class Triangle: public Polygon{
public:
virtual float area(){
return 0;
}
virtual int perimeter(){
return 0;
}
};
class Isosceles: public Triangle{
//todo take x and y find hypotenuse
//todo find area
//todo add 3 sides together to find perimeter
public:
int iso_area(int base, int other){
float height;
float answer;
height= sqrt(pow(other,2)-pow(base/2,2));
answer=base*height/2;
return answer;
}
int iso_perimeter(int x, int y){
return x+2*y;
}
void response(){
int side1=0;
int side2=0;
cout << "Please enter the base of the triangle.";
cin>>side1;
cout<<"Please enter the length of one of the two equal sides.";
cin>>side2;
area_poly = iso_area(side1, side2);
perimeter_poly = iso_perimeter(side1, side2);
if((side1 + side2) < side2){
cout << "Who you tryna fool these sides can't make up a triangle";
}
else if((side2+side2)< side1){
cout << "Who you tryna fool these sides can't make up a triangle";
}
else
cout<< "The area is "<< area() << " and the perimeter is " << perimeter() <<endl;
}
virtual float area(){
return area_poly;
}
virtual int perimeter(){
return perimeter_poly;
}
};
class Equallateral: public Triangle{
//todo find area using side basic geometry remember the angles and stuff im too lazy
public:
float equal_area(int side){
return (pow(3, .5)/4)*pow(side, 2);
}
int equal_perimeter(int side){
return side*3;
}
void response(){
int side = 0;
cout << "Please enter one of the sides of the triangle.";
cin >> side;
area_poly = equal_area(side);
perimeter_poly = equal_perimeter(side);
cout << "The area is "<< area() << " and the perimeter is " << perimeter() <<endl;
}
virtual float area(){
return area_poly;
}
virtual int perimeter(){
return perimeter_poly;
}
};
class Quadrilateral: public Polygon{
public:
virtual float area(){
return 0;
}
virtual int perimeter(){
return 0;
}
};
class Square: public Quadrilateral{
public:
int s_area(int side){
return side * side;
}
int s_perimeter(int side){
return side * 4;
}
void response(){
int side = 0;
cout << "Please enter the length of a side of the square ";
cin >> side;
area_poly = s_area(side);
perimeter_poly = s_perimeter(side);
cout << "The area is "<< area() << " and the perimeter is " << perimeter() <<endl;
}
virtual float area(){
return area_poly;
}
virtual int perimeter(){
return perimeter_poly;
}
};
class Rectangle: public Quadrilateral{
public:
int r_area(int height, int width){
return height * width;
}
int r_perimeter(int height, int width){
return (2 * height) + (2 * width);
}
void response(){
int height = 0;
int width = 0;
cout << "Please enter the height: ";
cin >> height;
cout << "Enter the width now: ";
cin >> width;
area_poly = r_area(height, width);
perimeter_poly = r_perimeter(height, width);
cout << "The area is "<< area() << " and the perimeter is " << perimeter() <<endl;
}
virtual float area(){
return area_poly;
}
virtual int perimeter(){
return perimeter_poly;
}
};
class Pentagon: public Polygon{
//theres a weird formula for area implement it
public:
float p_area(int side){
return (1.0/4.0)*sqrt(5*(5+2*sqrt(5)))*pow(side, 2);
}
int p_perimeter(int side){
return side * 5;
}
void response(){
cout << "Please enter the length of the side.";
int side = 0;
cin >> side;
area_poly = p_area(side);
perimeter_poly = p_perimeter(side);
cout << "The area is "<< area() << " and the perimeter is " << perimeter() <<endl;
}
virtual float area(){
return area_poly;
}
virtual int perimeter(){
return perimeter_poly;
}
};
class Hexagon: public Polygon{
//implement area of hexagon
public:
float h_area(int side){
return (3.0/2.0)*sqrt(3.0)*pow(side,2);
}
int h_perimeter(int side){
return side * 6;
}
void response(){
cout << "Please enter the length of the side.";
int side = 0;
cin >> side;
area_poly = h_area(side);
perimeter_poly = h_perimeter(side);
cout << "The area is "<< area() << " and the perimeter is " << perimeter() <<endl;
}
virtual float area(){
return area_poly;
}
virtual int perimeter(){
return perimeter_poly;
}
};
class Octagon: public Polygon{
//implement area of octogon
public:
float o_area(int side){
return 2*(1+sqrt(2))*pow(side, 2);
}
int o_perimeter(int side){
return side * 8;
}
void response(){
cout << "Please enter the length of the side.";
int side = 0;
cin >> side;
area_poly = o_area(side);
perimeter_poly = o_perimeter(side);
cout << "The area is "<< area() << " and the perimeter is " << perimeter() <<endl;
}
virtual float area(){
return area_poly;
}
virtual int perimeter(){
return perimeter_poly;
}
};
int main() {
string polygon_type = "";
string secondary_type = "";
cout << "Is your polygon a triangle, quadrilateral, pentagon, hexagon or octagon?\n";
cin >> polygon_type;
if(polygon_type == "triangle"){
cout << "Is your triangle a isosceles or equalateral triangle?";
cin >> secondary_type;
if(secondary_type == "isosceles"){
Isosceles triangle;
triangle.response();
}
else if(secondary_type =="equalateral"){
Equallateral triangle;
triangle.response();
}
}
else if(polygon_type == "quadrilateral"){
cout << "Is your quadrilateral a square or a rectangle? ";
cin >> secondary_type;
if(secondary_type == "square"){
Square s;
s.response();
}
else if(secondary_type == "rectangle"){
Rectangle r;
r.response();
}
}
else if(polygon_type == "pentagon"){
Pentagon p;
p.response();
}
else if(polygon_type == "hexagon"){
Hexagon h;
h.response();
}
else if(polygon_type == "octagon"){
Octagon o;
o.response();;
}
else{
cout << "Something went wrong. Please try again or just give me an A and be on your merry way :) I used to be a ta too you know. I know the pain.";
}
return 0;
}
<file_sep>/*
Authors: <NAME>, <NAME>, <NAME>
Course: Data Structures
Instructor: <NAME>
TA: <NAME>
Abstract: The program times 3 different algorithms for checking different sized arrays for repeated elements.
Preconditions: You may have to uncomment things if you want to test sorting algorithms and other things. We left them in the state when we find the size of the array for which the isunique algorithms run in one minute or less.
Postconditions: returns the times of the different algorithms on different sized arrays.
*/
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<ctime>
#include<vector>
using namespace std;
void randomArray(int length, int A[]){ //assigns values to the inputted array.
/* for(int k=0; k<length; k++){
A[k]=length-k;
}
int temp;
for(int k=0; k<length; k=k+2){
temp=A[k+1];
A[k+1]=A[k];
A[k]=temp;
}*/
for(int k=0; k<length; k++){
A[k]=k;
}
return;
}
void PrintArray(int length, int A[]){
if(length>20){
return;
}
std::cout << "Given: [";
for(int i = 0; i < length-1; i++){
std::cout << A[i] << ", ";
}
std::cout << A[length-1] << "]" << std::endl;
return;
}
void selectionSort(int tharray[], int length){ //selection sort
int minni=0;
int swapper;
for(int j=0; j<length-1; j++){
for(int k=j+1; k<length; k++){
if(tharray[k]<tharray[minni]){
minni=k;
}
}
if(minni!=j){
swapper=tharray[minni];
tharray[minni]=tharray[j];
tharray[j]=swapper;
}
}
return;
}
void bubbleSort(int A[], int length){ //classic bubble sort
bool done=false;
int temp;
while(!done){
done=true;
for(int k=1; k< length; k++){
if(A[k]< A[k-1]){
temp=A[k];
A[k]=A[k-1];
A[k-1]=temp;
done=false;
}
}
}
return;
}
void vectorSelectSort(vector<int> A){//helper function for bucketsort
int tempArray[A.size()];
for(unsigned int k=0; k<A.size(); k++){ //make vector into array
tempArray[k]=A[k];
}
A.clear();
selectionSort(tempArray, A.size());
for(unsigned int k=0; k<A.size(); k++){ //put sorted array into vector
A.push_back(tempArray[k]);
}
return;
}
void QuickSort(int Array[], int first, int last){
int i = first, j = last;
int tmp;
int pivot = Array[first + (last-first)/2];
// partition
while (i <= j) {
while (Array[i] < pivot)
i++;
while (Array[j] > pivot)
j--;
if (i <= j) {
tmp = Array[i];
Array[i] = Array[j];
Array[j] = tmp;
i++;
j--;
}
};
// recursion
if (first < j)
QuickSort(Array, first, j);
if (i < last)
QuickSort(Array, i, last);
return;
}
void bucketSort(int Array[], int length){
int minni=Array[0];
int maxxi=Array[0];
for(int k=0; k<length; k++){
if(Array[k]<minni){
minni=Array[k];
}
if(Array[k]>maxxi){
maxxi=Array[k];
}
}
if(length<=20){
selectionSort(Array,length);
//cout<<"SELECTION SORT USED"<<endl;
}
else{
int fakerange=(maxxi-minni)-((maxxi-minni)%5);
vector<int> firstVector; //buckets
vector<int> secondVector;
vector<int> thirdVector;
vector<int> fourthVector;
vector<int> fifthVector;
int firstMax=fakerange/5+minni;
int secondMax=(fakerange/5)*2+minni;
int thirdMax=(fakerange/5)*3+minni;
int fourthMax=(fakerange/5)*4+minni;
for(int k=0; k<length; k++){ //sorts the array into the buckets
if(Array[k]<=firstMax){
firstVector.push_back(Array[k]);
}
else if(Array[k]<=secondMax){
secondVector.push_back(Array[k]);
}
else if(Array[k]<=thirdMax){
thirdVector.push_back(Array[k]);
}
else if(Array[k]<=fourthMax){
fourthVector.push_back(Array[k]);
}
else if(Array[k]>fourthMax){
fifthVector.push_back(Array[k]);
}
}
vectorSelectSort(firstVector); //sorts the vectors with selection sort
vectorSelectSort(secondVector);
vectorSelectSort(thirdVector);
vectorSelectSort(fourthVector);
vectorSelectSort(fifthVector);
cout<<"firstVec: ";
for(unsigned int k=0; k<firstVector.size(); k++){
cout<<firstVector[k];
}
int counter=0;
for(unsigned int k=counter; k<firstVector.size(); k++){ //combines the vectors into the array
Array[k]=firstVector[k];
}
counter=firstVector.size();
for(unsigned int k=counter; k<counter+secondVector.size(); k++){
Array[k]=secondVector[k];
}
counter=counter+secondVector.size();
for(unsigned int k=counter; k<counter+thirdVector.size(); k++){
Array[k]=thirdVector[k];
}
counter=counter+thirdVector.size();
for(unsigned int k=counter; k<counter+fourthVector.size(); k++){
Array[k]=fourthVector[k];
}
counter=counter+fourthVector.size();
for(unsigned int k=counter; k<counter+fifthVector.size(); k++){
Array[k]=fifthVector[k];
}
}
return;
}
bool isUnique1(int A[], int first, int last){
if(first>=last){
return true;
}
if(!isUnique1(A, first, last-1)){
return false;
}
if(!isUnique1(A, first+1, last)){
return false;
}
return (A[first]!=A[last]);
}
bool isUnique2(int A[], int first, int last){
if(first>=last){
return true;
}
for(int k=first; k<last; k++){
for(int j=k+1; j<last; j++){
if(A[k]==A[j]){
return false;
}
}
}
return true;
}
bool isUnique3(int A[], int first, int last){
if(first>=last){
return true;
}
selectionSort(A,last);//assuming bucket sort is the fastest
for(int i=first; i<last; i++){
if(A[i]==A[i+1]){
return false;
}
}
return true;
}
int main(){
// int Array[length];
// cout << "Array has been initialized" << endl;
// randomArray(length,Array);
/* cout<<"Array: ";
for(int k=0; k<length; k++){
cout<<Array[k]<<"|";
}
cout<<endl;
// cout << "After random generation" << endl;
int bubbleArray[length];
for(int k=0; k<length; k++){ //makes bubbleArray a copy of Array
bubbleArray[k]=Array[k];
}
bubbleSort(bubbleArray, length);
cout << "bubbleArray: ";
for(int k=0; k<length; k++){
cout<<bubbleArray[k]<<"|";
}cout<<endl;
int selectionArray[length];
for(int k=0; k<length; k++){ //makes selectionArray a copy of Array
selectionArray[k]=Array[k];
}
selectionSort(selectionArray, length); // selection sort
cout<<"selectionArray: ";
for(int k=0; k<length; k++){
cout<<selectionArray[k]<<"|";
}cout<<endl;
int QuickArray[length];
for(int k=0; k<length; k++){ //makes QuickArray a copy of Array
QuickArray[k]=Array[k];
}
QuickSort(QuickArray, 0, length-1);
cout << "quickArray: ";
for(int k=0; k<length; k++){
cout<<QuickArray[k]<<"|";
}
cout << endl;
*/
for(int length=0; length<34; length++){
int Array[length];
randomArray(length,Array);
clock_t start1;
start1 = std::clock();
if(isUnique1(Array,0,length)==true){
cout<<"Algorithm 1 says it is unique."<< endl;
}
double time1=(std::clock() - start1) / (double)(CLOCKS_PER_SEC / 1000);
cout<<"length of "<<length<<" time--> isUnique1: "<<time1/1000.0<<" sec"<<endl;
}
for(int length=0; length<=195000; length=length+5000){
int Array[length];
randomArray(length,Array);
std::clock_t start2;
start2 = std::clock();
if(isUnique2(Array, 0, length)==true){
cout<<"Algorithm 2 says it is unique."<< endl;
}
double time2=(std::clock() - start2) / (double)(CLOCKS_PER_SEC / 1000);
cout<<"length of "<<length<<" time--> isUnique2: "<<time2/1000.0<<" sec"<<endl;
}
for(int length=0; length<150000; length=length+5000){
int Array[length];
randomArray(length,Array);
std::clock_t start3;
start3 = std::clock();
PrintArray(length,Array);
if(isUnique3(Array, 0, length)==true){
cout<<"Algorithm 3 says it is unique."<< endl;
}
double time3=(std::clock() - start3) / (double)(CLOCKS_PER_SEC / 1000);
cout<<"length of "<<length<<" time--> isUnique3: "<<time3/1000.0<<" sec"<<endl;
}
return 0;
}
<file_sep>/*
Authors: <NAME>, <NAME>, <NAME>
Course: Data Structures
Instructor: <NAME>
TA: <NAME>
Abstract: This program creates a gmail of given communications from the user. the program counts the subjects with the
same name and will let the user know how many emails are within a given communication. Once the user is done with
creating the first gmail, the copy constructor copies gmail and creates "Copymail", where you are able to test or
verify that the copy constructor works, or add more to Copymail.
Preconditions: User commands - "Display", "Insert", "Delete", and "Finish". Follow on-screen commands to add subjects.
Postconditions: An email to review all the subjects you entered.
*/
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<ctime>
#include<string>
#include<vector>
using namespace std;
/*=======================================================================================================================*/
//Inbox Class
class Inbox{
private:
int Number_of_Comms;
//Communication is the main make-up of Inbox It provides a list of Subjects to the user.
struct Communication{
string Subject;
int Number_of_Emails;
Communication *next; //Next string of emails
Communication *previous; //Previous string of emails
//Emails are the linked list within communication. Each node provides message details.
struct Email{
//Email details
string To;
string From;
string Message;
//These pointers navigate the linked list.
Email *Older_Email; // "*next"
Email *Newer_Email; // "*previous"
};//End Email
//This is the pointer that points to the front of an "Email" string (or top of the "Email" stack).
Email *NewestEmail; // "*head" (or "*top" of stack) of "Email"
};//End Communication
Communication *NewestComm; //Points to first Communication ("*top" of stack)
public:
//Constructors & Destructor
Inbox(); //Default Constructor
~Inbox(); //Destructor
Inbox(const Inbox& object); //Copy constructor, unsure of what to name the object. Maybe just "object"?
//Main methods for Inbox.
void Menu();
void InsertEmail(); //Prompts user for email information and adds it to linked list(s)
void DeleteCommunication(string subject); //Deletes a communication having a given subject.
Communication* SearchCommunication(string keyword); //Searches Inbox for a given Subject, will ask user for subject.
void DisplayInbox();
};//End Inbox
/*=======================================================================================================================*/
//Normal Constructor
Inbox::Inbox(){
Number_of_Comms = 0;
NewestComm = NULL;
}
/*=======================================================================================================================*/
//Copy Constructor
/*It should be noted that CommTraveler and EmailTraveler travel through the object's pointers
to acquire data. These pointers are not in any way related to the new Inbox being made.*/
Inbox::Inbox(const Inbox& object){
Number_of_Comms = object.Number_of_Comms;
//CommTraveler will travel through object's Comm Linked List to acquire data.
Communication *CommTraveler = object.NewestComm;
//Initial Setup for Comm loop
Communication *TempComm = new Communication();
//NULL node (not sure if this is necessary or not)
TempComm->Subject = ""; TempComm->Number_of_Emails = 0;
TempComm->previous = NULL; TempComm->next = NULL;
//Temporarily sets head pointer to NULL node, will adjust after creation.
NewestComm = TempComm;
while(CommTraveler != NULL){
Communication *newComm = new Communication();
//Get/Set data
newComm->Subject = CommTraveler->Subject;
newComm->Number_of_Emails = CommTraveler->Number_of_Emails;
/*---------------------------------------------Start Email Linked List Setup---------------------------------------------*/
//Email Traveler will travel through each email within CommTraveler to acquire data.
Communication::Email *EmailTraveler = CommTraveler->NewestEmail;
//Initial Setup for Email loop.
Communication::Email *TempEmail = new Communication::Email();
//NULL node (again, not sure if this is necessary or not)
TempEmail->To = ""; TempEmail->From = ""; TempEmail->Message = "";
TempEmail->Newer_Email = NULL; TempEmail->Older_Email = NULL;
//Again, temporarily sets head pointer to NULL node, will adjust after creation.
newComm->NewestEmail = TempEmail;
while(EmailTraveler != NULL){
Communication::Email *newEmail = new Communication::Email();
//Get/Set data
newEmail->To = EmailTraveler->To;
newEmail->From = EmailTraveler->From;
newEmail->Message = EmailTraveler->Message;
//Assignment of pointers. Remember Older_Email is "*next" and Newer_Email is "*previous"
TempEmail->Older_Email = newEmail; //Set the previous node's "*next" to current node.
newEmail->Newer_Email = TempEmail; //Set current's "*previous" to previous node, or NULL node if first loop
TempEmail = newEmail; //Set previous node to current node.
// newEmail = newEmail->Older_Email;
EmailTraveler = EmailTraveler->Older_Email; //Progress to next email
}
//Adjust back end
TempEmail->Older_Email = NULL; //Set last "*next" to NULL
//Adjust front end
if(newComm->NewestEmail->Older_Email != NULL){
newComm->NewestEmail = newComm->NewestEmail->Older_Email;//Move head from NULL node to first node
delete newComm->NewestEmail->Newer_Email; //Delete initial NULL node;
newComm->NewestEmail->Newer_Email = NULL; //Set first "*previous" to NULL
}
else{
delete newComm->NewestEmail;
newComm->NewestEmail = NULL;
}
/*----------------------------------------------End Email Linked List Setup----------------------------------------------*/
//Assignment of pointers. For Communication nodes
TempComm->next = newComm;
newComm->previous = TempComm;
TempComm = newComm;
// newComm = newComm->next;
CommTraveler = CommTraveler->next;//Progress to the next communication
}
//Adjust back end
TempComm->next = NULL;//Set last "*next" to NULL
//Adjust front end
if(NewestComm->next != NULL){
NewestComm = NewestComm->next;//Move head from NULL node to first node
delete NewestComm->previous; //Delete initial NULL node
NewestComm->previous = NULL; //Set first "*previous to NULL
}
else{
delete NewestComm;
NewestComm = NULL;
}
}//End Copy Constructor
/*=======================================================================================================================*/
//Destructor
Inbox::~Inbox(){
if(NewestComm != NULL){
while(NewestComm->next!=NULL){
//Delete emails within communication, if there exist any.
if(NewestComm->NewestEmail != NULL){
while(NewestComm->NewestEmail->Older_Email != NULL){
NewestComm->NewestEmail = NewestComm->NewestEmail->Older_Email;
delete NewestComm->NewestEmail->Newer_Email;
}
delete NewestComm->NewestEmail;
}
//Delete communication node
NewestComm = NewestComm->next;
delete NewestComm->previous;
}
delete NewestComm;
}
Number_of_Comms = 0;
}//End Destructor
/*=======================================================================================================================*/
//InsertEmail()
void Inbox::InsertEmail(){
vector<string> ArrOfStrs; //"Array Of Strings"
string UserInput;
cout << "Enter the subject of your email. (Type \"done\" to finish)\n";
do{
getline(cin, UserInput);
ArrOfStrs.push_back(UserInput);
}while(UserInput != "done");
Communication* SubjectGiven;
for(int i = 0; i < ArrOfStrs.size()-1; i++){
SubjectGiven = SearchCommunication(ArrOfStrs[i]);
if(SubjectGiven == NULL){
SubjectGiven = new Communication;
SubjectGiven->Subject = ArrOfStrs[i];
SubjectGiven->Number_of_Emails = 1;
SubjectGiven->next = NewestComm;
SubjectGiven->previous = NULL;
SubjectGiven->NewestEmail = NULL;
if(NewestComm != NULL){
NewestComm->previous = SubjectGiven;
}
NewestComm = SubjectGiven;
Number_of_Comms++;
}
else{
//Increment number of Emails
SubjectGiven->Number_of_Emails++;
//Check if subject is already at front. If so, continue to next iteration of loop.
if(NewestComm->Subject == SubjectGiven->Subject){
continue;
}
//If not, adjust neighboring nodes' pointers...
SubjectGiven->previous->next = SubjectGiven->next;
if(SubjectGiven->next != NULL){
SubjectGiven->next->previous = SubjectGiven->previous;
}
//...then move node to front.
NewestComm->previous = SubjectGiven;
SubjectGiven->next = NewestComm;
SubjectGiven->previous = NULL;
NewestComm = SubjectGiven;
}
}
}//End InsertEmail()
/*=======================================================================================================================*/
//SearchCommunication()
Inbox::Communication* Inbox::SearchCommunication(string keyword){
if(NewestComm == NULL){
return NULL;
}
Communication* commPointer = NewestComm;
while(commPointer->Subject != keyword && commPointer->next != NULL){
commPointer = commPointer->next;
}
if(commPointer->Subject == keyword && commPointer->next == NULL){
return commPointer;
}
else if(commPointer->next == NULL){
return NULL;
}
return commPointer;
}//End SearchCommunication()
/*=======================================================================================================================*/
//DeleteCommunication(string)
void Inbox::DeleteCommunication(string subject){
Communication* target = SearchCommunication(subject);
//Check for stupidity
if(target == NULL){
cout << "Could not find given subject for deletion.\n";
return;
}
//Nullify data
target->Subject = "";
target->Number_of_Emails = 0;
//Delete Email list
if(target->NewestEmail != NULL){
while(target->NewestEmail->Older_Email != NULL){
target->NewestEmail = target->NewestEmail->Older_Email;
delete target->NewestEmail->Newer_Email;
}
delete target->NewestEmail;
}
//Adjust Comm pointers
if(target == NewestComm){
NewestComm = NewestComm->next;
}
if(target->previous != NULL){
target->previous->next = target->next;
}
if(target->next != NULL){
target->next->previous = target->previous;
}
delete target;
Number_of_Comms--;
return;
}//End DeleteCommunication(string)
/*=======================================================================================================================*/
//DisplayInbox()
void Inbox::DisplayInbox(){
if(NewestComm == NULL){
cout << "Nothing to display.\n\n";
return;
}
Communication *DisplayPointer;
DisplayPointer = NewestComm;
for(int i = 0; i < Number_of_Comms; i++){
cout << DisplayPointer->Subject << " - " << DisplayPointer->Number_of_Emails << "\n";
DisplayPointer = DisplayPointer->next;
}
return;
}//End DisplayInbox()
/*=======================================================================================================================*/
//Menu()
void Inbox::Menu(){
string Selection;
while(Selection !="Finish"){
cout << "Enter a command: ";
getline(cin, Selection);
if(Selection == "Display"){
DisplayInbox();
}
else if(Selection == "Insert"){
InsertEmail();
}
else if(Selection == "Delete"){
string delsubj;
cout << "Enter the subject you want to delete: ";
getline(cin, delsubj);
DeleteCommunication(delsubj);
}
else if(Selection == "Finish"){
string confirmation;
cout << "Confirm Exit? (y/n)\n";
getline(cin, confirmation);
if(confirmation != "y"){
Selection = "Not Exiting";
}
}
else{
cout << "Unrecognized command. Please read preconditions for commands.\n";
}
}
}//End Menu()
/*=======================================================================================================================*/
//main()
int main(){
Inbox gmail;
gmail.Menu();
Inbox Copymail(gmail);
Copymail.Menu();
return 0;
}//End main()
/*======================================================END PROGRAM======================================================*/
|
e2d3c98db7f63947f29182eeb3fa8f509048bdc9
|
[
"C++"
] | 5 |
C++
|
aaronchoi5/collab
|
701076c90e590d9221f4631a1e1b9347d55af30b
|
0d5ac8abdbb3476cfc57d8d77a597c9e56e4a6ec
|
refs/heads/master
|
<file_sep>class AdminController < ApplicationController
layout "admin_layout"
def index
@galleries = Gallery.all
end
end
<file_sep>class Gallery < ActiveRecord::Base
# validates :images, presence: true
has_attachments :images, accept: [:jpg, :png, :gif]
end
|
6328af8c99b6bb8693ef9c25251a3f03bb37eb09
|
[
"Ruby"
] | 2 |
Ruby
|
vanbumi/rails-sorongbis
|
6c0bd3171a73c4da85be91de7551ad9380474e5d
|
26ca8ff4bf078d0da42d4c7fa6132e9f639e9286
|
refs/heads/master
|
<file_sep>"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var mongo = __importStar(require("mongodb"));
var MongoHelper = /** @class */ (function () {
function MongoHelper() {
}
MongoHelper.connect = function () {
var uri = "mongodb+srv://" + this.USER + ":" + this.PASSWORD + "@courses-fv3mh.mongodb.net/test?retryWrites=true&w=majority";
return new Promise(function (resolve, reject) {
mongo.MongoClient.connect(uri, { useNewUrlParser: true }, function (err, client) {
if (err) {
console.log("something went wrong");
reject(err);
}
else {
console.log("successful connection");
MongoHelper.client = client;
resolve(client);
}
});
});
};
MongoHelper.prototype.disconnect = function () {
MongoHelper.client.close();
};
MongoHelper.USER = process.env.MONGODBUSERNAME;
MongoHelper.PASSWORD = process.env.MONGODBPASSWORD;
return MongoHelper;
}());
exports.MongoHelper = MongoHelper;
<file_sep>"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var express = require("express");
var mongoHelper_1 = require("./mongoHelper");
var cors = require("cors");
var util_1 = require("util");
var app = express();
app.use(cors());
var courseInfo;
app.get('/class', function (req, res) {
var code = req.query.code;
var limit = parseInt(req.query.limit, 10);
var college = req.query.college;
var department = req.query.department;
var credits = Array.isArray(req.query.credits) ? req.query.credits.map(function (item) { return parseInt(item, 10); }) : [parseInt(req.query.credits, 10)];
var creditsMin = util_1.isUndefined(req.query.creditsmin) ? undefined : Number(req.query.creditsmin);
var level = Array.isArray(req.query.level) ? req.query.level.map(function (item) { return parseInt(item, 10); }) : [parseInt(req.query.level, 10)];
var levelMin = util_1.isUndefined(req.query.levelmin) ? undefined : Number(req.query.levelmin);
var hub = req.query.hub;
if (!util_1.isUndefined(code)) {
courseInfo.findOne({ Code: code })
.then(function (doc) {
if (!doc) {
throw new Error("Couldn't find this class");
}
res.send(doc);
});
}
else {
var filters_1 = [];
/* Handle college parameter */
if (!util_1.isUndefined(college)) {
var filter = {};
if (typeof (college) == 'string') {
filter = { College: college };
}
else {
filter = { College: { $in: college } };
}
filters_1.push(filter);
}
/* Handle department parameter */
if (!util_1.isUndefined(department)) {
var filter = {};
if (typeof (department) == 'string') {
filter = { Department: department };
}
else {
filter = { Department: { $in: department } };
}
filters_1.push(filter);
}
/* Handle BU Hub requirement parameter */
if (!util_1.isUndefined(hub)) {
if (typeof (hub) == 'string') {
var filter = {};
filter = { HubList: hub };
filters_1.push(filter);
}
else {
hub.forEach(function (element) {
console.log(element);
filters_1.push({ HubList: element });
});
}
}
/* Handle credits parameter */
if (!isNaN(credits[0]) && !util_1.isUndefined(creditsMin)) {
filters_1.push({ $or: [{ Credits: { $in: credits } }, { Credits: { $gte: creditsMin } }] });
}
else if (!isNaN(credits[0])) {
filters_1.push({ Credits: { $in: credits } });
}
else if (!util_1.isUndefined(creditsMin)) {
filters_1.push({ Credits: { $gte: creditsMin } });
}
/* Handle class level parameter */
if (!isNaN(level[0]) || !util_1.isUndefined(levelMin)) {
var conditions_1 = [];
if (!isNaN(level[0])) {
level.forEach(function (level) {
conditions_1.push({ Level: { $gte: level, $lt: level + 100 } });
});
}
if (!util_1.isUndefined(levelMin)) {
conditions_1.push({ Level: { $gte: levelMin } });
}
filters_1.push({ $or: conditions_1 });
}
/* Join the filters and run query */
var innerFind = filters_1.length == 0 ? {} : { $and: filters_1 };
if (!util_1.isUndefined(limit)) {
courseInfo.find(innerFind).sort({ Code: 1 }).limit(limit).toArray(function (err, result) {
if (err)
throw err;
res.send(result);
});
}
else {
courseInfo.find(innerFind).sort({ Code: 1 }).toArray(function (err, result) {
if (err)
throw err;
res.send(result);
});
}
}
});
app.listen(3000, function () { return __awaiter(_this, void 0, void 0, function () {
var connection, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
console.log('example app listening on port 3000!');
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, mongoHelper_1.MongoHelper.connect()];
case 2:
connection = _a.sent();
courseInfo = connection.db('bucourses_db').collection('course_info');
console.log('connection successful :)');
return [3 /*break*/, 4];
case 3:
err_1 = _a.sent();
console.error('whoops!', err_1);
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); });
|
9f07486c8fd93727ac0a6b7c8089fd7ecef47ff1
|
[
"JavaScript"
] | 2 |
JavaScript
|
zwang3583/BUCourses
|
72562a89fd8dcdd9c7c968caf6fe052f35be1424
|
382feab9f69e0155d8f982e6690bcfe72270f994
|
refs/heads/master
|
<file_sep># Test_XSS
Выполнение задания. Реализация XSS атак
Стартовым файлом является header.php
После запуска он будет перебрасывать на форму ввода пары логин/пароль, файл registration.php. (существует 2 пользователя Admin/123456 и user1/myPass)
После авторизации откроется чат. (chat.html) Этот чат использует myCSS.css и post-store.js.
В папке imager лежат аватарки для чата.
get.php обрабатывает, присланные после успешной атаки, cookie и сохраняет их в файл (cookie.txt).
<file_sep><?php
$f = fopen("cookie.txt", "a+");
$t = implode(" ",$_GET);
fwrite($f, $t) or die("error write");
fwrite($f, "\n");
fclose($f);
?><file_sep>
<?php
header("Content-Type: text/html;charset=utf-8");
$base = array (
"Admin" => "<PASSWORD>", //pass = <PASSWORD>
"user1" => "<PASSWORD>" //pass = <PASSWORD>
);
function check($login, $pass) {
global $base;
if (array_key_exists("$login", $base))
if ($base["$login"] == $pass ) return true;
return false;
}
//-----------------------------------------------------------------------------------
$login = $_COOKIE['login'];
$pass = $_COOKIE['pass'];
if (check($login, $pass))
{
header("Location: chat.html?name=$login");
}
else
{
require 'registration.php';
}
?>
|
b1a766ab9d05e4fa1db8019d94d73bf99618a8a8
|
[
"Markdown",
"PHP"
] | 3 |
Markdown
|
VladislavAnd/Test_XSS
|
4bb55b4a2c86b95a96edc88c28e91a703cdc71b6
|
9a1c6a08e66664b83082c1b51a468c7acb23a20d
|
refs/heads/master
|
<repo_name>doney0222/PLC_monitoring_system<file_sep>/Python code/Get_data.py
"""
Get_data.py
----------------------------------------
PLC-PC 통신 연결
FINS Commands로 데이터 송수신
Maria DB를 이용한 데이터베이스 축적
멀티스레드를 이용한 다중접속 구현
서버 접속 시 상태 변수 생성
----------------------------------------
"""
## import modules
import socket
import binascii
import struct
from bitstring import BitArray
import mariadb
import threading
import time
import sys
from Data import *
import datetime
from UI import Error_Window_PLC_A,Error_Window_PLC_B,Error_Window_PLC_C,Error_Window_PLC_D,TimeOut_Error_Window,ConnectionRefused_Error_Window
from kakao_msg import kakao_send
# 데이터 초기화 및 설정
# PLC-A
check_server_a = ['failed']
datetime_a = [0 for i in range(0, 10)]
Belt_Pos_a = [0 for i in range(0, 10)]
Belt_Vel_a = [0 for i in range(0, 10)]
Circle_Pos_a = [0 for i in range(0, 10)]
Circle_Vel_a = [0 for i in range(0, 10)]
EC_error_code_a = []
MC_error_code_a = []
# PLC-B
check_server_b = ['failed']
datetime_b = [0 for i in range(0, 10)]
Belt_Pos_b = [0 for i in range(0, 10)]
Belt_Vel_b = [0 for i in range(0, 10)]
Circle_Pos_b = [0 for i in range(0, 10)]
Circle_Vel_b = [0 for i in range(0, 10)]
EC_error_code_b = []
MC_error_code_b = []
# PLC-C
check_server_c = ['failed']
datetime_c = [0 for i in range(0, 10)]
L_Pos = [0 for i in range(0, 10)]
L_Vel = [0 for i in range(0, 10)]
C_Pos = [0 for i in range(0, 10)]
C_Vel = [0 for i in range(0, 10)]
R_Pos = [0 for i in range(0, 10)]
R_Vel = [0 for i in range(0, 10)]
EC_error_code_c = []
MC_error_code_c = []
# PLC-D
check_server_d = ['failed']
datetime_d = [0 for i in range(0, 10)]
L_W_Pos = [0 for i in range(0, 10)]
L_B_Pos = [0 for i in range(0, 10)]
R_W_Pos = [0 for i in range(0, 10)]
R_B_Pos = [0 for i in range(0, 10)]
L_W_Vel = [0 for i in range(0, 10)]
L_B_Vel = [0 for i in range(0, 10)]
R_W_Vel = [0 for i in range(0, 10)]
R_B_Vel = [0 for i in range(0, 10)]
EC_error_code_d = []
MC_error_code_d = []
#PLC_State data
bool_data_a = [0]
bool_data_b = [0]
bool_data_c = [0]
bool_data_d = [0]
## sepuence
# Get_data_PLC_A
class PLC_A(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
self.running = True
self.thread_name = 'Thread_1'
self.plc_name = 'PLC-A'
self.format = '(' + self.thread_name + ' ' + self.plc_name + ')'
self.now = datetime.datetime.now()
self.time_format = '[' + self.now.strftime('%X') + ']'
self.running = True
def run(self):
# socket 선언 및 IP,포트정의
HOST_1 = '172.31.7.11'
PORT_1 = 9600
client_socket_1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
global check_server_a
global bool_data_a
# DB Connect을 위한 구성요소
try:
db_1 = mariadb.connect(
user = 'root',
password = '<PASSWORD>',
host = '127.0.0.1',
port = 3306,
database = 'test'
)
except mariadb.Error as e:
# print(f"Error connecting to MariaDB Platform : {e}")
sys.exit()
#DB의 Cursor 설정
cur_1 = db_1.cursor()
# 식별 정보
db_number = db_1
cur_number = cur_1
plc_id = "plc_a"
# run
print("{0} {1} : starting".format(self.time_format, self.format))
#Socket Connect
try:
client_socket_1.connect((HOST_1, PORT_1))
# print("{0} {1} : 서버와 연결되었습니다.".format(self.time_format, self.format))
del check_server_a[0]
check_server_a.insert(0, 'connected')
# First step(필수적) - FINS COMMAND
send_data = binascii.a2b_hex('46494e530000000c000000000000000000000000')
client_socket_1.sendall(send_data)
recv_data = client_socket_1.recv(1024)
data_0_1 = BitArray(bytes=recv_data, length=8, offset=152).bytes #FINS COMMAND를 사용하기위해 recv받은 값 Byte변환 후 저장
convert_0_1 = binascii.b2a_hex(data_0_1).decode() #Byte값 16진수화 후 디코딩 하여 저장
data_0_2 = BitArray(bytes=recv_data, length=8, offset=184).bytes
convert_0_2 = binascii.b2a_hex(data_0_2).decode()
# print("{} {} : [Server node address(hex)] {}".format(self.time_format, self.format, convert_0_1))
# print("{} {} : [Server node address(hex)] {}".format(self.time_format, self.format, convert_0_2))
# read data - FINS COMMAND
send_data = binascii.a2b_hex('46494e530000001a000000020000000080000201' + convert_0_2 + '0001' +convert_0_1 + '00000101820000000009')
while self.running:
client_socket_1.sendall(send_data)
recv_data = client_socket_1.recv(1024)
# data diffentation
diff_code = BitArray(bytes=recv_data, length=8, offset=232).bytes
if diff_code == b'\x00': #값이 정상적으로 전송된경우
data_1 = BitArray(bytes=recv_data, length=32, offset=240).bytes
convert_1 = Data_convert.data_convert(data_1)
data_2 = BitArray(bytes=recv_data, length=32, offset=272).bytes
convert_2 = Data_convert.data_convert(data_2)
data_3 = BitArray(bytes=recv_data, length=32, offset=304).bytes
convert_3 = Data_convert.data_convert(data_3)
data_4 = BitArray(bytes=recv_data, length=32, offset=336).bytes
convert_4 = Data_convert.data_convert(data_4)
data_5 = BitArray(bytes=recv_data, length=16, offset=368).bytes
convert_5 = binascii.b2a_hex(data_5).decode()
start_data = int(convert_5, 16)
if start_data == 1:
del bool_data_a[0]
bool_data_a.insert(0, 1)
elif start_data == 0:
del bool_data_a[0]
bool_data_a.insert(0, 0)
if bool_data_a[0] == 1: #PLC_A의 상태가 ON일때 조건
# write db
data_list_1 = [db_number, cur_number, plc_id, convert_1, convert_2, convert_3, convert_4]
Use_db.write_db(data_list_1)
# read db
read_key = [cur_number, plc_id]
read_data_1 = Use_db.read_db(read_key)
del datetime_a[0]
datetime_a.insert(9, read_data_1[0])
del Belt_Pos_a[0]
Belt_Pos_a.insert(9, read_data_1[1])
del Belt_Vel_a[0]
Belt_Vel_a.insert(9, read_data_1[2])
del Circle_Pos_a[0]
Circle_Pos_a.insert(9, read_data_1[3])
del Circle_Vel_a[0]
Circle_Vel_a.insert(9, read_data_1[4])
time.sleep(1)
elif diff_code == b'@': #값이 에러값이 전송될 경우
data_6 = BitArray(bytes=recv_data, length=64, offset=240).bytes
convert_6 = Data_convert.data_convert_error(data_6)
data_7 = BitArray(bytes=recv_data, length=64, offset=304).bytes
# print(data_7)
convert_7 = Data_convert.data_convert_error(data_7)
# write on db
data_list_2 = [db_number, cur_number, plc_id, convert_6, convert_7]
Use_db.write_db_error(data_list_2)
# read from db
read_key = [cur_number, plc_id]
read_data_2 = Use_db.read_db(read_key)
del check_server_a[0]
check_server_a.insert(0, 'failed')
if read_data_2[5] or read_data_2[6] != None:
EC_error_code_a.insert(0,read_data_2[5])
MC_error_code_a.insert(0,read_data_2[6])
Error_Window_PLC_A().mainloop()
kakao_send.refreshToken()
kakao_send.kakao_text()
break
except TimeoutError: #TimeoutError발생시 예외처리
TimeOut_Error_Window().mainloop()
del check_server_a[0]
check_server_a.insert(0, 'failed')
except ConnectionRefusedError: #ConnectionRefusedError발생시 예외처리
ConnectionRefused_Error_Window().mainloop()
del check_server_a[0]
check_server_a.insert(0, 'failed')
db_1.close()
client_socket_1.close()
del check_server_a[0]
check_server_a.insert(0, 'failed')
def error_code(self): #에러발생 이벤트 처리에 있어서 필요한 정보반환
return EC_error_code_a,MC_error_code_a
def resume(self):
self.running = True
def pause(self):
self.running = False
class PLC_B(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
self.running = True
self.thread_name = 'Thread_2'
self.plc_name = 'PLC-B'
self.format = '(' + self.thread_name + ' ' + self.plc_name + ')'
self.now = datetime.datetime.now()
self.time_format = '[' + self.now.strftime('%X') + ']'
self.running = True
def run(self):
# socket 초기값
HOST_2 = '172.31.3.22'
PORT_2 = 9600
client_socket_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
global check_server_b
global bool_data_b
# DB 초기값
try:
db_2 = mariadb.connect(
user = 'root',
password = 'jds',
host = '127.0.0.1',
port = 3306,
database = 'plc_db'
)
except mariadb.Error as e:
# print(f"Error connecting to MariaDB Platform : {e}")
sys.exit()
cur_2 = db_2.cursor()
# 식별 정보
db_number = db_2
cur_number = cur_2
plc_id = "plc_b"
# run
# print("{0} {1} : starting".format(self.time_format, self.format))
try:
client_socket_2.connect((HOST_2, PORT_2))
# print("{0} {1} : 서버와 연결되었습니다.".format(self.time_format, self.format))
del check_server_b[0]
check_server_b.insert(0, 'connected')
# request node - First step(필수적)
send_data = binascii.a2b_hex('46494e530000000c000000000000000000000000')
client_socket_2.sendall(send_data)
recv_data = client_socket_2.recv(1024)
data_0_1 = BitArray(bytes=recv_data, length=8, offset=152).bytes
convert_0_1 = binascii.b2a_hex(data_0_1).decode()
data_0_2 = BitArray(bytes=recv_data, length=8, offset=184).bytes
convert_0_2 = binascii.b2a_hex(data_0_2).decode()
# print("{} {} : [Server node address(hex)] {}".format(self.time_format, self.format, convert_0_1))
# print("{} {} : [Server node address(hex)] {}".format(self.time_format, self.format, convert_0_2))
# read data - 할당된 node를 대입하여 진행
send_data = binascii.a2b_hex('46494e530000001a000000020000000080000201' + convert_0_2 + '0001' +convert_0_1 + '00000101820000000009')
while self.running:
client_socket_2.sendall(send_data)
recv_data = client_socket_2.recv(1024)
# data diffentation
diff_code = BitArray(bytes=recv_data, length=8, offset=232).bytes
if diff_code == b'\x00':
data_1 = BitArray(bytes=recv_data, length=32, offset=240).bytes
convert_1 = Data_convert.data_convert(data_1)
data_2 = BitArray(bytes=recv_data, length=32, offset=272).bytes
convert_2 = Data_convert.data_convert(data_2)
data_3 = BitArray(bytes=recv_data, length=32, offset=304).bytes
convert_3 = Data_convert.data_convert(data_3)
data_4 = BitArray(bytes=recv_data, length=32, offset=336).bytes
convert_4 = Data_convert.data_convert(data_4)
data_5 = BitArray(bytes=recv_data, length=16, offset=368).bytes
convert_5 = binascii.b2a_hex(data_5).decode()
start_data = int(convert_5, 16)
if start_data == 1:
del bool_data_b[0]
bool_data_b.insert(0, 1)
elif start_data == 0:
del bool_data_b[0]
bool_data_b.insert(0, 0)
if bool_data_b[0] == 1:
# write on db
data_list_1 = [db_number, cur_number, plc_id, convert_1, convert_2, convert_3, convert_4]
Use_db.write_db(data_list_1)
# read from db
read_key = [cur_number, plc_id]
read_data_1 = Use_db.read_db(read_key)
global datetime_b, Belt_Pos_b, Belt_Vel_b, Circle_Pos_b, Circle_Vel_b
del datetime_b[0]
datetime_b.insert(9, read_data_1[0])
del Belt_Pos_b[0]
Belt_Pos_b.insert(9, read_data_1[1])
del Belt_Vel_b[0]
Belt_Vel_b.insert(9, read_data_1[2])
del Circle_Pos_b[0]
Circle_Pos_b.insert(9, read_data_1[3])
del Circle_Vel_b[0]
Circle_Vel_b.insert(9, read_data_1[4])
# print("[{0}] {1} : Belt_Pos {2} | Belt_Vel {3} | Circle_Pos {4} | Circle_Vel {5}".format(datetime_b[9], self.format, Belt_Pos_b[9], Belt_Vel_b[9], Circle_Pos_b[9], Circle_Vel_b[9]))
time.sleep(1)
elif diff_code == b'@':
data_6 = BitArray(bytes=recv_data, length=64, offset=240).bytes
convert_6 = Data_convert.data_convert_error(data_6)
data_7 = BitArray(bytes=recv_data, length=64, offset=304).bytes
convert_7 = Data_convert.data_convert_error(data_7)
# write on db
data_list_2 = [db_number, cur_number, plc_id, convert_6, convert_7]
Use_db.write_db_error(data_list_2)
# read from db
read_key = [cur_number, plc_id]
read_data_2 = Use_db.read_db(read_key)
# print("[{0}] {1} : [EC_Error] code {2} | [MC_Error] code {3}".format(datetime_b[9], self.format, read_data_2[5], read_data_2[6]))
del check_server_b[0]
check_server_b.insert(0, 'failed')
if read_data_2[5] or read_data_2[6] != None:
EC_error_code_b.insert(0,read_data_2[5])
MC_error_code_b.insert(0,read_data_2[6])
Error_Window_PLC_B().mainloop()
kakao_send.refreshToken()
kakao_send.kakao_text()
break
except TimeoutError:
# print("{0} {1} : (Error) 서버와 연결할 수 없습니다. IP주소와 포트번호를 다시 확인해주세요.".format(self.time_format, self.format))
TimeOut_Error_Window().mainloop()
del check_server_b[0]
check_server_b.insert(0, 'failed')
except ConnectionRefusedError:
# print("{0} {1} : (Error) 서버와의 연결이 거부되었습니다. 포트번호를 다시 확인해주세요.".format(self.time_format, self.format))
ConnectionRefused_Error_Window().mainloop()
del check_server_b[0]
check_server_b.insert(0, 'failed')
db_2.close()
client_socket_2.close()
del check_server_b[0]
check_server_b.insert(0, 'failed')
# print("{0} {1} : finishing".format(self.time_format, self.format))
def error_code(self):
return EC_error_code_b,MC_error_code_b
def resume(self):
self.running = True
def pause(self):
self.running = False
class PLC_C(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
self.running = True
self.thread_name = 'Thread_3'
self.plc_name = 'Delta_Robot'
self.format = '(' + self.thread_name + ' ' + self.plc_name + ')'
self.now = datetime.datetime.now()
self.time_format = '[' + self.now.strftime('%X') + ']'
self.running = True
def run(self):
# socket 초기값
HOST_2 = '172.31.7.26'
PORT_2 = 9600
client_socket_3 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
global check_server_c
global bool_data_c
# DB 초기값
try:
db_3 = mariadb.connect(
user = 'root',
password = '<PASSWORD>',
host = '127.0.0.1',
port = 3306,
database = 'test'
)
except mariadb.Error as e:
# print(f"Error connecting to MariaDB Platform : {e}")
sys.exit()
cur_3 = db_3.cursor()
# 식별 정보
db_number = db_3
cur_number = cur_3
plc_id = "plc_c"
# run
# print("{0} {1} : starting".format(self.time_format, self.format))
try:
client_socket_3.connect((HOST_2, PORT_2))
# print("{0} {1} : 서버와 연결되었습니다.".format(self.time_format, self.format))
del check_server_c[0]
check_server_c.insert(0, 'connected')
# request node - First step(필수적)
send_data = binascii.a2b_hex('46494e530000000c000000000000000000000000')
client_socket_3.sendall(send_data)
recv_data = client_socket_3.recv(1024)
data_0_1 = BitArray(bytes=recv_data, length=8, offset=152).bytes
convert_0_1 = binascii.b2a_hex(data_0_1).decode()
data_0_2 = BitArray(bytes=recv_data, length=8, offset=184).bytes
convert_0_2 = binascii.b2a_hex(data_0_2).decode()
# print("{} {} : [Server node address(hex)] {}".format(self.time_format, self.format, convert_0_1))
# print("{} {} : [Server node address(hex)] {}".format(self.time_format, self.format, convert_0_2))
# read data
send_data = binascii.a2b_hex('46494e530000001a000000020000000080000201' + convert_0_2 + '0001' +convert_0_1 + '00000101820000000013')
while self.running:
client_socket_3.sendall(send_data)
recv_data = client_socket_3.recv(1024)
# data diffentation
diff_code = BitArray(bytes=recv_data, length=8, offset=232).bytes
if diff_code == b'\x00':
data_1 = BitArray(bytes=recv_data, length=32, offset=240).bytes
convert_1 = Data_convert.data_convert(data_1)
data_2 = BitArray(bytes=recv_data, length=32, offset=272).bytes
convert_2 = Data_convert.data_convert(data_2)
data_3 = BitArray(bytes=recv_data, length=32, offset=304).bytes
convert_3 = Data_convert.data_convert(data_3)
data_4 = BitArray(bytes=recv_data, length=32, offset=336).bytes
convert_4 = Data_convert.data_convert(data_4)
data_8 = BitArray(bytes=recv_data, length=32, offset=368).bytes
convert_8 = Data_convert.data_convert(data_8)
data_9 = BitArray(bytes=recv_data, length=32, offset=400).bytes
convert_9 = Data_convert.data_convert(data_9)
data_5 = BitArray(bytes=recv_data, length=16, offset=432).bytes
convert_5 = binascii.b2a_hex(data_5).decode()
start_data = int(convert_5, 16)
if start_data == 1:
del bool_data_c[0]
bool_data_c.insert(0, 1)
elif start_data == 0:
del bool_data_c[0]
bool_data_c.insert(0, 0)
if bool_data_c[0] == 1:
# write on db
data_list_1 = [db_number, cur_number, plc_id, convert_1, convert_2, convert_3, convert_4, convert_8, convert_9]
Use_db.write_db_delta(data_list_1)
# read from db
read_key = [cur_number, plc_id]
read_data_1 = Use_db.read_db(read_key)
global datetime_c, L_Pos, L_Vel, C_Pos, C_Vel, R_Pos, R_Vel
del datetime_c[0]
datetime_c.insert(9, read_data_1[0])
del L_Pos[0]
L_Pos.insert(9, read_data_1[1])
del L_Vel[0]
L_Vel.insert(9, read_data_1[2])
del C_Pos[0]
C_Pos.insert(9, read_data_1[3])
del C_Vel[0]
C_Vel.insert(9, read_data_1[4])
del R_Pos[0]
R_Pos.insert(9, read_data_1[5])
del R_Vel[0]
R_Vel.insert(9, read_data_1[6])
# print("[{0}] {1} : L_Pos {2} | L_Vel {3} | C_Pos {4} | C_Vel {5} | R_Pos {6} | R_Vel {7}".format(datetime_c[9], self.format, L_Pos[9], L_Vel[9], C_Pos[9], C_Vel[9], R_Pos[9], R_Vel[9]))
time.sleep(1)
elif diff_code == b'@':
data_6 = BitArray(bytes=recv_data, length=64, offset=240).bytes
convert_6 = Data_convert.data_convert_error(data_6)
data_7 = BitArray(bytes=recv_data, length=64, offset=304).bytes
convert_7 = Data_convert.data_convert_error(data_7)
# write on db
data_list_2 = [db_number, cur_number, plc_id, convert_6, convert_7]
Use_db.write_db_error(data_list_2)
# read from db
read_key = [cur_number, plc_id]
read_data_2 = Use_db.read_db(read_key)
# print("[{0}] {1} : [EC_Error] code {2} | [MC_Error] code {3}".format(datetime_c[9], self.format, read_data_2[7], read_data_2[8]))
del check_server_c[0]
check_server_c.insert(0, 'failed')
if read_data_2[7] or read_data_2[8] != None:
EC_error_code_c.insert(0,read_data_2[7])
MC_error_code_c.insert(0,read_data_2[8])
Error_Window_PLC_C().mainloop()
kakao_send.refreshToken()
kakao_send.kakao_text()
break
except TimeoutError:
# print("{0} {1} : (Error) 서버와 연결할 수 없습니다. IP주소와 포트번호를 다시 확인해주세요.".format(self.time_format, self.format))
TimeOut_Error_Window().mainloop()
del check_server_c[0]
check_server_c.insert(0, 'failed')
except ConnectionRefusedError:
# print("{0} {1} : (Error) 서버와의 연결이 거부되었습니다. 포트번호를 다시 확인해주세요.".format(self.time_format, self.format))
ConnectionRefused_Error_Window().mainloop()
del check_server_c[0]
check_server_c.insert(0, 'failed')
db_3.close()
client_socket_3.close()
del check_server_c[0]
check_server_c.insert(0, 'failed')
# print("{0} {1} : finishing".format(self.time_format, self.format))
def error_code(self):
return EC_error_code_c,MC_error_code_c
def resume(self):
self.running = True
def pause(self):
self.running = False
class PLC_D(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
self.running = True
self.thread_name = 'Thread_4'
self.plc_name = 'Piano-Robot'
self.format = '(' + self.thread_name + ' ' + self.plc_name + ')'
self.now = datetime.datetime.now()
self.time_format = '[' + self.now.strftime('%X') + ']'
self.running = True
def run(self):
# socket 초기값
HOST_2 = '172.31.3.20'
PORT_2 = 9600
client_socket_4 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
global check_server_d
global bool_data_d
# DB 초기값
try:
db_4 = mariadb.connect(
user = 'root',
password = 'jds',
host = '127.0.0.1',
port = 3306,
database = 'plc_db'
)
except mariadb.Error as e:
# print(f"Error connecting to MariaDB Platform : {e}")
sys.exit()
cur_4 = db_4.cursor()
# 식별 정보
db_number = db_4
cur_number = cur_4
plc_id = "plc_d"
# run
# print("{0} {1} : starting".format(self.time_format, self.format))
try:
client_socket_4.connect((HOST_2, PORT_2))
# print("{0} {1} : 서버와 연결되었습니다.".format(self.time_format, self.format))
del check_server_d[0]
check_server_d.insert(0, 'connected')
# request node - First step(필수적)
send_data = binascii.a2b_hex('46494e530000000c000000000000000000000000')
client_socket_4.sendall(send_data)
recv_data = client_socket_4.recv(1024)
data_0_1 = BitArray(bytes=recv_data, length=8, offset=152).bytes
convert_0_1 = binascii.b2a_hex(data_0_1).decode()
data_0_2 = BitArray(bytes=recv_data, length=8, offset=184).bytes
convert_0_2 = binascii.b2a_hex(data_0_2).decode()
# print("{} {} : [Server node address(hex)] {}".format(self.time_format, self.format, convert_0_1))
# print("{} {} : [Server node address(hex)] {}".format(self.time_format, self.format, convert_0_2))
# read data - 할당된 node를 대입하여 진행
send_data = binascii.a2b_hex('46494e530000001a000000020000000080000201' + convert_0_2 + '0001' +convert_0_1 + '00000101820000000017')
while self.running:
client_socket_4.sendall(send_data)
recv_data = client_socket_4.recv(1024)
# data diffentation
diff_code = BitArray(bytes=recv_data, length=8, offset=232).bytes
if diff_code == b'\x00':
data_1 = BitArray(bytes=recv_data, length=32, offset=240).bytes
convert_1 = Data_convert.data_convert(data_1)
data_2 = BitArray(bytes=recv_data, length=32, offset=272).bytes
convert_2 = Data_convert.data_convert(data_2)
data_3 = BitArray(bytes=recv_data, length=32, offset=304).bytes
convert_3 = Data_convert.data_convert(data_3)
data_4 = BitArray(bytes=recv_data, length=32, offset=336).bytes
convert_4 = Data_convert.data_convert(data_4)
data_5 = BitArray(bytes=recv_data, length=32, offset=368).bytes
convert_5 = Data_convert.data_convert(data_5)
data_6 = BitArray(bytes=recv_data, length=32, offset=400).bytes
convert_6 = Data_convert.data_convert(data_6)
data_7 = BitArray(bytes=recv_data, length=32, offset=432).bytes
convert_7 = Data_convert.data_convert(data_7)
data_8 = BitArray(bytes=recv_data, length=32, offset=464).bytes
convert_8 = Data_convert.data_convert(data_8)
data_9 = BitArray(bytes=recv_data, length=16, offset=496).bytes
convert_9 = binascii.b2a_hex(data_9).decode()
start_data = int(convert_9, 16)
if start_data == 1:
del bool_data_d[0]
bool_data_d.insert(0, 1)
elif start_data == 0:
del bool_data_d[0]
bool_data_d.insert(0, 0)
if bool_data_d[0] == 1:
# write on db
data_list_1 = [db_number, cur_number, plc_id, convert_1, convert_2, convert_3, convert_4, convert_5, convert_6, convert_7, convert_8]
Use_db.write_db_piano(data_list_1)
# read from db
read_key = [cur_number, plc_id]
read_data_1 = Use_db.read_db(read_key)
global datetime_d, L_W_Pos, L_B_Pos, R_W_Pos, R_B_Pos, L_W_Vel, L_B_Vel, R_W_Vel, R_B_Vel
del datetime_d[0]
datetime_d.insert(9, read_data_1[0])
del L_W_Pos[0]
L_W_Pos.insert(9, read_data_1[1])
del L_B_Pos[0]
L_B_Pos.insert(9, read_data_1[2])
del R_W_Pos[0]
R_W_Pos.insert(9, read_data_1[3])
del R_B_Pos[0]
R_B_Pos.insert(9, read_data_1[4])
del L_W_Vel[0]
L_W_Vel.insert(9, read_data_1[5])
del L_B_Vel[0]
L_B_Vel.insert(9, read_data_1[6])
del R_W_Vel[0]
R_W_Vel.insert(9, read_data_1[7])
del R_B_Vel[0]
R_B_Vel.insert(9, read_data_1[8])
# print("[{0}] {1} : L_W_Pos {2} | L_B_Pos {3} | R_W_Pos {4} | R_B_Pos {5} | L_W_Vel {6} | L_B_Vel {7} | R_W_Vel {8} | R_B_Vel {9}".format(datetime_d[9], self.format, L_W_Pos[9], L_B_Pos[9], R_W_Pos[9], R_B_Pos[9], L_W_Vel[9], L_B_Vel[9], R_W_Vel[9], R_B_Vel[9]))
time.sleep(1)
elif diff_code == b'@':
data_10 = BitArray(bytes=recv_data, length=64, offset=240).bytes
convert_10 = Data_convert.data_convert_error(data_10)
data_11 = BitArray(bytes=recv_data, length=64, offset=304).bytes
convert_11 = Data_convert.data_convert_error(data_11)
# write on db
data_list_2 = [db_number, cur_number, plc_id, convert_10, convert_11]
Use_db.write_db_error(data_list_2)
# read from db
read_key = [cur_number, plc_id]
read_data_2 = Use_db.read_db(read_key)
# print("[{0}] {1} : [EC_Error] code {2} | [MC_Error] code {3}".format(datetime_b[9], self.format, read_data_2[9], read_data_2[10]))
del check_server_d[0]
check_server_d.insert(0, 'failed')
if read_data_2[9] or read_data_2[10] != None:
EC_error_code_d.insert(0,read_data_2[9])
MC_error_code_d.insert(0,read_data_2[10])
Error_Window_PLC_D().mainloop()
kakao_send.refreshToken()
kakao_send.kakao_text()
break
except TimeoutError:
# print("{0} {1} : (Error) 서버와 연결할 수 없습니다. IP주소와 포트번호를 다시 확인해주세요.".format(self.time_format, self.format))
TimeOut_Error_Window().mainloop()
del check_server_d[0]
check_server_d.insert(0, 'failed')
except ConnectionRefusedError:
# print("{0} {1} : (Error) 서버와의 연결이 거부되었습니다. 포트번호를 다시 확인해주세요.".format(self.time_format, self.format))
ConnectionRefused_Error_Window().mainloop()
del check_server_d[0]
check_server_d.insert(0, 'failed')
db_4.close()
client_socket_4.close()
del check_server_d[0]
check_server_d.insert(0, 'failed')
# print("{0} {1} : finishing".format(self.time_format, self.format))
def error_code(self):
return EC_error_code_d,MC_error_code_d
def resume(self):
self.running = True
def pause(self):
self.running = False<file_sep>/Python code/Sub_UI_1.py
"""
Sub_UI_1.py
tkinter를 사용하여 구성한 기본 UI
"""
## import modules
from tkinter import *
import os
from tkinter.font import Font
import sys
import Thread
from Get_data import *
## initial value
# file direction
current_file = os.path.dirname(__file__)
# color
color_main_bg = '#465260'
color_frame_bg = '#3A4552'
color_data_bg = '#3C4048'
## sequence
class SubFrame_1(Frame):
def __init__(self):
super().__init__(width=1330, height=750)
# font
self.font_25 = Font(size=25, weight='bold')
self.font_20 = Font(size=20, weight='bold')
self.font_15 = Font(size=15, weight='bold')
self.font_19 = Font(size=19, weight='bold')
self.font_12 = Font(size=12, weight='bold')
# 구성요소 불러오기
self.initUI()
def initUI(self):
# frame
frame_0 = Label(self, background=color_main_bg)
frame_0.place(x=0, y=0, width=1330, height=750)
frame_1 = Label(self, background=color_frame_bg)
frame_1.place(x=20, y=20, width=635, height=710)
frame_2 = Label(self, background=color_frame_bg)
frame_2.place(x=675, y=20, width=635, height=710)
# frame_1 구성요소
"""machine info"""
machine_name_1 = Label(self, text='PLC_A', font=self.font_25, fg='#FFFFFF', bg=color_frame_bg)
machine_name_1.place(x=20, y=20, width=635, height=60)
self.machine_image_1 = PhotoImage(file=os.path.join(current_file, 'machine_image_sample.png'))
machine_image_1 = Label(self, image=self.machine_image_1, bg='#FFFFFF')
machine_image_1.place(x=35, y=80, width=250, height=300)
"""comment"""
comment_frame_1 = Label(self, background=color_frame_bg)
comment_frame_1.place(x=300, y=80, width=340, height=140)
comment_title_1 = Label(self, text='Comment', font=self.font_20, fg='#FFFFFF', bg=color_frame_bg)
comment_title_1.place(x=305, y=80)
comment_1 = Label(self, text='This is sample.\nYou can see CAM mechanism.\nLine\nLine', font=self.font_15, justify='left',
fg='#FFFFFF', bg=color_frame_bg)
comment_1.place(x=305, y=115)
"""ON/OFF"""
run_title_1 = Label(self, text='Monitoring', font=self.font_20, fg='#FFFFFF', bg=color_frame_bg)
run_title_1.place(x=305, y=225)
self.run_btn_bg_image_1 = PhotoImage(file=os.path.join(current_file, 'button_background.png'))
run_button_bg_1 = Label(self, image=self.run_btn_bg_image_1, bg=color_frame_bg)
run_button_bg_1.place(x=465, y=220, width=170, height=50)
self.run_btn_on_image_1_1 = PhotoImage(file=os.path.join(current_file, 'button_on_1.png'))
self.run_btn_on_image_1_2 = PhotoImage(file=os.path.join(current_file, 'button_on_2.png'))
self.run_button_on_1 = Button(self, image=self.run_btn_on_image_1_2, bg='#FFFFFF', bd=0, state='normal',
command=self.btn_cmd_1)
self.run_button_on_1_2 = Label(self, image=self.run_btn_on_image_1_1, bg='#FFFFFF', bd=0)
self.run_button_on_1.place(x=470, y=225, width=80, height=40)
self.run_btn_off_image_1_1 = PhotoImage(file=os.path.join(current_file, 'button_off_1.png'))
self.run_btn_off_image_1_2 = PhotoImage(file=os.path.join(current_file, 'button_off_2.png'))
self.run_button_off_1 = Label(self, image=self.run_btn_off_image_1_1, bg='#FFFFFF', bd=0)
self.run_button_off_1_2 = Button(self, image=self.run_btn_off_image_1_2, bg='#FFFFFF', bd=0, state='normal',
command=self.btn_cmd_2)
self.run_button_off_1.place(x=550, y=225, width=80, height=40)
"""state"""
state_title_1 = Label(self, text='State', font=self.font_20, fg='#FFFFFF', bg=color_frame_bg)
state_title_1.place(x=305, y=285)
self.state_bg_image_1 = PhotoImage(file=os.path.join(current_file, 'state_background.png'))
state_bg_1 = Label(self, image=self.state_bg_image_1, bg=color_frame_bg)
state_bg_1.place(x=320, y=325, width=310, height=50)
self.state_run_image_1 = PhotoImage(file=os.path.join(current_file, 'state_run_2.png'))
self.state_run_1 = Label(self, image=self.state_run_image_1, bg='#FFFFFF')
self.state_run_1.place(x=325, y=325, width=100, height=50)
self.state_idle_image_1 = PhotoImage(file=os.path.join(current_file, 'state_idle_2.png'))
self.state_idle_1 = Label(self, image=self.state_idle_image_1, bg='#FFFFFF')
self.state_idle_1.place(x=425, y=325, width=100, height=50)
self.state_stop_image_1 = PhotoImage(file=os.path.join(current_file, 'state_stop_1.png'))
self.state_stop_1 = Label(self, image=self.state_stop_image_1, bg='#FFFFFF')
self.state_stop_1.place(x=525, y=325, width=100, height=50)
"""data""" #데이터
data_1_frame = Label(self, background=color_data_bg)
data_1_frame.place(x=35, y=395, width=605, height=320)
date_1_title = Label(self, text='Data', font=self.font_19, fg='#FFFFFF', background=color_data_bg)
date_1_title.place(x=40, y=395)
data_1_1_name = Label(self, text='Belf-Pos', font=self.font_15, fg='#FFFFFF', bg=color_data_bg)
data_1_1_name.place(x=45, y=430)
data_1_2_name = Label(self, text='Belf-Vel', font=self.font_15, fg='#FFFFFF', bg=color_data_bg)
data_1_2_name.place(x=45, y=460)
data_1_3_name = Label(self, text='Circle-Pos', font=self.font_15, fg='#FFFFFF', bg=color_data_bg)
data_1_3_name.place(x=345, y=430)
data_1_4_name = Label(self, text='Circle-Vel', font=self.font_15, fg='#FFFFFF', bg=color_data_bg)
data_1_4_name.place(x=345, y=460)
data_1_1_entry = Entry(self, justify='right')
data_1_1_entry.place(x=175, y=433, width=110, height=22)
data_1_2_entry = Entry(self, justify='right')
data_1_2_entry.place(x=175, y=463, width=110, height=22)
data_1_3_entry = Entry(self, justify='right')
data_1_3_entry.place(x=480, y=433, width=110, height=22)
data_1_4_entry = Entry(self, justify='right')
data_1_4_entry.place(x=480, y=463, width=110, height=22)
data_1_1_unit = Label(self, text='mm', font=self.font_12, fg='#FFFFFF', bg=color_data_bg)
data_1_1_unit.place(x=285, y=433)
data_1_2_unit = Label(self, text='mm/s', font=self.font_12, fg='#FFFFFF', bg=color_data_bg)
data_1_2_unit.place(x=285, y=463)
data_1_3_unit = Label(self, text='mm', font=self.font_12, fg='#FFFFFF', bg=color_data_bg)
data_1_3_unit.place(x=590, y=433)
data_1_4_unit = Label(self, text='mm/s', font=self.font_12, fg='#FFFFFF', bg=color_data_bg)
data_1_4_unit.place(x=590, y=463)
"""graph"""
canvas_1_1 = Canvas(self)
canvas_1_1.place(x=35, y=495, width=300, height=220)
canvas_1_2 = Canvas(self)
canvas_1_2.place(x=340, y=495, width=300, height=220)
# frame_2 구성요소
"""machine info"""
machine_name_2 = Label(self, text='PLC_B', font=self.font_25, fg='#FFFFFF', bg=color_frame_bg)
machine_name_2.place(x=675, y=20, width=635, height=60)
self.machine_image_2 = PhotoImage(file=os.path.join(current_file, 'machine_image_sample.png'))
machine_image_2 = Label(self, image=self.machine_image_2, bg='#FFFFFF')
machine_image_2.place(x=690, y=80, width=250, height=300)
"""comment"""
comment_frame_2 = Label(self, background=color_frame_bg)
comment_frame_2.place(x=955, y=80, width=340, height=140)
comment_title_2 = Label(self, text='Comment', font=self.font_20, fg='#FFFFFF', bg=color_frame_bg)
comment_title_2.place(x=960, y=80)
comment_2 = Label(self, text='This is sample.\nYou can see CAM mechanism.\nLine\nLine', font=self.font_15, justify='left',
fg='#FFFFFF', bg=color_frame_bg)
comment_2.place(x=960, y=115)
"""ON/OFF"""
run_title_2 = Label(self, text='Monitoring', font=self.font_20, fg='#FFFFFF', bg=color_frame_bg)
run_title_2.place(x=960, y=225)
self.run_btn_bg_image_2 = PhotoImage(file=os.path.join(current_file, 'button_background.png'))
run_button_bg_2 = Label(self, image=self.run_btn_bg_image_2, bg=color_frame_bg)
run_button_bg_2.place(x=1120, y=220, width=170, height=50)
self.run_btn_on_image_2_1 = PhotoImage(file=os.path.join(current_file, 'button_on_1.png'))
self.run_btn_on_image_2_2 = PhotoImage(file=os.path.join(current_file, 'button_on_2.png'))
self.run_button_on_2 = Button(self, image=self.run_btn_on_image_2_2, bg='#FFFFFF', bd=0, state='normal',
command=self.btn_cmd_3)
self.run_button_on_2_2 = Label(self, image=self.run_btn_on_image_2_1, bg='#FFFFFF', bd=0)
self.run_button_on_2.place(x=1125, y=225, width=80, height=40)
self.run_btn_off_image_2_1 = PhotoImage(file=os.path.join(current_file, 'button_off_1.png'))
self.run_btn_off_image_2_2 = PhotoImage(file=os.path.join(current_file, 'button_off_2.png'))
self.run_button_off_2 = Label(self, image=self.run_btn_off_image_2_1, bg='#FFFFFF', bd=0)
self.run_button_off_2_2 = Button(self, image=self.run_btn_off_image_2_2, bg='#FFFFFF', bd=0, state='normal',
command=self.btn_cmd_4)
self.run_button_off_2.place(x=1205, y=225, width=80, height=40)
"""state"""
state_title_2 = Label(self, text='State', font=self.font_20, fg='#FFFFFF', bg=color_frame_bg)
state_title_2.place(x=960, y=285)
self.state_bg_image_2 = PhotoImage(file=os.path.join(current_file, 'state_background.png'))
state_bg_2 = Label(self, image=self.state_bg_image_2, bg=color_frame_bg)
state_bg_2.place(x=975, y=325, width=310, height=50)
self.state_run_image_2 = PhotoImage(file=os.path.join(current_file, 'state_run_2.png'))
self.state_run_2 = Label(self, image=self.state_run_image_2, bg='#FFFFFF')
self.state_run_2.place(x=980, y=325, width=100, height=50)
self.state_idle_image_2 = PhotoImage(file=os.path.join(current_file, 'state_idle_2.png'))
self.state_idle_2 = Label(self, image=self.state_idle_image_2, bg='#FFFFFF')
self.state_idle_2.place(x=1080, y=325, width=100, height=50)
self.state_stop_image_2 = PhotoImage(file=os.path.join(current_file, 'state_stop_1.png'))
self.state_stop_2 = Label(self, image=self.state_stop_image_2, bg='#FFFFFF')
self.state_stop_2.place(x=1180, y=325, width=100, height=50)
"""data"""
data_2_frame = Label(self, background=color_data_bg)
data_2_frame.place(x=690, y=395, width=605, height=320)
date_2_title = Label(self, text='Data', font=self.font_19, fg='#FFFFFF', background=color_data_bg)
date_2_title.place(x=695, y=395)
data_2_1_name = Label(self, text='Belf-Pos', font=self.font_15, fg='#FFFFFF', bg=color_data_bg)
data_2_1_name.place(x=700, y=430)
data_2_2_name = Label(self, text='Belf-Vel', font=self.font_15, fg='#FFFFFF', bg=color_data_bg)
data_2_2_name.place(x=700, y=460)
data_2_3_name = Label(self, text='Circle-Pos', font=self.font_15, fg='#FFFFFF', bg=color_data_bg)
data_2_3_name.place(x=1000, y=430)
data_2_4_name = Label(self, text='Circle-Vel', font=self.font_15, fg='#FFFFFF', bg=color_data_bg)
data_2_4_name.place(x=1000, y=460)
data_2_1_entry = Entry(self, justify='right')
data_2_1_entry.place(x=830, y=433, width=110, height=22)
data_2_2_entry = Entry(self, justify='right')
data_2_2_entry.place(x=830, y=463, width=110, height=22)
data_2_3_entry = Entry(self, justify='right')
data_2_3_entry.place(x=1135, y=433, width=110, height=22)
data_2_4_entry = Entry(self, justify='right')
data_2_4_entry.place(x=1135, y=463, width=110, height=22)
data_2_1_unit = Label(self, text='mm', font=self.font_12, fg='#FFFFFF', bg=color_data_bg)
data_2_1_unit.place(x=940, y=433)
data_2_2_unit = Label(self, text='mm/s', font=self.font_12, fg='#FFFFFF', bg=color_data_bg)
data_2_2_unit.place(x=940, y=463)
data_2_3_unit = Label(self, text='mm', font=self.font_12, fg='#FFFFFF', bg=color_data_bg)
data_2_3_unit.place(x=1245, y=433)
data_2_4_unit = Label(self, text='mm/s', font=self.font_12, fg='#FFFFFF', bg=color_data_bg)
data_2_4_unit.place(x=1245, y=463)
"""graph""" #그래프를 그릴 바탕 캔버스 생성
canvas_2_1 = Canvas(self)
canvas_2_1.place(x=690, y=495, width=300, height=220)
canvas_2_2 = Canvas(self)
canvas_2_2.place(x=995, y=495, width=300, height=220)
def btn_cmd_1(self):
# worker(스레드) 생성
self.worker_1 = PLC_A()
self.worker_2 = Thread.CheckPLC_1(self)
self.worker_3 = Thread.Update_1(self)
# worker(스레드) 실행
self.worker_1.start()
self.worker_2.start()
self.worker_3.start()
self.run_button_off_1_2.place(x=550, y=225, width=80, height=40)
self.run_button_on_1_2.place(x=470, y=225, width=80, height=40)
self.run_button_off_1.configure(image=self.run_btn_off_image_1_2)
def btn_cmd_2(self):
# worker(스레드) 정지
self.worker_1.pause()
self.worker_2.pause()
self.worker_3.pause()
self.run_button_off_1_2.place_forget()
self.run_button_on_1_2.place_forget()
self.run_button_on_1.configure(image=self.run_btn_on_image_1_2, state='normal')
self.run_button_off_1.place(x=550, y=225, width=80, height=40)
self.run_button_off_1.configure(image=self.run_btn_off_image_1_1, state='normal')
def btn_cmd_3(self):
self.worker_4 = PLC_B()
self.worker_5 = Thread.CheckPLC_2(self)
self.worker_6 = Thread.Update_2(self)
self.worker_4.start()
self.worker_5.start()
self.worker_6.start()
self.run_button_off_2_2.place(x=1205, y=225, width=80, height=40)
self.run_button_on_2_2.place(x=1125, y=225, width=80, height=40)
self.run_button_off_2.configure(image=self.run_btn_off_image_2_2)
def btn_cmd_4(self):
self.worker_4.pause()
self.worker_5.pause()
self.worker_6.pause()
self.run_button_off_2_2.place_forget()
self.run_button_on_2_2.place_forget()
self.run_button_on_2.configure(image=self.run_btn_on_image_2_2, state='normal')
self.run_button_off_2.place(x=1205, y=225, width=80, height=40)
self.run_button_off_2.configure(image=self.run_btn_off_image_2_1, state='normal')
<file_sep>/Python code/Thread.py
"""
Thread ver_1.0.7
각 페이지별 스레딩 요소 부여
"""
## import modules
from tkinter import *
import os
from tkinter.font import Font
import threading
import datetime
import time
import sys
from Sub_UI_1 import *
from Sub_UI_2 import *
from Sub_UI_3 import *
from Get_data import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
## thread
#년,월,일 ,일 구현
class ShowDate(threading.Thread, Tk):
def __init__(self):
super().__init__()
self.daemon = True
def run(self):
font_day = Font(size=17, weight='bold')
date_live = datetime.datetime.now().strftime('%Y.%m.%d')
label = Label(font=font_day, fg='#FFFFFF', bg='#465260')
label.place(x=1327, y=36, height=25)
label.config(text=date_live)
label.after(1000, self.run)
#요일 구현
class ShowDay(threading.Thread, Tk):
def __init__(self):
super().__init__()
self.daemon = True
def run(self):
font_day = Font(size=17, weight='bold')
day_live = datetime.datetime.today().strftime('%A')
label = Label(font=font_day, fg='#FFFFFF', bg='#465260')
label.place(x=1455, y=34, height=27)
label.config(text=day_live)
label.after(1000, self.run)
# 시,분,초 구현
class ShowTime(threading.Thread, Tk):
def __init__(self):
super().__init__()
self.daemon = True
def run(self):
font_time = Font(size=45, weight='bold')
time_live = time.strftime('%H:%M:%S')
label = Label(font=font_time, fg='#FFFFFF', bg='#465260')
label.place(x=1320, y=65, width=235, height=50)
label.config(text=time_live)
label.after(1000, self.run)
#PLC_A의 상태 체크
class CheckPLC_1(threading.Thread, Frame):
def __init__(self, frame):
super().__init__()
self.daemon = True
self.frame = frame
self.running = True
def run(self):
self.state_run_image_1 = PhotoImage(file=os.path.join(current_file, 'state_run_1.png'))
self.state_run_image_2 = PhotoImage(file=os.path.join(current_file, 'state_run_2.png'))
self.state_run = Label(self.frame, image=self.state_run_image_2, bg='#FFFFFF')
self.state_run.place(x=325, y=325, width=100, height=50)
self.state_idle_image_1 = PhotoImage(file=os.path.join(current_file, 'state_idle_1.png'))
self.state_idle_image_2 = PhotoImage(file=os.path.join(current_file, 'state_idle_2.png'))
self.state_idle = Label(self.frame, image=self.state_idle_image_2, bg='#FFFFFF')
self.state_idle.place(x=425, y=325, width=100, height=50)
self.state_stop_image_1 = PhotoImage(file=os.path.join(current_file, 'state_stop_1.png'))
self.state_stop_image_2 = PhotoImage(file=os.path.join(current_file, 'state_stop_2.png'))
self.state_stop = Label(self.frame, image=self.state_stop_image_1, bg='#FFFFFF')
self.state_stop.place(x=525, y=325, width=100, height=50)
# 상태 변경
while self.running:
if check_server_a[0] == 'failed':
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_1)
elif bool_data_a[0] == 0 and check_server_a[0] == 'connected':
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_1)
self.state_stop.configure(image=self.state_stop_image_2)
elif bool_data_a[0] == 1 and check_server_a[0] == 'connected':
self.state_run.configure(image=self.state_run_image_1)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_2)
time.sleep(1)
def resume(self):
self.running = True
def pause(self):
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_1)
self.running = False
#PLC_B의 상태 체크
class CheckPLC_2(threading.Thread, Frame):
def __init__(self, frame):
super().__init__()
self.daemon = True
self.frame = frame
self.running = True
def run(self):
self.state_run_image_1 = PhotoImage(file=os.path.join(current_file, 'state_run_1.png'))
self.state_run_image_2 = PhotoImage(file=os.path.join(current_file, 'state_run_2.png'))
self.state_run = Label(self.frame, image=self.state_run_image_2, bg='#FFFFFF')
self.state_run.place(x=980, y=325, width=100, height=50)
self.state_idle_image_1 = PhotoImage(file=os.path.join(current_file, 'state_idle_1.png'))
self.state_idle_image_2 = PhotoImage(file=os.path.join(current_file, 'state_idle_2.png'))
self.state_idle = Label(self.frame, image=self.state_idle_image_2, bg='#FFFFFF')
self.state_idle.place(x=1080, y=325, width=100, height=50)
self.state_stop_image_1 = PhotoImage(file=os.path.join(current_file, 'state_stop_1.png'))
self.state_stop_image_2 = PhotoImage(file=os.path.join(current_file, 'state_stop_2.png'))
self.state_stop = Label(self.frame, image=self.state_stop_image_1, bg='#FFFFFF')
self.state_stop.place(x=1180, y=325, width=100, height=50)
# 상태 변경
while self.running:
if check_server_b[0] == 'failed':
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_1)
elif bool_data_b[0] == 0 and check_server_b[0] == 'connected':
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_1)
self.state_stop.configure(image=self.state_stop_image_2)
elif bool_data_b[0] == 1 and check_server_b[0] == 'connected':
self.state_run.configure(image=self.state_run_image_1)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_2)
time.sleep(1)
def resume(self):
self.running = True
def pause(self):
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_1)
self.running = False
#PLC_C의 상태 체크
class CheckPLC_3(threading.Thread, Frame):
def __init__(self, frame):
super().__init__()
self.daemon = True
self.frame = frame
self.running = True
def run(self):
self.state_run_image_1 = PhotoImage(file=os.path.join(current_file, 'state_run_1.png'))
self.state_run_image_2 = PhotoImage(file=os.path.join(current_file, 'state_run_2.png'))
self.state_run = Label(self.frame, image=self.state_run_image_2, bg='#FFFFFF')
self.state_run.place(x=325, y=325, width=100, height=50)
self.state_idle_image_1 = PhotoImage(file=os.path.join(current_file, 'state_idle_1.png'))
self.state_idle_image_2 = PhotoImage(file=os.path.join(current_file, 'state_idle_2.png'))
self.state_idle = Label(self.frame, image=self.state_idle_image_2, bg='#FFFFFF')
self.state_idle.place(x=425, y=325, width=100, height=50)
self.state_stop_image_1 = PhotoImage(file=os.path.join(current_file, 'state_stop_1.png'))
self.state_stop_image_2 = PhotoImage(file=os.path.join(current_file, 'state_stop_2.png'))
self.state_stop = Label(self.frame, image=self.state_stop_image_1, bg='#FFFFFF')
self.state_stop.place(x=525, y=325, width=100, height=50)
# 상태 변경
while self.running:
if check_server_c[0] == 'failed':
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_1)
elif bool_data_c[0] == 0 and check_server_c[0] == 'connected':
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_1)
self.state_stop.configure(image=self.state_stop_image_2)
elif bool_data_c[0] == 1 and check_server_c[0] == 'connected':
self.state_run.configure(image=self.state_run_image_1)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_2)
time.sleep(1)
def resume(self):
self.running = True
def pause(self):
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_1)
self.running = False
#PLC_D의 상태 체크
class CheckPLC_4(threading.Thread, Frame):
def __init__(self, frame):
super().__init__()
self.daemon = True
self.frame = frame
self.running = True
def run(self):
self.state_run_image_1 = PhotoImage(file=os.path.join(current_file, 'state_run_1.png'))
self.state_run_image_2 = PhotoImage(file=os.path.join(current_file, 'state_run_2.png'))
self.state_run = Label(self.frame, image=self.state_run_image_2, bg='#FFFFFF')
self.state_run.place(x=980, y=325, width=100, height=50)
self.state_idle_image_1 = PhotoImage(file=os.path.join(current_file, 'state_idle_1.png'))
self.state_idle_image_2 = PhotoImage(file=os.path.join(current_file, 'state_idle_2.png'))
self.state_idle = Label(self.frame, image=self.state_idle_image_2, bg='#FFFFFF')
self.state_idle.place(x=1080, y=325, width=100, height=50)
self.state_stop_image_1 = PhotoImage(file=os.path.join(current_file, 'state_stop_1.png'))
self.state_stop_image_2 = PhotoImage(file=os.path.join(current_file, 'state_stop_2.png'))
self.state_stop = Label(self.frame, image=self.state_stop_image_1, bg='#FFFFFF')
self.state_stop.place(x=1180, y=325, width=100, height=50)
# 상태 변경
while self.running:
if check_server_d[0] == 'failed':
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_1)
elif bool_data_d[0] == 0 and check_server_d[0] == 'connected':
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_1)
self.state_stop.configure(image=self.state_stop_image_2)
elif bool_data_d[0] == 1 and check_server_d[0] == 'connected':
self.state_run.configure(image=self.state_run_image_1)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_2)
time.sleep(1)
def resume(self):
self.running = True
def pause(self):
self.state_run.configure(image=self.state_run_image_2)
self.state_idle.configure(image=self.state_idle_image_2)
self.state_stop.configure(image=self.state_stop_image_1)
self.running = False
#PLC에서 전송된 값들을 Update해주는 클래스
class Update_1(threading.Thread, Frame):
def __init__(self, frame):
super().__init__()
self.daemon = True
self.frame = frame
self.running = True
def run(self):
# print
data_1_1_entry = Entry(self.frame, justify='right')
data_1_1_entry.place(x=175, y=433, width=110, height=22)
data_1_2_entry = Entry(self.frame, justify='right')
data_1_2_entry.place(x=175, y=463, width=110, height=22)
data_1_3_entry = Entry(self.frame, justify='right')
data_1_3_entry.place(x=480, y=433, width=110, height=22)
data_1_4_entry = Entry(self.frame, justify='right')
data_1_4_entry.place(x=480, y=463, width=110, height=22)
fig_1 = plt.figure() # 그래프를 그려주는 코드
x_1 = [0 for i in range(0, 10)]
y_1 = [0 for i in range(0, 10)]
fig_2 = plt.figure()
x_2 = [0 for i in range(0, 10)]
y_2 = [0 for i in range(0, 10)]
canvas_1 = FigureCanvasTkAgg(fig_1, master=self.frame)
canvas_1.get_tk_widget().place(x=35, y=495, width=300, height=220)
canvas_2 = FigureCanvasTkAgg(fig_2, master=self.frame)
canvas_2.get_tk_widget().place(x=340, y=495, width=300, height=220)
while self.running: #그래프에 적용시킬 데이터 Update 및 delete
data_1_1_entry.delete(0, END)
data_1_1_entry.insert(0, Belt_Pos_a[9])
data_1_1_entry.update()
data_1_2_entry.delete(0, END)
data_1_2_entry.insert(0, Belt_Vel_a[9])
data_1_2_entry.update()
data_1_3_entry.delete(0, END)
data_1_3_entry.insert(0, Circle_Pos_a[9])
data_1_3_entry.update()
data_1_4_entry.delete(0, END)
data_1_4_entry.insert(0, Circle_Vel_a[9])
data_1_4_entry.update()
fig_1.clear() #그래프 클리어(현재 업데이트를 캔버스로 하기때문에 무조건 클리어를 해주어야함)
ax_1 = fig_1.add_subplot(1, 1, 1) #그래프 구현
ax_1.set(ylim=[0, 400], title='Position_Belt')
ax_1.plot(x_1, y_1, color='blue')
fig_2.clear()
ax_2 = fig_2.add_subplot(1, 1, 1)
ax_2.set(ylim=[0, 400], title='Position_Circle')
ax_2.plot(x_2, y_2, color='red')
canvas_1.draw()
canvas_1.get_tk_widget().update()
canvas_2.draw()
canvas_2.get_tk_widget().update()
new_x_1 = x_1[9] + 1
del x_1[0]
x_1.insert(9, new_x_1)
del y_1[0]
y_1.insert(9, Belt_Pos_a[9])
new_x_2 = x_2[9] + 1
del x_2[0]
x_2.insert(9, new_x_2)
del y_2[0]
y_2.insert(9, Circle_Pos_a[9])
time.sleep(1)
def resume(self):
self.running = True
def pause(self):
self.running = False
class Update_2(threading.Thread, Frame):
def __init__(self, frame):
super().__init__()
self.daemon = True
self.frame = frame
self.running = True
def run(self):
# print
data_1_1_entry = Entry(self.frame, justify='right')
data_1_1_entry.place(x=830, y=433, width=110, height=22)
data_1_2_entry = Entry(self.frame, justify='right')
data_1_2_entry.place(x=830, y=463, width=110, height=22)
data_1_3_entry = Entry(self.frame, justify='right')
data_1_3_entry.place(x=1135, y=433, width=110, height=22)
data_1_4_entry = Entry(self.frame, justify='right')
data_1_4_entry.place(x=1135, y=463, width=110, height=22)
# draw
fig_1 = plt.figure()
x_1 = [0 for i in range(0, 10)]
y_1 = [0 for i in range(0, 10)]
fig_2 = plt.figure()
x_2 = [0 for i in range(0, 10)]
y_2 = [0 for i in range(0, 10)]
canvas_1 = FigureCanvasTkAgg(fig_1, master=self.frame)
canvas_1.get_tk_widget().place(x=690, y=495, width=300, height=220)
canvas_2 = FigureCanvasTkAgg(fig_2, master=self.frame)
canvas_2.get_tk_widget().place(x=995, y=495, width=300, height=220)
while self.running:
data_1_1_entry.delete(0, END)
data_1_1_entry.insert(0, Belt_Pos_b[9])
data_1_1_entry.update()
data_1_2_entry.delete(0, END)
data_1_2_entry.insert(0, Belt_Vel_b[9])
data_1_2_entry.update()
data_1_3_entry.delete(0, END)
data_1_3_entry.insert(0, Circle_Pos_b[9])
data_1_3_entry.update()
data_1_4_entry.delete(0, END)
data_1_4_entry.insert(0, Circle_Vel_b[9])
data_1_4_entry.update()
fig_1.clear()
ax_1 = fig_1.add_subplot(1, 1, 1)
ax_1.set(ylim=[0, 400], title='Position_Belt')
ax_1.plot(x_1, y_1, color='blue')
fig_2.clear()
ax_2 = fig_2.add_subplot(1, 1, 1)
ax_2.set(ylim=[0, 400], title='Position_Circle')
ax_2.plot(x_2, y_2, color='red')
canvas_1.draw()
canvas_1.get_tk_widget().update()
canvas_2.draw()
canvas_2.get_tk_widget().update()
new_x_1 = x_1[9] + 1
del x_1[0]
x_1.insert(9, new_x_1)
del y_1[0]
y_1.insert(9, Belt_Pos_b[9])
new_x_2 = x_2[9] + 1
del x_2[0]
x_2.insert(9, new_x_2)
del y_2[0]
y_2.insert(9, Circle_Pos_b[9])
time.sleep(1)
def resume(self):
self.running = True
def pause(self):
self.running = False
class Update_3(threading.Thread, Frame):
def __init__(self, frame):
super().__init__()
self.daemon = True
self.frame = frame
self.running = True
def run(self):
# print
data_1_1_entry = Entry(self.frame, justify='right')
data_1_1_entry.place(x=110, y=433, width=80, height=22)
data_1_2_entry = Entry(self.frame, justify='right')
data_1_2_entry.place(x=110, y=463, width=80, height=22)
data_1_3_entry = Entry(self.frame, justify='right')
data_1_3_entry.place(x=305, y=433, width=80, height=22)
data_1_4_entry = Entry(self.frame, justify='right')
data_1_4_entry.place(x=305, y=463, width=80, height=22)
data_1_5_entry = Entry(self.frame, justify='right')
data_1_5_entry.place(x=510, y=433, width=80, height=22)
data_1_6_entry = Entry(self.frame, justify='right')
data_1_6_entry.place(x=510, y=463, width=80, height=22)
# draw
fig_1 = plt.figure()
x_1 = [0 for i in range(0, 10)]
y_1_1 = [0 for i in range(0, 10)]
y_1_2 = [0 for i in range(0, 10)]
y_1_3 = [0 for i in range(0, 10)]
fig_2 = plt.figure()
x_2 = [0 for i in range(0, 10)]
y_2_1 = [0 for i in range(0, 10)]
y_2_2 = [0 for i in range(0, 10)]
y_2_3 = [0 for i in range(0, 10)]
canvas_1 = FigureCanvasTkAgg(fig_1, master=self.frame)
canvas_1.get_tk_widget().place(x=35, y=495, width=300, height=220)
canvas_2 = FigureCanvasTkAgg(fig_2, master=self.frame)
canvas_2.get_tk_widget().place(x=340, y=495, width=300, height=220)
while self.running:
data_1_1_entry.delete(0, END)
data_1_1_entry.insert(0, L_Pos[9])
data_1_1_entry.update()
data_1_2_entry.delete(0, END)
data_1_2_entry.insert(0, L_Vel[9])
data_1_2_entry.update()
data_1_3_entry.delete(0, END)
data_1_3_entry.insert(0, C_Pos[9])
data_1_3_entry.update()
data_1_4_entry.delete(0, END)
data_1_4_entry.insert(0, C_Vel[9])
data_1_4_entry.update()
data_1_5_entry.delete(0, END)
data_1_5_entry.insert(0, R_Pos[9])
data_1_5_entry.update()
data_1_6_entry.delete(0, END)
data_1_6_entry.insert(0, R_Vel[9])
data_1_6_entry.update()
fig_1.clear()
ax_1 = fig_1.add_subplot(1, 1, 1)
ax_1.set(ylim=[0, 120], title='Position')
ax_1.plot(x_1, y_1_1, color='blue', label='L')
ax_1.plot(x_1, y_1_2, color='red', label='C')
ax_1.plot(x_1, y_1_3, color='green', label='R')
ax_1.legend(loc='upper right')
fig_2.clear()
ax_2 = fig_2.add_subplot(1, 1, 1)
ax_2.set(ylim=[0, 35], title='Velocity')
ax_2.plot(x_2, y_2_1, color='blue', label='L')
ax_2.plot(x_2, y_2_2, color='red', label='C')
ax_2.plot(x_2, y_2_3, color='green', label='R')
ax_2.legend(loc='upper right')
canvas_1.draw()
canvas_1.get_tk_widget().update()
canvas_2.draw()
canvas_2.get_tk_widget().update()
new_x_1 = x_1[9] + 1
del x_1[0]
x_1.insert(9, new_x_1)
del y_1_1[0]
y_1_1.insert(9, L_Pos[9])
del y_1_2[0]
y_1_2.insert(9, C_Pos[9])
del y_1_3[0]
y_1_3.insert(9, R_Pos[9])
new_x_2 = x_2[9] + 1
del x_2[0]
x_2.insert(9, new_x_2)
del y_2_1[0]
y_2_1.insert(9, L_Vel[9])
del y_2_2[0]
y_2_2.insert(9, C_Vel[9])
del y_2_3[0]
y_2_3.insert(9, R_Vel[9])
time.sleep(1)
def resume(self):
self.running = True
def pause(self):
self.running = False
class Update_4(threading.Thread, Frame):
def __init__(self, frame):
super().__init__()
self.daemon = True
self.frame = frame
self.running = True
def run(self):
# print
data_1_1_entry = Entry(self.frame, justify='right')
data_1_1_entry.place(x=745, y=433, width=55, height=22)
data_1_2_entry = Entry(self.frame, justify='right')
data_1_2_entry.place(x=745, y=463, width=55, height=22)
data_1_3_entry = Entry(self.frame, justify='right')
data_1_3_entry.place(x=885, y=433, width=55, height=22)
data_1_4_entry = Entry(self.frame, justify='right')
data_1_4_entry.place(x=885, y=463, width=55, height=22)
data_1_5_entry = Entry(self.frame, justify='right')
data_1_5_entry.place(x=1040, y=433, width=55, height=22)
data_1_6_entry = Entry(self.frame, justify='right')
data_1_6_entry.place(x=1040, y=463, width=55, height=22)
data_1_7_entry = Entry(self.frame, justify='right')
data_1_7_entry.place(x=1190, y=433, width=55, height=22)
data_1_8_entry = Entry(self.frame, justify='right')
data_1_8_entry.place(x=1190, y=463, width=55, height=22)
# draw
fig_1 = plt.figure()
x_1 = [1+i for i in range(4)]
y_1 = [0 for i in range(4)]
xticks_1 = ['L_W', 'L_B', 'R_W', 'R_B']
fig_2 = plt.figure()
x_2 = [1+i for i in range(4)]
y_2 = [0 for i in range(4)]
xticks_2 = ['L_W', 'L_B', 'R_W', 'R_B']
canvas_1 = FigureCanvasTkAgg(fig_1, master=self.frame)
canvas_1.get_tk_widget().place(x=690, y=495, width=300, height=220)
canvas_2 = FigureCanvasTkAgg(fig_2, master=self.frame)
canvas_2.get_tk_widget().place(x=995, y=495, width=300, height=220)
while self.running:
data_1_1_entry.delete(0, END)
data_1_1_entry.insert(0, L_W_Pos[9])
data_1_1_entry.update()
data_1_2_entry.delete(0, END)
data_1_2_entry.insert(0, L_B_Pos[9])
data_1_2_entry.update()
data_1_3_entry.delete(0, END)
data_1_3_entry.insert(0, R_W_Pos[9])
data_1_3_entry.update()
data_1_4_entry.delete(0, END)
data_1_4_entry.insert(0, R_B_Pos[9])
data_1_4_entry.update()
data_1_5_entry.delete(0, END)
data_1_5_entry.insert(0, L_W_Vel[9])
data_1_5_entry.update()
data_1_6_entry.delete(0, END)
data_1_6_entry.insert(0, L_B_Vel[9])
data_1_6_entry.update()
data_1_7_entry.delete(0, END)
data_1_7_entry.insert(0, R_W_Vel[9])
data_1_7_entry.update()
data_1_8_entry.delete(0, END)
data_1_8_entry.insert(0, R_B_Vel[9])
data_1_8_entry.update()
fig_1.clear()
ax_1 = fig_1.add_subplot(1, 1, 1)
ax_1.set(ylim=[0, 400], title='Position')
ax_1.bar(x_1, y_1, color='blue')
ax_1.set_xticks(x_1)
ax_1.set_xticklabels(xticks_1)
fig_2.clear()
ax_2 = fig_2.add_subplot(1, 1, 1)
ax_2.set(ylim=[0, 400], title='Velocity')
ax_2.bar(x_2, y_2, color='red')
ax_2.set_xticks(x_2)
ax_2.set_xticklabels(xticks_2)
canvas_1.draw()
canvas_1.get_tk_widget().update()
canvas_2.draw()
canvas_2.get_tk_widget().update()
del y_1[0]
y_1.insert(0, L_W_Pos[9])
del y_1[1]
y_1.insert(1, L_B_Pos[9])
del y_1[2]
y_1.insert(2, R_W_Pos[9])
del y_1[3]
y_1.insert(3, R_B_Pos[9])
del y_2[0]
y_2.insert(0, L_W_Vel[9])
del y_2[1]
y_2.insert(1, L_B_Vel[9])
del y_2[2]
y_2.insert(2, R_W_Vel[9])
del y_2[3]
y_2.insert(3, R_B_Vel[9])
time.sleep(1)
def resume(self):
self.running = True
def pause(self):
self.running = False<file_sep>/Python code/kakao_msg.py
"""
kakao_msg.py
에러발생시 OPEN API를 사용하여 작동하는 이벤트
OPEN API를 사용하기 위한 필수 요소를 작성한 함수
"""
from tkinter.constants import NONE
import requests
import json
from datetime import *
import time
import Get_data
class kakao_send():
def tokens(): #KAKAO메세지를위한 토큰 재발급이 되지않았을때 토큰값을 발급해야함
url = "https://kauth.kakao.com/oauth/token"
data = { #메세지를 보내기 위한 필요한 데이터
"grant_type" : "authorization_code",
"client_id" : "<KEY>",
"redirect_uri" : "https://localhost.com",
"code" : "wK1q2P1Th_gn-omzLEAjYuYkUvL23-Yd5ogrfOZIZhuna3-yOZNp2qhk4l-SMYZK8PE8UAopcFAAAAF8RJHEYQ"
} #정해진 시간안에 리프레쉬 하지않으면 코드 기능 상실
response = requests.post(url, data=data)
tokens = response.json()
print(tokens)
with open("kakao_token.json", "w") as fp:
json.dump(tokens, fp)
def refreshToken(): #토큰값 재발급
with open("kakao_token.json","r") as fp:
token = json.load(fp)
REST_API_KEY = "<KEY>"
url = "https://kauth.kakao.com/oauth/token"
data = {
"grant_type": "refresh_token",
"client_id":f"{REST_API_KEY}",
"refresh_token": token['refresh_token'] #refresh_token 값
}
resp = requests.post(url , data=data)
token['access_token'] = resp.json()['access_token']
with open("kakao_token.json", "w") as fp:
json.dump(token, fp)
return(token)
def kakao_text(): #카카오톡메세지를 보내는 코드
list_time = []
list_time.insert(0,time.strftime('%y-%m-%d %H:%M:%S'))
get_error_code = Get_data.PLC_C()
error_code = get_error_code.error_code()
with open("kakao_token.json","r") as fp:
tokens = json.load(fp)
kcreds = {"access_token" : tokens.get('access_token')}
kheaders = {"Authorization": "Bearer " + kcreds.get('access_token')}
kakaotalk_template_url = "https://kapi.kakao.com/v2/api/talk/memo/default/send"
naver_url = "https://naver.com" #web_url 항목을 넣기 위한 주소(아무거나 상관 없음) 필수 조건
text = f"""{list_time[0]} \nError Code\nEC_Error {error_code[0]}\nMC_Error {error_code[1]}\n에러가 발생했습니다. 기동을 중지합니다."""
template = { #메세지를 구성하는 템플릿 구성
"object_type": "text",
"text": text,
"link":{"web_url" : naver_url}
}
payload = {"template_object" : json.dumps(template)} # JSON 형식 -> 문자열 변환
res = requests.post(kakaotalk_template_url, data=payload, headers=kheaders) # 카카오톡 보내기
# if res.json().get('result_code') == 0:
# # print('메시지를 성공적보냈습니다.')
# else:
# # print('메시지를 성공적으로 보내지 못했습니다. 오류메시지 : ' + str(res.json()))<file_sep>/README.md
# Python을 이용한 실시간 공정 모니터링 시스템
<img src="./img/image01.png">
## 프로젝트의 목적
- 스마트팩토리 관련 교육을 받는 학생들이 쉽게 이용할 수 있는 공정 모니터링 시스템 제작
- 공정 작동 중 이상상황 발생시 즉시 관리자에게 알림을 보내는 이상알림 기능 제작
## 개발 환경
- 운영체제 : Windows 10
- PC 프로그래밍 : Visual Studio Code
- PLC 프로그래밍 : Sysmac Studio
- 사용언어 : Python
## 기능
- 소켓 통신을 이용한 PLC 데이터 수집
- 멀티스레드 적용을 통한 다중 PLC 연결 및 데이터 송수신
- 데이터 베이스 연동을 통한 데이터 축적
- 간편한 모니터링 UI
- 그래프를 이용한 데이터 출력
- 이상상황 발생시 OpenAPI를 이용한 카카오톡 메시지 전송
- 이상상황 발생시 OpenAPI를 이용한 네이버 메일 전송
<file_sep>/Python code/UI.py
"""
UI.py
UI 업데이트 v2
페이지 전환의 개념을 notebook을 이용한 UI
notebook을 이용할 때 내부 frame을 가진 frame은 적용이 안됨.
-> frame을 시각적인 표현만 하기로 함.
off를 누르면 모니터링 스레딩 종료
"""
## import modules
from tkinter import *
from tkinter.ttk import *
import os
from tkinter.font import Font
import sys
from Sub_UI_1 import *
from Sub_UI_2 import *
from Sub_UI_3 import *
from Thread import *
from winsound import *
import Get_data
## initial value
# file direction
current_file = os.path.dirname(__file__)
# color
color_main_bg = '#465260'
color_frame_bg = '#3A4552'
color_tab_bg = '#3A4757'
color_btn_normal = '#364153'
color_btn_clicked = '#2A313E'
## sub_section_0
class Subframe_0(Frame):
def __init__(self):
super().__init__(width=1330, height=750)
self.initUI()
def initUI(self):
# frame
frame_0 = Label(self, background=color_main_bg)
frame_0.place(x=0, y=0, width=1330, height=750)
frame_1 = Label(self, background=color_frame_bg)
frame_1.place(x=20, y=20, width=1290, height=710)
## main section
class MainWindow(Tk):
def __init__(self):
super().__init__()
# window size (16:9 비율)
w = 1600 # 창 너비
h = 900 # 창 높이
sw = self.winfo_screenwidth() # 스크린 너비
sh = self.winfo_screenheight() # 스크린 높이
x = int((sw - w) / 2) # 창 생성 시 x 좌표
y = int((sh - h) / 2) # 창 생성 시 y 좌표
# window format
self.title('Factory Monitoring') # 프로그램 타이틀
self.geometry('{0}x{1}+{2}+{3}'.format(w, h, x, y)) # 창 생성 조건 설정
self.resizable(False, False) # 창 사이즈 고정
self.iconbitmap(os.path.join(current_file, 'icon.ico'))
# font
self.font_version = Font(size=12)
self.font_main_title_1 = Font(size=45, weight='bold')
self.font_main_title_2 = Font(size=30, weight='bold')
self.font_tab_button = Font(size=18, weight='bold')
# worker 생성
self.worker_1 = ShowDate()
self.worker_2 = ShowDay()
self.worker_3 = ShowTime()
# 구성요소 불러오기
self.initUI()
def initUI(self):
# notebook
self.notebook = Notebook(self, width=1330, height=750) # notebook 생성
self.notebook.place(x=269, y=127)
page_0 = Subframe_0()
self.notebook.add(page_0)
page_1 = SubFrame_1()
self.notebook.add(page_1)
page_2 = SubFrame_2()
self.notebook.add(page_2)
page_3 = SubFrame_3()
self.notebook.add(page_3)
# title
frame_title = Frame(self, background=color_main_bg) # title
frame_title.place(x=0, y=0, width=1600, height=150)
self.title_image = PhotoImage(file=os.path.join(current_file, 'main_title_60px.png'))
title_label_1 = Label(frame_title, image=self.title_image, bg=color_main_bg)
title_label_1.place(x=430, y=40, width=60, height=60)
title_label_2 = Label(frame_title, text='KOPO Factory', font=self.font_main_title_1, fg='#FFFFFF', bg=color_main_bg)
title_label_2.place(x=500, y=35)
title_label_3 = Label(frame_title, text='[Seongnam]', font=self.font_main_title_2, fg='#FFFFFF', bg=color_main_bg)
title_label_3.place(x=915, y=50)
title_label_4 = Label(frame_title, text='Made by AI+X\nVer 1.0.7', font=self.font_version, fg='#7F7F7F', bg=color_main_bg, justify='left')
title_label_4.place(x=20, y=95)
division_line = Label(frame_title, background='#7F7F7F') # 구분선
division_line.place(x=0, y=145, width=1600, height=5)
self.worker_1.start() # 날짜 표시
self.worker_2.start() # 요일 표시
self.worker_3.start() # 시간 표시
# side tab menu
frame_tab = Frame(self, background=color_tab_bg)
frame_tab.place(x=0, y=150, width=270, height=750)
self.tab_button_1 = Button(frame_tab, text='H O M E', font=self.font_tab_button, fg='#FFFFFF', bg=color_btn_clicked, bd=0,
activeforeground='#FFFFFF', activebackground=color_btn_clicked, command=self.btn_cmd_1)
self.tab_button_1.place(x=0, y=30, width=270, height=50)
self.tab_button_2 = Button(frame_tab, text='Section1', font=self.font_tab_button, fg='#FFFFFF', bg=color_btn_normal, bd=0,
activeforeground='#FFFFFF', activebackground=color_btn_clicked, command=self.btn_cmd_2)
self.tab_button_2.place(x=0, y=80, width=270, height=50)
self.tab_button_3 = Button(frame_tab, text='Section2', font=self.font_tab_button, fg='#FFFFFF', bg=color_btn_normal, bd=0,
activeforeground='#FFFFFF', activebackground=color_btn_clicked, command=self.btn_cmd_3)
self.tab_button_3.place(x=0, y=130, width=270, height=50)
self.tab_button_4 = Button(frame_tab, text='Section3', font=self.font_tab_button, fg='#FFFFFF', bg=color_btn_normal, bd=0,
activeforeground='#FFFFFF', activebackground=color_btn_clicked, command=self.btn_cmd_4)
self.tab_button_4.place(x=0, y=180, width=270, height=50)
def btn_cmd_1(self):
self.tab_button_1.configure(bg=color_btn_clicked)
self.tab_button_2.configure(bg=color_btn_normal)
self.tab_button_3.configure(bg=color_btn_normal)
self.tab_button_4.configure(bg=color_btn_normal)
self.notebook.select(0)
def btn_cmd_2(self):
self.tab_button_1.configure(bg=color_btn_normal)
self.tab_button_2.configure(bg=color_btn_clicked)
self.tab_button_3.configure(bg=color_btn_normal)
self.tab_button_4.configure(bg=color_btn_normal)
self.notebook.select(1)
def btn_cmd_3(self):
self.tab_button_1.configure(bg=color_btn_normal)
self.tab_button_2.configure(bg=color_btn_normal)
self.tab_button_3.configure(bg=color_btn_clicked)
self.tab_button_4.configure(bg=color_btn_normal)
self.notebook.select(2)
def btn_cmd_4(self):
self.tab_button_1.configure(bg=color_btn_normal)
self.tab_button_2.configure(bg=color_btn_normal)
self.tab_button_3.configure(bg=color_btn_normal)
self.tab_button_4.configure(bg=color_btn_clicked)
self.notebook.select(3)
#PLC_A의 에러발생이벤트
class Error_Window_PLC_A(Tk):
def __init__(self):
super().__init__()
get_error_code = Get_data.PLC_A()
error_code = get_error_code.error_code()
self.title('MOTER_ERROR')
self.geometry('500x300+800+500')
self.configure(background='#465260')
self.iconbitmap(os.path.join(current_file,'warning_105171.ico'))
PlaySound('Windows Ding.wav',SND_FILENAME)
self.Error_image = PhotoImage(file=os.path.join(current_file, 'warning_105171.png'),master=self)
error_image = Label(self, image=self.Error_image,bg='#465260')
error_image.place(x=10,y=85)
error_msg= '에러가 발생하였습니다 \n\n EC_Error_Code : {0} \n\nMC_Error_Code : {1}\n\n장비를 재시작 해주세요'.format((error_code[0]),error_code[1])
error_text = Label(self,text=error_msg,bg='#465260',fg = "White",font=('Lucida Grande',18))
error_text.place(x=90,y=30)
self.Error_image2 = PhotoImage(file=os.path.join(current_file, 'button_background3.png'),master=self)
error_label = Label(self,image=self.Error_image2,bd=0,bg='#465260')
error_label.place(x=175,y=215)
self.Error_image3 = PhotoImage(file=os.path.join(current_file, 'Error_button.png'),master=self)
error_button = Button(self,image=self.Error_image3,bd=0,bg='white',command=self.error_btu_cmd)
error_button.place(x=180,y=220)
def error_btu_cmd(self):
self.destroy()
#PLC_B의 에러발생이벤트
class Error_Window_PLC_B(Tk):
def __init__(self):
super().__init__()
get_error_code = Get_data.PLC_B()
error_code = get_error_code.error_code()
self.title('MOTER_ERROR')
self.geometry('500x300+800+500')
self.configure(background='#465260')
self.iconbitmap(os.path.join(current_file,'warning_105171.ico'))
PlaySound('Windows Ding.wav',SND_FILENAME)
self.Error_image = PhotoImage(file=os.path.join(current_file, 'warning_105171.png'),master=self)
error_image = Label(self, image=self.Error_image,bg='#465260')
error_image.place(x=10,y=85)
error_msg= '에러가 발생하였습니다 \n\n EC_Error_Code : {0} \n\nMC_Error_Code : {1}\n\n장비를 재시작 해주세요'.format((error_code[0]),error_code[1])
error_text = Label(self,text=error_msg,bg='#465260',fg = "White",font=('Lucida Grande',18))
error_text.place(x=90,y=30)
self.Error_image2 = PhotoImage(file=os.path.join(current_file, 'button_background3.png'),master=self)
error_label = Label(self,image=self.Error_image2,bd=0,bg='#465260')
error_label.place(x=175,y=215)
self.Error_image3 = PhotoImage(file=os.path.join(current_file, 'Error_button.png'),master=self)
error_button = Button(self,image=self.Error_image3,bd=0,bg='white',command=self.error_btu_cmd)
error_button.place(x=180,y=220)
def error_btu_cmd(self):
self.destroy()
#PLC_C의 에러발생이벤트
class Error_Window_PLC_C(Tk):
def __init__(self):
super().__init__()
get_error_code = Get_data.PLC_C()
error_code = get_error_code.error_code()
self.title('MOTER_ERROR')
self.geometry('500x300+800+500')
self.configure(background='#465260')
self.iconbitmap(os.path.join(current_file,'warning_105171.ico'))
PlaySound('Windows Ding.wav',SND_FILENAME)
self.Error_image = PhotoImage(file=os.path.join(current_file, 'warning_105171.png'),master=self)
error_image = Label(self, image=self.Error_image,bg='#465260')
error_image.place(x=10,y=85)
error_msg= '에러가 발생하였습니다 \n\n EC_Error_Code : {0} \n\nMC_Error_Code : {1}\n\n장비를 재시작 해주세요'.format((error_code[0]),error_code[1])
error_text = Label(self,text=error_msg,bg='#465260',fg = "White",font=('Lucida Grande',18))
error_text.place(x=90,y=30)
self.Error_image2 = PhotoImage(file=os.path.join(current_file, 'button_background3.png'),master=self)
error_label = Label(self,image=self.Error_image2,bd=0,bg='#465260')
error_label.place(x=175,y=215)
self.Error_image3 = PhotoImage(file=os.path.join(current_file, 'Error_button.png'),master=self)
error_button = Button(self,image=self.Error_image3,bd=0,bg='white',command=self.error_btu_cmd)
error_button.place(x=180,y=220)
def error_btu_cmd(self):
self.destroy()
#PLC_D의 에러발생이벤트
class Error_Window_PLC_D(Tk):
def __init__(self):
super().__init__()
get_error_code = Get_data.PLC_D()
error_code = get_error_code.error_code()
self.title('MOTER_ERROR')
self.geometry('500x300+800+500')
self.configure(background='#465260')
self.iconbitmap(os.path.join(current_file,'warning_105171.ico'))
PlaySound('Windows Ding.wav',SND_FILENAME)
self.Error_image = PhotoImage(file=os.path.join(current_file, 'warning_105171.png'),master=self)
error_image = Label(self, image=self.Error_image,bg='#465260')
error_image.place(x=10,y=85)
error_msg= '에러가 발생하였습니다 \n\n EC_Error_Code : {0} \n\nMC_Error_Code : {1}\n\n장비를 재시작 해주세요'.format((error_code[0]),error_code[1])
error_text = Label(self,text=error_msg,bg='#465260',fg = "White",font=('Lucida Grande',18))
error_text.place(x=90,y=30)
self.Error_image2 = PhotoImage(file=os.path.join(current_file, 'button_background3.png'),master=self)
error_label = Label(self,image=self.Error_image2,bd=0,bg='#465260')
error_label.place(x=175,y=215)
self.Error_image3 = PhotoImage(file=os.path.join(current_file, 'Error_button.png'),master=self)
error_button = Button(self,image=self.Error_image3,bd=0,bg='white',command=self.error_btu_cmd)
error_button.place(x=180,y=220)
def error_btu_cmd(self):
self.destroy()
#소켓연결 타임아웃이벤트
class TimeOut_Error_Window(Tk):
def __init__(self):
super().__init__()
self.title('TIMEOUT_ERROR')
self.geometry('500x200+800+500')
self.configure(background='#465260')
self.iconbitmap(os.path.join(current_file,'warning_105171.ico'))
PlaySound('Windows Ding.wav',SND_FILENAME)
self.Error_image = PhotoImage(file=os.path.join(current_file, 'warning_105171.png'),master=self)
error_image = Label(self, image=self.Error_image,bg='#465260')
error_image.place(x=10,y=35)
error_text = Label(self,text='(Error) 서버와 연결할 수 없습니다.\n\nIP주소와 포트번호를 다시 확인해주세요.',bg='#465260',fg = "White",font=('Lucida Grande',15))
error_text.place(x=90,y=30)
self.Error_image2 = PhotoImage(file=os.path.join(current_file, 'button_background3.png'),master=self)
error_label = Label(self,image=self.Error_image2,bd=0,bg='#465260')
error_label.place(x=175,y=115)
self.Error_image3 = PhotoImage(file=os.path.join(current_file, 'Error_button.png'),master=self)
error_button = Button(self,image=self.Error_image3,bd=0,bg='white',command=self.error_btu_cmd)
error_button.place(x=180,y=120)
def error_btu_cmd(self):
self.destroy()
#소켓연결 포트연결이상 이벤트
class ConnectionRefused_Error_Window(Tk):
def __init__(self):
super().__init__()
self.title('CONNECTION_ERROR')
self.geometry('500x200+800+500')
self.configure(background='#465260')
self.iconbitmap(os.path.join(current_file,'warning_105171.ico'))
PlaySound('Windows Ding.wav',SND_FILENAME)
self.Error_image = PhotoImage(file=os.path.join(current_file, 'warning_105171.png'),master=self)
error_image = Label(self, image=self.Error_image,bg='#465260')
error_image.place(x=10,y=35)
error_text = Label(self,text='(Error) 서버와의 연결이 거부되었습니다.\n\n포트번호를 다시 확인해주세요.',bg='#465260',fg = "White",font=('Lucida Grande',15))
error_text.place(x=90,y=30)
self.Error_image2 = PhotoImage(file=os.path.join(current_file, 'button_background3.png'),master=self)
error_label = Label(self,image=self.Error_image2,bd=0,bg='#465260')
error_label.place(x=175,y=115)
self.Error_image3 = PhotoImage(file=os.path.join(current_file, 'Error_button.png'),master=self)
error_button = Button(self,image=self.Error_image3,bd=0,bg='white',command=self.error_btu_cmd)
error_button.place(x=180,y=120)
def error_btu_cmd(self):
self.destroy()
def main():
app = MainWindow()
app.mainloop()
if __name__ == '__main__':
main()<file_sep>/Python code/Data.py
"""
Data.py
----------------------------------------
수집한 데이터의 변환 및 데이터데이스에 축적
"""
## import modules
import binascii
import struct
from bitstring import BitArray
import mariadb
## sequence
# data_convert
class Data_convert:
def data_convert(get): #통신으로 인해 섞인 데이터순서를 변환해주는 함수
get_1 = BitArray(bytes=get, length=16).bytes
get_2 = BitArray(bytes=get, length=16, offset=16).bytes
cut_1 = list(get_1)
cut_2 = list(get_2)
cut_1.reverse()
cut_2.reverse()
c = bytearray(cut_1 + cut_2)
unpack = struct.unpack('f', c)
changed_form = list(unpack)
result = round(changed_form[0], 3)
return result
def data_convert_error(get): #통신으로 인해 섞인 에러코드 데이터순서를 변환해주는 함수
data_1 = BitArray(bytes=get, length=16).bytes
data_2 = BitArray(bytes=get, length=16, offset=16).bytes
data_3 = BitArray(bytes=get, length=32, offset=32).bytes
cut_1 = list(data_1)
cut_2 = list(data_2)
cut_1.reverse()
cut_2.reverse()
array= bytearray(cut_1 + cut_2)
total = array + data_3
changed_form = bytes(total)
result = "0x" + changed_form.decode()
return result
# use_DB
class Use_db:
# write_db
def write_db(get):
db_number = get[0]
cur_number = get[1]
plc_id = get[2]
data_1 = get[3]
data_2 = get[4]
data_3 = get[5]
data_4 = get[6]
try:
insert_query = "INSERT INTO " + plc_id + " (Belt_Pos, Belt_Vel, Circle_Pos, Circle_Vel) VALUES (?,?,?,?)" # 쿼리문 작성
cur_number.execute( insert_query, (data_1, data_2, data_3, data_4)) # 쿼리문 실행
db_number.commit() # Commit 메소드를 실행하여 db에 적용
except mariadb.Error as e:
# print("Error connecting to MariaDB Platform : {}".format(e))
pass
def write_db_delta(get):
db_number = get[0]
cur_number = get[1]
plc_id = get[2]
data_1 = get[3]
data_2 = get[4]
data_3 = get[5]
data_4 = get[6]
data_5 = get[7]
data_6 = get[8]
try:
insert_query = "INSERT INTO " + plc_id + " (L_Pos, L_Vel, C_Pos, C_Vel, R_Pos, R_Vel) VALUES (?,?,?,?,?,?)"
cur_number.execute( insert_query, (data_1, data_2, data_3, data_4, data_5, data_6))
db_number.commit()
except mariadb.Error as e:
# print("Error connecting to MariaDB Platform : {}".format(e))
pass
def write_db_piano(get):
db_number = get[0]
cur_number = get[1]
plc_id = get[2]
data_1 = get[3]
data_2 = get[4]
data_3 = get[5]
data_4 = get[6]
data_5 = get[7]
data_6 = get[8]
data_7 = get[9]
data_8 = get[10]
try:
insert_query = "INSERT INTO " + plc_id + " (L_W_Pos, L_B_Pos, R_W_Pos, R_B_Pos, L_W_Vel, L_B_Vel, R_W_Vel, R_B_Vel) VALUES (?,?,?,?,?,?,?,?)"
cur_number.execute( insert_query, (data_1, data_2, data_3, data_4, data_5, data_6, data_7, data_8))
db_number.commit()
except mariadb.Error as e:
# print("Error connecting to MariaDB Platform : {}".format(e))
pass
def write_db_error(get):
db_number = get[0]
cur_number = get[1]
plc_id = get[2]
data_1 = get[3]
data_2 = get[4]
try:
insert_query = "INSERT INTO " + plc_id + " (ECError, MCError) VALUES (?,?)"
cur_number.execute( insert_query, (data_1, data_2))
db_number.commit()
except mariadb.Error as e:
# print("Error connecting to MariaDB Platform : {}".format(e))
pass
# read_db
def read_db(get):
cur_number = get[0]
plc_id = get[1]
cur_number.execute("SELECT * FROM " + plc_id)
db_row = cur_number.fetchall()
last_row = db_row[-1]
last_row_list = list(last_row)
return last_row_list
|
666cd6cf051cf3ef94c822a7bd6b2eb29e1d1829
|
[
"Markdown",
"Python"
] | 7 |
Python
|
doney0222/PLC_monitoring_system
|
872f21be075712886210a70a5b8445d6e33558f6
|
a7e39886a23c8f9993c4835c42c67be164b5218b
|
refs/heads/master
|
<file_sep>var path, Stream, Sprockets, VinylNodeCollection, RequireState, Base, Locals, SprocketsStream, Environment, Transform, PassThrough, ref$;
path = require('path');
Stream = require('stream');
Sprockets = require('../index');
VinylNodeCollection = require('../vinyl_node_collection');
RequireState = require('../vinyl_node_collection/require_state');
Base = require('./base');
Locals = require('./locals');
SprocketsStream = require('./stream');
Environment = (function(superclass){
var prototype = extend$((import$(Environment, superclass).displayName = 'Environment', Environment), superclass).prototype, constructor = Environment;
function Environment(){
this.engines = Object.create(Sprockets.engines);
this.engine_extensions = Object.create(Sprockets.engine_extensions);
this.mime_exts = Object.create(Sprockets.mime_exts);
this.mime_types = Object.create(Sprockets.mime_types);
this.templates = Object.create(Sprockets.templates);
this.preprocessors = Object.create(Sprockets.preprocessors);
this.postprocessors = Object.create(Sprockets.postprocessors);
this.view_locals = Object.create(Sprockets.viewLocals);
this.manifest_filepaths = {};
this.vinyl_node_collections = {};
this.is_produciton = process.env.NODE_ENV === 'production';
this.base_paths = [];
}
Object.defineProperty(prototype, 'isProduction', {
get: function(){
return this.is_produciton;
},
configurable: true,
enumerable: true
});
Object.defineProperty(prototype, 'basePaths', {
get: function(){
return this.base_paths;
},
configurable: true,
enumerable: true
});
Object.defineProperty(prototype, 'viewLocals', {
get: function(){
return Locals.call(Object.create(this.view_locals), this);
},
configurable: true,
enumerable: true
});
prototype.createJavascriptsStream = function(){
return this._createStream('application/javascript');
};
prototype.createStylesheetsStream = function(){
return this._createStream('text/css');
};
prototype.createHtmlsStream = function(){
return this._createStream('text/html');
};
return Environment;
}(Base));
module.exports = Environment;
Transform = Stream.Transform, PassThrough = Stream.PassThrough;
ref$ = Environment.prototype;
ref$._addBasePath = function(it){
var base_paths, i$, len$, basePath;
base_paths = this.base_paths;
for (i$ = 0, len$ = base_paths.length; i$ < len$; ++i$) {
basePath = base_paths[i$];
if (basePath === it) {
return false;
}
}
return !!base_paths.push(it);
};
ref$._createStream = function(mime_type){
var targetExtention, collection, ref$, tplEngines, extEngines, dispatchStartStream, dispatchEngineStream, dispatchEndStream, stream, this$ = this;
targetExtention = this.mime_types[mime_type].extensions[0];
collection = (ref$ = this.vinyl_node_collections)[mime_type] || (ref$[mime_type] = new VinylNodeCollection());
collection.updateVersion();
function createTemplates(extname){
var passThroughStream;
passThroughStream = new PassThrough({
objectMode: true
});
this$.templates[extname](this$, passThroughStream, dispatchEngineStream);
return passThroughStream;
}
function getOrCreateTemplates(extname){
return tplEngines[extname] || (tplEngines[extname] = createTemplates(extname));
}
function createEngines(extname){
var passThroughStream;
passThroughStream = new PassThrough({
objectMode: true
});
this$.engines[extname](this$, passThroughStream, dispatchEngineStream);
return passThroughStream;
}
function getOrCreateEngines(extname){
return extEngines[extname] || (extEngines[extname] = createEngines(extname));
}
tplEngines = {};
extEngines = {};
dispatchStartStream = new Transform({
objectMode: true
});
dispatchStartStream._transform = function(file, enc, done){
var extname;
extname = path.extname(file.path);
if (path.extname(path.basename(file.path, extname)) && this$.templates[extname]) {
getOrCreateTemplates(extname).write(file);
} else {
getOrCreateEngines(extname).write(file);
}
done();
};
dispatchEngineStream = new Transform({
objectMode: true
});
dispatchEngineStream._transform = function(file, enc, done){
getOrCreateEngines(path.extname(file.path)).write(file);
done();
};
dispatchEndStream = new Transform({
objectMode: true
});
dispatchEndStream._transform = function(file, enc, done){
collection.finalizeNode(file, stream);
stream._endEventually();
done();
};
extEngines[targetExtention] = new PassThrough({
objectMode: true
});
this.engines[targetExtention](this, extEngines[targetExtention], dispatchEndStream);
return stream = new SprocketsStream({
mimeType: mime_type,
environment: this,
collection: collection,
dispatchStartStream: dispatchStartStream
});
};
ref$._endStream = function(stream){
var mimeType, Postprocessor, collection;
mimeType = stream.mimeType;
Postprocessor = this.postprocessors[mimeType];
collection = this.vinyl_node_collections[mimeType];
new Postprocessor(this, collection, stream).process();
};
function extend$(sub, sup){
function fun(){} fun.prototype = (sub.superclass = sup).prototype;
(sub.prototype = new fun).constructor = sub;
if (typeof sup.extended == 'function') sup.extended(sub);
return sub;
}
function import$(obj, src){
var own = {}.hasOwnProperty;
for (var key in src) if (own.call(src, key)) obj[key] = src[key];
return obj;
}<file_sep>module.exports = {
registerEngine: function(ext, engineFn, options){
var that;
this.engines[ext] = engineFn;
if (that = options.mime_type) {
this.engine_extensions[ext] = this.mime_types[that].extensions[0];
}
}
};<file_sep>var PassThrough;
module.exports = PassThrough = (function(){
PassThrough.displayName = 'PassThrough';
var prototype = PassThrough.prototype, constructor = PassThrough;
function PassThrough(environment, collection, stream){
this.environment = environment;
this.collection = collection;
this.stream = stream;
}
prototype.process = function(){
this.collection.vinyls.forEach(this.stream.push, this.stream);
};
return PassThrough;
}());<file_sep>## 0.3.0 (2014-07-02)
#### Bug Fixes
* **VinylNodeCollection:** split src path with dest vinyl to resolve bug ([2ef393dd](https://github.com/tomchentw/sprocket/commit/2ef393dd6d97905937d22779e6d0a9c535a1fe2b))
#### Features
* **Engines:** lazy loaded engines depedencies ([6055aef4](https://github.com/tomchentw/sprocket/commit/6055aef4b979df8b0b7deb3d2d49345bae80a6e2))
* **Preprocessors:** lazy loaded preprocessors depedencies ([63cd29d9](https://github.com/tomchentw/sprocket/commit/63cd29d9e19147b76643ae073563d8d0ed92e644))
* **Sprockets:**
* lazily link engines and templates ([c2f60bca](https://github.com/tomchentw/sprocket/commit/c2f60bca682deb2e31db7605699cef779b3abef9))
* add templates support and ejs for html ([ce9260ba](https://github.com/tomchentw/sprocket/commit/ce9260ba6268e2f07ab53078a440770b495860c6))
### 0.2.4 (2014-07-02)
#### Bug Fixes
* **Node:** update version directly if it's stable ([556132d6](https://github.com/tomchentw/sprocket/commit/556132d6036dbe4788ca3d71838dfc2d36d0fd10))
#### Features
* **package.json:** update dependencies ([072d3446](https://github.com/tomchentw/sprocket/commit/072d34460a8b2e6f75922331226b17c454fc19d5))
### 0.2.3 (2014-06-28)
#### Bug Fixes
* **Engines:** correct multimatch pattern for gulp-filter ([f37cfa0d](https://github.com/tomchentw/sprocket/commit/f37cfa0da87edab18063d9555d72958332ebe6aa))
### 0.2.2 (2014-06-27)
#### Features
* **Sprockets:** add to base_path for directory vinyls ([0bb54dc5](https://github.com/tomchentw/sprocket/commit/0bb54dc57fda47286c7486f29fdc24a92d62ba27))
* **Node:** added full content cached support ([64ce2944](https://github.com/tomchentw/sprocket/commit/64ce2944bb13314749955925c955332e6eed619b))
### 0.2.1 (2014-06-22)
## 0.2.0 (2014-06-22)
#### Features
* **Sprocket:** rewrite module from ruby ([6c91e27f](https://github.com/tomchentw/sprocket/commit/6c91e27fb06ec4bda706b1fe5b8527e907ce1a6a))
* **Sprockets:**
* add ejs template support ([ebd3a813](https://github.com/tomchentw/sprocket/commit/ebd3a813f2fe88e8182713a15c5a03d617676a7c))
* added viewLocals for prototype chain ([315990a1](https://github.com/tomchentw/sprocket/commit/315990a1c35e58b7838f0ce9be2ae922ce333bb7))
* added htmls stream support and postprocessors ([cacd1cd8](https://github.com/tomchentw/sprocket/commit/cacd1cd80dd97bce08fab5b33eea4f8ebb30a9d8))
* remove old sprocket ([4d6a8b87](https://github.com/tomchentw/sprocket/commit/4d6a8b87f98b1b9a8da7b8f826fe3602e47d7404))
* remove preprocessor and compressor ([a046396e](https://github.com/tomchentw/sprocket/commit/a046396e6aa66d6468190b03a161050fcdd1176e))
* **package.json:** update dependencies for html and ejs ([0eea92d2](https://github.com/tomchentw/sprocket/commit/0eea92d29e24132765e8f5323879ead22218a1c6))
### 0.1.2 (2014-06-20)
#### Features
* **package.json:** add less extension support ([92bc3d0c](https://github.com/tomchentw/sprocket/commit/92bc3d0c331a49893a0488753f19ac3750d0a4cb))
### 0.1.1 (2014-06-15)
#### Bug Fixes
* **package.json:** downgrade through2 to 0.5.1 ([f76333ff](https://github.com/tomchentw/sprocket/commit/f76333ff582886106355b82cabbe9c825cbf68d4))
## 0.1.0 (2014-06-15)
#### Features
* **SprocketEnvironment:** remove nconf dependency ([61318e3a](https://github.com/tomchentw/sprocket/commit/61318e3a576a0be0b8c6c03ab4ea5fac8eafc102))
#### Breaking Changes
* remove nconf support, please set process.env.NODE_ENV directly
([61318e3a](https://github.com/tomchentw/sprocket/commit/61318e3a576a0be0b8c6c03ab4ea5fac8eafc102))
### 0.0.2 (2014-06-14)
#### Bug Fixes
* **RequireState:** manifest filepath ([975eae15](https://github.com/tomchentw/sprocket/commit/975eae15e8012163601ac0e410e0c33c1fee8c44))
* **SprocketRequireState:** MANIFEST_BASENAME only in getManifestFilepath ([dca05971](https://github.com/tomchentw/sprocket/commit/dca0597109816dd870ad19518e8cd3e7d2f509c7))
* **VinylNode.SuperNode:** recursively build dependencies in forEach ([1acc430d](https://github.com/tomchentw/sprocket/commit/1acc430d47ca0f54c0952e4bc836f48eaec69dc5))
* **VinylNodeCollection:** bugs with prefilled .min files ([3f46854a](https://github.com/tomchentw/sprocket/commit/3f46854a54f60fe2f3b563db5fe2381ab6375c26))
#### Features
* **Edge.Circular:** add circular for require_self ([20573608](https://github.com/tomchentw/sprocket/commit/20573608203acfc17c70501fb9de6346b9e4c114))
* **RequireState:** extract manifest creation code and prettify it ([05fe4920](https://github.com/tomchentw/sprocket/commit/05fe49208d0ea2e6e10943b2b1f4b9b1f6b1e301))
* **Sprocket:**
* better API for expose and watch ([13b1fb46](https://github.com/tomchentw/sprocket/commit/13b1fb46ce9e3e75bd10cb380e1402c0faccfa75))
* add development environment support ([0903d0f3](https://github.com/tomchentw/sprocket/commit/0903d0f30c8c41973ba8aaf1966d257b936dd122))
* add environment, gulp and view helpers ([dd1a8b8a](https://github.com/tomchentw/sprocket/commit/dd1a8b8a6c66ef59e04ebdbe452f9c38aa8cf6c9))
* **SprocketCollection:** store dependencies as object ([ca03e82b](https://github.com/tomchentw/sprocket/commit/ca03e82bb9d667d146fd0ab218ef8a3bef77f3f8))
* **SuperNode.Directory:** add require_directory support ([cddbe83a](https://github.com/tomchentw/sprocket/commit/cddbe83afc705f0fa8e1de6056fd61e06aa39041))
* **SupportedExtname:** extract as class and fix several bugs ([21cfa5ed](https://github.com/tomchentw/sprocket/commit/21cfa5ed41fb2ffade004ae2dea4479990e6a120))
* **VinylNode:**
* fix dependencies changes while watcher active ([331d6b57](https://github.com/tomchentw/sprocket/commit/331d6b5726b60b12137891021b0aeeef1c0650c1))
* export Collection and other classes ([cc573bf4](https://github.com/tomchentw/sprocket/commit/cc573bf4e2e0a90f59a9513a45238d1cad4a67e1))
* **VinylNode.Collection:** add require_self support and update directive regex ([4d1c6d6b](https://github.com/tomchentw/sprocket/commit/4d1c6d6bc8b1d40e88d9c8eda45098b9380df52c))
* **VinylNodeCollection:** add reversioning support ([38e1a804](https://github.com/tomchentw/sprocket/commit/38e1a804e57a754150603ccca174a3d17dcb3a0e))
<file_sep>module.exports = (function(){
exports.displayName = 'exports';
var prototype = exports.prototype, constructor = exports;
function exports(keyPath, _collection){
this.keyPath = keyPath;
this._collection = _collection;
this._inRequireStates = [true];
this._keyPaths = {};
this._vinyls = [];
this._totalBufferSize = 0;
}
Object.defineProperty(prototype, 'keyPaths', {
get: function(){
return this._keyPaths;
},
configurable: true,
enumerable: true
});
Object.defineProperty(prototype, 'vinyls', {
get: function(){
return this._vinyls;
},
configurable: true,
enumerable: true
});
prototype.bufferWithSeperator = function(seperator){
return new Buffer(this._totalBufferSize + this._vinyls.length * seperator.length);
};
prototype.buildDependenciesInState = function(edge){
this._inRequireStates.push(edge.isRequireState);
try {
return edge._buildDependencies(this);
} finally {
this._inRequireStates.pop();
}
};
prototype.needRequireOrInclude = function(node){
var ref$;
if ((ref$ = this._inRequireStates)[ref$.length - 1]) {
return !this._keyPaths[node.keyPath];
} else {
return true;
}
};
prototype.addNodeIfNeeded = function(node){
var vinyl;
if (this.needRequireOrInclude(node)) {
vinyl = node.vinyl;
this._keyPaths[node.keyPath] = true;
if (vinyl.isBuffer()) {
this._vinyls.push(vinyl);
this._totalBufferSize += vinyl.contents.length;
}
}
};
return exports;
}());<file_sep>module.exports = {
registerPreprocessor: function(mime_type, preprocessor){
this.preprocessors[mime_type] = preprocessor;
},
registerPostprocessor: function(mime_type, postprocessor){
this.postprocessors[mime_type] = postprocessor;
}
};
|
a65b923c92cfe0c487db02023f4b51232328972f
|
[
"JavaScript",
"Markdown"
] | 6 |
JavaScript
|
MrOrz/sprocket
|
5ab694afbcafbd25764af58c5698c5ae9a9311d8
|
224b98736a3d02da8d5e5752061700d8690def63
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MVC;
/**
*
* @author HP
*/
public class AdminMVC {
AdminView adminview = new AdminView();
AdminModel adminmodel = new AdminModel();
AdminDAO adminDAO = new AdminDAO();
LihatAdminView lihatview = new LihatAdminView();
AdminController admincontroller = new AdminController(adminmodel, adminview, adminDAO, lihatview);
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MVC;
/**
*
* @author HP
*/
import java.awt.event.*;
import javax.swing.*;
public class LoginController {
LoginView loginview;
public LoginController(LoginView loginview){
this.loginview = loginview;
loginview.tombol2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String uname = loginview.getUname();
String pw = loginview.getPw();
if(uname.isEmpty() || pw.isEmpty()){
JOptionPane.showMessageDialog(null, "Username atau Password kosong");
} else if (uname.equals("admin") && pw.equals("<PASSWORD>")){
loginview.setVisible(false);
JOptionPane.showMessageDialog(null, "Login Berhasil");
new AdminMVC();
} else if (uname.equals("karyawan") && pw.equals("<PASSWORD>")){
loginview.setVisible(false);
JOptionPane.showMessageDialog(null, "Login Berhasil");
new KaryawanMVC();
}else {
JOptionPane.showMessageDialog(null, "Username atau Password salah");
}
}
});
loginview.back.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
loginview.setVisible(false);
}
});
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MVC;
/**
*
* @author HP
*/
public class AdminModel {
private String nama, posisi, alamat, no_hp, id;
private String gaji, jam, search, id_p, tunjangan, pajak, total;
//contructor
public void setAdminModel(String nnama, String nposisi, String nalamat, String nno_hp, String ngaji, String njam, String ntunjangan, String npajak, String ntotal, String nid_p){
this.nama = nnama;
this.posisi= nposisi;
this.alamat= nalamat;
this.no_hp= nno_hp;
this.gaji= ngaji;
this.jam= njam;
this.tunjangan= ntunjangan;
this.pajak= npajak;
this.total= ntotal;
this.id_p= nid_p;
}
public String getNama(){
return nama;
}
public void setNama(String nama){
this.nama = nama;
}
public String getPosisi(){
return posisi;
}
public void setPosisi(String posisi){
this.posisi = posisi;
}
public String getAlamat(){
return alamat;
}
public void setAlamat(String alamat){
this.alamat = alamat;
}
public String getNoHP(){
return no_hp;
}
public void setNoHP(String no_hp){
this.no_hp = no_hp;
}
public String getGaji(){
return gaji;
}
public void setGaji(String gaji){
this.gaji = gaji;
}
public String getJam(){
return jam;
}
public void setJam(String jam){
this.jam = jam;
}
public String getSearch(){
return search;
}
public void setSearch(String search){
this.search = search;
}
public String getId_p(){
return id_p;
}
public void setId_p(String id_p){
this.id_p = id_p;
}
public String getTunjangan(){
return tunjangan;
}
public void setTunjangan(String tunjangan){
this.tunjangan = tunjangan;
}
public String getPajak(){
return pajak;
}
public void setPajak(String pajak){
this.pajak = pajak;
}
public String getTotal(){
return total;
}
public void setTotal(String total){
this.total = total;
}
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MVC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author HP
*/
public class AdminDAO {
private int jmlData;
private Connection koneksi;
private Statement statement;
//constructor berfungsi utk melakukan sebuah koneksi saat ada object baru dibuat
public AdminDAO(){
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/gaji";
koneksi = DriverManager.getConnection(url, "root", "");
statement = koneksi.createStatement();
JOptionPane.showMessageDialog(null, "Koneksi Berhasil");
} catch (ClassNotFoundException ex){
JOptionPane.showMessageDialog(null, "Class Not Found : " + ex);
} catch (SQLException ex){
JOptionPane.showMessageDialog(null, "SQL Exception : " + ex);
}
}
public void Insert(AdminModel Model){
try{
String query = "INSERT INTO admin VALUES (NULL,'"+Model.getId_p()+"','"+
Model.getNama()+"','"+Model.getPosisi()+"','"+
Model.getAlamat()+"','"+Model.getNoHP()+"','"+Model.getGaji()+"','"+Model.getJam()+"','"+
Model.getTunjangan()+"','"+Model.getPajak()+"','"+Model.getTotal()+"')";
statement.executeUpdate(query); //execute querynya
JOptionPane.showMessageDialog(null, "Data disimpan");
} catch (Exception sql){
JOptionPane.showMessageDialog(null, sql.getMessage());
}
}
//utk mengambil data dari db dan mengatur ke dalam tabel
public String[][] readAdmin(){
try{
//baris sejumlah data, kolomnya ada 8
String data[][] = new String[getJmldata()][7];
//penganmbilan dta dlm java dari db
String query = "SELECT * FROM admin";
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()){ //lanjut kedata selanjutnya jmlData bertambah
data[jmlData][0] = resultSet.getString("id_admin");//penomoran
data[jmlData][1] = resultSet.getString("nama_a");//id adalah nama field di database
data[jmlData][2] = resultSet.getString("posisi_a");
data[jmlData][3] = resultSet.getString("gaji_a");
data[jmlData][4] = resultSet.getString("jam");
data[jmlData][5] = resultSet.getString("tunjangan");
data[jmlData][6] = resultSet.getString("total");
jmlData++; //barisnya berpindah terus
}
return data;
} catch (SQLException e){
System.out.println(e.getMessage());
System.out.println("SQL Error");
return null;
}
}
public int getJmldata(){
try{
//pengambilan data kedlm java dri db
String query = "SELECT * FROM admin";
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()){//lanjut kedata selanjutnya, jmlData bertambah
jmlData++;
}
return jmlData;
} catch (SQLException e){
System.out.println(e.getMessage());
System.out.println("SQL Error");
return 0;
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MVC;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableModel;
/**
*
* @author HP
*/
public class LihatAdminView extends JFrame{
JLabel ljudul;
JButton show, home, tambah, data, petunjuk, admin;
JTable tabel;
DefaultTableModel tableModel;
JScrollPane scrollPane;//buat scroll
Object namaKolom[] = {"ID", "Nama", "Posisi", "Gaji Pokok", "Jam Lembur", "Tunjangan", "Total Gaji"};//membuat kolom dlm array
Statement statement;
public LihatAdminView(){
setTitle("FORM PENGISIAN DATA FILM");
String cstatus[] = {"Selesai","Belum"};//membuat isi combobox
//atur tabel
tableModel = new DefaultTableModel(namaKolom,0); //0 baris
tabel = new JTable(tableModel);
scrollPane = new JScrollPane(tabel);
//atur tabel
ljudul = new JLabel("Nama");
//atur tombol
show = new JButton("Show");
home = new JButton("Home");
tambah = new JButton("Tambah");
petunjuk = new JButton("Petunjuk");
admin = new JButton("Admin");
data = new JButton("Data");
setLayout(null);
add(ljudul);
add(show);
add(home);
add(tambah);
add(petunjuk);
add(admin);
add(data);
add(scrollPane);
ljudul.setBounds(25, 230, 50, 20);
data.setBounds(740, 247, 75, 25);
petunjuk.setBounds(420, 395, 80, 25);
show.setBounds(520, 395, 75, 25);
tambah.setBounds(615, 395, 75, 25);
home.setBounds(710, 395, 75, 25);
admin.setBounds(800, 395, 55, 25);
scrollPane.setBounds(25, 25, 825, 200);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
setSize(900,500); //atur luas jendela
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
|
ad9a918110dc3db0a55da2da32b18e6ce415b4e7
|
[
"Java"
] | 5 |
Java
|
Farisa123180103/responsi
|
adb3e66fd7b5482fab392ce8a3a30a12dc93e2ff
|
dbca56ddfe6b102ae71f3eca3f5b3a452cb5fac3
|
refs/heads/master
|
<repo_name>lramirezq/newmodels<file_sep>/app/controllers/busquedas_controller.rb
class BusquedasController < ApplicationController
def modelo
puts "Buscando Modelo...."
sql_specific = ""
sql_specific += "and \"tipo_id\" ilike ? "
sql_specific += "and \"tipo_id\" ilike ? "
puts sql_specific
#Recibendo Parametros
tid = params[:tipo_id]
if tid !=nil && !tid.empty?
puts "Tipo ID ***************" + tid + "*********************"
end
nid = params[:numero_id]
if nid !=nil && !nid.empty?
puts "Numero ID ***************" + nid + "*********************"
end
nombres = params[:nombres]
if nombres !=nil && !nombres.empty?
puts "Nombres ***************" + nombres + "*********************"
end
apellidos = params[:apellidos]
if apellidos !=nil && !apellidos.empty?
puts "Nombres ***************" + apellidos + "*********************"
end
sexo = params[:sexo]
if sexo !=nil && !sexo.empty?
puts "Sexo ***************" + sexo + "*********************"
end
fnacimiento = params[:fecha_nacimiento]
puts "fnacimiento ***************" + fnacimiento.to_s + "*********************"
nacionalidad = params[:nacionalidad]
if nacionalidad !=nil && !nacionalidad.empty?
puts "nacionalidad ***************" + nacionalidad + "*********************"
end
tfijo = params[:telefono_fijo]
if tfijo !=nil && !tfijo.empty?
puts "tfijo ***************" + tfijo + "*********************"
end
movil = params[:movil]
if movil !=nil && !movil.empty?
puts "movil ***************" + movil + "*********************"
end
direccion = params[:direccion]
if direccion !=nil && !direccion.empty?
puts "direccion ***************" + direccion + "*********************"
end
comuna = params[:comuna]
if comuna !=nil && !comuna.empty?
puts "comuna ***************" + comuna + "*********************"
end
ciudad = params[:ciudad]
if ciudad !=nil && !ciudad.empty?
puts "ciudad ***************" + ciudad + "*********************"
end
pais = params[:pais]
if pais !=nil && !pais.empty?
puts "pais ***************" + pais + "*********************"
end
licencia = params[:licencia]
if licencia !=nil && !licencia.empty?
puts "licencia ***************" + licencia + "*********************"
end
agencia = params[:agencia]
if agencia !=nil && !agencia.empty?
puts "agencia ***************" + agencia + "*********************"
end
email = params[:email]
if email !=nil && !email.empty?
puts "email ***************" + email + "*********************"
end
r_tipo_id = params[:tipo_id_responsable]
if r_tipo_id !=nil && !r_tipo_id.empty?
puts "r_tipo_id ***************" + r_tipo_id + "*********************"
end
r_numero_id = params[:numero_id_responsable]
if r_numero_id !=nil && !r_numero_id.empty?
puts "r_numero_id ***************" + r_numero_id + "*********************"
end
r_nombres = params[:nombres_responsable]
if r_nombres !=nil && !r_nombres.empty?
puts "r_nombres ***************" + r_nombres + "*********************"
end
r_apellidos = params[:apellidos_responsable]
if r_apellidos !=nil && !r_apellidos.empty?
puts "r_apellidos ***************" + r_apellidos + "*********************"
end
estatura = params[:estatura]
if estatura !=nil && !estatura.empty?
puts "estatura ***************" + estatura + "*********************"
end
calzado = params[:calzado]
if calzado !=nil && !calzado.empty?
puts "calzado ***************" + calzado + "*********************"
end
idiomas = params[:idiomas]
if idiomas !=nil && !idiomas.empty?
puts "idiomas ***************" + idiomas + "*********************"
end
tpantalon = params[:tpantalon]
if tpantalon !=nil && !tpantalon.empty?
puts "tpantalon ***************" + tpantalon + "*********************"
end
tcamisa = params[:tcamisa]
if tcamisa !=nil && !tcamisa.empty?
puts "tcamisa ***************" + tcamisa + "*********************"
end
busto = params[:busto]
if busto !=nil && !busto.empty?
puts "busto ***************" + busto + "*********************"
end
cintura = params[:cintura]
if cintura !=nil && !cintura.empty?
puts "cintura ***************" + cintura + "*********************"
end
cadera = params[:cadera]
if cadera !=nil && !cadera.empty?
puts "cadera ***************" + cadera + "*********************"
end
ccabello = params[:ccabello]
if ccabello !=nil && !ccabello.empty?
puts "ccabello ***************" + ccabello + "*********************"
end
lcabello = params[:lcabello]
if lcabello !=nil && !lcabello.empty?
puts "lcabello ***************" + lcabello + "*********************"
end
etnia = params[:etnia]
if etnia !=nil && !etnia.empty?
puts "etnia ***************" + etnia + "*********************"
end
cojos = params[:cojos]
if cojos !=nil && !cojos.empty?
puts "cojos ***************" + cojos + "*********************"
end
hot = params[:hot]
if hot !=nil && !hot.empty?
puts "hot ***************" + hot + "*********************"
else
hot = false
end
hobbie = params[:hobbie]
if hobbie !=nil && !hobbie.empty?
puts "hobbie ***************" + hobbie + "*********************"
end
mcuello = params[:mcuello]
if mcuello !=nil && !mcuello.empty?
puts "mcuello ***************" + mcuello + "*********************"
end
terno = params[:terno]
if terno !=nil && !terno.empty?
puts "terno ***************" + terno + "*********************"
end
desfile = params[:desfile]
if desfile !=nil && !desfile.empty?
puts "desfile ***************" + desfile + "*********************"
else
desfile = false
end
dientes = params[:dientes]
if dientes !=nil && !dientes.empty?
puts "dientes ***************" + dientes + "*********************"
else
dientes = false
end
actor = params[:actor]
if actor !=nil && !actor.empty?
puts "actor ***************" + actor + "*********************"
else
actor = false
end
frenillos = params[:frenillos]
if frenillos !=nil && !frenillos.empty?
puts "frenillos ***************" + frenillos + "*********************"
else
frenillos = false
end
experiencia = params[:experiencia]
if experiencia !=nil && !experiencia.empty?
puts "experiencia ***************" + experiencia + "*********************"
else
experiencia = false
end
#Comenzamos a Buscar !!
query = "select * from modelos inner join caracteristicas
on modelos.\"id\" = caracteristicas.\"modelo_id\"
where \"tipo_id\" ilike ?
and \"numero_id\" ilike ?
and \"nombres\" ilike ?
and \"apellidos\" ilike ?
and \"sexo\" ilike ?
and \"nacionalidad\" ilike ?
and \"tipo_id_responsable\" ilike ?
and \"numero_id_responsable\" ilike ?
and \"nombres_responsable\" ilike ?
and \"apellidos_responsable\" ilike ?
and \"telefono_fijo\" ilike ?
and \"movil\" ilike ?
and \"direccion\" ilike ?
and \"comuna\" ilike ?
and \"ciudad\" ilike ?
and \"pais\" ilike ?
and \"licencia\" ilike ?
and \"email\" ilike ?
and \"estatura\" ilike ?
and \"calzado\" ilike ?
and \"idiomas\" ilike ?
and \"tpantalon\" ilike ?
and \"tcamisa\" ilike ?
and \"busto\" ilike ?
and \"cintura\" ilike ?
and \"cadera\" ilike ?
and \"cojos\" ilike ?
and \"ccabello\" ilike ?
and \"lcabello\" ilike ?
and \"etnia\" ilike ?
and \"hobbie\" ilike ?
and \"mcuello\" ilike ?
and \"terno\" ilike ?
--Booleans
and \"desfile\" = ?
and \"dientes\" = ?
and \"actor\" = ?
and \"frenillos\" = ?
and \"experiencia\" = ?
and \"hot\" = ?"
puts "Esta query se Ejecutara [" + query +"]"
@modelos = Modelo.find_by_sql [query,
"%#{tid}%",
"%#{nid}%",
"%#{nombres}%",
"%#{apellidos}%",
"%#{sexo}%",
"%#{nacionalidad}%",
"%#{r_tipo_id}%",
"%#{r_numero_id}%",
"%#{r_nombres}%",
"%#{r_apellidos}%",
"%#{tfijo}%",
"%#{movil}%",
"%#{direccion}%",
"%#{comuna}%",
"%#{ciudad}%",
"%#{pais}%",
"%#{licencia}%",
"%#{email}%",
"%#{estatura}%",
"%#{calzado}%",
"%#{idiomas}%",
"%#{tpantalon}%",
"%#{tcamisa}%",
"%#{busto}%",
"%#{cintura}%",
"%#{cadera}%",
"%#{cojos}%",
"%#{ccabello}%",
"%#{lcabello}%",
"%#{etnia}%",
"%#{hobbie}%",
"%#{mcuello}%",
"%#{terno}%",
"#{desfile}",
"#{dientes}",
"#{actor}",
"#{frenillos}",
"#{experiencia}",
"#{hot}"
]
#Enviamos resultados a la vista !!
respond_to do |format|
format.html # modelo.html.erb
format.xml { render :xml => @reports }
end
end
end
<file_sep>/app/models/foto.rb
class Foto < ActiveRecord::Base
belongs_to :modelo
has_attached_file :picture, :default_url => '/images/perfil.png',
:styles => {
:thumb=> "50x50#",
:small => "300x300>",
:large => "600x600>"
}
validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/png']
end
<file_sep>/public/javascripts/application.js
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("true");
$(link).closest(".fields").hide();
}
function remove_fields_act(link) {
$(link).prev("input[type=hidden]").val("true");
$(link).closest(".fields").hide();
recalcular();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).before(content.replace(regexp, new_id));
}
function add_fields_act(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).before(content.replace(regexp, new_id));
recalcular();
}
function add_fields_especial(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).before(content.replace(regexp, new_id));
}
function aparece(id){
objeto=document.getElementById(id);
objeto.style.display="block";
}
function desaparece(id){
objeto=document.getElementById(id);
objeto.style.display="none";
}
function tipo_id(id){
tipoid = id.id
rut = tipoid.replace('tipoidentificacion', 'rut');
rid= rut;
rut = "#"+rut;
if(id.value =="RUN"){
$(rut).Rut({
on_error: function(){ document.getElementById(rid).value=""; document.getElementById(rid).focus; alert('El rut ingresado es incorrecto'); }, format_on: 'keyup'
});
}else{
$(rut).val("");
$(rut).unbind();
}
}
function tipo_id_competencia(id){
tipoid = id.id
rut = tipoid.replace('tipo_id', 'rutmodelo');
rid= rut;
rut = "#"+rut;
if(id.value =="RUN"){
$(rut).Rut({
on_error: function(){ document.getElementById(rid).value=""; document.getElementById(rid).focus; alert('El rut ingresado es incorrecto'); }, format_on: 'keyup'
});
}else{
$(rut).val("");
$(rut).unbind();
}
}
function buscaEvento(id){
//alert(id.value);
$.getScript('/javascripts/causas.js?codigo=' + id.value);
}
function upvictimas(id){
$.getScript('/javascripts/victimas.js?rut=' + id.value+ "&control=" + id.id);
}
function upimputados(id){
$.getScript('/javascripts/imputados.js?rut=' + id.value+ "&control=" + id.id);
}
function estado_causa(id){
if(id.value=="Terminada"){
alert("Debe agregar Informe de Causa Terminada")
$("#field_terminada").show("slow");
}else{
$("#field_terminada").hide("slow");
}
}
function tipo_id(id){
tipoid = id.id
rut = tipoid.replace('tipo_id', 'numero_id');
rid= rut;
rut = "#"+rut;
if(id.value =="RUN"){
$(rut).Rut({
on_error: function(){ document.getElementById(rid).value=""; document.getElementById(rid).focus; alert('El rut ingresado es incorrecto'); }, format_on: 'keyup'
});
}else{
$(rut).val("");
$(rut).unbind();
}
}
function calculaEdad(x){
alert(x.value);
}
function recalcular(){
//Contar Actividades
var a = 56;
x = 0;y=0;i=0;j=0;totalcheck=0;totalchecktrue=0;
while (i == 0){
if(document.getElementById("proyecto_fases_attributes_"+x+"_actividads_attributes_"+y+"_estado")){
totalcheck++;
obj = document.getElementById("proyecto_fases_attributes_"+x+"_actividads_attributes_"+y+"_estado");
if(obj.checked){
totalchecktrue++;
}
y++;
j=0;
}else{
y=0;
x++;
j++;
}
if(j==2){
i=1;
}
}
a = (totalchecktrue * 100 / totalcheck);
$("#progressbar").progressbar({ value: a });
$("#porcentaje").val(a.toFixed(2));
$("#proyecto_porcentaje").val(a.toFixed(2));
}
function upperCase(elem) {
var x=elem.value
elem.value=x.toUpperCase()
}
function testing(x, f){
id = f.id;
id_proyecto = $("#proyecto_id").val();
id = id.substring(0, id.length - 24);
id = "#"+id+"valida";
rechaza = id.substring(0, id.length - 6);
rechaza+="rechaza"
if (x =="valida"){
$(id).attr('checked', true);
$(rechaza).attr('checked', false);
}else{
$(id).attr('checked', false);
$(rechaza).attr('checked', true);
}
document.forms["edit_proyecto_"+id_proyecto].submit();
}
function calcular_edad(dia_nacim,mes_nacim,anio_nacim)
{
fecha_hoy = new Date();
ahora_anio = fecha_hoy.getYear();
ahora_mes = fecha_hoy.getMonth();
ahora_dia = fecha_hoy.getDate();
edad = (ahora_anio + 1900) - anio_nacim;
if ( ahora_mes < (mes_nacim - 1))
{
edad--;
}
if (((mes_nacim - 1) == ahora_mes) && (ahora_dia < dia_nacim))
{
edad--;
}
if (edad > 1900)
{
edad -= 1900;
}
return edad;
}
$(document).ready(function ()
{
$('#modelo_fecha_nacimiento_3i').change(function() {
dia = $('#modelo_fecha_nacimiento_3i').val();
mes = $('#modelo_fecha_nacimiento_2i').val();
anno = $('#modelo_fecha_nacimiento_1i').val();
edad = calcular_edad(dia,mes,anno);
$('#edad').val(edad);
if (edad < 18){
$('#responsable').attr("style", "visibility: visible")
}else{
$('#responsable').attr("style", "visibility: hidden")
}
});
$('#modelo_fecha_nacimiento_2i').change(function() {
dia = $('#modelo_fecha_nacimiento_3i').val();
mes = $('#modelo_fecha_nacimiento_2i').val();
anno = $('#modelo_fecha_nacimiento_1i').val();
edad = calcular_edad(dia,mes,anno);
$('#edad').val(edad);
if (edad < 18){
$('#responsable').attr("style", "visibility: visible")
}else{
$('#responsable').attr("style", "visibility: hidden")
}
});
$('#modelo_fecha_nacimiento_1i').change(function() {
dia = $('#modelo_fecha_nacimiento_3i').val();
mes = $('#modelo_fecha_nacimiento_2i').val();
anno = $('#modelo_fecha_nacimiento_1i').val();
edad = calcular_edad(dia,mes,anno);
$('#edad').val(edad);
if (edad < 18){
$('#responsable').attr("style", "visibility: visible")
}else{
$('#responsable').attr("style", "visibility: hidden")
}
});
//Do XML / XSL transformation here
});
function buscaCliente(id){
$.getScript('/javascripts/cliente.js?id=' + id);
}
function buscaModelo(id){
$.getScript('/javascripts/modelo.js?numero_id=' + id.value + '&idf=' + id.id);
}
function recalcular_edad(){
dia = $('#modelo_fecha_nacimiento_3i').val();
mes = $('#modelo_fecha_nacimiento_2i').val();
anno = $('#modelo_fecha_nacimiento_1i').val();
edad = calcular_edad(dia,mes,anno);
$('#edad').val(edad);
if (edad < 18){
$('#responsable').attr("style", "visibility: visible")
}else{
$('#responsable').attr("style", "visibility: hidden")
}
}<file_sep>/app/mailers/evento_mailer.rb
class EventoMailer < ActionMailer::Base
default :from => "<EMAIL>"
# Metodo de envio para informes
def enviar_informes(competencia, root_url)
@root_url = root_url.to_s.gsub(/\/+$/, '')
@competencia = competencia
@destinos = Mantenedor.mail_evento.collect {|d| d.valor}.join(', ')
puts "Esto llego aca !" + competencia.tipocompetencia.to_s
#Recibo destinos desde el mantenedor
mail(:to => @destinos, :subject => "New Models | Envio Detalle de Competencias - #{competencia.id.to_s}")
end
end
<file_sep>/app/controllers/javascripts_controller.rb
# -*- coding: utf-8 -*-
class JavascriptsController < ApplicationController
def comunas
@comunas = Mantenedor.comunas
@regiones = Mantenedor.regiones
respond_to do |format|
format.js {render :layout => false}
end
end
def cliente
@cliente = Cliente.find(params[:id])
respond_to do |format|
format.js {render :layout => false}
end
end
def modelo
m = Modelo.where(:numero_id => params[:numero_id])
@modelo = m[0]
puts "elnombre => " + @modelo.to_s
respond_to do |format|
format.js {render :layout => false}
end
end
end
<file_sep>/app/models/detallecompetencia.rb
class Detallecompetencia < ActiveRecord::Base
belongs_to :competencia
end
<file_sep>/app/models/documento.rb
class Documento < ActiveRecord::Base
belongs_to :fase
has_attached_file :archivo
validates_attachment_presence :archivo
validates_attachment_size :archivo, :less_than => 3.megabytes
end
<file_sep>/app/models/modelo.rb
class Modelo < ActiveRecord::Base
validates_uniqueness_of :numero_id
has_one :caracteristica, :dependent => :destroy
accepts_nested_attributes_for :caracteristica, :allow_destroy => true
has_many :telefonos, :dependent => :destroy
accepts_nested_attributes_for :telefonos, :allow_destroy => true
has_many :albums, :dependent => :destroy
accepts_nested_attributes_for :albums, :allow_destroy => true
validates_presence_of :tipo_id, :numero_id, :nombres, :apellidos, :sexo, :fecha_nacimiento, :nacionalidad, :movil, :direccion, :comuna, :email
mount_uploader :image, ImageUploader
end
<file_sep>/app/models/archivo.rb
class Archivo < ActiveRecord::Base
belongs_to :fase
has_attached_file :adjunto
validates_presence_of :detalle
validates_attachment_presence :adjunto
end
|
e3d92ed8c378c84ba552ab8ef502816358998d88
|
[
"JavaScript",
"Ruby"
] | 9 |
Ruby
|
lramirezq/newmodels
|
9f78ba024d2f5b586ef56f43b4a51bb3a05cc182
|
c059607d123fdc788a0e6b379ff88025947b4110
|
refs/heads/main
|
<file_sep>import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import Variable
import torch.nn.functional as F
def YOLO_loss(pred_confidence, pred_box, ann_confidence, ann_box):
# input:
# pred_confidence -- the predicted class labels from YOLO, [batch_size, 5,5, num_of_classes]
# pred_box -- the predicted bounding boxes from YOLO, [batch_size, 5,5, 4]
# ann_confidence -- the ground truth class labels, [batch_size, 5,5, num_of_classes]
# ann_box -- the ground truth bounding boxes, [batch_size, 5,5, 4]
#
# output:
# loss -- a single number for the value of the loss function, [1]
# TODO: write a loss function for YOLO
#
# For confidence (class labels), use cross entropy (F.cross_entropy)
# You can try F.binary_cross_entropy and see which loss is better
# For box (bounding boxes), use smooth L1 (F.smooth_l1_loss).
# Note that you need to consider cells carrying objects and empty cells separately.
# I suggest you to reshape confidence to [batch_size*5*5, num_of_classes]
# and reshape box to [batch_size*5*5, 4].
# Then you need to figure out how you can get the indices of all cells carrying objects,
# and use confidence[indices], box[indices] to select those cells.
ann_confidence = ann_confidence.reshape((-1, 4))
pred_confidence = pred_confidence.reshape((-1, 4))
ann_box = ann_box.reshape((-1, 4))
pred_box = pred_box.reshape((-1, 4))
# select cells
obj = torch.where(ann_confidence[:, -1] == 1)
no_obj = torch.where(ann_confidence[:, -1] == 0)
#print('pred obj', pred_confidence[obj])
#print('pred no_obj', pred_confidence[no_obj])
loss_conf = F.binary_cross_entropy(pred_confidence[obj], ann_confidence[obj]) + 3 * F.binary_cross_entropy(pred_confidence[no_obj], ann_confidence[no_obj])
loss_box = F.smooth_l1_loss(pred_box[obj], ann_box[obj])
loss = loss_conf + loss_box
return loss
'''
YOLO network
Please refer to the hand-out for better visualization
N is batch_size
bn is batch normalization layer
relu is ReLU activation layer
conv(cin,cout,ksize,stride) is convolution layer
cin - the number of input channels
cout - the number of output channels
ksize - kernel size
stride - stride
padding - you need to figure this out by yourself
input -> [N,3,320,320]
conv( 3, 64, 3, 2),bn,relu -> [N,64,160,160]
conv( 64, 64, 3, 1),bn,relu -> [N,64,160,160]
conv( 64, 64, 3, 1),bn,relu -> [N,64,160,160]
conv( 64,128, 3, 2),bn,relu -> [N,128,80,80]
conv(128,128, 3, 1),bn,relu -> [N,128,80,80]
conv(128,128, 3, 1),bn,relu -> [N,128,80,80]
conv(128,256, 3, 2),bn,relu -> [N,256,40,40]
conv(256,256, 3, 1),bn,relu -> [N,256,40,40]
conv(256,256, 3, 1),bn,relu -> [N,256,40,40]
conv(256,512, 3, 2),bn,relu -> [N,512,20,20]
conv(512,512, 3, 1),bn,relu -> [N,512,20,20]
conv(512,512, 3, 1),bn,relu -> [N,512,20,20]
conv(512,256, 3, 2),bn,relu -> [N,256,10,10]
conv(256,256, 1, 1),bn,relu -> [N,256,10,10]
conv(256,256, 3, 2),bn,relu -> [N,256,5,5] (the last hidden layer)
output layer 1 - confidence
(from the last hidden layer)
conv(256,num_of_classes, 3, 1),softmax? -> [N,num_of_classes,5,5]
permute (or transpose) -> [N,5,5,num_of_classes]
output layer 2 - bounding boxes
(from the last hidden layer)
conv(256, 4, 3, 1) -> [N,4,5,5]
permute (or transpose) -> [N,5,5,4]
'''
class YOLO(nn.Module):
def __init__(self, class_num):
super(YOLO, self).__init__()
self.class_num = class_num # num_of_classes, in this assignment, 4: cat, dog, person, background
#TODO: define layers
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
)
self.conv2 = nn.Sequential(
nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
)
self.conv3 = nn.Sequential(
nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
)
self.conv4 = nn.Sequential(
nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(512),
nn.ReLU(),
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(512),
nn.ReLU(),
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(512),
nn.ReLU(),
)
self.conv5 = nn.Sequential(
nn.Conv2d(in_channels=512, out_channels=256, kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=1, stride=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(256),
nn.ReLU()
)
self.left = nn.Sequential(
nn.Conv2d(in_channels=256, out_channels=4, kernel_size=3, stride=1, padding=1, bias=True)
)
self.right = nn.Sequential(
nn.Conv2d(in_channels=256, out_channels=4, kernel_size=3, stride=1, padding=1, bias=True),
nn.Softmax(dim=2)
)
def forward(self, x):
# input:
# x -- images, [batch_size, 3, 320, 320]
#print('x shape:', x.shape)
x = x/255.0 # normalize image. If you already normalized your input image in the dataloader, remove this line.
# TODO: define forward
# should you apply softmax to confidence? (search the pytorch tutorial for F.cross_entropy.) If yes, which dimension should you apply softmax?
x = self.conv1(x)
#print(x.shape)
x = self.conv2(x)
#print(x.shape)
x = self.conv3(x)
#print(x.shape)
x = self.conv4(x)
#print(x.shape)
x = self.conv5(x)
#print(x.shape)
x1 = self.left(x)
#print('x1:', x1.shape)
x2 = self.right(x)
#print('x2:', x2.shape)
# sanity check: print the size/shape of the confidence and bboxes, make sure they are as follows:
# confidence - [batch_size,5,5,num_of_classes]
# bboxes - [batch_size,5,5,4]
confidence = x1.permute((0, 2, 3, 1))
# print('x1:', confidence.shape)
confidence = torch.sigmoid(confidence)
bboxes = x2.permute((0, 2, 3, 1))
# print('x2:', bboxes.shape)
bboxes = torch.sigmoid(bboxes)
return confidence, bboxes
<file_sep>import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
import os
import cv2
def match(ann_box, ann_confidence, cat_id, x_min, y_min, x_max, y_max):
# input:
# ann_box -- [5,5,4], ground truth bounding boxes to be updated
# ann_confidence -- [5,5,number_of_classes], ground truth class labels to be updated
# cat_id -- class id, 0-cat, 1-dog, 2-person
# x_min,y_min,x_max,y_max -- bounding box
size = 5 # the size of the output grid
# update ann_box and ann_confidence
w = (x_max-x_min)
h = (y_max-y_min)
center_x = (x_min + w/2)
center_y = (y_min + h/2)
x, y, idx_i, idx_j = 0, 0, 0, 0
# find the corresponding cell
for i in np.arange(0, 1, 0.2): # 5*5
if i < center_x < (i + 0.2):
x = idx_i
idx_i += 1
for j in np.arange(0, 1, 0.2):
if j < center_y < (j + 0.2):
y = idx_j
idx_j += 1
ann_box[y, x, :] = [center_x, center_y, w, h]
ann_confidence[y, x, 3] = 0 # not background
ann_confidence[y, x, cat_id] = 1
return ann_box, ann_confidence
class COCO(torch.utils.data.Dataset):
def __init__(self, imgdir, anndir, class_num, train=True, image_size=320):
self.train = train
self.imgdir = imgdir
self.anndir = anndir
self.class_num = class_num
self.img_names = os.listdir(self.imgdir)
self.image_size = image_size
# notice:
# you can split the dataset into 90% training and 10% validation here, by slicing self.img_names with respect to self.train
def __len__(self):
return len(self.img_names)
def __getitem__(self, index):
size = 5 # the size of the output grid
ann_box = np.zeros([5, 5, 4], np.float32) # 5*5 bounding boxes
ann_confidence = np.zeros([5, 5, self.class_num], np.float32) # 5*5 one-hot vectors
# one-hot vectors with four classes
# [1,0,0,0] -> cat
# [0,1,0,0] -> dog
# [0,0,1,0] -> person
# [0,0,0,1] -> background
ann_confidence[:, :, -1] = 1 # the default class for all cells is set to "background"
img_name = self.imgdir+self.img_names[index]
ann_name = self.anndir+self.img_names[index][:-3]+"txt"
# TODO:
# 1. prepare the image [3,320,320], by reading image "img_name" first.
# 2. prepare ann_box and ann_confidence, by reading txt file "ann_name" first.
if self.train: # train
image = cv2.imread(img_name)
height, width, _ = image.shape
# resize
image = cv2.resize(image, (self.image_size, self.image_size)) # (320, 320, 3)
image = image.transpose(2, 0, 1) # (3, 320, 320)
ann_info = open(ann_name)
info = ann_info.readlines()
for object_info in info:
obj = object_info.split()
class_id, x_min, y_min, w, h = obj
class_id = int(class_id)
x_min = (float(x_min))
y_min = (float(y_min))
w = (float(w))
h = (float(h))
x_max = ((x_min + w) / width)
y_max = ((y_min + h) / height)
x_min = (x_min / width)
y_min = (y_min / height)
ann_box, ann_confidence = match(ann_box, ann_confidence, class_id, x_min, y_min, x_max, y_max)
# 3. use the above function "match" to update ann_box and ann_confidence,
# for each bounding box in "ann_name".
# 4. Data augmentation. You need to implement random cropping first.
# You can try adding other augmentations to get better results.
# to use function "match":
# match(ann_box,ann_confidence,class_id,x_min,y_min,x_max,y_max)
# where [x_min,y_min,x_max,y_max] is from the ground truth bounding box,
# normalized with respect to the width or height of the image.
# you may wonder maybe it is better to input [x_center, y_center, box_width, box_height].
# maybe it is better.
# BUT please do not change the inputs.
# Because you will need to input [x_min,y_min,x_max,y_max] for SSD.
# It is better to keep function inputs consistent.
# note: please make sure x_min,y_min,x_max,y_max
# are normalized with respect to the width or height of the image.
# For example, point (x=100, y=200) in a image with (width=1000, height=500)
# will be normalized to (x/width=0.1,y/height=0.4)
#print('ann box shape', ann_box.shape)
#print(ann_box)
#print('ann confidence shape', ann_confidence.shape)
#print(ann_confidence)
else: # test, do not have ann dir
image = cv2.imread(img_name)
height, width, _ = image.shape
# resize
image = cv2.resize(image, (self.image_size, self.image_size)) # (320, 320, 3)
image = image.transpose(2, 0, 1) # (3, 320, 320)
return image, ann_box, ann_confidence
'''
if __name__ == '__main__':
dataset = COCO("data/train/images/", "data/train/annotations/", 4, train=True, image_size=320)
a = 0
'''
<file_sep>import numpy as np
import cv2
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
# use [blue green red] to represent different classes
def visualize_pred(windowname, pred_confidence, pred_box, ann_confidence, ann_box, image_):
# input:
# windowname -- the name of the window to display the images
# pred_confidence -- the predicted class labels from YOLO, [5,5, num_of_classes]
# pred_box -- the predicted bounding boxes from YOLO, [5,5, 4]
# ann_confidence -- the ground truth class labels, [5,5, num_of_classes]
# ann_box -- the ground truth bounding boxes, [5,5, 4]
# image_ -- the input image to the network
size, _, class_num = pred_confidence.shape
# size = 5, the size of the output grid
# class_num = 4
class_num = class_num-1
# class_num = 3 now, because we do not need the last class (background)
image = np.transpose(image_, (1, 2, 0)).astype(np.uint8)
image1 = np.zeros(image.shape, np.uint8)
image2 = np.zeros(image.shape, np.uint8)
image3 = np.zeros(image.shape, np.uint8)
image4 = np.zeros(image.shape, np.uint8)
image1[:] = image[:]
image2[:] = image[:]
image3[:] = image[:]
image4[:] = image[:]
# image1: draw ground truth bounding boxes on image1
# image2: draw ground truth "default" boxes on image2
# (to show that you have assigned the object to the correct cell/cells)
# image3: draw network-predicted bounding boxes on image3
# image4: draw network-predicted "default" boxes on image4
# (to show which cell does your network think that contains an object)
img_size = image.shape[0]
cell_size = int(img_size/5)
# draw ground truth
for yind in range(size):
for xind in range(size):
for j in range(class_num):
if ann_confidence[yind, xind, j] > 0.5:
#print('ann [yind, xind, j]', yind, xind, ann_confidence[yind, xind, j])
# if the network/ground_truth has high confidence on cell[yind,xind] with class[j]
# TODO:
# image1: draw ground truth bounding boxes on image1
# image2: draw ground truth "default" boxes on image2
# (to show that you have assigned the object to the correct cell/cells)
# center_x, center_y, width, height
center_x = ann_box[yind, xind, 0]*img_size
center_y = ann_box[yind, xind, 1]*img_size
w = ann_box[yind, xind, 2]*img_size
h = ann_box[yind, xind, 3]*img_size
x1 = int(center_x-w/2)
y1 = int(center_y-h/2)
x2 = int(center_x+w/2)
y2 = int(center_y+h/2)
# you can use cv2.rectangle as follows:
start_point = (x1, y1) # top left corner, x1<x2, y1<y2
end_point = (x2, y2) # bottom right corner
color = colors[j] # use red green blue to represent different classes
thickness = 2
image1 = cv2.rectangle(image1, start_point, end_point, color, thickness)
start = (int(xind*cell_size), int(yind*cell_size))
end = (int((xind+1)*cell_size), int((yind+1)*cell_size))
image2 = cv2.rectangle(image2, start, end, color, thickness)
#pred
for yind in range(size):
for xind in range(size):
for j in range(class_num):
if pred_confidence[yind, xind, j] > 0.5:
#print('pred [yind, xind, j]', yind, xind, pred_confidence[yind, xind, j])
# TODO:
# image3: draw network-predicted bounding boxes on image3
# image4: draw network-predicted "default" boxes on image4 (to show which cell does your network think that contains an object)
center_x = pred_box[yind, xind, 0] * img_size
center_y = pred_box[yind, xind, 1] * img_size
w = pred_box[yind, xind, 2] * img_size
h = pred_box[yind, xind, 3] * img_size
x1 = int(center_x - w / 2)
y1 = int(center_y - h / 2)
x2 = int(center_x + w / 2)
y2 = int(center_y + h / 2)
# you can use cv2.rectangle as follows:
start_point = (x1, y1) # top left corner, x1<x2, y1<y2
end_point = (x2, y2) # bottom right corner
color = colors[j] # use red green blue to represent different classes
thickness = 2
image3 = cv2.rectangle(image3, start_point, end_point, color, thickness)
start = (int(xind * cell_size), int(yind * cell_size))
end = (int((xind + 1) * cell_size), int((yind + 1) * cell_size))
image4 = cv2.rectangle(image4, start, end, color, thickness)
# combine four images into one
h, w, _ = image1.shape
image = np.zeros([h*2, w*2, 3], np.uint8)
image[:h, :w] = image1
image[:h, w:] = image2
image[h:, :w] = image3
image[h:, w:] = image4
#cv2.imshow(windowname+" [[gt_box,gt_dft],[pd_box,pd_dft]]", image)
#cv2.waitKey(1)
# if you are using a server, you may not be able to display the image.
# in that case, please save the image using cv2.imwrite and check the saved image for visualization.
cv2.imwrite('results/sample.jpg', image)
# this is an example implementation of IOU.
# you can define your own iou function if you are not used to the inputs of this one.
def iou(boxes, x_min,y_min,x_max,y_max):
# input:
# boxes -- [num_of_boxes, 4], a list of boxes stored as [box_1,box_2, ...],
# where box_1 = [x1_min,y1_min,x1_max,y1_max].
# x_min,y_min,x_max,y_max -- another box (box_r)
# output:
# ious between the "boxes" and the "another box": [iou(box_1,box_r), iou(box_2,box_r), ...], shape = [num_of_boxes]
inter = np.maximum(np.minimum(boxes[:, 2], x_max)-np.maximum(boxes[:, 0], x_min), 0)*np.maximum(np.minimum(boxes[:, 3], y_max)-np.maximum(boxes[:, 1], y_min), 0)
area_a = (boxes[:, 2]-boxes[:, 0])*(boxes[:, 3]-boxes[:, 1])
area_b = (x_max-x_min)*(y_max-y_min)
union = area_a + area_b - inter
return inter/np.maximum(union, 1e-8)
# this function will be used later
def non_maximum_suppression(confidence_t, box_t, overlap=0.5, threshold=0.5):
# input:
# confidence_t -- the predicted class labels from YOLO, [5,5, num_of_classes]
# box_t -- the predicted bounding boxes from YOLO, [5,5, 4]
# overlap -- if two bounding boxes in the same class have iou > overlap, then one of the boxes must be suppressed
# threshold -- if one class in one cell has confidence > threshold, then consider this cell carrying a bounding box with this class.
# output:
# depends on your implementation.
# if you wish to reuse the visualize_pred function above, you need to return a "suppressed" version of confidence [5,5, num_of_classes].
# you can also directly return the final bounding boxes and classes, and write a new visualization function for that.
size, _, class_num = confidence_t.shape
# size = 5, the size of the output grid
# class_num = 4
# TODO: non maximum suppression
# you can reshape the confidence and box to [5*5,class_num], [5*5,4], for better indexing
'''
if __name__ == '__main__':
a = 1
'''
<file_sep># YOLO
YOLO - Object Detection CNN
|
f9b4f7a8143ec226574b729c999127419e0b5642
|
[
"Markdown",
"Python"
] | 4 |
Python
|
fdshan/YOLO
|
ce8e2ae0f36be640fff9306a4fc3edd920f5a904
|
412ad6f24c555a36bf55e4082e2052fa7c4a0d76
|
refs/heads/master
|
<repo_name>bettero77/udsu_oop_<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(numbers)
set(CMAKE_CXX_STANDARD 17)
add_executable(numbers main.cpp Integerr.cpp Decimal.cpp Integer.cpp Integer.h)<file_sep>/main.cpp
#include <iostream>
#include <iterator>
#include "Decimal.cpp"
using namespace std;
int main() {
cout << "Hello, World!" << endl;
// Integerr *number1;
Decimal *decimal = new Decimal();
// number1 = decimal;
array<char, 2> arr = {'6','8'};
// int a[] = { -5, 10, 15 };
// number1->setValue(arr);
// number1->add(*number1);
decimal->setValue(arr);
decimal->add(decimal);
cout << "End" << endl;
return 0;
}
<file_sep>/Decimal.cpp
//
// Created by <NAME> on 28.04.2020.
//
//#include "Decimal.h"
#include <iostream>
#include "Integerr.cpp"
using namespace std;
class Decimal : public Integerr {
public:
Integerr* add(Integerr *integer) override {
array<char, 2> savedValue = this->getValue();
cout << savedValue[1] << endl;
cout << 'B' << endl;
return integer;
};
// .get
// parse from char number array with coma to double
//add two doubles
//serialize back to char array
// .set
};<file_sep>/Integer.h
//
// Created by <NAME> on 29.04.2020.
//
#ifndef NUMBERS_INTEGER_H
#define NUMBERS_INTEGER_H
class Integer {
};
#endif //NUMBERS_INTEGER_H
<file_sep>/Integer.cpp
//
// Created by <NAME> on 29.04.2020.
//
#include "Integer.h"
<file_sep>/Integerr.cpp
//
// Created by <NAME> on 28.04.2020.
//
//#include "Integerr.h"
#include <iostream>
#include <iterator>
#include <array>
using namespace std;
class Integerr {
public:
virtual Integerr* add(Integerr *integer) {
cout << 'K';
return integer;
};
// virtual Integerr subtract(Integerr integer);
// virtual Integerr multiply(Integerr integer);
// virtual Integerr divide(Integerr integer);
//
// virtual void printValue();
array<char, 2> getValue() {
return _value;
};
void setValue(array<char, 2> value) {
_value = value;
};
private:
array<char, 2> _value = {};
};
|
4eaf674d4b639dd44b28713663a65bbb44958df6
|
[
"CMake",
"C++"
] | 6 |
CMake
|
bettero77/udsu_oop_
|
6ec36f05b91405a5868438fffb946fd9da038fad
|
b239a7b470757711941290796d026c4edd728112
|
refs/heads/master
|
<repo_name>jayshoo/colonbot<file_sep>/colonbot/KeepAliveThread.py
from threading import Thread
from time import sleep
class KeepAlive(Thread):
def __init__(self, delay, sendMethod):
Thread.__init__(self)
self.delay = delay
self.send = sendMethod
def run(self):
while True:
sleep(self.delay)
self.send(' ')
<file_sep>/codquery_test.py
import cod
conn = cod.Connection('bowels.dyndns-server.com')
print conn.status()
print conn.status()
print conn.status()
<file_sep>/minecraft/__init__.py
from minecraftquery import *
<file_sep>/cod/__init__.py
from cod4query import *
<file_sep>/minecraft_test.py
import minecraft
addr = 'minecraft.joshu.net'
addr = '172.16.31.10'
conn = minecraft.Connection(addr)
print conn.status()
<file_sep>/colonbot/ProcessingThread.py
from threading import Thread
class ProcessingThread(Thread):
def __init__(self, client):
Thread.__init__(self)
self.client = client
def run(self):
while self.client.Process(1):
pass
<file_sep>/colonbot/__init__.py
from ColonBot import *
from KeepAliveThread import *
from ProcessingThread import *
<file_sep>/colonbot.py
#!/usr/bin/python
from time import sleep
from threading import Thread
import xmpp, ConfigParser, re
from colonbot import *
import cod, minecraft
class MinecraftBot(Thread):
def __init__(self, ipAddress, port=25565):
Thread.__init__(self)
self.client = minecraft.Connection(ipAddress, port)
self.players = '0'
self.running = True
def run(self):
while self.running:
sleep(15)
response = self.client.status()
if response is None:
continue
if response['players'] <> self.players:
message = '[MINECRAFT] Now playing: %s/%s (was: %s/%s)' % (
response['players'],
response['maxplayers'],
self.players,
response['maxplayers'])
self.callback(message)
self.players = response['players']
class CodBot(Thread):
def __init__(self, ipAddress, port=28960):
Thread.__init__(self)
self.client = cod.Connection(ipAddress, port)
self.players = []
self.running = True
def run(self):
while self.running:
sleep(15)
response = self.client.status()
if response is None:
continue
if len(response['players']) <> len(self.players):
message = '[COD] Now playing %d (was: %d)' % (
len(response['players']),
len(self.players))
for player in response['players']:
if player not in self.players:
message = message + ' +<%s>' % self.formatPlayer(player)
for player in self.players:
if player not in response['players']:
message = message + ' -<%s>' % self.formatPlayer(player)
self.callback(message)
self.players = response['players']
def formatPlayer(self, player):
result = re.search('"(.*)"', player)
if result:
return result.group(1)
else:
return ''
class ColonBot(Thread):
def __init__(self, username, password, conference, nickname):
Thread.__init__(self)
self.username = username
self.password = <PASSWORD>
self.conference = conference
self.nickname = nickname
self.confJID = '%s/%s' % (conference, nickname)
self.connect()
self.services = []
self.running = True
def __del__(self):
self.quit()
def run(self):
# spawn new thread for background message processing
self.jabberThread = ProcessingThread(self.client)
self.jabberThread.start()
self.keepAliveThread = KeepAlive(30, self.client.send)
self.keepAliveThread.start()
while self.running:
command = raw_input('> ')
self.eval(command)
def addService(self, service):
service.callback = self.say
self.services.append(service)
service.start()
def connect(self):
# setup a client and connect
self.jid = xmpp.protocol.JID(self.username)
self.client = xmpp.Client(self.jid.getDomain(), debug=[]) # debug
self.client.connect()
self.client.RegisterHandler('message', self.messageHandler)
self.client.auth(self.jid.getNode(), self.password)
self.client.sendInitPresence()
# broadcast our intent to join the conference
joinRoom = xmpp.Presence(to=self.confJID)
self.client.send(joinRoom)
def messageHandler(self, sess, mess):
topic = mess.getSubject()
body = mess.getBody()
# check if topic changed
if topic:
self.topic = topic
result = re.search(u'\u200b.*?\u200b(.*)', self.topic)
if result:
existing = result.group(1)
else:
existing = self.topic
# check if the message is addressed to us
if (body
and u'jabber:x:delay' not in mess.getProperties()
and body.find(self.nickname + ':') == 0):
result = re.search(self.nickname + ':(.*)', body, re.DOTALL)
if result:
self.eval(result.group(1).strip())
## print 'subj: ' + repr(mess.getSubject())
## print 'body: ' + repr(mess.getBody())
## print 'prop: ' + repr(mess.getProperties())
def quit(self):
leaveRoom = xmpp.Presence(to=self.confJID, typ='unavailable')
self.client.send(leaveRoom)
def say(self, message):
msg = xmpp.protocol.Message(self.conference, message, typ='groupchat')
self.client.send(msg)
def eval(self, command):
try:
# asking for trouble
exec command
except Exception as ex:
self.say('Failed execution: ' + command + '\n' + repr(ex))
def setTopic(self, topic):
msg = xmpp.protocol.Message(
self.conference,
typ='groupchat',
subject=topic)
self.client.send(msg)
config = ConfigParser.ConfigParser()
config.read('colonbot.cfg')
username = config.get('colonbot', 'username')
password = config.get('<PASSWORD>', 'password')
conference = config.get('colonbot', 'conference')
nickname = config.get('colonbot', 'nickname')
bot = ColonBot(username, password, conference, nickname)
bot.addService(CodBot('bowels.dyndns-server.com'))
bot.addService(MinecraftBot('192.168.127.12'))
bot.start()
bot.join()
<file_sep>/minecraft/minecraftquery.py
import socket
class Message:
STATUS = "\xFE"
class Connection:
def __init__(self, ipAddress, port=25565, bufferSize = 4096):
self.ip = ipAddress
self.port = port
self.bufferSize = 4096
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(2)
self.sock.connect((self.ip, self.port))
def close(self):
self.sock.close()
def send(self, message):
self.sock.send(message)
def response(self):
response = {}
msg = self.sock.recv(self.bufferSize)
last = msg
if len(msg) == self.bufferSize:
while last != '':
last = self.sock.recv(self.bufferSize)
if last == '': break
msg = msg + last
# AWFUL HACKY STRING DECODING, BEWARE
msgparts = [x.replace("\x00","").replace("\xFF","").replace("$","")
for x in msg.split("\xA7\x00")]
response['name'] = msgparts[0]
response['players'] = msgparts[1]
response['maxplayers'] = msgparts[2]
return response
def status(self):
try:
self.connect()
self.send(Message.STATUS)
return self.response()
except:
return None
<file_sep>/cod/cod4query.py
import socket
class Message:
STATUS = "\xFF\xFF\xFF\xFFgetstatus\x00"
class Connection:
def __init__(self, ipAddress, port=28960, bufferSize = 4096):
self.ip = ipAddress
self.port = port
self.bufferSize = 4096
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(2)
self.sock.connect((self.ip, self.port))
def close(self):
self.sock.close()
def send(self, message):
self.sock.send("\xFF\xFF\xFF\xFF")
self.sock.send(message)
self.sock.send("\x00")
def response(self):
response = {}
msg = self.sock.recv(self.bufferSize)
last = msg
if len(msg) == self.bufferSize:
while last != '':
last = self.sock.recv(self.bufferSize)
if last == '': break
msg = msg + last
msgparts = msg.strip("\n").split("\n")
response['type'] = msgparts.pop(0).strip("\xFF\x00\n")
props = msgparts.pop(0).split('\\')
response['players'] = msgparts # todo: list comprehension to amplify
props.pop(0) # remove empty element caused by leading \ char
while len(props) > 0:
key = props.pop(0)
value = props.pop(0)
response[key] = value
return response
def status(self):
try:
self.connect()
self.send(Message.STATUS)
return self.response()
except:
return None
|
080e8b56472d427ed23eeb63c6e982ba19d98431
|
[
"Python"
] | 10 |
Python
|
jayshoo/colonbot
|
2a1e469dbab971dcf2821e43c1a904f66e1b3097
|
bc156939b53b341794f2019f95c443f6af2dc0f5
|
refs/heads/master
|
<repo_name>MrRahi/e-commerce-site<file_sep>/signup.php
<?php
include_once 'config.php';
$name = $_POST["name"];
$email = $_POST["email"];
$number = $_POST["number"];
$address = $_POST["address"];
$password = $_POST["password"];
$sql = "INSERT INTO users (name, email, number, password, address)
VALUES('$name','$email','$number','$password','$address')";
$result = mysqli_query($conn, $sql);
header("Location: login.php?signup=success");
?><file_sep>/adminProducts.php
<!DOCTYPE html>
<?php
include('adminsession.php');
?>
<html>
<head>
<title>adminProducts</title>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #91a39e;
}
li
{
float: left;
}
li a
{
display: block;
color: white;
text-align: center;
padding: 10px 16px;
text-decoration: none;
}
li a:hover
{
background-color: #d0f030;
}
.productBox{
text-align: center;
padding: 10px;
}
.card {
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
transition: 0.3s;
width: 300px;
}
.card:hover {
background-color: #DAF7A6;
}
.container {
padding: 2px 16px;
}
</style>
</head>
<body style="background-color:#35706a;">
<ul>
<li><a href="adminpage.php">Home</a></li>
<li><a href = "logout.php">Sign Out</a></li>
<li style="float: right;"><a href = "#">Welcome, <?php echo $login_session; ?></a></li>
</ul>
<?php
$sql = "select productName, description, price, name
from products";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
//$row = mysqli_fetch_array($result);
$productName = $row['productName'];
$description = $row['description'];
$price = $row['price'];
$image = $row['name'];
$image_src = "upload/".$image;
echo "<div class='productBox'>";
//foreach ($productsBox as $product){
//<a href="'products.php?page=product&id="'<?php=$row['id']' class="product">
echo "<div class='card'>";
echo "<img src='".$image_src."' alt='Avatar' style='width:100%'>";
echo "<div class='container'>";
echo "<h4><b>".$productName."</b></h4>";
echo "<p>".$description."</p>";
echo "<p>".$price."</p>";
echo "<input type='submit'>";
echo "</div>";
echo "</div>";
echo "</div>";
}
} else {
echo "0 results";
}
?>
</body>
</html><file_sep>/adminlogin.php
<!DOCTYPE html>
<html>
<head>
<title>Admin Login</title>
<style>
.registrationDiv
{
width: 400px;
margin: auto;
background-color:#C0C0C0;
padding: 40px;
box-shadow: 10px 10px 10px #aaaaaa;
}
.fields
{
border-radius: 5px;
border-style:none;
height: 40px;
}
.button1
{
border-radius:5px;
height: 40px;
width: 80px;
background-color:#F5F5DC;
}
</style>
</head>
<body style="background-color:#35706a;">
<div class="registrationDiv">
<h1>Admin Login</h1>
<form method="POST">
<label><b>Email:</b></label><br>
<input class="fields" type="email" placeholder="Enter Email" name="email" id="email" required><br><br>
<label><b>Password:</b></label><br>
<input class="fields" type="password" placeholder="Enter Password" name="password" id="password" required><br><br><br><br>
<input class="button1" type="submit" name="submit" value="Login"></input>
</form>
<br><br>
<a class="loginLinks" href="login.php">User Login</a>
</div>
<?php
include("config.php");
session_start();
$count=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from form
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$sql = "SELECT id
FROM adminuser
WHERE email = '$email' and password = '$<PASSWORD>'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1)
{
$_SESSION['email'] = $email;
header("location: adminpage.php");
}
elseif($count==0)
{
echo "<p style='color:black; text-align: center;'>" . "Your Login email or Password is invalid" ."</p>";
$count=3;
}
else
{
$error = "Your Login email or Password is invalid";
echo "<p style='color:red; text-align: center;'>" . $error ."</p>";
}
}
?>
</body>
</html><file_sep>/adminpage.php
<!DOCTYPE html>
<html>
<head>
<title>Admin Page</title>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #91a39e;
}
li
{
float: left;
}
li a
{
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover
{
background-color: #d0f030;
}
.fields
{
border-width:5px;
border-style:double;
height: 40px;
}
.users
{
box-shadow: 5px 10px;
padding : 1em;
width: 100%;
height: 200px;
box-sizing: border-box;
background-color: #E4E4D9;
background-image:linear-gradient(175deg, rgba(0,0,0,0) 95%, #8da389 95%),
linear-gradient( 85deg, rgba(0,0,0,0) 95%, #8da389 95%),
linear-gradient(175deg, rgba(0,0,0,0) 90%, #b4b07f 90%),
linear-gradient( 85deg, rgba(0,0,0,0) 92%, #b4b07f 92%),
linear-gradient(175deg, rgba(0,0,0,0) 85%, #c5a68e 85%),
linear-gradient( 85deg, rgba(0,0,0,0) 89%, #c5a68e 89%),
linear-gradient(175deg, rgba(0,0,0,0) 80%, #ba9499 80%),
linear-gradient( 85deg, rgba(0,0,0,0) 86%, #ba9499 86%),
linear-gradient(175deg, rgba(0,0,0,0) 75%, #9f8fa4 75%),
linear-gradient( 85deg, rgba(0,0,0,0) 83%, #9f8fa4 83%),
linear-gradient(175deg, rgba(0,0,0,0) 70%, #74a6ae 70%),
linear-gradient( 85deg, rgba(0,0,0,0) 80%, #74a6ae 80%);
}
.addProducts{
margin:auto;
border: 1px solid black;
box-shadow: 5px 10px;
background-color: #E4E4D9;
background-image:linear-gradient(175deg, rgba(0,0,0,0) 95%, #8da389 95%),
linear-gradient( 85deg, rgba(0,0,0,0) 95%, #8da389 95%),
linear-gradient(175deg, rgba(0,0,0,0) 90%, #b4b07f 90%),
linear-gradient( 85deg, rgba(0,0,0,0) 92%, #b4b07f 92%),
linear-gradient(175deg, rgba(0,0,0,0) 85%, #c5a68e 85%),
linear-gradient( 85deg, rgba(0,0,0,0) 89%, #c5a68e 89%),
linear-gradient(175deg, rgba(0,0,0,0) 80%, #ba9499 80%),
linear-gradient( 85deg, rgba(0,0,0,0) 86%, #ba9499 86%),
linear-gradient(175deg, rgba(0,0,0,0) 75%, #9f8fa4 75%),
linear-gradient( 85deg, rgba(0,0,0,0) 83%, #9f8fa4 83%),
linear-gradient(175deg, rgba(0,0,0,0) 70%, #74a6ae 70%),
linear-gradient( 85deg, rgba(0,0,0,0) 80%, #74a6ae 80%);
}
.users
{
padding:8px;
width: 50%;
margin: auto;
}
.addProducts
{
padding:8px;
width: 50%;
margin: auto;
}
</style>
</head>
<body style="background-color:#35706a;">
<ul>
<li><a href=" ">Home</a></li>
<li><a href="adminproducts.php">Products</a></li>
<li><a href = "logout.php">Log Out</a></li>
<li><a href = "aboutus.php">About Us</a></li>
</ul>
<div class="users">
<h1>Users</h1>
<?php
include_once('config.php');
$sql = "SELECT id, name, email, number, address
FROM users
ORDER BY id";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "".$row["id"].", Name:-".$row["name"]. ", Email:-".$row["email"].", Number:-".$row["number"].", Address:-".$row["address"]. "<br>";
}
}
else
{
echo "0 results";
}
?>
</div>
<br><br>
<?php
include("config.php");
session_start();
if(isset($_POST['addproduct'])){
$productName = $_POST["productName"];
$description = $_POST["description"];
$price = $_POST["price"];
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
$query = "insert into products(productName, description, price, name)
values('$productName','$description','$price','".$name."')";
mysqli_query($conn,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<div class="addProducts">
<h1>Add Products</h1>
<form method="post" action="" enctype='multipart/form-data'>
<label><b>Product Name:</b></label><br>
<input class="fields" type="text" placeholder="Enter Product Name" name="productName" id="productName" required><br><br>
<label><b>Description:</b></label><br>
<input class="fields" style="width:250px;" type="text" placeholder="Enter Description" name="description" id="description" required><br><br>
<label><b>Price:</b></label><br>
<input class="fields" type="number" placeholder="Enter Price" name="price" id="price" required><br><br>
<input type='file' name='file' /><br><br>
<input type="submit" name="addproduct" value="Add Product"></input>
</form>
</div>
</body>
</html><file_sep>/index.php
<!DOCTYPE html>
<?php
include('session.php');
?>
<html>
<head>
<title>"Triple Billionaire"</title>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #91a39e;
}
li
{
float: left;
}
li a
{
display: block;
color: white;
text-align: center;
padding: 10px 16px;
text-decoration: none;
}
li a:hover
{
background-color: #d0f030;
}
.article{
border:1px solid;
border-top-width:0px;
border-right-width:0px;
border-bottom-width:5px;
border-bottom-color:#FFBF21;
border-left-width:10px;
border-left-color:#FFBF21;
}
.footer
{
width: 100%;
background-color: black;
color: white;
text-align: center;
padding: 10px;
}
</style>
<!-- Bootstrap-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body style="background-color:#35706a"; >
<!-- Navigation bar-->
<ul>
<li><a class="active" href="index.php">Home</a></li>
<li><a href="products.php">Products</a></li>
<li><a href = "logout.php">Sign Out</a></li>
<li style="float: right;"><a href = "#">Welcome,
<?php
echo $login_session;
?>
</a></li>
</ul>
<!-- SlideShow-->
<div id="carouselExampleControls" class="carousel slide bg-inverse w-50 ml-auto mr-auto" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="images/cover1.png" alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="images/cover2.png" alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block w-100" src="images/cover3.png" alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div><br><br><br>
<div class="article">
<h4 style="color:MediumSeaGreen;">
<i> <strong> Looking for quality products at Minimum Price? Want to save your
hard earnings and precious time? Tired of searching items and get
confused in the crowd? Then, <p style="color:Tomato;">“Triple Billionaire (E-commerce site)” </p>
is your solution of those problems. It is a trustworthy E-commerce
site where you can easily find your necessary best products at the
minimum best price. So, why are you waiting for? Just grab your
products from <p style="color:Tomato;">“Triple Billionaire”</p> and save your valuable time. </strong> </i>
</h4>
</div>
<!-- Footer-->
<br><br>
<div class="footer">
<p>Contact us on: </p>
<p>All rights reserved 2021</p>
</div>
</body>
</html>
|
7a90fb545ef9058a95576adb2d32f0cec205bb89
|
[
"PHP"
] | 5 |
PHP
|
MrRahi/e-commerce-site
|
d8265ed55d6816d6dd90944453364117dfa2b26f
|
a93f403fb3ab1d72ebbc0a1cf773b1fd6cb90553
|
refs/heads/master
|
<repo_name>giulianojordao/flutter_app<file_sep>/settings.gradle
// Generated file. Do not edit.
rootProject.name = 'android'
setBinding(new Binding([gradle: this]))
evaluate(new File('include_flutter.groovy'))
<file_sep>/fu.py
# coding=utf-8
import os
import shutil
import requests
import zipfile
group = 'rpi'
widget = 'button'
version = "0.2.0"
# text是否包含content
def is_contain(text, content):
if text.find(content) != -1:
return True
else:
return False
def is_empty(s):
return len(s) == 0
def update_widget(local_path, group, widget, version):
base_url = 'http://gitlab.alibaba-inc.com/{group}/{widget}/repository/archive.zip?ref=publish/{version}'
url = base_url.format(group=group, widget=widget, version=version)
print (widget + " 组件地址:" + url)
response = requests.get(url)
with open(widget + ".zip", "wb") as code:
code.write(response.content)
try:
shutil.rmtree("lib/widget/" + widget)
except IOError:
print("清理老版本 " + widget + " 组件失败!可能的原因是,此前尚未引入该组件.")
else:
print("清理老版本 " + widget + " 组件成功!")
with zipfile.ZipFile(widget + ".zip", 'r') as zip:
temp_file = "temp_" + widget
zip.extractall(temp_file)
for file in zip.namelist():
if file.endswith("/src/"):
if not local_path.endswith("/"):
local_path = local_path + "/"
shutil.move(temp_file + "/" + file, local_path + widget)
print (widget + " 组件更新成功!")
break
os.unlink(widget + ".zip")
shutil.rmtree(temp_file)
print ("清理 " + widget + " 组件临时文件完成!")
print ("-----------")
local_path = "/lib/widget/"
with open("flutter_ui.txt", "r") as file:
for line in file:
line = line.strip().lstrip().rstrip(',').replace(' ', '')
if is_contain(line, "=") or is_contain(line, "^"):
# print ("读取到的内容:\n" + line)
if line.startswith("path"):
local_path = line.replace('path=', '').replace('"', '')
print ('local_path: ' + local_path)
print (".........")
elif is_contain(line, '^'):
split_line = line.split(':^')
widget = split_line[0]
version = split_line[1]
print ('widget: ' + widget)
print ('version: ' + version)
update_widget(local_path, group, widget, version)
|
23500d5ffb79ed12a32b8294198185999854360c
|
[
"Python",
"Gradle"
] | 2 |
Gradle
|
giulianojordao/flutter_app
|
132933e9ffc705007ade303e07c779f5a78b3523
|
b6b3d0c62d64c50b5f8216a147048b08332ccbb0
|
refs/heads/master
|
<file_sep>package com.xuecheng.api.cms;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.ResponseResult;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
/**
* @Author: 98050
* @Time: 2019-03-19 15:00
* @Feature: 页面查询接口
*/
@RequestMapping("/cms/page")
@Api(value = "cms页面管理接口",description = "cms页面管理接口,提供对页面的CRUD")
public interface CmsPageControllerApi {
/**
* 页面分页查询
* @param page 页码
* @param size 页大小
* @param queryPageRequest 查询参数
* @return
*/
@ApiOperation("分页查询页面列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "page",value = "页码",required = true,paramType = "path",dataType = "int"),
@ApiImplicitParam(name = "size",value = "页大小",required = true,paramType = "path",dataType = "int")
})
@ApiResponses({
@ApiResponse(code = 10000,message = "操作成功"),
@ApiResponse(code = 11111,message = "操作失败")
})
@GetMapping("/list/{page}/{size}")
QueryResponseResult findList(@PathVariable("page") int page, @PathVariable("size") int size, QueryPageRequest queryPageRequest);
/**
* 页面新增
* @param cmsPage
* @return
*/
@ApiOperation("页面添加")
@PostMapping("/add")
@ApiResponses({
@ApiResponse(code = 10000,message = "操作成功"),
@ApiResponse(code = 11111,message = "操作失败")
})
CmsPageResult add(@RequestBody CmsPage cmsPage);
/**
* 根据id查询页面
* @param id
* @return
*/
@ApiOperation("根据Id查询页面")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "页面Id",required = true,paramType = "path",dataType = "String")
})
@GetMapping("/get/{id}")
@ApiResponses({
@ApiResponse(code = 10000,message = "操作成功"),
@ApiResponse(code = 11111,message = "操作失败")
})
CmsPageResult findById(@PathVariable String id);
/**
* 根据id修改页面
* @param id
* @param cmsPage
* @return
*/
@ApiOperation("修改页面")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "页面Id",required = true,paramType = "path",dataType = "String")
})
@PutMapping("/update/{id}")
@ApiResponses({
@ApiResponse(code = 10000,message = "操作成功"),
@ApiResponse(code = 11111,message = "操作失败")
})
CmsPageResult update(@PathVariable String id,@RequestBody CmsPage cmsPage);
/**
* 删除页面
* @param id
* @return
*/
@ApiOperation("删除页面")
@DeleteMapping("/delete/{id}")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "页面Id",required = true,paramType = "path",dataType = "String")
})
@ApiResponses({
@ApiResponse(code = 10000,message = "操作成功"),
@ApiResponse(code = 11111,message = "操作失败")
})
ResponseResult delete(@PathVariable String id);
}<file_sep>package com.xuecheng.managecms.controller;
import com.xuecheng.api.cms.CmsPageControllerApi;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.managecms.service.CmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: 98050
* @Time: 2019-03-19 19:06
* @Feature:
*/
@RestController
@RequestMapping("/cms/page")
public class CmsPageController implements CmsPageControllerApi {
@Autowired
private CmsService cmsService;
@Override
@GetMapping("/list/{page}/{size}")
public QueryResponseResult findList(@PathVariable("page") int page, @PathVariable("size") int size, QueryPageRequest queryPageRequest) {
return cmsService.queryByPage(page, size, queryPageRequest);
}
@Override
@PostMapping("/add")
public CmsPageResult add(@RequestBody CmsPage cmsPage) {
return cmsService.add(cmsPage);
}
@Override
@GetMapping("/get/{id}")
public CmsPageResult findById(@PathVariable String id) {
System.out.println(id);
CmsPage cmsPage = cmsService.findById(id);
if (cmsPage != null){
return new CmsPageResult(CommonCode.SUCCESS, cmsPage);
}else {
return new CmsPageResult(CommonCode.FAIL, null);
}
}
@Override
@PutMapping("/update/{id}")
public CmsPageResult update(@PathVariable String id, @RequestBody CmsPage cmsPage) {
return cmsService.update(id,cmsPage);
}
@Override
@DeleteMapping("/delete/{id}")
public ResponseResult delete(@PathVariable String id) {
return cmsService.delete(id);
}
}
|
ccb77016fe63f8320db9a618bd0a9db6342158c1
|
[
"Java"
] | 2 |
Java
|
JasonTang0606/xcEdu_Service
|
5f4469adb44dfdee6248fcc3d0ef037a01c06608
|
695b546793c9f35f4984cf5a650206c0dce50cb0
|
refs/heads/master
|
<repo_name>OEmilius/Prefix<file_sep>/controllers/default.py
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################
def index():
import os
import csv
def min_order(num): return 1 if num%10 else 10*min_order(num//10)
def prefixes(low, high):
def forward(num, order):
nxt = num + order
if nxt == high + 1: return [num//order]
if nxt > high + 1: return backward(num, order//10)
if not num%(order*10): return forward(num, order*10)
return [num//order] + forward(nxt, order)
def backward(num, order):
nxt = num + order
if nxt == high + 1: return [num//order]
if nxt > high + 1: return backward(num, order//10)
return [num//order] + backward(nxt, order)
return forward(low, min_order(low))
def to_cp1251(s):
return s.decode('utf-8').encode('cp1251')
def find_prefix(codes):
pfx = []
for cnacld in codes:
my_list = prefixes(int(cnacld[0]), int(cnacld[1]))
pfx.extend(map(str,my_list))
return pfx
def CLDGRP(prefix_list,GRP,name):
add_cldgrp = []
for p in prefix_list:
add_cldgrp.append("ADD CLDGRP: CLD=K'8" + str(p) + ', GRPT=OG, GRP=' + GRP + ', NAME="' + name+'";')
return add_cldgrp
def CNACLD(prefix_list, route_sel_code, desc):
add_cnacld = []
for p in prefix_list:
add_cnacld.append("ADD CNACLD: PFX=K'8"+str(p)+', CSTP=BASE, CSA=NTT, RSC=' +route_sel_code+' , MINL=11, MAXL=11, CHSC=0, SDESCRIPTION="' +desc+'", EA=NO;')
return add_cnacld
def combine(ranges):
#attension tis def modified incoming paramiters
i = 0
new = []
found = True
while found == True:
if i < len(ranges)-1:
if (int(ranges[i][1]) + 1) == int(ranges[i+1][0]):
r = [ranges[i][0],ranges[i+1][1]]
ranges[i] = r
a = ranges.pop(i+1)
else:
i += 1
else:
found = False
return ranges
r = 'Моск'
html = 'Данные из файла app../static/Kody_DEF-9kh.csv. Префиксы учетом объединения диапазонов<br>'
region = r.decode('utf-8').encode('cp1251')
oper = ['Мобильные ТелеСистемы', 'МегаФон', 'Московская сотовая связь','Вымпел-Коммуникации']
operators = map(to_cp1251, oper)
region = r.decode('utf-8').encode('cp1251')
mts = []
megafon = []
mss =[]
beeline = []
filename = os.path.join(request.folder, 'static', 'Kody_DEF-9kh.csv')
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter = ';')
for row in reader:
if row[5].find(region) >= 0:
if row[4].find(operators[0]) >=0:
mts.append([row[0] + row[1].rjust(7,'0'),row[0] + row[2].rjust(7,'0')])
elif row[4].find(operators[1]) >= 0:
megafon.append([row[0] + row[1].rjust(7,'0'),row[0] + row[2].rjust(7,'0')])
elif row[4].find(operators[2]) >= 0:
mss.append([row[0] + row[1].rjust(7,'0'),row[0] + row[2].rjust(7,'0')])
elif row[4].find(operators[3]) >= 0:
beeline.append([row[0] + row[1].rjust(7,'0'),row[0] + row[2].rjust(7,'0')])
combine(mts)
combine(megafon)
combine(mss)
combine(beeline)
mts_pfx = find_prefix(mts)
megafon_pfx = find_prefix(megafon)
mss_pfx = find_prefix(mss)
beeline_pfx = find_prefix(beeline)
#return dict(message="hello from prefix.py")
html += '<h3>MTS</h3>'
html += str(mts_pfx)
html += '<br>pfx count' + str(len(mts_pfx))
html += '<h3>Megafon</h3>'
html += 'len Megafon after combine' + str(len(megafon)) + '<br>'
html += str(megafon_pfx)
html += '<br>pfx count' + str(len(megafon_pfx))
html += '<h3>MSS</h3>'
html += str(mss_pfx)
html += '<h3>Beeline</h3>'
html += str(beeline_pfx)
html += '<hr>'
html += '<textarea cols=120 rows=10>'
html += '\r\n'.join(CNACLD(mts_pfx, '252', 'MTC_msk'))
html += '</textarea>'
html += '<hr>'
html += '<textarea cols=120 rows=10>'
html += '\r\n'.join(CLDGRP(mts_pfx, '26', 'MTC_msk'))
html += '</textarea>'
################################ megafon
html += '<hr>'
html += '<textarea cols=120 rows=10>'
html += '\r\n'.join(CNACLD(megafon_pfx, '251', 'Mega_msk'))
html += '</textarea>'
html += '<hr>'
html += '<textarea cols=120 rows=10>'
html += '\r\n'.join(CLDGRP(megafon_pfx, '25', 'Mega_msk'))
html += '</textarea>'
################################ MCC
html += '<hr>'
html += '<textarea cols=120 rows=10>'
html += '\r\n'.join(CNACLD(mss_pfx, '253', 'MSS_msk'))
html += '</textarea>'
html += '<hr>'
html += '<textarea cols=120 rows=10>'
html += '\r\n'.join(CLDGRP(mss_pfx, '27', 'MSS_msk'))
html += '</textarea>'
############################### beeline
html += '<hr>'
html += '<textarea cols=120 rows=10>'
html += '\r\n'.join(CNACLD(beeline_pfx, '250', 'Bi_msk'))
html += '</textarea>'
html += '<hr>'
html += '<textarea cols=120 rows=10>'
html += '\r\n'.join(CLDGRP(beeline_pfx, '24', 'Bi_msk'))
html += '</textarea>'
return html
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_password
use @auth.requires_login()
@auth.requires_membership('group name')
@auth.requires_permission('read','table name',record_id)
to decorate functions that need access control
"""
return dict(form=auth())
def download():
"""
allows downloading of uploaded files
http://..../[app]/default/download/[filename]
"""
return response.download(request, db)
def call():
"""
exposes services. for example:
http://..../[app]/default/call/jsonrpc
decorate with @services.jsonrpc the functions to expose
supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
"""
return service()
@auth.requires_signature()
def data():
"""
http://..../[app]/default/data/tables
http://..../[app]/default/data/create/[table]
http://..../[app]/default/data/read/[table]/[id]
http://..../[app]/default/data/update/[table]/[id]
http://..../[app]/default/data/delete/[table]/[id]
http://..../[app]/default/data/select/[table]
http://..../[app]/default/data/search/[table]
but URLs must be signed, i.e. linked with
A('table',_href=URL('data/tables',user_signature=True))
or with the signed load operator
LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
"""
return dict(form=crud())
|
97bf81e9368e064db030e48b5cf63fb9ca8033d1
|
[
"Python"
] | 1 |
Python
|
OEmilius/Prefix
|
a37dfcf3701fc074c00c2af4458e8878bf1b83b8
|
887e97c130e790f829eb305d3d3786e015481c03
|
refs/heads/master
|
<repo_name>richmondx/SS6PlayerForUnrealEngine4<file_sep>/Ss6PlayerExamples/Plugins/SpriteStudio6/Source/SpriteStudio6/Public/Data/SsAnimePack.h
#pragma once
#include "SsTypes.h"
#include "SsAttribute.h"
#include "SsAnimePack.generated.h"
/// アニメーション再生設定情報です。
USTRUCT()
struct SPRITESTUDIO6_API FSsAnimationSettings
{
GENERATED_USTRUCT_BODY()
public:
UPROPERTY(VisibleAnywhere, Category=SsAnimationSettings)
int32 Fps; //!< 再生FPS
UPROPERTY(VisibleAnywhere, Category=SsAnimationSettings)
int32 FrameCount; //!< フレーム数
UPROPERTY(VisibleAnywhere, Category=SsAnimationSettings)
FVector2D CanvasSize; //!< キャンバスサイズ(元基準枠)。ビューポートのサイズとイコールではない。
UPROPERTY(VisibleAnywhere, Category=SsAnimationSettings)
FVector2D Pivot; //!< キャンバスの原点。0,0 が中央。-0.5, +0.5 が左上
UPROPERTY(VisibleAnywhere, Category=SsAnimationSettings)
int32 StartFrame; //!< アニメーションの開始フレーム
UPROPERTY(VisibleAnywhere, Category=SsAnimationSettings)
int32 EndFrame; //!< アニメーションの終了フレーム
};
//パーツ一つあたりの情報を保持するデータです。
USTRUCT()
struct SPRITESTUDIO6_API FSsPart
{
GENERATED_USTRUCT_BODY()
public:
UPROPERTY(VisibleAnywhere, Category=SsPart)
FName PartName;
UPROPERTY(VisibleAnywhere, Category=SsPart)
int32 ArrayIndex; //!< ツリーを配列に展開した時のインデックス
UPROPERTY(VisibleAnywhere, Category=SsPart)
int32 ParentIndex; //!< 親パーツのインデックス
UPROPERTY(VisibleAnywhere, Category=SsPart)
TEnumAsByte<SsPartType::Type> Type; //!< 種別
UPROPERTY(VisibleAnywhere, Category=SsPart)
TEnumAsByte<SsBoundsType::Type> BoundsType; //!< 当たり判定として使うか?使う場合はその形状。
UPROPERTY(VisibleAnywhere, Category=SsPart)
TEnumAsByte<SsInheritType::Type> InheritType; //!< アトリビュート値の継承方法
UPROPERTY(VisibleAnywhere, Category=SsPart)
TEnumAsByte<SsBlendType::Type> AlphaBlendType; //!< αブレンドの演算式
// UPROPERTY(VisibleAnywhere, Category=SsPart)
// int32 Show; //!< [編集用データ] パーツの表示・非常時
// UPROPERTY(VisibleAnywhere, Category=SsPart)
// int32 Locked; //!< [編集用データ] パーツのロック状態
UPROPERTY(VisibleAnywhere, Category=SsPart)
FName ColorLabel; //!< カラーラベル
UPROPERTY(VisibleAnywhere, Category=SsPart)
bool MaskInfluence; //!< マスクの影響を受けるかどうか
UPROPERTY(VisibleAnywhere, Category=SsPart)
float InheritRates[(int32)SsAttributeKind::Num]; ///< 親の値の継承率。SS4との互換性のため残されているが0 or 1
UPROPERTY(VisibleAnywhere, Category=SsPart)
FName RefAnimePack; ///< 参照アニメ名
UPROPERTY(VisibleAnywhere, Category=SsPart)
FName RefAnime; ///< 参照アニメ名
UPROPERTY(VisibleAnywhere, Category=SsPart)
FName RefEffectName; ///< 割り当てたパーティクル名
UPROPERTY(VisibleAnywhere, Category=SsPart)
int32 BoneLength; //!< ボーンの長さ
UPROPERTY(VisibleAnywhere, Category=SsPart)
FVector2D BonePosition; //!< ボーンの座標
UPROPERTY(VisibleAnywhere, Category=SsPart)
float BoneRotation; //!< ボーンの角度
UPROPERTY(VisibleAnywhere, Category=SsPart)
FVector2D WeightPosition; //!< ウェイトの位置
UPROPERTY(VisibleAnywhere, Category=SsPart)
float WeightImpact; //!< ウェイトの強さ
UPROPERTY(VisibleAnywhere, Category=SsPart)
int32 IKDepth; //!< IK深度
UPROPERTY(VisibleAnywhere, Category=SsPart)
TEnumAsByte<SsIkRotationArrow::Type> IKRotationArrow; //!< 回転方向
public:
FSsPart()
: PartName(NAME_None)
, ArrayIndex(0)
, ParentIndex(0)
, Type(SsPartType::Invalid)
, BoundsType(SsBoundsType::Invalid)
, InheritType(SsInheritType::Invalid)
, AlphaBlendType(SsBlendType::Invalid)
, MaskInfluence(true)
{
BoneLength = 0;
BonePosition = FVector2D::ZeroVector;
BoneRotation = 0.f;
WeightPosition = FVector2D::ZeroVector;
WeightImpact = 0.f;
IKDepth = 0;
IKRotationArrow = SsIkRotationArrow::Arrowfree;
for (int i = 0; i < (int32)SsAttributeKind::Num; ++i)
{
InheritRates[i] = 1.f;
}
// イメージ反転は継承しない
InheritRates[(int32)SsAttributeKind::Imgfliph] = 0.f;
InheritRates[(int32)SsAttributeKind::Imgflipv] = 0.f;
}
};
#define SSMESHPART_BONEMAX (128)
USTRUCT()
struct SPRITESTUDIO6_API FSsMeshBindInfo
{
GENERATED_USTRUCT_BODY()
UPROPERTY() // 要素数が多くDetailsウィンドウが極端に重くなってしまうため、VisibleAnywhereを付けない
int32 Weight[SSMESHPART_BONEMAX];
UPROPERTY() // 要素数が多くDetailsウィンドウが極端に重くなってしまうため、VisibleAnywhereを付けない
FName BoneName[SSMESHPART_BONEMAX];
UPROPERTY() // 要素数が多くDetailsウィンドウが極端に重くなってしまうため、VisibleAnywhereを付けない
int32 BoneIndex[SSMESHPART_BONEMAX];
UPROPERTY() // 要素数が多くDetailsウィンドウが極端に重くなってしまうため、VisibleAnywhereを付けない
FVector Offset[SSMESHPART_BONEMAX];
UPROPERTY(VisibleAnywhere, Category=SsMeshBindInfo)
int32 BindBoneNum;
FSsMeshBindInfo()
{
for(int32 i = 0; i < SSMESHPART_BONEMAX; ++i)
{
Weight[i] = 0;
BoneIndex[i] = 0;
Offset[i] = FVector::ZeroVector;
}
BindBoneNum = 0;
}
};
//メッシュ1枚毎の情報
USTRUCT()
struct SPRITESTUDIO6_API FSsMeshBind
{
GENERATED_USTRUCT_BODY()
UPROPERTY(VisibleAnywhere, Category=SsMeshBind)
FString MeshName;
UPROPERTY(VisibleAnywhere, Category=SsMeshBind)
TArray<FSsMeshBindInfo> MeshVerticesBindArray;
};
//アニメーションを構成するパーツをリスト化したものです。
USTRUCT()
struct SPRITESTUDIO6_API FSsModel
{
GENERATED_USTRUCT_BODY()
public:
UPROPERTY(VisibleAnywhere, Category=SsModel)
TArray<FSsPart> PartList; //!<格納されているパーツのリスト
struct FSsAnimation* SetupAnimation; //< 参照するセットアップアニメ
UPROPERTY(VisibleAnywhere, Category=SsModel)
TArray<FSsMeshBind> MeshList;
UPROPERTY(VisibleAnywhere, Category=SsModel)
TMap<FName, int32> BoneList;
};
USTRUCT()
struct SPRITESTUDIO6_API FSsPartAnime
{
GENERATED_USTRUCT_BODY()
void Serialize(FArchive& Ar);
public:
UPROPERTY(VisibleAnywhere, Category=SsPartAnime)
FName PartName;
UPROPERTY(VisibleAnywhere, Category=SsPartAnime)
TArray<FSsAttribute> Attributes;
};
/// ラベル。ループ先などに指定する
USTRUCT()
struct SPRITESTUDIO6_API FSsLabel
{
GENERATED_USTRUCT_BODY()
public:
UPROPERTY(VisibleAnywhere, Category=SsLabel)
FName LabelName; ///< 名前 [変数名変更禁止]
UPROPERTY(VisibleAnywhere, Category=SsLabel)
int32 Time; ///< 設置された時間(フレーム) [変数名変更禁止]
};
USTRUCT()
struct SPRITESTUDIO6_API FSsAnimation
{
GENERATED_USTRUCT_BODY()
void Serialize(FArchive& Ar);
public:
UPROPERTY(VisibleAnywhere, Category=SsAnimation)
FName AnimationName; /// アニメーションの名称
UPROPERTY(VisibleAnywhere, Category=SsAnimation)
bool OverrideSettings; /// このインスタンスが持つ設定を使いanimePack の設定を参照しない。FPS, frameCount は常に自身の設定を使う。
UPROPERTY(VisibleAnywhere, Category=SsAnimation)
FSsAnimationSettings Settings; /// 設定情報
UPROPERTY() // 要素数が多くDetailsウィンドウが極端に重くなってしまうため、VisibleAnywhereを付けない
TArray<FSsPartAnime> PartAnimes; /// パーツ毎のアニメーションキーフレームが格納されるリスト
UPROPERTY(VisibleAnywhere, Category=SsAnimation)
TArray<FSsLabel> Labels; /// アニメーションが持つラベルのリストです。
UPROPERTY(VisibleAnywhere, Category=SsAnimation)
bool IsSetup; ///< セットアップアニメか?
public:
int32 GetFrameCount() const { return Settings.EndFrame - Settings.StartFrame + 1; }
};
/**
*@class SsAnimePack
*@brief パーツを組み合わせた構造とその構造を使用するアニメーションを格納するデータです。
パーツの組み合わせ構造をSsModel、Modelを使用するアニメデータをSsAnimationで定義しています。
*/
USTRUCT()
struct SPRITESTUDIO6_API FSsAnimePack
{
GENERATED_USTRUCT_BODY()
void Serialize(FArchive& Ar);
public:
UPROPERTY(VisibleAnywhere, Category=SsAnimePack)
FString Version;
UPROPERTY(VisibleAnywhere, Category=SsAnimePack)
FSsAnimationSettings Settings; //!< 設定情報
UPROPERTY(VisibleAnywhere, Category=SsAnimePack)
FName AnimePackName; //!< アニメーションパック名称
UPROPERTY(VisibleAnywhere, Category=SsAnimePack)
FSsModel Model; //!< パーツ情報の格納先
UPROPERTY(VisibleAnywhere, Category=SsAnimePack)
TArray<FName> CellmapNames; //!< 使用されているセルマップの名称
UPROPERTY(VisibleAnywhere, Category=SsAnimePack)
TArray<FSsAnimation> AnimeList; //!< 格納されている子アニメーションのリスト
// アニメーション名からインデックスを取得する
int32 FindAnimationIndex(const FName& Name) const;
// 名前からアニメーションを取得する
const FSsAnimation* FindAnimation(const FName& Name) const;
// Setup以外の最も小さいアニメーションインデックスを取得する
// Setupしか存在しない場合は0を返す(通常はあり得ない)
int32 FindMinimumAnimationIndexExcludingSetup() const;
};
<file_sep>/Ss6PlayerExamples/Plugins/SpriteStudio6/Source/SpriteStudio6/Public/UMG/SsPlayerWidget.h
#pragma once
#include "UMG.h"
#include "SsTypes.h"
#include "SsPlayerTickResult.h"
#include "SsPlayer.h"
#include "SsPlayPropertySync.h"
#include "SsPlayerWidget.generated.h"
class UMaterialInterface;
class USs6Project;
class SSsPlayerWidget;
DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FSsWidgetEndPlaySignature2, FName, AnimPackName, FName, AnimationName, int32, AnimPackIndex, int32, AnimationIndex);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FSsWidgetUserDataSignature2, FName, PartName, int32, PartIndex, int32, KeyFrame, FSsUserDataValue, UserData);
// SsPlayerWidgetの描画モード
UENUM()
namespace ESsPlayerWidgetRenderMode
{
enum Type
{
// UMGデフォルトの描画モードです
// アルファブレンドモードはミックス/加算のみ反映されます
UMG_Default,
// 描画方法はUMG_Defaultと同等ですが、Maskedマテリアルを使用するため、半透明は2値化されます
// アルファブレンドモードはミックスのみ反映されます
UMG_Masked,
// 一旦オフスクリーンレンダリングしたテクスチャを描画します。
// UMG_Defaultに比べて処理が重くなりますが、BaseMaterilを変更することで、特殊な効果を実装することが可能です。
// 子Widgetのアタッチがサポートされません
UMG_OffScreen,
};
}
//
// SpriteStudio6 Player Widget
// sspjデータを再生/UMG上で描画する
//
UCLASS(ClassGroup=SpriteStudio, meta=(DisplayName="Ss Player Widget"))
class SPRITESTUDIO6_API USsPlayerWidget : public UPanelWidget, public FSsPlayPropertySync
{
GENERATED_UCLASS_BODY()
public:
// UObject interface
virtual void BeginDestroy() override;
virtual void Serialize(FArchive& Ar) override;
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
// UVisual interface
virtual void ReleaseSlateResources(bool bReleaseChildren) override;
// UWidget interface
virtual void SynchronizeProperties() override;
#if WITH_EDITOR
virtual const FText GetPaletteCategory() override { return FText::FromString(TEXT("Sprite Studio")); }
#endif
public:
void OnSlateTick(float DeltaTime);
protected:
// UWidget interface
virtual TSharedRef<SWidget> RebuildWidget() override;
// UPanelWidget interface
virtual UClass* GetSlotClass() const override;
virtual void OnSlotAdded(UPanelSlot* InSlot) override;
virtual void OnSlotRemoved(UPanelSlot* InSlot) override;
private:
FSsPlayer Player;
TSharedPtr<SSsPlayerWidget> PlayerWidget;
TMap<UMaterialInterface*, TSharedPtr<struct FSlateMaterialBrush>> BrushMap;
UPROPERTY(Transient)
UMaterialInstanceDynamic* OffScreenMID;
UPROPERTY(Transient)
UTexture* OffScreenRenderTarget;
TMap<UMaterialInterface*, TMap<UTexture*, UMaterialInstanceDynamic*>> PartsMIDMaps;
UPROPERTY(Transient)
TMap<int32, UMaterialInterface*> MaterialReplacementMap;
UPROPERTY(Transient)
TMap<int32, UMaterialInterface*> MaterialReplacementMapPerBlendMode;
#if WITH_EDITOR
private:
// 1フレームに複数回Tick呼び出しされてしまう問題の対処用
float BackWorldTime;
#endif
public:
// 公開PROPERTY
//
// SpriteStudioAsset
//
// 再生するSsProject
UPROPERTY(Category="SpriteStudioAsset", EditAnywhere, BlueprintReadOnly, meta=(DisplayThumbnail="true"))
USs6Project* SsProject;
//
// SpriteStudioPlayerSettings
//
// 自動更新. Offの場合はUpdatePlayer()を呼び出してアニメーションを更新します.
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly, AdvancedDisplay)
bool bAutoUpdate;
// 自動再生
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly, AdvancedDisplay)
bool bAutoPlay;
// 自動再生時のAnimPack名
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly)
FName AutoPlayAnimPackName;
// 自動再生時のAnimation名
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly)
FName AutoPlayAnimationName;
// 自動再生時のAnimPackIndex
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly)
int32 AutoPlayAnimPackIndex;
// 自動再生時のAnimationIndex
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly)
int32 AutoPlayAnimationIndex;
// 自動再生時の開始フレーム
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly, AdvancedDisplay)
int32 AutoPlayStartFrame;
// 自動再生時の再生速度(負の値で逆再生)
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly, AdvancedDisplay)
float AutoPlayRate;
// 自動再生時のループ回数(0で無限ループ)
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly, AdvancedDisplay)
int32 AutoPlayLoopCount;
// 自動再生時の往復再生
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadOnly, AdvancedDisplay)
bool bAutoPlayRoundTrip;
// ウィジェットが非表示の時はアニメーションを更新しない
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadWrite, AdvancedDisplay)
bool bDontUpdateIfHidden;
// Pause中でもTickする
UPROPERTY(Category="SpriteStudioPlaySettings", EditAnywhere, BlueprintReadWrite, AdvancedDisplay)
bool bTickableWhenPaused;
//
// SpriteStudioRenderSettings
//
// 描画モード
UPROPERTY(Category="SpriteStudioRenderSettings", EditAnywhere, BlueprintReadOnly)
TEnumAsByte<ESsPlayerWidgetRenderMode::Type> RenderMode;
// 描画モードがOffScreenの場合のベースマテリアル
UPROPERTY(Category="SpriteStudioRenderSettings", EditAnywhere, BlueprintReadOnly, meta=(DisplayName="OffScreen Material", DisplayThumbnail="true"), AdvancedDisplay)
UMaterialInterface* BaseMaterial;
// オフスクリーンレンダリングの際の解像度
UPROPERTY(Category="SpriteStudioRenderSettings", EditAnywhere, BlueprintReadOnly, AdvancedDisplay)
FVector2D OffScreenRenderResolution;
// オフスクリーンレンダリングの際のクリアカラー
UPROPERTY(Category="SpriteStudioRenderSettings", EditAnywhere, BlueprintReadWrite, AdvancedDisplay)
FColor OffScreenClearColor;
// 親Widgetのアルファ値を反映するか
UPROPERTY(Category="SpriteStudioRenderSettings", EditAnywhere, BlueprintReadOnly)
bool bReflectParentAlpha;
//
// SpriteStudioCallback
//
// 再生終了イベント
UPROPERTY(BlueprintAssignable, Category="SpriteStudioCallback")
FSsWidgetEndPlaySignature2 OnSsEndPlay;
// ユーザーデータイベント
UPROPERTY(BlueprintAssignable, Category="SpriteStudioCallback")
FSsWidgetUserDataSignature2 OnSsUserData;
//
// Misc
//
// 実際に描画に使用されているMaterialInstanceDynamic
UPROPERTY(Transient, BlueprintReadOnly, Category="SpriteStudio")
TArray<UMaterialInstanceDynamic*> RenderMIDs;
public:
// BP公開関数
// アニメーションの更新
// AutoUpdate=false の場合はこの関数を直接呼び出して下さい
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void UpdatePlayer(float DeltaSeconds);
// 描画対象テクスチャを取得
UFUNCTION(Category="SpriteStudio", BlueprintPure)
UTexture* GetRenderTarget();
// アニメーションの再生開始
UFUNCTION(Category="SpriteStudio", BlueprintCallable, meta=(AdvancedDisplay="2"))
bool Play(FName AnimPackName, FName AnimationName, int32 StartFrame=0, float PlayRate=1.f, int32 LoopCount=0, bool bRoundTrip=false);
// アニメーションの再生開始(インデックス指定)
UFUNCTION(Category="SpriteStudio", BlueprintCallable, meta=(AdvancedDisplay="2"))
bool PlayByIndex(int32 AnimPackIndex, int32 AnimationIndex, int32 StartFrame=0, float PlayRate=1.f, int32 LoopCount=0, bool bRoundTrip=false);
// シーケンスの再生開始
UFUNCTION(Category="SpriteStudio", BlueprintCallable, meta=(AdvancedDisplay="2"))
bool PlaySequence(FName SequencePackName, FName SequenceName, int32 StartFrame=0, float PlayRate=1.f);
// シーケンスの再生開始(インデックス指定)
UFUNCTION(Category="SpriteStudio", BlueprintCallable, meta=(AdvancedDisplay="2"))
bool PlaySequenceByIndex(int32 SequencePackIndex, int32 SequenceIndex, int32 StartFrame=0, float PlayRate=1.f);
// 再生中のアニメーション名を取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void GetPlayingAnimationName(FName& OutAnimPackName, FName& OutAnimationName) const;
// 再生中のアニメーションインデックスを取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void GetPlayingAnimationIndex(int32& OutAnimPackIndex, int32& OutAnimationIndex) const;
// 再生中のシーケンス名を取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void GetPlayingSequenceName(FName& OutSequencePackName, FName& OutSequenceName) const;
// 再生中のシーケンスインデックスを取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void GetPlayingSequenceIndex(int32& OutSequencePackIndex, int32& OutSequenceIndex) const;
// アニメーション再生の一時停止
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void Pause();
// 一時停止したアニメーション再生の再開
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
bool Resume();
// アニメーションが再生中かを取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
bool IsPlaying() const;
// シーケンスを再生中かを取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
bool IsPlayingSequence() const;
// セットされたSsProjectのAnimPack数を取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
int32 GetNumAnimPacks() const;
// 指定されたAnimPackのAnimation数を取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
int32 GetNumAnimations(FName AnimPackName) const;
// 指定されたAnimPackのAnimation数を取得(インデックス指定)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
int32 GetNumAnimationsByIndex(int32 AnimPackIndex) const;
// セットされたSsProjectのSequencePack数を取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
int32 GetNumSequencePacks() const;
// 指定されたSequencePackのSequence数を取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
int32 GetNumSequences(FName SequencePackName) const;
// 指定されたSequencePackのSequence数を取得(インデックス指定)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
int32 GetNumSequencesByIndex(int32 SequencePackIndex) const;
// シーケンスIDからインデックスを取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
bool GetSequenceIndexById(FName SequencePackName, int32 SequenceId, int32& OutSequencePackIndex, int32& OutSequneceIndex) const;
// 指定フレームへジャンプ
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void SetPlayFrame(float Frame);
// 現在のフレームを取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
float GetPlayFrame() const;
// ループ数を設定(0で無限ループ)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void SetLoopCount(int32 InLoopCount);
// 残りループ数を取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
int32 GetLoopCount() const;
// 往復再生するかを設定
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void SetRoundTrip(bool bInRoundTrip);
// 往復再生中かを取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
bool IsRoundTrip() const;
// 再生速度を設定(負の値で逆再生)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void SetPlayRate(float InRate=1.f);
// 再生速度を取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
float GetPlayRate() const;
// 水平反転の設定
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void SetFlipH(bool InFlipH);
// 水平反転の取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
bool GetFlipH() const;
// 垂直反転の設定
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void SetFlipV(bool InFlipV);
// 垂直反転の取得
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
bool GetFlipV() const;
// 置き換えテクスチャの登録
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void AddTextureReplacement(FName PartName, UTexture* Texture);
// 置き換えテクスチャの登録(インデックス指定)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void AddTextureReplacementByIndex(int32 PartIndex, UTexture* Texture);
// 置き換えテクスチャの登録解除
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void RemoveTextureReplacement(FName PartName);
// 置き換えテクスチャの登録解除(インデックス指定)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void RemoveTextureReplacementByIndex(int32 PartIndex);
// 全ての置き換えテクスチャの登録解除
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void RemoveTextureReplacementAll();
// 置き換えマテリアルの登録(パーツ単位)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void AddMaterialReplacement(FName PartName, UMaterialInterface* InBaseMaterial);
// 置き換えマテリアルの登録(パーツ単位)(インデックス指定)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void AddMaterialReplacementByIndex(int32 PartIndex, UMaterialInterface* InBaseMaterial);
// 置き換えマテリアルの登録解除(パーツ単位)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void RemoveMaterialReplacement(FName PartName);
// 置き換えマテリアルの登録解除(パーツ単位)(インデックス指定)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void RemoveMaterialReplacementByIndex(int32 PartIndex);
// 全ての置き換えマテリアルの登録解除(パーツ単位)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void RemoveMaterialReplacementAll();
// 置き換えマテリアルの登録(ブレンドモード単位)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void AddMaterialReplacementPerBlendMode(EAlphaBlendType AlphaBlendMode, EColorBlendType ColorBlendMode, UMaterialInterface* InBaseMaterial);
// 置き換えマテリアルの登録解除(ブレンドモード単位)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void RemoveMaterialReplacementPerBlendMode(EAlphaBlendType AlphaBlendMode, EColorBlendType ColorBlendMode);
// 全ての置き換えマテリアルの登録解除(ブレンドモード単位)
UFUNCTION(Category="SpriteStudio", BlueprintCallable)
void RemoveMaterialReplacementAllPerBlendMode();
// パーツのカラーラベルを取得
UFUNCTION(Category = SpriteStudio, BlueprintCallable)
FName GetPartColorLabel(FName PartName);
// パーツのカラーラベルを取得(インデックス指定)
UFUNCTION(Category = SpriteStudio, BlueprintCallable)
FName GetPartColorLabelByIndex(int32 PartIndex);
// ウィジェット内のパーツのTransformを取得
UFUNCTION(Category = SpriteStudio, BlueprintCallable)
bool GetPartTransform(FName PartName, FVector2D& OutPosition, float& OutAngle, FVector2D& OutScale) const;
// ウィジェット内のパーツのTransformを取得(インデックス指定)
UFUNCTION(Category = SpriteStudio, BlueprintCallable)
bool GetPartTransformByIndex(int32 PartIndex, FVector2D& OutPosition, float& OutAngle, FVector2D& OutScale) const;
};
<file_sep>/Ss6PlayerExamples/Plugins/SpriteStudio6/Source/SpriteStudio6/Private/SSSDK/ssplayer_PartState.h
#ifndef __SSPLAYER_PARTSTATE__
#define __SSPLAYER_PARTSTATE__
//#include "../Loader/ssloader.h"
//#include "../Helper/ssHelper.h"
#include "ssplayer_cellmap.h"
class SsAnimeDecoder;
//class SsEffectRenderer;
class SsEffectRenderV2;
class SsMeshPart;
///パーツの状態を保持するクラスです。
struct SsPartState
{
int index; ///パーツのインデックスと一対一になるID
float vertices[3 * 5]; ///< 座標
// float colors[4 * 4]; ///< カラー (4頂点分)
float uvs[2 * 5]; ///< UV (4隅+中央)
float matrix[4 * 4]; ///< 行列
float matrixLocal[4 * 4]; ///< ローカル行列
SsPartState* parent; /// 親へのポインタ
float* inheritRates; ///< 継承設定の参照先。inheritType がparentだと親のを見に行く。透過的に遡るのでルートから先に設定されている必要がある。
FVector position; ///< 位置。あくまで親パーツ基準のローカル座標
FVector rotation; ///< 回転角。degree
FVector2D scale; ///< スケール
FVector2D localscale; ///< ローカルスケール
float alpha; ///< 不透明度 0~1
float localalpha; ///< ローカル不透明度 0~1
int prio; ///< 優先度
// bool hFlip; ///< 水平反転 ※Ver6では非対応
// bool vFlip; ///< 垂直反転 ※Ver6では非対応
bool hide; ///< 非表示にする
FVector2D pivotOffset; ///< 原点のオフセット。旧SSの原点は左上基準にしたこの値に相当する。0,0が中央+0.5,+0.5が右上になる。参照セルがある場合はセルの原点に+する=オフセット扱いになる。
// FVector2D anchor; ///< アンカーポイント。親パーツのどの位置に引っ付けるか?0,0が中央+0.5,+0.5が右上になる。 ※Ver6では非対応
FVector2D size; ///< 表示サイズ
bool imageFlipH; /// セル画像を水平反転するか
bool imageFlipV; /// セル画像を垂直反転するか
FVector2D uvTranslate; ///< UV 平行移動
float uvRotation; ///< UV 回転
FVector2D uvScale; ///< UV スケール
// float boundingRadius; ///< 当たり判定用の円の半径
SsCellValue cellValue; ///< セルアニメの値
SsPartsColorAnime partsColorValue;///< カラーアニメの値
// SsColorAnime colorValue; ///< カラーアニメの値
FSsVertexAnime vertexValue; ///< 頂点アニメの値
SsEffectAttr effectValue; ///< エフェクトの値
int effectTime;
float effectTimeTotal;
// int effectseed;
bool noCells; /// セル参照が見つからない
bool is_parts_color; /// パーツカラーが使用される
// bool is_color_blend; /// カラーブレンドが使用される (描画コストが高いシェーダが使われるためフラグ化) ※Ver6では非対応
bool is_vertex_transform; /// 頂点変形が使用される (描画コストが高いシェーダが使われるためフラグ化)
bool is_localAlpha; /// ローカル不透明度を使用している
bool is_defrom; /// デフォームアトリビュートを使用している
SsInstanceAttr instanceValue;
SsBlendType::Type alphaBlendType;
SsAnimeDecoder* refAnime;
SsCellMapList* refCellMapList;
SsEffectRenderV2* refEffect;
// //V4互換計算用
// FVector _temp_position;
// FVector _temp_rotation;
// FVector2D _temp_scale;
SsPartType::Type partType;
int masklimen;
bool maskInfluence;
SsMeshPart* meshPart;
SsDeformAttr deformValue;
FSsPart* part;
SsPartState();
virtual ~SsPartState();
void destroy();
void init();
bool inherits_(SsAttributeKind::Type kind) const {return inheritRates[(int)kind] != 0.f;}
void reset();
// UE4 TArray::Sort() 用
bool operator < (const SsPartState& Other) const
{
return (prio != Other.prio) ? (prio < Other.prio) : (index < Other.index);
}
};
#endif
<file_sep>/Ss6PlayerExamples/Plugins/SpriteStudio6/Source/SpriteStudio6/Private/Component/SsRenderPlaneProxy.cpp
#include "SsRenderPlaneProxy.h"
#include "DynamicMeshBuilder.h"
#include "SsPlayerComponent.h"
// IndexBuffer
void FSsPlaneIndexBuffer::InitRHI()
{
FRHIResourceCreateInfo CreateInfo;
void* Buffer = nullptr;
IndexBufferRHI = RHICreateAndLockIndexBuffer(sizeof(uint16), 6 * sizeof(uint16), BUF_Static, CreateInfo, Buffer);
((uint16*)Buffer)[0] = 0;
((uint16*)Buffer)[1] = 2;
((uint16*)Buffer)[2] = 1;
((uint16*)Buffer)[3] = 1;
((uint16*)Buffer)[4] = 2;
((uint16*)Buffer)[5] = 3;
RHIUnlockIndexBuffer(IndexBufferRHI);
}
// コンストラクタ
FSsRenderPlaneProxy::FSsRenderPlaneProxy(USsPlayerComponent* InComponent, UMaterialInterface* InMaterial)
: FPrimitiveSceneProxy(InComponent)
, CanvasSizeUU(100.f, 100.f)
, Pivot(0.f, 0.f)
, VertexFactory(GetScene().GetFeatureLevel(), "FSsRenderPlaneProxy")
{
// FPrimitiveSceneProxy
bWillEverBeLit = false;
Component = InComponent;
Material = InMaterial;
bVerifyUsedMaterials = false;
}
// デストラクタ
FSsRenderPlaneProxy::~FSsRenderPlaneProxy()
{
VertexBuffers.PositionVertexBuffer.ReleaseResource();
VertexBuffers.StaticMeshVertexBuffer.ReleaseResource();
VertexBuffers.ColorVertexBuffer.ReleaseResource();
IndexBuffer.ReleaseResource();
VertexFactory.ReleaseResource();
}
SIZE_T FSsRenderPlaneProxy::GetTypeHash() const
{
static size_t UniquePointer;
return reinterpret_cast<size_t>(&UniquePointer);
}
void FSsRenderPlaneProxy::CreateRenderThreadResources()
{
VertexBuffers.InitWithDummyData(&VertexFactory, 4);
IndexBuffer.InitResource();
}
void FSsRenderPlaneProxy::GetDynamicMeshElements(const TArray<const FSceneView*>& Views, const FSceneViewFamily& ViewFamily, uint32 VisibilityMap, FMeshElementCollector& Collector) const
{
QUICK_SCOPE_CYCLE_COUNTER( STAT_SsRenderSceneProxy_GetDynamicMeshElements );
const bool bWireframe = AllowDebugViewmodes() && ViewFamily.EngineShowFlags.Wireframe;
FMaterialRenderProxy* MaterialProxy = NULL;
if(bWireframe)
{
FColoredMaterialRenderProxy* WireframeMaterialInstance = new FColoredMaterialRenderProxy(
GEngine->WireframeMaterial ? GEngine->WireframeMaterial->GetRenderProxy() : NULL,
FLinearColor(0, 0.5f, 1.f)
);
Collector.RegisterOneFrameMaterialProxy(WireframeMaterialInstance);
MaterialProxy = WireframeMaterialInstance;
}
else
{
if(NULL == Material)
{
return;
}
MaterialProxy = Material->GetRenderProxy();
}
for(int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
{
if(VisibilityMap & (1 << ViewIndex))
{
const FSceneView* View = Views[ViewIndex];
// Draw the mesh.
FMeshBatch& Mesh = Collector.AllocateMesh();
Mesh.VertexFactory = &VertexFactory;
Mesh.MaterialRenderProxy = MaterialProxy;
Mesh.ReverseCulling = IsLocalToWorldDeterminantNegative();
Mesh.CastShadow = true;
Mesh.DepthPriorityGroup = SDPG_World;
Mesh.Type = PT_TriangleList;
Mesh.bDisableBackfaceCulling = true;
Mesh.bCanApplyViewModeOverrides = false;
FMeshBatchElement& BatchElement = Mesh.Elements[0];
BatchElement.IndexBuffer = &IndexBuffer;
BatchElement.FirstIndex = 0;
BatchElement.MinVertexIndex = 0;
BatchElement.MaxVertexIndex = 3;
BatchElement.NumPrimitives = 2;
Collector.AddMesh(ViewIndex, Mesh);
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
// Render bounds
RenderBounds(Collector.GetPDI(ViewIndex), ViewFamily.EngineShowFlags, GetBounds(), IsSelected());
#endif
}
}
}
FPrimitiveViewRelevance FSsRenderPlaneProxy::GetViewRelevance(const FSceneView* View) const
{
FPrimitiveViewRelevance Result;
Result.bDrawRelevance = IsShown(View);
Result.bRenderCustomDepth = ShouldRenderCustomDepth();
Result.bRenderInMainPass = ShouldRenderInMainPass();
Result.bUsesLightingChannels = false;
Result.bOpaque = true;
Result.bSeparateTranslucency = true;
Result.bNormalTranslucency = false;
Result.bShadowRelevance = IsShadowCast(View);
Result.bDynamicRelevance = true;
return Result;
}
uint32 FSsRenderPlaneProxy::GetMemoryFootprint() const
{
return sizeof(*this) + GetAllocatedSize();
}
void FSsRenderPlaneProxy::SetDynamicData_RenderThread()
{
TArray<FDynamicMeshVertex> Vertices;
Vertices.Empty(4);
Vertices.AddUninitialized(4);
FVector2D PivotOffSet = -(Pivot * CanvasSizeUU);
Vertices[0] = FDynamicMeshVertex(FVector(0.f, PivotOffSet.X - CanvasSizeUU.X/2.f, PivotOffSet.Y + CanvasSizeUU.Y/2.f), FVector(1.f, 0.f, 0.f), FVector(0.f, 0.f, 1.f), FVector2D(0.f, 0.f), FColor(255, 255, 255, 255));
Vertices[1] = FDynamicMeshVertex(FVector(0.f, PivotOffSet.X + CanvasSizeUU.X/2.f, PivotOffSet.Y + CanvasSizeUU.Y/2.f), FVector(1.f, 0.f, 0.f), FVector(0.f, 0.f, 1.f), FVector2D(1.f, 0.f), FColor(255, 255, 255, 255));
Vertices[2] = FDynamicMeshVertex(FVector(0.f, PivotOffSet.X - CanvasSizeUU.X/2.f, PivotOffSet.Y - CanvasSizeUU.Y/2.f), FVector(1.f, 0.f, 0.f), FVector(0.f, 0.f, 1.f), FVector2D(0.f, 1.f), FColor(255, 255, 255, 255));
Vertices[3] = FDynamicMeshVertex(FVector(0.f, PivotOffSet.X + CanvasSizeUU.X/2.f, PivotOffSet.Y - CanvasSizeUU.Y/2.f), FVector(1.f, 0.f, 0.f), FVector(0.f, 0.f, 1.f), FVector2D(1.f, 1.f), FColor(255, 255, 255, 255));
for(int32 i = 0; i < 4; ++i)
{
VertexBuffers.PositionVertexBuffer.VertexPosition(i) = Vertices[i].Position;
VertexBuffers.StaticMeshVertexBuffer.SetVertexTangents(i, Vertices[i].TangentX.ToFVector(), Vertices[i].GetTangentY(), Vertices[i].TangentZ.ToFVector());
VertexBuffers.StaticMeshVertexBuffer.SetVertexUV(i, 0, Vertices[i].TextureCoordinate[0]);
VertexBuffers.ColorVertexBuffer.VertexColor(i) = Vertices[i].Color;
}
{
auto& VertexBuffer = VertexBuffers.PositionVertexBuffer;
void* VertexBufferData = RHILockVertexBuffer(VertexBuffer.VertexBufferRHI, 0, VertexBuffer.GetNumVertices() * VertexBuffer.GetStride(), RLM_WriteOnly);
FMemory::Memcpy(VertexBufferData, VertexBuffer.GetVertexData(), VertexBuffer.GetNumVertices() * VertexBuffer.GetStride());
RHIUnlockVertexBuffer(VertexBuffer.VertexBufferRHI);
}
{
auto& VertexBuffer = VertexBuffers.ColorVertexBuffer;
void* VertexBufferData = RHILockVertexBuffer(VertexBuffer.VertexBufferRHI, 0, VertexBuffer.GetNumVertices() * VertexBuffer.GetStride(), RLM_WriteOnly);
FMemory::Memcpy(VertexBufferData, VertexBuffer.GetVertexData(), VertexBuffer.GetNumVertices() * VertexBuffer.GetStride());
RHIUnlockVertexBuffer(VertexBuffer.VertexBufferRHI);
}
{
auto& VertexBuffer = VertexBuffers.StaticMeshVertexBuffer;
void* VertexBufferData = RHILockVertexBuffer(VertexBuffer.TangentsVertexBuffer.VertexBufferRHI, 0, VertexBuffer.GetTangentSize(), RLM_WriteOnly);
FMemory::Memcpy(VertexBufferData, VertexBuffer.GetTangentData(), VertexBuffer.GetTangentSize());
RHIUnlockVertexBuffer(VertexBuffer.TangentsVertexBuffer.VertexBufferRHI);
}
{
auto& VertexBuffer = VertexBuffers.StaticMeshVertexBuffer;
void* VertexBufferData = RHILockVertexBuffer(VertexBuffer.TexCoordVertexBuffer.VertexBufferRHI, 0, VertexBuffer.GetTexCoordSize(), RLM_WriteOnly);
FMemory::Memcpy(VertexBufferData, VertexBuffer.GetTexCoordData(), VertexBuffer.GetTexCoordSize());
RHIUnlockVertexBuffer(VertexBuffer.TexCoordVertexBuffer.VertexBufferRHI);
}
}
<file_sep>/README.md
### SS6Player for Unreal Engine 4
- ドキュメント
https://github.com/SpriteStudio/SS6PlayerForUnrealEngine4/wiki
- チュートリアル
http://www.webtech.co.jp/help/ja/spritestudio/guide/output6/unrealengine4/
- BluePrintリファレンス
https://github.com/SpriteStudio/SS6PlayerForUnrealEngine4/wiki/BluePrintリファレンス
- Component/Widget、プロパティリファレンス ?
http://www.webtech.co.jp/help/ja/spritestudio/guide/output6/unrealengine4/component/
- 制限事項
https://github.com/SpriteStudio/SS6PlayerForUnrealEngine4/wiki/TIPS-制限事項
##### v1.5.0への更新の際の注意点
v1.5.0にて、パーツカラーの不具合修正と合わせてプラグイン内のマテリアルを大きく修正しました
v1.4系以前のマテリアルを基にカスタムマテリアルを作成されていた場合は、新しいマテリアルを基に修正されることを推奨します
##### 対応UE4バージョン
UE4.26
※ 旧バージョンのUE4で使用したい場合は、該当のTagから取得して下さい
|
2d12e03c837d5e5c12c0a63f5536004186e54fdd
|
[
"Markdown",
"C++"
] | 5 |
C++
|
richmondx/SS6PlayerForUnrealEngine4
|
adb77c6f41c56e48348735cf4525eea889ecff43
|
8a7eb93d5e87034df5fc25a3dd1cf25e181fece7
|
refs/heads/master
|
<file_sep>#!/bin/sh
# Requires:
# autoconf
# automake
# libtool
# uuid-dev
# libaio-dev
blktap_repo='<EMAIL>:comstud/blktap'
branch='add_vhd2raw'
if [ ! -d blktap.git ] ; then
git clone ${blktap_repo} blktap.git
if [ $? -ne 0 ] ; then
echo "Error: Couldn't clone ${blktap_repo}."
exit 1
fi
fi
cd blktap.git || exit 1
git checkout ${branch} || exit 1
if [ ! -f vhd/Makefile ] ; then
./autogen.sh &&
./configure
if [ $? -ne 0 ] ; then
echo 'Error: configure failed.'
exit 1
fi
fi
cd vhd && make
if [ $? -ne 0 ] ; then
echo 'Error: Build failed.'
exit 1
fi
<file_sep>libvhd-builder
==============
libvhd build script. Simple script to checkout blktap code and compile
the vhd library and utils. This builds my version which adds a vhdutil
command to convert to raw.
|
b8760de5eb019557aef94e3ee3da9a0dbc507dc2
|
[
"Markdown",
"Shell"
] | 2 |
Shell
|
comstud/libvhd-builder
|
29b5c988d216de277799aef03117937d7b9f51d2
|
665671864ba0e6bbd3cdd21d41bea696e876505d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.