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>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class SellService {
constructor(private httpClient:HttpClient) { }
public baseUrl: string = '//localhost:8080';
public sell(javaCar: number) {
return this.httpClient.post(this.baseUrl + '/sell/sell', + javaCar);
}
}
<file_sep>import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { ProductionService } from '../production.service';
import { AccountingService } from '../accounting.service';
@Component({
selector: 'app-production',
templateUrl: './production.component.html',
styleUrls: ['./production.component.css']
})
export class ProductionComponent implements OnInit {
constructor(private productionService: ProductionService, private accounting: AccountingService) { }
@Output()
sendProductionIntArray = new EventEmitter<number[]>();
visible: false;
javaCar: number;
htmlProduction: number = 0;
addCar(car: number[]) {
this.javaCar = car[7];
}
production() {
this.productionService.production(this.htmlProduction).subscribe(
(production: number[]) => {
console.log(production[0]);
console.log(production[1]);
console.log(production[2]);
console.log(production[3]);
this.javaCar = production[3];
this.sendProductionIntArray.next(production);
this.htmlProduction = 0;
}
);
}
ngOnInit() {
this.accounting.everyData().subscribe(
(data: number[]) => {
this.javaCar = data[11];
}
);
}
}
<file_sep>package hu.flowacademy.Cegvezeto.game.controller;
import hu.flowacademy.Cegvezeto.game.Logic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "production")
public class ProductionController {
@Autowired
private Logic logic;
@CrossOrigin(origins = "*", allowedHeaders="*")
@PostMapping("/production")
public int[] production(@RequestBody int n) {
return logic.production(n);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { AccountingService } from '../accounting.service';
@Component({
selector: 'app-accounting',
templateUrl: './accounting.component.html',
styleUrls: ['./accounting.component.css']
})
export class AccountingComponent implements OnInit {
constructor(private accounting: AccountingService) { }
visible: false;
monthAdvertisingCost: number = 0;
monthWorkersWages: number;
randomPlusReklam: number;
realSelling: number;
monthIncome: number;
companyMoney: number;
addAcounting(values: number[]) {
this.monthAdvertisingCost = values[1];
this.monthWorkersWages = values[2];
this.randomPlusReklam = values[3];
this.realSelling = values[4];
this.monthIncome = values[5];
this.companyMoney = values[6];
}
ngOnInit() {
this.accounting.everyData().subscribe(
(data: number[]) => {
this.monthAdvertisingCost = data[1];
this.monthWorkersWages = data[2];
this.randomPlusReklam = data[3];
this.realSelling = data[4];
this.monthIncome = data[5];
this.companyMoney = data[6];
console.log(this.monthAdvertisingCost);
}
);
}
}
<file_sep>package hu.flowacademy.Cegvezeto.game.controller;
import hu.flowacademy.Cegvezeto.game.Logic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "worker")
public class WorkerController {
@Autowired
private Logic logic;
@CrossOrigin(origins = "*", allowedHeaders="*")
@PostMapping("/buy-workere")
public Integer buyWorker(@RequestBody int n) {
return logic.hiringWorkers(n);
}
@CrossOrigin(origins = "*", allowedHeaders="*")
@PostMapping("/dismiss-worker")
public Integer dismissWorker(@RequestBody int n) {
return logic.dismissWorkers(n);
}
@CrossOrigin(origins = "*")
@GetMapping("/buy-worker")
public int javaWorkers() {
return logic.javaWorkers();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GameService {
constructor(private httpClient: HttpClient) { }
factoryName: string = '';
public baseUrl: string = '//localhost:8080';
public getFactoryName() {
return this.factoryName;
}
public saveFactoryName(name: any) {
this.factoryName = name;
return this.factoryName;
}
public buyChasis(htmlChasis: number) {
return this.httpClient.post(this.baseUrl + '/ingredient/buy-chasise', + htmlChasis);
}
public buyWheel(htmlWheel: number) {
return this.httpClient.post(this.baseUrl + '/ingredient/buy-wheele', + htmlWheel);
}
public buyEngin(htmlEngin: number) {
return this.httpClient.post(this.baseUrl + '/ingredient/buy-engine', + htmlEngin);
}
public getWheel() {
return this.httpClient.get(this.baseUrl + '/ingredient/buy-wheel');
}
public getChasis() {
return this.httpClient.get(this.baseUrl + '/ingredient/buy-chasis');
}
public getEngin() {
return this.httpClient.get(this.baseUrl + '/ingredient/buy-engin');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { GameService } from '../game.service';
import { AccountingService } from '../accounting.service';
@Component({
selector: 'app-cegvezeto',
templateUrl: './cegvezeto.component.html',
styleUrls: ['./cegvezeto.component.css']
})
export class CegvezetoComponent implements OnInit {
constructor(private gameService: GameService, private accounting:AccountingService) { }
visible: boolean = false;
javaWheel: number;
htmlWheel: number = 0;
javaChasis: number;
htmlChasis: number = 0;
javaEngin: number;
htmlEngin: number = 0;
add(value: number[]) {
this.javaWheel = value[0];
this.javaChasis = value[1];
this.javaEngin = value[2];
}
buyWheel() {
this.gameService.buyWheel(this.htmlWheel).subscribe(
(wheel: any) => {
console.log(wheel);
this.javaWheel = wheel;
this.htmlWheel = 0;
}
);
}
buyChasis() {
this.gameService.buyChasis(this.htmlChasis).subscribe(
(chasis: any) => {
console.log(chasis);
this.javaChasis = chasis;
this.htmlChasis = 0;
}
);
}
buyEngin() {
this.gameService.buyEngin(this.htmlEngin).subscribe(
(engin: any) => {
console.log(engin);
this.javaEngin = engin;
this.htmlEngin = 0;
}
);
}
ngOnInit() {
this.accounting.everyData().subscribe(
(data: number[]) => {
this.javaWheel = data[8];
this.javaChasis = data[9];
this.javaEngin = data[10];
}
);
}
}
<file_sep><app-main></app-main><br>
<p class="text">Itt tudsz reklámra költeni. Minden egyes megvásárolt reklám után 5 %-kal nő az eladási arányod. Az eladási arány maximum 100% lehet!</p>
<div class="advertisement">
<input type="number" [(ngModel)]="htmlAdvertisement" name="htmlAdvertisement" min="0">
<button (click)="buyAdvertisement()" class="btn btn-info">Hiredetés vásárlása</button>
<button (click)="sellAdvertisement()" class="btn btn-danger">Hirdetés lemondása</button>
</div><br>
<p class="text"> Jelenlegi reklám egységed: {{ javaAdvertisement }} </p>
<div class="pics">
<img id="radio" src="./assets/pictures/radio.jpg" alt="radio">
<img id="tv" src="./assets/pictures/tv.png" alt="tv">
<img id="laptop" src="./assets/pictures/laptop.jpg" alt="laptop">
</div><file_sep>import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { SellService } from '../sell.service';
import { AccountingService } from '../accounting.service';
@Component({
selector: 'app-sell',
templateUrl: './sell.component.html',
styleUrls: ['./sell.component.css']
})
export class SellComponent implements OnInit {
constructor(private sellService: SellService, private accounting: AccountingService) { }
@Output()
sendSellIntArray = new EventEmitter<number[]>();
@Output()
plusDate = new EventEmitter();
htmlSellingPrise: number = 0;
visible: boolean = false;
javaCar: number = 0;
maxSellingPrice: number = 0;
sell() {
this.sellService.sell(this.htmlSellingPrise).subscribe(
(car: number[]) => {
this.javaCar = car[11];
this.plusDate.next();
this.sendSellIntArray.next(car);
this.htmlSellingPrise = 0;
}
);
}
ngOnInit() {
this.accounting.everyData().subscribe(
(data: number[]) => {
this.javaCar = data[11];
this.maxSellingPrice = data[13];
}
);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CegvezetoComponent } from './cegvezeto/cegvezeto.component';
import { MainComponent } from './main/main.component';
import { AccountingComponent } from './accounting/accounting.component';
import { AdvertisementComponent } from './advertisement/advertisement.component';
import { ProductionComponent } from './production/production.component';
import { SellComponent } from './sell/sell.component';
import { WorkerComponent } from './worker/worker.component';
import { StartComponent } from './start/start.component';
const routes: Routes = [
{path: '', component: StartComponent},
{path: 'main', component: MainComponent},
{path: 'accounting', component: AccountingComponent},
{path: 'advertisement', component: AdvertisementComponent},
{path: 'ingredients', component: CegvezetoComponent},
{path: 'production', component: ProductionComponent},
{path: 'sell', component: SellComponent},
{path: 'worker', component: WorkerComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class WorkerService {
constructor(private httpClient: HttpClient) { }
public baseUrl: string = '//localhost:8080';
public buyWorker(htmlWorker: number) {
return this.httpClient.post(this.baseUrl + '/worker/buy-workere', + htmlWorker);
}
public getWorker() {
return this.httpClient.get(this.baseUrl + '/worker/buy-worker');
}
public dismissWorker(htmlWorker: number) {
return this.httpClient.post(this.baseUrl + '/worker/dismiss-worker', + htmlWorker);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ProductionService {
constructor(private httpClient: HttpClient) { }
public baseUrl: string = '//localhost:8080';
public production(htmlProduction: number) {
return this.httpClient.post(this.baseUrl + '/production/production', + htmlProduction);
}
}
<file_sep>package hu.flowacademy.Cegvezeto.game.controller;
import hu.flowacademy.Cegvezeto.game.Logic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "ingredient")
public class IngredientController {
@Autowired
private Logic logic;
@CrossOrigin(origins = "*", allowedHeaders="*")
@PostMapping("/buy-wheele")
public Integer wheel(@RequestBody int n) {
return logic.buyWheel(n);
}
@CrossOrigin(origins = "*", allowedHeaders="*")
@PostMapping("/buy-chasise")
public Integer chasis(@RequestBody int n) {
return logic.buyChasis(n);
}
@CrossOrigin(origins = "*", allowedHeaders = "*")
@PostMapping("/buy-engine")
public Integer engin(@RequestBody int n) { return logic.buyEngin(n); }
@CrossOrigin(origins = "*")
@GetMapping("/buy-wheel")
public int htmlWheel() {
return logic.javaWheel();
}
@CrossOrigin(origins="*")
@GetMapping("/buy-chasis")
public int htmlChasis() {
return logic.javaChasis();
}
@CrossOrigin(origins = "*")
@GetMapping("/buy-engin")
public int javaEngin() {
return logic.javaEngin();
}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { GameService } from '../game.service';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
constructor(private router: Router, private gameService: GameService) { }
today = new Date();
/* @Input()
factoryName: string;
*/
factoryName: string = "";
plusMonth() {
this.today = new Date(this.today.getFullYear(), this.today.getMonth() + 1, this.today.getDate());
}
goToAccounting() {
this.router.navigate(['accounting']);
}
goToAdvertisement() {
this.router.navigate(['advertisement']);
}
goToIngredients() {
this.router.navigate(['ingredients']);
}
goToProduction() {
this.router.navigate(['production']);
}
goToSell() {
this.router.navigate(['sell']);
}
goToWorker() {
this.router.navigate(['worker']);
}
ngOnInit() {
this.gameService.getFactoryName();
this.factoryName = this.gameService.getFactoryName();
}
}
<file_sep>package hu.flowacademy.Cegvezeto.game;
public class Workers {
private final int WORKERWAGE = 50000;
private int workerWage;
private final int PRODUCTIONSPEED = 30;
private int productionSpeed;
private int workersNumber;
private int productionQuantityNumber;
public int getProductionQuantityNumber() {
return workersNumber*productionSpeed;
}
public int getWorkersNumber() {
return workersNumber;
}
public void setWorkersNumber(int workersNumber) {
this.workersNumber = workersNumber;
}
public Workers(int workersNumber, int productionQuantityNumber) {
this.workersNumber = workersNumber;
this.workerWage = WORKERWAGE;
this.productionSpeed = PRODUCTIONSPEED;
this.productionQuantityNumber = productionQuantityNumber;
}
public int getWage() {
return workerWage;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { GameService } from '../game.service';
@Component({
selector: 'app-start',
templateUrl: './start.component.html',
styleUrls: ['./start.component.css']
})
export class StartComponent implements OnInit {
constructor(private router: Router, private gameService: GameService) { }
factoryName: any = '';
start() {
this.router.navigate(['main']);
this.gameService.saveFactoryName(this.factoryName);
}
ngOnInit() {
}
}
<file_sep><app-main></app-main><br>
<p class="text">Itt eladhatod a már elkészített termékeidet! Az eladás után új hónap következik. Ekkor frissül a könyvelés oldal is!Ne feledd, minél több reklámot vásárolsz, annál több autót fogsz tudni eladni!</p>
<div class="button">
<input type="number" [(ngModel)]="htmlSellingPrise" name="htmlSellingPrise" min="0" max="3125">
<button (click)="sell()" class="btn btn-info">Eladás</button>
</div><br>
<p class="text">Eddig legyártott autóid száma: {{ javaCar}}</p>
<p class="text">Maximális eladási ár: {{ maxSellingPrice }} Fabatka lehet!</p>
<div class="pics">
<img id="sell" src="./assets/pictures/sell.gif" alt="production">
</div><file_sep>import { Component, OnInit } from '@angular/core';
import { WorkerService } from '../worker.service';
@Component({
selector: 'app-worker',
templateUrl: './worker.component.html',
styleUrls: ['./worker.component.css']
})
export class WorkerComponent implements OnInit {
constructor(private workerService: WorkerService) { }
javaWorker: number;
htmlWorker: number = 0;
buyWorker() {
this.workerService.buyWorker(this.htmlWorker).subscribe(
(worker: number) => {
console.log(worker);
this.javaWorker = worker;
this.htmlWorker = 0;
}
);
}
dismissWorker() {
this.workerService.dismissWorker(this.htmlWorker).subscribe(
(worker: any) => {
console.log(worker);
this.javaWorker = worker;
this.htmlWorker = 0;
}
);
}
ngOnInit() {
this.workerService.getWorker().subscribe(
(workers: number) => {
this.javaWorker = workers;
console.log(this.javaWorker);
}
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { AdvertisementService } from '../advertisement.service';
import { AccountingService } from '../accounting.service';
@Component({
selector: 'app-advertisement',
templateUrl: './advertisement.component.html',
styleUrls: ['./advertisement.component.css']
})
export class AdvertisementComponent implements OnInit {
constructor(private advertisementService: AdvertisementService, private accounting: AccountingService) { }
javaAdvertisement: number;
htmlAdvertisement: number = 0
buyAdvertisement() {
this.advertisementService.buyAdvertisement(this.htmlAdvertisement).subscribe(
(advertisement: any) => {
console.log(advertisement);
this.javaAdvertisement = advertisement;
this.htmlAdvertisement = 0;
}
);
}
sellAdvertisement() {
this.advertisementService.sellAdvertisement(this.htmlAdvertisement).subscribe(
(advertisement: any) => {
console.log(advertisement);
this.javaAdvertisement = advertisement;
}
);
}
ngOnInit() {
this.accounting.everyData().subscribe(
(data: number[]) => {
this.javaAdvertisement = data[12];
}
);
}
}
<file_sep>package hu.flowacademy.Cegvezeto.game.controller;
import hu.flowacademy.Cegvezeto.game.Logic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "logic")
public class LogicController {
@Autowired
private Logic logic;
@CrossOrigin(origins="*")
@GetMapping("/logic")
public int[] logic() {
return logic.everyData();
}
}
<file_sep># Cegvezeto
Simple game
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AccountingService {
constructor(private httpClient: HttpClient) { }
public baseUrl: string = '//localhost:8080';
public everyData() {
return this.httpClient.get(this.baseUrl + '/logic/logic');
}
}
| d65a253eed611fc08f3a7bce64a1caabaccf9621 | [
"Markdown",
"Java",
"TypeScript",
"HTML"
] | 22 | TypeScript | micsikz/Cegvezeto | 18a961f0c8b223968c1ab207a75d6225ff4941c3 | dc16bb7bd624ede346354fe35044f7f9cbed5cfa |
refs/heads/master | <repo_name>divecastro/inkindex-frontend<file_sep>/src/reducers/reducer_filters.js
import {ADD_FILTER,REMOVE_FILTER} from '../actions/index';
export default function(state = [], action) {
var x;
switch (action.type) {
//REMOVE WHEN DONE
case ADD_FILTER:
if(action.payload)
console.log("New Filter Added!");
if(action.payload === "") {
console.log("No value, skipping filter")
return state;
}
for(x in state) {
if(state[x].valueOf() === action.payload.valueOf()) {
console.log("Filter pre-existing. Pass")
return state;
}
}
console.log(state.concat(action.payload))
//Proper way to deep copy. Create an entirely new state to return
return state.concat(action.payload);
case REMOVE_FILTER:
console.log("Filter Removal started!");
//If the filter exists, find and remove it
for(x in state) {
if(state[x].valueOf() === action.payload.valueOf()) {
console.log("Filter removed!!")
//Somehow this allows a deep copy? Shit i dunno
let newstate = [...state];
newstate.splice(state.indexOf(state[x]),1);
return newstate;
}
}
return state
default:
return state;
}
}<file_sep>/src/actions/index.js
//Defines types of broadcast signals
//TODO Tie all to functionality. ONLY AS REQUIRED. Dont muddy code just to finish functions
//before they are useful lmao. Also remove everything to do with dummy when happy
export const DUMMY = "DUMMY";
export const SET_SEARCHTERM = "SETNAME";
export const ADD_FILTER = "ADD_FILTER";
export const REMOVE_FILTER = "REMOVE_FILTER";
export const SET_LOCATION = "SET_LOCATION";
export const SET_RADIUS = "SET_RADIUS";
export const RESET_FILTERS = "RESET_FILTERS";
export const UPDATE_RESULTS ="UPDATE_RESULTS";
/*
* TODO REMOVE
*/
export function DummyAction(e=null) {
console.log(`Dummy emitted: ${e}`)
return {
type: DUMMY,
payload: e
}
}
export function updateResults(e=null) {
console.log(`Results added:`)
console.log(e)
return {
type: UPDATE_RESULTS,
payload: e
}
}
export function addFilter(e=null) {
console.log(`Filter add emitted: ${e}`)
return {
type: ADD_FILTER,
payload: e
}
}
export function removeFilter(e=null) {
console.log(`Filter remove emitted: ${e}`)
return {
type: REMOVE_FILTER,
payload: e
}
}
<file_sep>/src/reducers/index.js
import { combineReducers } from 'redux';
import DummyReducer from './reducer_dummy';
import ResultsReducer from './reducer_results';
import FiltersReducer from './reducer_filters';
const rootReducer = combineReducers({
dummy: DummyReducer,
results: ResultsReducer,
filters: FiltersReducer
});
export default rootReducer;
<file_sep>/src/SearchTextInput.js
import React, { Component } from 'react';
import Select from 'react-select';
import {connect} from 'react-redux'
//TODO TODO Refactor the way values and names work to instead use the artist/studio key.
class SearchTextInput extends Component {
state = {
selectedOption: null,
}
getOptions() {
//Get options from the current result set
return this.props.results.map((result) => {
return ({value: result.name.toLowerCase(),label: result.name})
})
}
handleChange = (selectedOption) => {
//TODO TIE TO A REDUX ACTION TO ACTUALLY SEND USER TO CORRECT PAGE
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<div className="Text-filter">
<Select
value={selectedOption}
onChange={this.handleChange}
options={this.getOptions()}
placeholder="Enter Artist or Studio Name"
noOptionsMessage={() =>
<a onClick={()=>{alert("Submission page")}}>
"No Artist/Studio Found. Check your city or submit a new artist! Here (make only this part blue +clickable lol)"
</a>
}
/>
{/* <input placeholder="Enter Artist or Studio Name"></input>
<button>Submit name query</button> */}
</div>
);
}
}
function mapStateToProps(state) {
return {
results: state.results
}
}
export default connect(mapStateToProps, null)(SearchTextInput);<file_sep>/src/reducers/reducer_results.js
import {UPDATE_RESULTS} from '../actions/index';
export default function(state = [], action) {
switch (action.type) {
//REMOVE WHEN DONE
case UPDATE_RESULTS:
console.log("New Resultset received - Fresh load or city changed");
return action.payload;
default:
return state;
}
} | 0b9c7bdf33d5c41b8a2f41283366869428d801cb | [
"JavaScript"
] | 5 | JavaScript | divecastro/inkindex-frontend | cea73fa10a352d3037718140703792e91b8ddb14 | fdc771de541e4732ce2fb084e34679916ffba5a7 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
import HTMLTestRunnerA
import sys
# from asn1crypto._ffi import null
# from twisted.python.test.deprecatedattributes import message
import os
reload(sys)
sys.setdefaultencoding( "utf-8" )
class HKautoCase02(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.katalon.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_h_k_load(self):
u"""登录HKCRM系统"""
driver = self.driver
driver.get("http://172.17.24.77:8210/web-ngboss?")
driver.find_element_by_id("STAFF_ID").click()
driver.find_element_by_id("STAFF_ID").clear()
driver.find_element_by_id("STAFF_ID").send_keys("9<PASSWORD>")
driver.find_element_by_id("PASSWORD").click()
driver.find_element_by_id("PASSWORD").clear()
driver.find_element_by_id("PASSWORD").send_keys("<PASSWORD>")
driver.find_element_by_id("loginBtn").click()
time.sleep(2)
#去掉系统提示弹窗
driver.find_element_by_xpath('/html/body/div[9]/div[1]/div[2]/div/div/div[2]/button[1]').click()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
Jy=driver.find_element_by_xpath('//*[@id="welTab_tab_li_1"]').text
print Jy
if Jy==u"菜单地图":
print u"系统登录成功"
def test_load(self):
#供后续方法复用
driver = self.driver
driver.get("http://172.17.24.75:8080/web-ngboss?")
driver.find_element_by_id("STAFF_ID").click()
driver.find_element_by_id("STAFF_ID").clear()
driver.find_element_by_id("STAFF_ID").send_keys("91110029")
driver.find_element_by_id("PASSWORD").click()
driver.find_element_by_id("PASSWORD").clear()
driver.find_element_by_id("PASSWORD").send_keys("123456")
driver.find_element_by_id("loginBtn").click()
time.sleep(2)
#去掉系统提示弹窗
driver.find_element_by_xpath('/html/body/div[9]/div[1]/div[2]/div/div/div[2]/button[1]').click()
def test_PlanChange_Rule(self):
u"""套餐变更-无服务号码登录"""
driver = self.driver
HKautoCase02.test_load(self)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="welTab_tab_li_1"]').click()
time.sleep(3)
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='停开机'])[1]/following::div[2]").click()
driver.find_element_by_id("101501").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_115"]'))
Jy000=driver.find_element_by_xpath("/html/body/div/div/div[2]/div[1]/div[2]").text
#print Jy000
if Jy000[0:16]==u"请进行服务号码登录后再进行操作!":
print u"服务号码登录前置规则校验成功"
else:
print u"服务号码登录前置规则校验失败"
def test_VasDeal_Rule(self):
u"""VAS受理-无服务号码登录"""
driver = self.driver
HKautoCase02.test_load(self)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="welTab_tab_li_1"]').click()
time.sleep(3)
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='停开机'])[1]/following::div[2]").click()
driver.find_element_by_id("101502").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_115"]'))
Jy001=driver.find_element_by_xpath("/html/body/div/div/div[2]/div[1]/div[2]").text
#print Jy000
if Jy001[0:16]==u"请进行服务号码登录后再进行操作!":
print u"服务号码登录前置规则校验成功"
else:
print u"服务号码登录前置规则校验失败"
def test_ChangeSimCard(self):
u"""补换卡-无服务号码登录"""
driver = self.driver
HKautoCase02.test_load(self)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="welTab_tab_li_1"]').click()
time.sleep(3)
driver.find_element_by_id("welTab_tab_li_1").click()
# driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='销户'])[2]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='开台'])[1]/following::div[2]").click()
driver.find_element_by_id("101403").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_115"]'))
Jy002=driver.find_element_by_xpath("/html/body/div/div/div[2]/div[1]/div[2]").text
print Jy002[14:30]
if Jy002[14:30]==u"请进行服务号码登陆后再进行操作!":
print u"服务号码登录前置规则校验成功"
else:
print u"服务号码登录前置规则校验失败"
def test_DestoryCus_Rule(self):
u"""销户-无服务号码登录"""
driver = self.driver
HKautoCase02.test_load(self)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="welTab_tab_li_1"]').click()
time.sleep(3)
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='NGBOSS-TEST'])[1]/following::div[9]").click()
driver.find_element_by_id("101102").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_115"]'))
Jy003=driver.find_element_by_xpath("/html/body/div/div/div[2]/div[1]/div[2]").text
print Jy003[14:30]
if Jy003[14:30]==u"请进行服务号码登陆后再进行操作!":
print u"服务号码登录前置规则校验成功"
else:
print u"服务号码登录前置规则校验失败"
def test_WLAN_Rule(self):
u"""宽带移机-无服务号码登录"""
driver = self.driver
HKautoCase02.test_load(self)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="welTab_tab_li_1"]').click()
time.sleep(3)
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='资费变更'])[1]/following::div[2]").click()
driver.find_element_by_id("101202").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_115"]'))
Jy004=driver.find_element_by_xpath("/html/body/div/div/div[2]/div[1]/div[2]").text
print Jy004[0:14]
if Jy004[0:14] == "用户没有登录或者登录已经失效 ":
print u"服务号码登录前置规则校验成功"
else:
print u"服务号码登录前置规则校验失败"
#对弹窗异常的处理
# def close_alert_and_get_its_text(self):
# try:
# alert = self.driver.switch_to_alert()
# alert_text = alert.text
# if self.accept_next_alert:
# alert.accept()
# else:
# alert.dismiss()
# return alert_text
# finally: self.accept_next_alert = True
def test_VAS_ydg(self):
u"""VAS已订购列表查询"""
driver = self.driver
HKautoCase02.test_load(self)
driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys("96630663")
driver.find_element_by_id("LOGIN_BTN").click()
time.sleep(3)
#self.assertEqual(u"入参参数为空异常!", self.close_alert_and_get_its_text())
#self.assertEqual(u"服务名称:bassi_IQueryOmMsgRecommendContentCSV_queryOmMsgRecommendContentQBO 调用服务bassi_IQueryOmMsgRecommendContentCSV_queryOmMsgRecommendContentQBO的业务代码发生异常", self.close_alert_and_get_its_text())
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='停开机'])[1]/following::div[2]").click()
driver.find_element_by_id("101502").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_128"]'))
# Jy005=driver.find_element_by_xpath('/html/body/div[1]/div/div[6]/ul/li[1]').text
# /html/body/div[1]/div/div[6]/ul/li[2]
for i in range(1,45):
# XpathA='/html/body/div[1]/div[2]/div/div/div[2]/div[1]/div[1]/div/div[1]/div/table/tbody/tr{}'.format([int(i)])
XpathA='/html/body/div[1]/div/div[6]/ul/li[]'.format([int(i)])
#print XpathA
Jy005=driver.find_element_by_xpath(XpathA).text
print Jy005
def test_VAS_Query(self):
u"""VAS受理查询组件"""
driver = self.driver
HKautoCase02.test_load(self)
driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys("96630663")
driver.find_element_by_id("LOGIN_BTN").click()
time.sleep(3)
#self.assertEqual(u"入参参数为空异常!", self.close_alert_and_get_its_text())
#time.sleep(3)
#self.assertEqual(u"服务名称:bassi_IQueryOmMsgRecommendContentCSV_queryOmMsgRecommendContentQBO 调用服务bassi_IQueryOmMsgRecommendContentCSV_queryOmMsgRecommendContentQBO的业务代码发生异常", self.close_alert_and_get_its_text())
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='停开机'])[1]/following::div[2]").click()
driver.find_element_by_id("101502").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_128"]'))
driver.find_element_by_xpath('//*[@id="insSearch"]').click()
driver.find_element_by_xpath('//*[@id="insSearch"]').clear()
driver.find_element_by_xpath('//*[@id="insSearch"]').send_keys('<PASSWORD>')
driver.find_element_by_xpath('/html/body/div[1]/div/div[5]/div/div[2]/span/button').click()
time.sleep(5)
Jy006=driver.find_element_by_xpath('/html/body/div[1]/div/div[6]/ul/li[1]').text
if Jy006[0:20]=='#SMS Package Intra 8':
print u"""查询组件功能校验成功"""
else:
print u"""查询组件功能校验失败"""
def test_VAS_Add(self):
u"""VAS订购页面"""
driver = self.driver
HKautoCase02.test_load(self)
driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys("96630663")
driver.find_element_by_id("LOGIN_BTN").click()
time.sleep(3)
self.assertEqual(u"入参参数为空异常!", self.close_alert_and_get_its_text(),'NOT SAME')
self.assertEqual(u"服务名称:bassi_IQueryOmMsgRecommendContentCSV_queryOmMsgRecommendContentQBO 调用服务bassi_IQueryOmMsgRecommendContentCSV_queryOmMsgRecommendContentQBO的业务代码发生异常", self.close_alert_and_get_its_text())
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='停开机'])[1]/following::div[2]").click()
driver.find_element_by_id("101502").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_128"]'))
#进入订购页面
driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/button').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
Jy007=driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[1]/div/div/ul/li').text
if Jy007==u"""vas受理二级目录""":
print 'Go Add Success'
else:
print 'Go Add Default'
def test_VAS_MessaQuery(self):
u"""VAS目录查询组件功能校验"""
driver = self.driver
HKautoCase02.test_VAS_Add(self)
driver.find_element_by_xpath('//*[@id="searchOfferkeyWord"]').click()
driver.find_element_by_xpath('//*[@id="searchOfferkeyWord"]').clear()
driver.find_element_by_xpath('//*[@id="searchOfferkeyWord"]').send_keys('<KEY>9')
time.sleep(3)
Jy008=driver.find_element_by_xpath('//*[@id="offerId_200234"]').text
if Jy008=='#ISMS Pkg $19':
print 'Query Success'
else:
print 'Query Default'
def test_upload(self):
driver = self.driver
HKautoCase02.test_load(self)
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_id("menus_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000220").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_115"]'))
driver.find_element_by_id("busiNameValue_span").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='--请选择--'])[2]/following::div[1]").click()
#driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Upload'])[1]/following::span[3]").click()
#driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Upload'])[2]/following::input[2]").clear()
driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Upload'])[2]/following::input[2]").send_keys(u"D:\\工作\\导入文件\\SIM卡入库.txt")
driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[1]/div[2]/ul/li[7]/div[2]/span/span[6]/form/input").send_keys(u"D:\\工作\\导入文件\\SIM卡入库.txt")
time.sleep(500)
print u"success!"
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
#unittest.main()#运行所有test开头的测试用例
testunit=unittest.TestSuite()
#将测试用例加入到测试容器中
testunit.addTest(HKautoCase02("test_h_k_load"))
# testunit.addTest(HKautoCase02("test_PlanChange_Rule"))
# testunit.addTest(HKautoCase02("test_VasDeal_Rule"))
# testunit.addTest(HKautoCase02("test_ChangeSimCard"))
# testunit.addTest(HKautoCase02("test_DestoryCus_Rule"))
# testunit.addTest(HKautoCase02("test_WLAN_Rule"))
# testunit.addTest(HKautoCase02("test_VAS_ydg"))
# testunit.addTest(HKautoCase02("test_VAS_Query"))
# testunit.addTest(HKautoCase02("test_VAS_Add"))
# testunit.addTest(HKautoCase02("test_VAS_MessaQuery"))
# testunit.addTest(HKautoCase02("test_upload"))
now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
#打开一个文件,将result写入此file中
fp=open("result"+now+".html",'wb')
runner=HTMLTestRunnerA.HTMLTestRunner(stream=fp,title='Test Report',description=u'南基五期香港新CRM自动化测试,test by taozhan')
runner.run(testunit)
fp.close()<file_sep>#-*- coding:utf-8 -*-
'''
Created on 2018年11月21日
@author: taozhan
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
import HTMLTestRunnerA
import sys
# from asn1crypto._ffi import null
# from twisted.python.test.deprecatedattributes import message
import os
reload(sys)
sys.setdefaultencoding( "utf-8" )
class autocase11yue(unittest.TestCase):
def setUp(self):#初始化部分
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.katalon.com/"
self.verificationErrors = []
self.accept_next_alert = True
#登录CRM主页
def load(self):
driver = self.driver
driver.get("http://1172.16.58.3:8826/crmweb/?service=page/Login")
driver.find_element_by_id("OPER_CODE").click()
driver.find_element_by_id("OPER_CODE").clear()
driver.find_element_by_id("OPER_CODE").send_keys("91110029")
driver.find_element_by_id("PASSWORD").click()
driver.find_element_by_id("PASSWORD").clear()
driver.find_element_by_id("PASSWORD").send_keys("<PASSWORD>")
driver.find_element_by_id("login_btn").click()
#服务号码登录
def test_FuWoHaoMaLoad(self,number):
u"""服务号码登录"""
driver = self.driver
autocase11yue.load(self)
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='营业员 / 91110029'])[1]/following::li[2]").click()
driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys(number)
driver.find_element_by_id("LOGIN_BTN").click()
#异常订单信息查询
def test_GetOrderErrPrint(self):
u"""订单异常信息查询"""
driver = self.driver
autocase11yue.load(self)
time.sleep(5)
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
#进入个人业务
driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
#进入订单查询页面
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='一号双终端副卡开户'])[1]/following::li[1]").click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | relative=parent | ]]
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=1 | ]]
time.sleep(5)
#查询页面
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
#driver.find_element_by_css_selector('css=input[type="text"]')
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='导出'])[1]/following::input[2]").click()
time.sleep(5)
driver.find_element_by_id("cond_ORDER_ID").click()
driver.find_element_by_id("cond_ORDER_ID").clear()
driver.find_element_by_id("cond_ORDER_ID").send_keys("181111000594445")
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='结束日期'])[1]/following::button[1]").click()
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='竣工订单查询'])[1]/following::input[1]").click()
driver.find_element_by_id("showDetailButton").click()
time.sleep(5)
#driver.close()
#黑名单校验
def test_IdentifityHMD(self):
u"""黑名单验证"""
driver =self.driver
autocase11yue.load(self)
time.sleep(5)
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
#进入个人业务
driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.find_element_by_xpath('//*[@id="menu_l2_2"]/div/div[4]/ul/li[3]').click()
#driver.find_element_by_xpath('//*[@id="menu_l2_2"]/div/div[4]/ul/li[3]').click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | relative=parent | ]]
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=1 | ]]
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("CUST_INFO_DIV").click()
driver.find_element_by_id("editInfoButton").click()
time.sleep(5)
driver.find_element_by_id("PARTY_NAME").click()
driver.find_element_by_id("PARTY_NAME").clear()
driver.find_element_by_id("PARTY_NAME").send_keys(u"多诺万")
driver.find_element_by_id("IDEN_NR").click()
driver.find_element_by_id("IDEN_NR").clear()
driver.find_element_by_id("IDEN_NR").send_keys("440103199003070539")
driver.find_element_by_id("IDEN_NR_BUTTON").click()
time.sleep(5)
#---------------------------------------------
#这里加一个判断是否达到测试要求
objeee=driver.find_element_by_xpath('//*[@id="wade_messagebox-bf13ceff87ff389ac56a906e76ed36de_ct"]').text
#attribute =obj.text
print objeee
if objeee== u"该证件号码是特殊名单!":
print "Successful verification of special list"
else:
print "Special list check failure"
time.sleep(3)
driver.find_element_by_xpath('//*[@id="wade_messagebox-bf13ceff87ff389ac56a906e76ed36de_ct"]').click()
#driver.close()
#一证五号校验
def test_YiZhengWuHao(self):
u"""一证五号校验"""
driver =self.driver
autocase11yue.load(self)
time.sleep(5)
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
#进入个人业务
driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.find_element_by_xpath('//*[@id="menu_l2_2"]/div/div[4]/ul/li[3]').click()
#driver.find_element_by_xpath('//*[@id="menu_l2_2"]/div/div[4]/ul/li[3]').click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | relative=parent | ]]
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=1 | ]]
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("CUST_INFO_DIV").click()
driver.find_element_by_id("editInfoButton").click()
time.sleep(5)
driver.find_element_by_id("PARTY_NAME").click()
driver.find_element_by_id("PARTY_NAME").clear()
driver.find_element_by_id("PARTY_NAME").send_keys(u"陶展")
driver.find_element_by_id("IDEN_NR").click()
driver.find_element_by_id("IDEN_NR").clear()
driver.find_element_by_id("IDEN_NR").send_keys("430124199304118372")
driver.find_element_by_id("IDEN_NR_BUTTON").click()
time.sleep(5)
#---------------------------------------------
#加校验,弹出框的提示对的上即返回成功
a=driver.find_element_by_xpath('//*[@id="wade_tipbox-1_content"]').text
print a
if a ==u'省内一证多号验证:该证件号码只能使用[2]次,现在已经达到了最大数!':
print 'One card multi-number check is normal'
else:
print 'A multi-number check anomaly'
#欠费校验
def test_QianFei(self):
u"""欠费校验"""
driver =self.driver
autocase11yue.load(self)
time.sleep(5)
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
#进入个人业务
driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.find_element_by_xpath('//*[@id="menu_l2_2"]/div/div[4]/ul/li[3]').click()
#driver.find_element_by_xpath('//*[@id="menu_l2_2"]/div/div[4]/ul/li[3]').click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | relative=parent | ]]
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=1 | ]]
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("CUST_INFO_DIV").click()
driver.find_element_by_id("editInfoButton").click()
time.sleep(5)
driver.find_element_by_id("PARTY_NAME").click()
driver.find_element_by_id("PARTY_NAME").clear()
driver.find_element_by_id("PARTY_NAME").send_keys(u"多玩")
driver.find_element_by_id("IDEN_NR").click()
driver.find_element_by_id("IDEN_NR").clear()
driver.find_element_by_id("IDEN_NR").send_keys("110101197811075620")
driver.find_element_by_id("IDEN_NR_BUTTON").click()
time.sleep(5)
#-----------------------------------------------------
#这里截取欠费的字符就好
qf=driver.find_element_by_xpath('//*[@id="wade_messagebox-c5c33bf56d85d24c78640100df197c4c_ct"]').text
#attribute =obj.text
qfpanduan=qf[0:4]
#print (type(qf))
if qfpanduan== u".客户欠费":
print "Customer arrears are judged to be normal"
else:
print "Customer default judgment anomaly"
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[46]/div/div[2]/div[2]/button').click()
#一证多名校验
def test_YiZhengDuoMing(self):
u"""一证多名校验"""
driver =self.driver
autocase11yue.load(self)
time.sleep(5)
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
#进入个人业务
driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.find_element_by_xpath('//*[@id="menu_l2_2"]/div/div[4]/ul/li[3]').click()
#driver.find_element_by_xpath('//*[@id="menu_l2_2"]/div/div[4]/ul/li[3]').click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | relative=parent | ]]
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=1 | ]]
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("CUST_INFO_DIV").click()
driver.find_element_by_id("editInfoButton").click()
time.sleep(5)
driver.find_element_by_id("PARTY_NAME").click()
driver.find_element_by_id("PARTY_NAME").clear()
driver.find_element_by_id("PARTY_NAME").send_keys(u"陶曦阳")
driver.find_element_by_id("IDEN_NR").click()
driver.find_element_by_id("IDEN_NR").clear()
driver.find_element_by_id("IDEN_NR").send_keys("430124199304118372")
driver.find_element_by_id("IDEN_NR_BUTTON").click()
time.sleep(5)
bid=driver.find_element_by_xpath('//*[@id="wade_messagebox-6ac7754849cedcbeffb201c1de26b456_ct"]').text
#print bid
ff=re.findall("PARTY_NAME",bid)
#这里截取一下字符串,取开头几个字符就好/正则表达是抓取出字符
print ff
if ff[0] == 'PARTY_NAME':
print 'One success of multiple verification'
else:
print 'One multiple checkout anomaly'
#HLR信息管理-新增
def test_HLR_ADD(self):
u"""HLR新增"""
driver = self.driver
autocase11yue.load(self)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='客户管理'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='资源价格管理'])[1]/following::li[1]").click()
time.sleep(2)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("addButton").click()
driver.find_element_by_id("add_NUM_SEG").click()
driver.find_element_by_id("add_NUM_SEG").clear()
driver.find_element_by_id("add_NUM_SEG").send_keys("1880094")
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='重置'])[2]/following::button[1]").click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
hlrJYneiron=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
#hlrll=driver.find_elements_by_css_selector('#wade_messagebox-4aa8d22d38aa3a1a036048e5162f24e9_ct').text
print hlrJYneiron
order_id=re.findall('\d{14}', hlrJYneiron)
print order_id
if order_id=='' or len(order_id)==0:
print (u'HLR 入库失败')
else:
print (u'HLRr入库成功')
#IMSI与HLR信息管理
def test_IMS_HLR_ADD(self):
u"""IMS_HLR新增"""
driver = self.driver
autocase11yue.load(self)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='客户管理'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='HLR信息管理'])[1]/following::li[1]").click()
time.sleep(2)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("addButton").click()
driver.find_element_by_id("add_START_IMSI").click()
# ERROR: Caught exception [ERROR: Unsupported command [doubleClick | id=add_START_IMSI | ]
driver.find_element_by_id("add_START_IMSI").clear()
driver.find_element_by_id("add_START_IMSI").send_keys("460066660000000")
driver.find_element_by_id("add_END_IMSI").click()
driver.find_element_by_id("add_END_IMSI").clear()
driver.find_element_by_id("add_END_IMSI").send_keys("460066660000010")
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='重置'])[2]/following::button[1]").click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
IMSJYneiron=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
#hlrll=driver.find_elements_by_css_selector('#wade_messagebox-4aa8d22d38aa3a1a036048e5162f24e9_ct').text
print IMSJYneiron
order_id=re.findall('\d{14}', IMSJYneiron)
print order_id
if order_id=='' or len(order_id)==0:
print (u'IMS 新增业务办理失败')
else:
print (u'IMS 新增业务办理成功')
#受理撤单
def test_ShouLiCheDan(self):
u"""受理撤单"""
driver = self.driver
autocase11yue.test_FuWoHaoMaLoad(self,'18798907431')
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='业务示例'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='改号关联关系取消'])[1]/following::li[1]").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_69"]'))
driver.find_element_by_id("qryBox").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='开始时间'])[1]/following::span[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='分期支付'])[1]/following::div[9]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='分期支付'])[1]/following::div[7]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='六'])[1]/following::span[1]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='结束时间'])[1]/following::span[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='六'])[1]/following::span[28]").click()
driver.find_element_by_id("queryButton").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='受理区县'])[1]/following::td[1]").click()
driver.find_element_by_id("CSSUBMIT_BUTTON").click()
time.sleep(3)
driver.find_element_by_id("sofeeconfirmButton").click()
messageA=driver.find_element_by_xpath('//*[@id="wade_messagebox-8a125e7591b006eb0ef5b279bed54fab_title"]').text
print messageA
if messageA==u'错误提示':
print u"受理撤单失败"
else:
print u"受理撤单成功"
def test_HuanHao(self):
u"""换号"""
driver = self.driver
autocase11yue.test_FuWoHaoMaLoad(self, '13518972376')
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='业务示例'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='跨省补换卡'])[2]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_69"]'))
time.sleep(2)
piupiupiu=driver.find_element_by_xpath('/html/body/div/div/div[2]/div[1]/div[2]').text
#/html/body/div/div/div[2]/div[1]/div[2]
#/html/body/div[starts-with(@class,content)]
print piupiupiu
#time.sleep(30)
def test_FufeiGuanXiQuery(self):
u"""付费关系查询"""
driver = self.driver
autocase11yue.test_FuWoHaoMaLoad(self, "13518972376")
time.sleep(2)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='业务示例'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='交换机'])[1]/following::li[1]").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_69"]'))
driver.find_element_by_id("queryByTel").click()
time.sleep(3)
driver.find_element_by_id("myQryTab_tab_li_5").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="consumeRelationship"]'))
aaa=driver.find_element_by_xpath('//*[starts-with(@id,table2)]').text
print aaa
# forFUfri=driver.find_element_by_xpath('//*[@id="table2"]/div/div/table/tbody/tr/td[1]').text
# res_tr = r'<td>(.*?)</td>'
# m_tr = re.findall(res_tr,aaa)
# print m_tr
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
# def getFile(self,test_dir):
# u"""获取报告路径"""
# #列举test_dir目录下的所有文件,结果以列表形式返回。
# lists=os.listdir(test_dir)
# #sort按key的关键字进行排序,lambda的入参fn为lists列表的元素,获取文件的最后修改时间
# #最后对lists元素,按文件修改时间大小从小到大排序。
# lists.sort(key=lambda fn:os.path.getmtime(test_dir+'\\'+fn))
# #获取最新文件的绝对路径
# file_path=os.path.join(test_dir,lists[-1])
# # L=file_path.split('\\')
# # file_path='\\\\'.join(L)
# return file_path
# print file_path
if __name__ == "__main__":
#unittest.main()#运行所有test开头的测试用例
testunit=unittest.TestSuite()
#将测试用例加入到测试容器中
# testunit.addTest(autocase11yue("test_GetOrderErrPrint"))
testunit.addTest(autocase11yue("test_IdentifityHMD"))
# testunit.addTest(autocase11yue("test_YiZhengWuHao"))
# testunit.addTest(autocase11yue("test_QianFei"))
# testunit.addTest(autocase11yue("test_YiZhengDuoMing"))
# testunit.addTest(autocase11yue("test_HLR_ADD"))
# testunit.addTest(autocase11yue("test_IMS_HLR_ADD"))
# testunit.addTest(autocase11yue("test_ShouLiCheDan"))
# testunit.addTest(autocase11yue("test_HuanHao"))
# testunit.addTest(autocase11yue("test_FufeiGuanXiQuery"))
#获取当前时间,这样便于下面的使用。
now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
#打开一个文件,将result写入此file中
fp=open("result"+now+".html",'wb')
runner=HTMLTestRunnerA.HTMLTestRunner(stream=fp,title='Test Report',description=u'南基五期新CRM个人业务自动化测试,test by taozhan')
runner.run(testunit)
fp.close()
#瞎JB写,调用getFile方法输出报告路径
# test_report_dir='D:\pythontest\testresult'
# new_report=autocase11yue.getFile(test_report_dir)
<file_sep># -*- coding: utf-8 -*-
'''
Created on 2019年4月26日
@author: Taozhan
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
import HTMLTestRunnerA
import cx_Oracle
import os
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
class HKautocase04(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.katalon.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_AccessLoad(self,access_num):
#供后续复用
u"""服务号码登录"""
driver = self.driver
driver.get("http://172.17.24.75:8080/web-ngboss?")
driver.find_element_by_id("STAFF_ID").click()
driver.find_element_by_id("STAFF_ID").clear()
driver.find_element_by_id("STAFF_ID").send_keys("91110029")
driver.find_element_by_id("PASSWORD").click()
driver.find_element_by_id("PASSWORD").clear()
driver.find_element_by_id("PASSWORD").send_keys("<PASSWORD>")
driver.find_element_by_id("loginBtn").click()
time.sleep(2)
#去掉系统提示弹窗
driver.find_element_by_xpath('/html/body/div[9]/div[1]/div[2]/div/div/div[2]/button[1]').click()
driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys(access_num)
driver.find_element_by_id("LOGIN_BTN").click()
time.sleep(3)
def test_(self):
u'''Mymobile信息查询'''
#页面功能未完善,暂仅测试页面进入
driver=self.driver
HKautocase04.test_AccessLoad(self,'93157018')
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
#点击Mymobile元素
driver.find_element_by_xpath('//*[@id="Mymobile"]').click()
time.sleep(3)
def test_VasReset(self):
u'''VAS服务重置'''
driver=self.driver
HKautocase04.test_AccessLoad(self,'93157018')
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
#点击【reset】
driver.find_element_by_xpath('//*[@id="310021_insLi"]').click()
time.sleep(3)
#提交订单
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
#二次确认页面确认提交
driver.find_element_by_xpath('//*[@id="myDialog"]/div/div[3]/div[1]/button[2]').click()
time.sleep(5)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resB=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
order_idB = re.search( r'\d{15}', resB).group(0)
print order_idB
def test_QueryBaseVas(self):
u'''BASE VAS查询'''
driver = self.driver
HKautocase04.test_load(self)
driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys("51068332")
driver.find_element_by_id("LOGIN_BTN").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='停开机'])[1]/following::div[2]").click()
driver.find_element_by_id("101502").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_128"]'))
for i in range(1,60):
XpathA='/html/body/div[1]/div/div[5]/ul/li[]'.format([int(i)])
Jy005=driver.find_element_by_xpath(XpathA).text
print Jy005
def test_QueryExitOffer(self):
u'''已订购列表数据查询'''
driver = self.driver
HKautocase04.test_load(self)
driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys("51068332")
driver.find_element_by_id("LOGIN_BTN").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='停开机'])[1]/following::div[3]").click()
driver.find_element_by_id("101502").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_128"]'))
for i in range(1,45):
XpathA='/html/body/div[1]/div/div[6]/ul/li[]'.format([int(i)])
Jy005=driver.find_element_by_xpath(XpathA).text
print Jy005
def test_QueryOffer(self):
u'''初始化页面查询组件功能校验'''
driver = self.driver
HKautocase04.test_load(self)
driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys("96630663")
driver.find_element_by_id("LOGIN_BTN").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='停开机'])[1]/following::div[3]").click()
driver.find_element_by_id("101502").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_128"]'))
driver.find_element_by_xpath('//*[@id="insSearch"]').click()
driver.find_element_by_xpath('//*[@id="insSearch"]').clear()
driver.find_element_by_xpath('//*[@id="insSearch"]').send_keys('<PASSWORD>')
driver.find_element_by_xpath('/html/body/div[1]/div/div[5]/div/div[2]/span/button').click()
time.sleep(5)
Jy006=driver.find_element_by_xpath('/html/body/div[1]/div/div[6]/ul/li[1]').text
if Jy006[0:20]=='#SMS Package Intra 8':
print u"""查询组件功能校验成功"""
else:
print u"""查询组件功能校验失败"""
def test_AddButtonClick(self):
u'''ADD订购主页登录'''
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select access_num from (select access_num from ins1.um_subscriber_852 where subscriber_type=1 and subscriber_status=1 and rownum<1000 order by dbms_random.value) where rownum< 2"
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase04.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(2)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[2]/div[2]/div/div[2]/div[3]/div[2]/div[2]/div/ul/li[6]/div[1]')
time.sleep(2)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
if self.isElementPresent('id','insSearch'):
print u"ADD组件功能正常!"
else:
print u"ADD组件功能异常"
def test_OfferCataQuery(self):
u'''OFFER目录查询组件功能校验'''
driver = self.driver
HKautocase04.test_AddButtonClick(self)
time.sleep(3)
driver.find_element_by_xpath('//*[@id="searchOfferkeyWord"]').click()
driver.find_element_by_xpath('//*[@id="searchOfferkeyWord"]').clear()
driver.find_element_by_xpath('//*[@id="searchOfferkeyWord"]').send_keys('4G Handset Rebate Contract Upgrade')
time.sleep(3)
Jy008=driver.find_element_by_xpath('//*[@id="offerId_311234"]').text
if Jy008=='4G Handset Rebate Contract Upgrade9':
print 'Query Success'
else:
print 'Query Default'
def test_ADDoffer(self):
u"""OFFER订购"""
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select access_num from (select access_num from ins1.um_subscriber_852 where subscriber_type=1 and subscriber_status=1 and rownum<1000 order by dbms_random.value) where rownum< 2"
c.execute(sql)
rs=c.fetchall()
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase04.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(2)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[2]/div[2]/div/div[2]/div[3]/div[2]/div[2]/div/ul/li[6]/div[1]')
time.sleep(2)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath("/html/body/div[1]/div/div[1]/div/button").click()
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
driver.find_element_by_id("offerName_200234").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="iframe1"]'))
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[2]/ul[3]/li[2]/div[2]/span/span/span[1]/span').click()
driver.find_element_by_xpath('/html/body/div[8]/div[2]/div/div[7]/button[3]').click()
time.sleep(3)
driver.find_element_by_id("OFFER_BUTTON_SUBMIT").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div/div[3]/div[1]/button[2]').click()
time.sleep(5)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resA=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
order_idA = re.search( r'\d{15}', resA).group(0)
driver.find_element_by_xpath('/html/body/div[8]/div/div[2]/div[2]/button').click()
print order_idA
def test_ChangeOfferCha(self):
u'''OFFER特征值变更'''
driver=self.driver
HKautocase04.test_AccessLoad(self,'93163518')
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath('//*[@id="200021_insLi"]').click()
time.sleep(5)
driver.find_element_by_xpath('//*[@id="chaSpec_152852000032"]').send_keys("333")
time.sleep(2)
driver.find_element_by_xpath('//*[@id="OFFER_BUTTON_CHANGE"]').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="myDialog"]/div/div[3]/div[1]/button[2]').click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resB=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
order_idB = re.search( r'\d{15}', resB).group(0)
print order_idB
def test_DeleteOffer(self):
u'''OFFER退订'''
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select access_num from (select access_num from ins1.um_subscriber_852 where subscriber_type=1
and subscriber_status=1 and rownum<1000 order by dbms_random.value) where rownum< 2'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase04.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(2)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(2)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
time.sleep(2)
driver.find_element_by_xpath("/html/body/div[1]/div/div[6]/ul/li[1]/div[4]").click()#删除
time.sleep(3)
if self.isElementPresent('id','EDIT_EXP_DATE'):#手动录入时间场景
driver.find_element_by_xpath('//*[@id="EDIT_EXP_DATE"]').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="_Wade_DropDownCalendar_float"]/div[2]/div/div[7]/button[3]').click()
time.sleep(5)
driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div/div/div[3]/div/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div/div[3]/div[1]/button[2]').click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resB=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
order_idB = re.search( r'\d{15}', resB).group(0)
print order_idB
else:#默认生效时间场景
driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div/div/div[3]/div/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div/div[3]/div[1]/button[2]').click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resB=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
order_idB = re.search( r'\d{15}', resB).group(0)
print order_idB
def test_DryNUM(self):
u'''OFFER受理-销户用户校验'''
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='select access_num from ins1.UM_SUBSCRIBER_852 where SUBSCRIBER_TYPE=1 and subscriber_status=4'
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase04.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_129"]'))
err1=driver.find_element_by_xpath('/html/body/div/div/div[2]').text
print err1
def test_SuspendNUM(self):
u'''OFFER受理-停机用户校验'''
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select t.access_num from ins1.um_subscriber_852 t, ins1.um_prod_sta_852 m
where t.subscriber_ins_id = m.subscriber_ins_id
and t.data_status = '1'
and t.subscriber_status = '1'
and t.subscriber_type = '1'
and m.prod_status = '2'
'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase04.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
err2=driver.find_element_by_xpath('/html/body/div/div/div[2]').text
print err2
def test_IngOrdNUM(self):
u'''商品变更在途工单客户OFFER受理'''
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select access_num from ord.om_line where order_id in
(select order_id from ord.om_order t where t.busi_code ='500140000002')
'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase04.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
err3=driver.find_element_by_xpath('/html/body/div/div/div[2]').text
print err3
def test_IngCusNUM(self):
u'''客户资料在途工单客户OFFER受理'''
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select access_num from ord.om_line where order_id in
(select order_id from ord.om_order t where t.busi_code ='500220000005')
'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[2]
HKautocase04.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
time.sleep(5)
#//*[@id="insSearch"]
if self.isElementPresent('id','insSearch'):
print u"校验成功!"
else:
print u"校验失败"
def test_UnActiveNUM(self):
u'''开户未激活客户OFFER订购校验'''
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select access_num from ins1.UM_SUBSCRIBER_852 where SUBSCRIBER_TYPE=1 and subscriber_status=10"
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
time.sleep(5)
HKautocase04.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_128"]'))
time.sleep(5)
#//*[@id="insSearch"]
if self.isElementPresent('id','insSearch'):
print u"校验成功!"
else:
print u"校验失败"
def test_OfferHC(self):
u'''OFFER订购互斥校验'''
driver=self.driver
HKautocase04.test_AccessLoad(self,"50033104")
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[3]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/button').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
time.sleep(3)
driver.find_element_by_id("searchOfferkeyWord").click()
driver.find_element_by_id("searchOfferkeyWord").click()
driver.find_element_by_id("searchOfferkeyWord").clear()
driver.find_element_by_id("searchOfferkeyWord").send_keys("300307")
driver.find_element_by_xpath('//*[@id="searchOffersearchButton"]').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="offerId_200792"]').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="iframe1"]'))
driver.find_element_by_xpath('//*[@id="OFFER_BUTTON_SUBMIT"]').click()
time.sleep(2)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/button').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
time.sleep(3)
driver.find_element_by_id("searchOfferkeyWord").click()
driver.find_element_by_id("searchOfferkeyWord").click()
driver.find_element_by_id("searchOfferkeyWord").clear()
driver.find_element_by_id("searchOfferkeyWord").send_keys("300308")
driver.find_element_by_xpath('//*[@id="searchOffersearchButton"]').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="offerId_200348"]').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="iframe2"]'))
driver.find_element_by_xpath('//*[@id="cha<PASSWORD>52223104_152852000017"]').send_keys('888')
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[2]/ul[3]/li[2]/div[2]/span/span/span[1]').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[8]/div[2]/div/div[7]/button[3]').click()
driver.find_element_by_xpath('//*[@id="OFFER_BUTTON_SUBMIT"]').click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath('/html/body/div[2]/div[1]').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div/div[3]/div[1]/button[2]').click()
time.sleep(5)
HC=driver.find_element_by_xpath('html/body/div[8]/div/div[2]/div/div[2]').text
print HC
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
#unittest.main()#运行所有test开头的测试用例
testunit=unittest.TestSuite()
#将测试用例加入到测试容器中
testunit.addTest(HKautocase04('test_Mymobile'))
testunit.addTest(HKautocase04('test_VasReset'))
testunit.addTest(HKautocase04('test_QueryBaseVas'))
testunit.addTest(HKautocase04('test_QueryExitOffer'))
testunit.addTest(HKautocase04('test_QueryOffer'))
testunit.addTest(HKautocase04('test_AddButtonClick'))
testunit.addTest(HKautocase04('test_OfferCataQuery'))
testunit.addTest(HKautocase04('test_ADDoffer'))
testunit.addTest(HKautocase04('test_ChangeOfferCha'))
testunit.addTest(HKautocase04('test_DeleteOffer'))
testunit.addTest(HKautocase04('test_DryNUM'))
testunit.addTest(HKautocase04('test_SuspendNUM'))
testunit.addTest(HKautocase04('test_IngOrdNUM'))
testunit.addTest(HKautocase04('test_IngCusNUM'))
testunit.addTest(HKautocase04('test_UnActiveNUM'))
testunit.addTest(HKautocase04('test_OfferHC'))
now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
#打开一个文件,将result写入此file中
fp=open("result"+now+".html",'wb')
runner=HTMLTestRunnerA.HTMLTestRunner(stream=fp,title='Test Report',description=u'南基五期香港新CRM自动化测试,test by taozhan')
runner.run(testunit)
fp.close()<file_sep># -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
from HKautocase02 import HKautoCase02
import HTMLTestRunnerA
import cx_Oracle
from sre_parse import Pattern
import re
from selenium.common.exceptions import NoSuchElementException#从selenium.common.exceptions 模块导入 NoSuchElementException类
"""
select access_num from (select access_num from ins1.um_subscriber_852 where subscriber_type=1 and
subscriber_status=1 and rownum<100 order by dbms_random.value) where rownum< 2;
"""
class HKautocase03(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.katalon.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_AccessLoad(self,access_num):
#供后续复用
u"""服务号码登录"""
driver = self.driver
driver.get("http://172.17.24.75:8085/web-ngboss")
driver.find_element_by_id("STAFF_ID").click()
driver.find_element_by_id("STAFF_ID").clear()
driver.find_element_by_id("STAFF_ID").send_keys("P91110029")
driver.find_element_by_id("PASSWORD").click()
driver.find_element_by_id("PASSWORD").clear()
driver.find_element_by_id("PASSWORD").send_keys("<PASSWORD>")
driver.find_element_by_id("loginBtn").click()
time.sleep(3)
#去掉系统提示弹窗
driver.find_element_by_xpath('/html/body/div[9]/div[1]/div[2]/div/div/div[2]/button[1]').click()
#driver.find_element_by_id("NO_PASSWORD_LOGIN_CHECKBOX").click()
driver.find_element_by_id("LOGIN_NUM").click()
driver.find_element_by_id("LOGIN_NUM").clear()
driver.find_element_by_id("LOGIN_NUM").send_keys(access_num)
driver.find_element_by_id("LOGIN_BTN").click()
time.sleep(1)
driver.find_element_by_xpath("/html/body/div[25]/div/div[2]/div[1]/div[2]/div/div[1]/input").click()
time.sleep(0.5)
driver.find_element_by_xpath("/html/body/div[25]/div/div[2]/div[2]/button[1]/span[1]").click()
def test_VasAdd(self):
u"""VAS订购"""
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select access_num from (select access_num from ins1.um_subscriber_852 where subscriber_type=1 and subscriber_status=1 and rownum<1000 order by dbms_random.value) where rownum< 2"
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase03.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(2)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[1]/div/div[3]/div[2]/div[2]/div/div[2]/div[3]/div[2]/div[2]/div/ul/li[6]/div[1]')
time.sleep(2)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath("/html/body/div[1]/div/div[1]/div/button").click()
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
driver.find_element_by_id("offerName_200234").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="iframe1"]'))
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[2]/ul[3]/li[2]/div[2]/span/span/span[1]/span').click()
driver.find_element_by_xpath('/html/body/div[8]/div[2]/div/div[7]/button[3]').click()
time.sleep(3)
#driver.find_element_by_xpath('/html/body/div[9]/div[2]/div/div[7]/button[3]').click()
driver.find_element_by_id("OFFER_BUTTON_SUBMIT").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div/div[3]/div[1]/button[2]').click()
#driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Close'])[1]/following::button[1]").click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resA=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
#order_idA=driver.find_element_by_xpath('//*[@id="wade_messagebox-d209225d1f681451139643f0e3029310_ct"]').text
#print resA
order_idA = re.search( r'\d{15}', resA).group(0)
driver.find_element_by_xpath('/html/body/div[8]/div/div[2]/div[2]/button').click()
print order_idA
time.sleep(10)#加延时确保后续取到订单号再查表
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select order_line_id,order_id,party_role_id,subscriber_ins_id,busi_item_code,access_num,valid_date,expire_date,data_status from ord.om_line_f_201903 t where t.order_id=%s" %order_idA
#sql="select order_line_id,order_id,party_role_id,subscriber_ins_id,busi_item_code,access_num,valid_date,expire_date,data_status from ord.om_line_f_201903 t where t.order_id='"+order_idA+"'"
c.execute(sql)
rsA=c.fetchall()
print rsA
c.close()
conn.close()
def isElementPresent(self,by,value):
u"""判断页面是否存在元素"""
try:
element = self.driver.find_element(by = by, value= value)
#原文是except NoSuchElementException, e:
except NoSuchElementException as e:
#打印异常信息
print(e)
#发生了NoSuchElementException异常,说明页面中未找到该元素,返回False
return False
else:
#没有发生异常,表示在页面中找到了该元素,返回True
return True
def test_VasDelete(self):
u"""VAS退订"""
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select access_num from (select access_num from ins1.um_subscriber_852 where subscriber_type=1
and subscriber_status=1 and rownum<1000 order by dbms_random.value) where rownum< 2'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase03.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(2)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(2)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
time.sleep(2)
driver.find_element_by_xpath("/html/body/div[1]/div/div[6]/ul/li[1]/div[4]").click()#删除
time.sleep(3)
if self.isElementPresent('id','EDIT_EXP_DATE'):#手动录入时间场景
driver.find_element_by_xpath('//*[@id="EDIT_EXP_DATE"]').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="_Wade_DropDownCalendar_float"]/div[2]/div/div[7]/button[3]').click()
time.sleep(5)
driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div/div/div[3]/div/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div/div[3]/div[1]/button[2]').click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resB=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
order_idB = re.search( r'\d{15}', resB).group(0)
#driver.find_element_by_xpath('/html/body/div[10]/div/div[2]/div[2]/button').click()
print order_idB
time.sleep(10)#加延时确保后续取到订单号再查表
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select order_line_id,order_id,party_role_id,subscriber_ins_id,busi_item_code,access_num,valid_date,expire_date,data_status from ord.om_line_f_201903 t where t.order_id=%s" %order_idB
c.execute(sql)
rsA=c.fetchall()
print rsA
c.close()
conn.close()
else:#默认生效时间场景
driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div/div/div[3]/div/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div/div[3]/div[1]/button[2]').click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resB=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
order_idB = re.search( r'\d{15}', resB).group(0)
#driver.find_element_by_xpath('/html/body/div[11]/div/div[2]/div[2]/button').click()
print order_idB
time.sleep(10)#加延时确保后续取到订单号再查表
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select order_line_id,order_id,party_role_id,subscriber_ins_id,busi_item_code,access_num,valid_date,expire_date,data_status from ord.om_line_f_201903 t where t.order_id=%s" %order_idB
c.execute(sql)
rsA=c.fetchall()
print rsA
c.close()
conn.close()
def test_VasQryDestory(self):
u"""VAS受理销户用户校验"""
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='select access_num from ins1.UM_SUBSCRIBER_852 where SUBSCRIBER_TYPE=1 and subscriber_status=4'
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase03.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_129"]'))
err1=driver.find_element_by_xpath('/html/body/div/div/div[2]').text
print err1
def test_VasQrySuspend(self):
u"""VAS受理停机用户校验"""
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select t.access_num from ins1.um_subscriber_852 t, ins1.um_prod_sta_852 m
where t.subscriber_ins_id = m.subscriber_ins_id
and t.data_status = '1'
and t.subscriber_status = '1'
and t.subscriber_type = '1'
and m.prod_status = '2'
'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase03.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
err2=driver.find_element_by_xpath('/html/body/div/div/div[2]').text
print err2
def test_VasQryCOrder(self):
u"""VAS受理-变更在途工单校验"""
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select access_num from ord.om_line where order_id in
(select order_id from ord.om_order t where t.busi_code ='500140000002')
'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
HKautocase03.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
err3=driver.find_element_by_xpath('/html/body/div/div/div[2]').text
print err3
def test_ActiveDateQuery(self):
u'''查客户激活时间'''
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select access_num from ord.om_line where order_id in
(select order_id from ord.om_order t where t.busi_code ='500220000005')
'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[2]
HKautocase03.test_AccessLoad(self,y)
time.sleep(5)
driver.find_element_by_xpath('//*[@id="myMoblie"]').click()
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_136"]'))
time.sleep(1)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="baseFrame"]'))
goal=driver.find_element_by_xpath('/html/body/div[2]/div[1]/div[3]/ul/li[17]').text
print goal
def test_VasQryNOrder(self):
u"""VAS受理-客户资料变更在途工单校验"""
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql='''select access_num from ord.om_line where order_id in
(select order_id from ord.om_order t where t.busi_code ='500220000005')
'''
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[2]
HKautocase03.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
time.sleep(5)
#//*[@id="insSearch"]
if self.isElementPresent('id','insSearch'):
print u"校验成功!"
else:
print u"校验失败"
def test_VasQryNactive(self):
u"""VAS受理-开户未激活用户校验"""
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select access_num from ins1.UM_SUBSCRIBER_852 where SUBSCRIBER_TYPE=1 and subscriber_status=10"
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
driver=self.driver
y=rs[0]
time.sleep(5)
HKautocase03.test_AccessLoad(self,y)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_128"]'))
time.sleep(5)
#//*[@id="insSearch"]
if self.isElementPresent('id','insSearch'):
print u"校验成功!"
else:
print u"校验失败"
def test_VasChange(self):
u"""VAS特征值变更"""
driver=self.driver
HKautocase03.test_AccessLoad(self,'93157018')
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath('//*[@id="200021_insLi"]').click()
time.sleep(5)
# js="document.getElementById('Part_152852000032').style.display='block';"
# driver.execute_script(js)
driver.find_element_by_xpath('//*[@id="chaSpec_152852000032"]').send_keys("333")
time.sleep(2)
driver.find_element_by_xpath('//*[@id="OFFER_BUTTON_CHANGE"]').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[2]/div[1]/button').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="myDialog"]/div/div[3]/div[1]/button[2]').click()
time.sleep(10)
SBwadeKuangJIA="wade_messagebox-(.*?)_ct"
resB=driver.find_element_by_xpath('//*[starts-with(@id,SBwadeKuangJIA)]').text
order_idB = re.search( r'\d{15}', resB).group(0)
#driver.find_element_by_xpath('/html/body/div[11]/div/div[2]/div[2]/button').click()
print order_idB
time.sleep(10)#加延时确保后续取到订单号再查表
tns=cx_Oracle.makedsn('172.17.24.68',1522,'hkcrmtst')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select order_line_id,order_id,party_role_id,subscriber_ins_id,busi_item_code,access_num,valid_date,expire_date,data_status from ord.om_line_f_201903 t where t.order_id=%s" %order_idB
c.execute(sql)
rsA=c.fetchall()
print rsA
c.close()
conn.close()
def test_VasTimeIsNull(self):
u"""VAS受理-订购生效时间非空校验"""
driver=self.driver
HKautocase03.test_AccessLoad(self,"52223104")
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/button').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
driver.find_element_by_id("offerName_200234").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="iframe1"]'))
time.sleep(3)
driver.find_element_by_id("OFFER_BUTTON_SUBMIT").click()
time.sleep(3)
IsNullMessa=driver.find_element_by_xpath('//*[@id="wade_tipbox-1_content"]').text
print IsNullMessa
def test_VasSpecIsNull(self):
u"""VAS受理-订购特征值非空校验"""
driver=self.driver
HKautocase03.test_AccessLoad(self,"52223104")
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/button').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
time.sleep(3)
driver.find_element_by_xpath('//*[@id="searchOfferkeyWord"]').send_keys("KID")
driver.find_element_by_xpath('//*[@id="searchOffersearchButton"]').click()
time.sleep(3)
driver.find_element_by_id("offerName_200844").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="iframe1"]'))
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[2]/ul[3]/li[2]/div[2]/span/span/span[1]/span').click()
driver.find_element_by_xpath('/html/body/div[9]/div[2]/div/div[7]/button[3]').click()
time.sleep(1)
driver.find_element_by_id("OFFER_BUTTON_SUBMIT").click()
time.sleep(3)
IsNullMessa=driver.find_element_by_xpath('html/body/div[10]/div/div[2]/div/div[2]').text
print IsNullMessa
def test_VasHC(self):
u"""VAS受理-互斥订购"""
driver=self.driver
HKautocase03.test_AccessLoad(self,"52223104")
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_id("welTab_tab_li_1").click()
time.sleep(5)
driver.find_element_by_id("menus_tab_li_2").click()
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='宽带业务'])[1]/following::div[2]").click()
driver.find_element_by_id("10000219").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/button').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
time.sleep(3)
driver.find_element_by_id("searchOfferkeyWord").click()
driver.find_element_by_id("searchOfferkeyWord").click()
driver.find_element_by_id("searchOfferkeyWord").clear()
driver.find_element_by_id("searchOfferkeyWord").send_keys("200792")
driver.find_element_by_xpath('//*[@id="searchOffersearchButton"]').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="offerId_200792"]').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="iframe1"]'))
driver.find_element_by_xpath('//*[@id="OFFER_BUTTON_SUBMIT"]').click()
time.sleep(2)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/button').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="offerFrame"]'))
time.sleep(3)
driver.find_element_by_id("searchOfferkeyWord").click()
driver.find_element_by_id("searchOfferkeyWord").click()
driver.find_element_by_id("searchOfferkeyWord").clear()
driver.find_element_by_id("searchOfferkeyWord").send_keys("200348")
driver.find_element_by_xpath('//*[@id="searchOffersearchButton"]').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="offerId_200348"]').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="iframe2"]'))
driver.find_element_by_xpath('//*[@id="chaSpec_52223104_152852000017"]').send_keys('888')
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[2]/ul[3]/li[2]/div[2]/span/span/span[1]').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[8]/div[2]/div/div[7]/button[3]').click()
driver.find_element_by_xpath('//*[@id="OFFER_BUTTON_SUBMIT"]').click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_148"]'))
driver.find_element_by_xpath('/html/body/div[2]/div[1]').click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div/div[3]/div[1]/button[2]').click()
time.sleep(5)
HC=driver.find_element_by_xpath('html/body/div[8]/div/div[2]/div/div[2]').text
print HC
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
#unittest.main()#运行所有test开头的测试用例
testunit=unittest.TestSuite()
#将测试用例加入到测试容器中
# testunit.addTest(HKautocase03('test_VasChange'))
# testunit.addTest(HKautocase03('test_VasQryDestory'))
# testunit.addTest(HKautocase03("test_VasDelete"))
# testunit.addTest(HKautocase03("test_VasAdd"))
# testunit.addTest(HKautocase03('test_VasQrySuspend'))
# testunit.addTest(HKautocase03('test_VasQryCOrder'))
# testunit.addTest(HKautocase03('test_VasQryNOrder'))
# testunit.addTest(HKautocase03('test_VasSpecIsNull'))
# testunit.addTest(HKautocase03('test_VasTimeIsNull'))
# testunit.addTest(HKautocase03('test_VasHC'))
# testunit.addTest(HKautocase03('test_VasQryNactive'))
testunit.addTest(HKautocase03('test_ActiveDateQuery'))
now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
#打开一个文件,将result写入此file中
fp=open("result"+now+".html",'wb')
runner=HTMLTestRunnerA.HTMLTestRunner(stream=fp,title='Test Report',description=u'南基五期香港新CRM自动化测试,test by taozhan')
runner.run(testunit)
fp.close()<file_sep># -*-coding:utf-8 -*-
'''
Created on 2019年1月19日
@author:Taozhan
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
from autocase11 import autocase11yue
import autocase11
import HTMLTestRunnerA
class autocase0901(autocase11.autocase11yue):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.katalon.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_VmGroupADD(self):
u"""虚拟组新增"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(1)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='操作员上岗'])[1]/following::li[1]").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("addButton").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='虚拟组类型'])[4]/following::span[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='话务班组'])[2]/following::div[1]").click()
driver.find_element_by_id("condition_GROUP_NAME").click()
driver.find_element_by_id("condition_GROUP_NAME").clear()
driver.find_element_by_id("condition_GROUP_NAME").send_keys(u"虚拟一组")
driver.find_element_by_id("confirmButton").click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[7]/div/div[2]/div[2]/button[1]').click()
time.sleep(3)
RET=driver.find_element_by_xpath('//*[@id="wade_messagebox-7d67d44b138069da347b912e05066846_title"]').text
print RET
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='新增成功'])[1]/following::button[1]").click()
def test_VmGroupQuery(self):
u"""虚拟组信息查询"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='操作员上岗'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='删除'])[1]/following::button[1]").click()
driver.find_element_by_id("GROUP_NAME").click()
driver.find_element_by_id("GROUP_NAME").clear()
driver.find_element_by_id("GROUP_NAME").send_keys(u"虚拟一组")
driver.find_element_by_id("qryButton").click()
time.sleep(3)
Message=driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div/div/div[1]/div/table/tbody').text
print Message
def test_VmGroupEdit(self):
u"""虚拟组信息修改"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='操作员上岗'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='删除'])[1]/following::button[1]").click()
driver.find_element_by_id("GROUP_NAME").click()
driver.find_element_by_id("GROUP_NAME").clear()
driver.find_element_by_id("GROUP_NAME").send_keys(u"虚拟一组")
driver.find_element_by_id("qryButton").click()
time.sleep(3)
driver.find_element_by_id("ROLE_MGT").click()
driver.find_element_by_id("editButton").click()
driver.find_element_by_id("cond_GROUP_NAME").click()
driver.find_element_by_id("cond_GROUP_NAME").clear()
driver.find_element_by_id("cond_GROUP_NAME").send_keys(u"虚拟二组")
driver.find_element_by_id("modifyButton").click()
driver.find_element_by_xpath('/html/body/div[7]/div/div[2]/div[2]/button[1]').click()
time.sleep(3)
RET01=driver.find_element_by_xpath('//*[@id="wade_messagebox-<PASSWORD>"]').text
print RET01
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='修改成功'])[1]/following::button[1]").click()
def test_VmGroupDelete(self):
u"""虚拟组删除"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='操作员上岗'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='删除'])[1]/following::button[1]").click()
driver.find_element_by_id("GROUP_NAME").click()
driver.find_element_by_id("GROUP_NAME").clear()
driver.find_element_by_id("GROUP_NAME").send_keys(u"虚拟二组")
driver.find_element_by_id("qryButton").click()
time.sleep(3)
driver.find_element_by_id("ROLE_MGT").click()
driver.find_element_by_id("deleteButton").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='确认要删除吗?'])[1]/following::button[1]").click()
time.sleep(3)
RET02=driver.find_element_by_xpath('//*[@id="wade_messagebox-<PASSWORD>_title"]').text
print RET02
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='业务受理成功!'])[1]/following::button[1]").click()
def test_VmGroupManAdd(self):
u"""虚拟组成员新增"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='虚拟组管理'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='虚拟组'])[1]/following::span[2]").click()
driver.find_element_by_id("GROUP_NAME").click()
driver.find_element_by_id("GROUP_NAME").clear()
driver.find_element_by_id("GROUP_NAME").send_keys(u"米琪")
driver.find_element_by_id("qryButton").click()
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='组名称:'])[1]/following::span[1]").click()
driver.find_element_by_id("addButton").click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/div/div/div[2]/div/div[1]/ul/li[2]/div[2]/span/span').click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="frame_editPopup_group2_item849def3a05e939183749adfcf260522b"]'))
driver.find_element_by_xpath('//*[@class="e_select"]').click
time.sleep(3)
driver.find_element_by_xpath('//*[@id="mySelect_float"]/div[2]/div/div/ul/li[3]/div').click()
time.sleep(3)
driver.find_element_by_id("OPERATOR_ID").click()
driver.find_element_by_id("OPERATOR_ID").clear()
driver.find_element_by_id("OPERATOR_ID").send_keys("91110020")
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='员工姓名'])[1]/following::button[1]").click()
driver.find_element_by_name("operator").click()
driver.find_element_by_id("confirmButton").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='确认要新增虚拟组成员91110020吗?'])[1]/following::button[1]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='操作成功!'])[1]/following::button[1]").click()
def test_GNJAdd(self):
u"""功能集新增"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='系统权限行为维护'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("addButton").click()
driver.find_element_by_id("condition_ROLE_NAME").click()
driver.find_element_by_id("condition_ROLE_NAME").clear()
driver.find_element_by_id("condition_ROLE_NAME").send_keys(u"虚拟功能集")
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='功能集类型'])[5]/following::span[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='资源类'])[3]/following::div[1]").click()
driver.find_element_by_id("condition_REGION_CODE_span").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='--请选择--'])[16]/following::div[1]").click()
driver.find_element_by_id("condition_DOMAIN_ID_span").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='--请选择--'])[16]/following::div[1]").click()
driver.find_element_by_id("confirmButton").click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[14]/div/div[2]/div[2]/button[1]').click()
time.sleep(3)
messageee=driver.find_element_by_xpath('//*[@id="wade_messagebox-7d67d44b138069da347b912e05066846_title"]').text
print messageee
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='新增成功'])[1]/following::button[1]").click()
def test_GNJQuery(self):
u"""功能集查询"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='系统权限行为维护'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='删除'])[1]/following::button[1]").click()
driver.find_element_by_id("ROLE_NAME").click()
driver.find_element_by_id("ROLE_NAME").clear()
driver.find_element_by_id("ROLE_NAME").send_keys(u"虚拟功能集")
driver.find_element_by_id("qryButton").click()
time.sleep(5)
RES=driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div/div/div[1]/div/table/tbody').text
print RES
def test_GNJEdit(self):
u"""功能集修改"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='系统权限行为维护'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='删除'])[1]/following::button[1]").click()
driver.find_element_by_id("ROLE_NAME").click()
driver.find_element_by_id("ROLE_NAME").clear()
driver.find_element_by_id("ROLE_NAME").send_keys(u"虚拟功能集")
driver.find_element_by_id("qryButton").click()
time.sleep(3)
driver.find_element_by_id("ROLE_MGT").click()
driver.find_element_by_id("editButton").click()
driver.find_element_by_id("cond_ROLE_NAME").click()
driver.find_element_by_id("cond_ROLE_NAME").clear()
driver.find_element_by_id("cond_ROLE_NAME").send_keys(u"虚拟功能集一")
driver.find_element_by_id("modifyButton").click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[14]/div/div[2]/div[2]/button[1]').click()
time.sleep(3)
RES01=driver.find_element_by_xpath('//*[@id="wade_messagebox-0a844469c0371a6a292f672f522081c2_title"]').text
print RES01
def test_GNJDelete(self):
u"""功能集删除"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='系统权限行为维护'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='删除'])[1]/following::button[1]").click()
driver.find_element_by_id("ROLE_NAME").click()
driver.find_element_by_id("ROLE_NAME").clear()
driver.find_element_by_id("ROLE_NAME").send_keys(u"虚拟功能集一")
driver.find_element_by_id("qryButton").click()
driver.find_element_by_id("ROLE_MGT").click()
driver.find_element_by_id("deleteButton").click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[14]/div/div[2]/div[2]/button[1]').click()
time.sleep(3)
RES02=driver.find_element_by_xpath('//*[@id="wade_messagebox-<PASSWORD>"]').text
print RES02
def test_GNJCdAdd(self):
u"""功能集系统菜单分配权限"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='功能集关系管理'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
time.sleep(5)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='功能集'])[1]/following::span[2]").click()
driver.find_element_by_id("ROLE_NAME").click()
driver.find_element_by_id("ROLE_NAME").clear()
driver.find_element_by_id("ROLE_NAME").send_keys(u"卢")
driver.find_element_by_id("qryButton").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='功能集编号:'])[1]/following::span[1]").click()
driver.find_element_by_id("grantRightButton").click()
driver.find_element_by_id("queryButton").click()
driver.find_element_by_id("FUNCTION").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='失效日期:'])[1]/following::button[1]").click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[18]/div/div[2]/div[2]/button[1]').click()
time.sleep(3)
RES03=driver.find_element_by_xpath('//*[@id="wade_messagebox-41a09a6eba201eaa9bee6bb98ca43849_title"]').text
print RES03
def test_VmGroupManDlete(self):
u"""虚拟组成员删除"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
time.sleep(3)
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人查询'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='虚拟组管理'])[1]/following::li[1]").click()
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='虚拟组'])[1]/following::span[2]").click()
time.sleep(3)
driver.find_element_by_id("GROUP_NAME").click()
driver.find_element_by_id("GROUP_NAME").clear()
driver.find_element_by_id("GROUP_NAME").send_keys(u"虚拟三组")
driver.find_element_by_id("qryButton").click()
time.sleep(3)
#//*[@id="scroller32"]/div[1]/div[1]/ul/li/div
driver.find_element_by_xpath('//*[@id="scroller32"]/div[1]/div[1]/ul/li/div').click()
time.sleep(5)
driver.find_element_by_xpath('//*[@id="PackageRightPart"]/div/div/div/div/div/table/tbody/tr[2]/td').click()
driver.find_element_by_id("deleteButton").click()
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[11]/div/div[2]/div[2]/button[1]').click()
time.sleep(3)
messagee=driver.find_element_by_xpath('//*[@id="wade_messagebox-9209358670f30487059ce524c5999b73_title"]').text
print messagee
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='操作成功!'])[1]/following::button[1]").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
#unittest.main()#运行所有test开头的测试用例
testunit=unittest.TestSuite()
#将测试用例加入到测试容器中
testunit.addTest(autocase0901("test_VmGroupADD"))
testunit.addTest(autocase0901("test_VmGroupQuery"))
testunit.addTest(autocase0901("test_VmGroupEdit"))
testunit.addTest(autocase0901("test_VmGroupDelete"))
#testunit.addTest(autocase0901("test_VmGroupManAdd"))
testunit.addTest(autocase0901("test_VmGroupManDlete"))
testunit.addTest(autocase0901("test_GNJAdd"))
testunit.addTest(autocase0901("test_GNJQuery"))
testunit.addTest(autocase0901("test_GNJEdit"))
testunit.addTest(autocase0901("test_GNJDelete"))
testunit.addTest(autocase0901("test_GNJCdAdd"))
#获取当前时间,这样便于下面的使用。
now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
#打开一个文件,将result写入此file中
fp=open("result"+now+".html",'wb')
runner=HTMLTestRunnerA.HTMLTestRunner(stream=fp,title='Test Report',description=u'南基五期新CRM个人业务自动化测试,test by taozhan')
runner.run(testunit)
fp.close()
<file_sep>#-*- coding:utf-8 -*-
'''
Created on 2018年12月20日
@author: Administrator
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
from autocase11 import autocase11yue
import autocase11
import HTMLTestRunnerA
import cx_Oracle
from __builtin__ import int
class autocase12yue(autocase11.autocase11yue):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.katalon.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_DLLRule01(self):
u"""大流量套餐副卡开户实名制校验"""
driver = self.driver
autocase11yue.test_FuWoHaoMaLoad(self,'13989010639')#调用已有的服务号码登录方法
time.sleep(5)
#driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
#driver.find_element_by_xpath('//*[@id="menu_ct"]')
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[1]/div/ul/li[2]/div[1]').click()
#driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[4]/div/div[4]/ul/li[6]').click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_69"]'))
#c_msg c_msg-full c_msg-h c_msg-error c_msg-phone-v
time.sleep(1)
ZLa=driver.find_element_by_xpath('//*[@class="content"]').text
#print ZLa
# array=[]
# for c in ZLa:
# array.append(c)
# print array[1:11]
#print ZLa[0:12]
if ZLa[0:12] == "【1500000005】":
print u"实名制规则校验成功"
else:
print u"实名制规则校验失败"
def test_DLLRule02(self):
u"""大流量套餐副卡开户一证五号校验"""
driver = self.driver
autocase11yue.test_FuWoHaoMaLoad(self,'18208014971')#调用已有的服务号码登录方法
time.sleep(5)
#driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[1]/div/ul/li[2]/div[1]').click()
#driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[4]/div/div[4]/ul/li[6]').click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_69"]'))
#c_msg c_msg-full c_msg-h c_msg-error c_msg-phone-v
time.sleep(1)
ZLb=driver.find_element_by_xpath('//*[@class="content"]').text
if ZLb[0:12]=="【1500000029】":
print u"一证多名规则校验成功"
else:
print u"一证多名规则校验失败"
def test_DLLRule03(self):
u"""大流量套餐副卡开户欠费校验"""
driver = self.driver
autocase11yue.test_FuWoHaoMaLoad(self,'18308011766')#调用已有的服务号码登录方法
time.sleep(5)
#driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[1]/div/ul/li[2]/div[1]').click()
#driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[4]/div/div[4]/ul/li[6]').click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_69"]'))
#c_msg c_msg-full c_msg-h c_msg-error c_msg-phone-v
time.sleep(1)
ZLc=driver.find_element_by_xpath('//*[@class="content"]').text
#print ZLc[0:18]
if ZLc[0:18]=="【1500000005】 用户已欠费":
print u"欠费规则校验成功"
else:
print u"欠费规则校验失败"
def test_DLLRule04(self):
u"""大流量套餐副卡开户证件类型校验"""
driver = self.driver
autocase11yue.test_FuWoHaoMaLoad(self,'14718919090')#调用已有的服务号码登录方法
time.sleep(5)
#driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[1]/div/ul/li[2]/div[1]').click()
#driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[4]/div/div[4]/ul/li[6]').click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_69"]'))
#c_msg c_msg-full c_msg-h c_msg-error c_msg-phone-v
time.sleep(1)
ZLd=driver.find_element_by_xpath('//*[@class="content"]').text
#print ZLd[0:-7]
if ZLd[0:-7]== u"CRMWEB_210000:号码是非身份证开户主卡,不允许办理副卡":
print u"可办理证件类型规则校验成功"
else:
print u"可办理证件类型规则校验失败"
def test_DLLRule05(self):
u"""大流量套餐副卡可开户套餐校验"""
driver = self.driver
autocase11yue.test_FuWoHaoMaLoad(self,'17889115038')#调用已有的服务号码登录方法
time.sleep(5)
#driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[1]/div/ul/li[2]/div[1]').click()
#driver.find_element_by_xpath('//*[@id="menu_l1_ul"]/li[2]').click()
driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/div[4]/div/div[4]/ul/li[6]').click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_69"]'))
#c_msg c_msg-full c_msg-h c_msg-error c_msg-phone-v
time.sleep(1)
ZLe=driver.find_element_by_xpath('//*[@class="content"]').text
print ZLe[0:-7]
if ZLe[0:-7]== u"CRMWEB_210000:该主号没有在生效的国内大流量套餐!":
print u"副卡开户套餐规则校验成功"
else:
print u"副卡开户套餐规则校验失败"
#查询数据库可开户主套餐配置
tns=cx_Oracle.makedsn('172.16.9.28',1522,'ng3cs')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select code_value from (SELECT t.*,t.rowid FROM base.bs_static_data t where t.code_type='UNLIMIT_QUANTITY_CONFIG_ORDER_TIMES')"
c.execute(sql)
rs=c.fetchall()
print rs
c.close()
conn.close()
def test_CustIdentity(self):
u"""客户证件信息查询"""
driver = self.driver
autocase11yue.load(self)
time.sleep(5)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='权限管理'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='特殊客户名单管理'])[1]/following::li[1]").click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | relative=parent | ]]
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=1 | ]]
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='手机号码'])[1]/preceding::div[1]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='证件类型:'])[1]/following::span[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='--请选择--'])[2]/following::div[1]").click()
driver.find_element_by_id("cond_GROUP_NAME").click()
driver.find_element_by_id("cond_GROUP_NAME").clear()
driver.find_element_by_id("cond_GROUP_NAME").send_keys("089167444080000000")
driver.find_element_by_id("qryButton").click()
time.sleep(3)
exel=driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div/div/div[2]/table/thead/tr').text
CustMesseage=driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div/div/div[1]/div/table/tbody/tr').text
print exel
print CustMesseage
def test_YiZhengDduoMing(self):
u"""一证多名查询"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人业务'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='免填单打印'])[2]/following::li[1]").click()
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | relative=parent | ]]
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=1 | ]]
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("qryBox").click()
driver.find_element_by_id("cond_IDEN_TYPE_CODE_span").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='--请选择--'])[2]/following::div[1]").click()
driver.find_element_by_id("cond_IDEN_NR").click()
driver.find_element_by_id("cond_IDEN_NR").clear()
driver.find_element_by_id("cond_IDEN_NR").send_keys("430124199304118372")
driver.find_element_by_id("qryButton").click()
#time.sleep(900)
datee=driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[2]/div[1]/div[1]/div/div[2]/table/thead/tr').text
print datee
#datee1=driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[2]/div[1]/div[1]/div/div[1]/div/table/tbody/{}'.format(str(i))for i in range(1,6)).text
for i in range(1,7):
XpathA='/html/body/div[1]/div[2]/div/div/div[2]/div[1]/div[1]/div/div[1]/div/table/tbody/tr{}'.format([int(i)])
#print XpathA
datee1=driver.find_element_by_xpath(XpathA).text
print datee1
def test_AccountMessageChange(self):
u"""账户资料变更"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath('//*[@id="menu_ct"]')
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='权限管理'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='个人'])[1]/following::li[1]").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("cond_SEARCH_VALUE").click()
driver.find_element_by_id("cond_SEARCH_VALUE").clear()
driver.find_element_by_id("cond_SEARCH_VALUE").send_keys("13638994528")
#driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='查询值:'])[1]/following::button[1]").click()
driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/ul/li[3]/button').click()
time.sleep(30)
#driver.find_element_by_xpath('//*[@id="acctPart"]').click()
driver.find_element_by_id("acctinfo_ACCT_NAME").click()
driver.find_element_by_id("acctinfo_ACCT_NAME").clear()
driver.find_element_by_id("acctinfo_ACCT_NAME").send_keys(u"海阔天高")
driver.find_element_by_id("submit").click()
time.sleep(5)
AccountMe=driver.find_element_by_xpath('/html/body/div[18]/div/div[2]/div[1]').text
print AccountMe
def test_SnMessageQuery(self):
u"""白卡信息查询"""
#查询出信息后,和数据库数据比对,输出比对结果
#select * from res.res_empty_origin t where t.sn like '85180001080081969030';
driver = self.driver
autocase11yue.load(self)
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | index=0 | ]]
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='客户管理'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='SIM卡管理'])[1]/following::li[1]").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("idle_SN_S").click()
driver.find_element_by_id("idle_SN_S").clear()
driver.find_element_by_id("idle_SN_S").send_keys("85180001080081969030")
driver.find_element_by_id("idle_SN_E").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='重置'])[1]/following::button[1]").click()
time.sleep(5)
SnMessa=driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div/div/div[1]/div/table/tbody/tr').text
# print SnMessa
# print type(SnMessa)
#查询数据库白卡的状态res_state
tns=cx_Oracle.makedsn('172.16.9.28',1522,'ng3cs')
conn=cx_Oracle.connect('aitest','aitest_1234',tns)
c=conn.cursor()
sql="select res_state from (select * from res.res_empty_origin t where t.sn like '85180001080081969030')"
c.execute(sql)
rs=c.fetchall()
#print rs
c.close()
conn.close()
#比对前台信息&数据库状态
str = ''.join(rs[0])
if SnMessa[22]==str[0]:
print u"白卡信息查询功能无异常"
else:
print u"白卡信息查询功能异常"
def test_editACCESSNUMBER(self):
u"""号码生成"""
#前置条件为先HLR信息管理生成号段,这部分查看autocase11yue.test_HLR_ADD方法
#SELECT t.*,rowid FROM RES.RES_NUMSEG_HLR t where op_id='91110029' order by valid_date desc;
driver = self.driver
autocase11yue.load(self)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='客户管理'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='号码查询'])[1]/following::li[1]").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("edit_ACCESS_NUMBER_S").click()
driver.find_element_by_id("edit_ACCESS_NUMBER_S").clear()
driver.find_element_by_id("edit_ACCESS_NUMBER_S").send_keys("18809900011")
driver.find_element_by_id("edit_NUM").click()
driver.find_element_by_id("edit_NUM").clear()
driver.find_element_by_id("edit_NUM").send_keys("1")
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='结束号码'])[1]/following::div[1]").click()
driver.find_element_by_id("instock").click()
time.sleep(5)
NumCreateMessa=driver.find_element_by_xpath('/html/body/div[16]/div/div[2]').text
print NumCreateMessa
def test_simEntry(self):
u"""SIM卡入库"""
#前置条件为先IMS与HLR信息管理生成IMS号段,这部分查看autocase11yue.test_IMS_HLR_ADD方法
#SELECT t.*,rowid FROM RES.RES_IMSI_NUMSEG_REL t where op_id='91110029' order by valid_date desc;
driver = self.driver
autocase11yue.load(self)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='客户管理'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='SIM卡信息查询'])[1]/following::li[1]").click()
time.sleep(5)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='资源类别:'])[1]/following::span[2]").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="frame_2e1b48d61b0891ebe7ec3e431bc9e666"]'))
driver.find_element_by_name("RES_TYPE_TREE").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='资源规格:'])[1]/following::span[2]").click()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="frame_e5b9057dd81ca55ab7548d03ac45220d"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='【20023】4G-USIM卡'])[1]/following::input[1]").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("SPAN_MGMT_COUNTY").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="frame_<PASSWORD>"]'))
driver.find_element_by_name("DISTRICT_NAME").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("SPAN_STORE_ID").click()
time.sleep(3)
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="frame_<PASSWORD>"]'))
driver.find_element_by_name("STORE_NAME").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="nav<PASSWORD>"]'))
driver.find_element_by_name("REMARKS").click()
driver.find_element_by_name("REMARKS").clear()
driver.find_element_by_name("REMARKS").send_keys("AutoTest")
driver.find_element_by_id("idle_USE_TYPE_span").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='--请选择--'])[3]/following::div[1]").click()
driver.find_element_by_id("IMPORT_TYPE_span").click()
driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='IMSI ICC_ID PIN1 PIN2 PUK1 PUK2 KI OPC'])[1]/following::div[1]").click()
time.sleep(3)
#driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='文件1:'])[1]/following::span[5]").click()
#driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='文件1:'])[1]/following::input[3]").clear()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='文件1:'])[1]/following::input[3]").send_keys(u"D:\\工作\\导入文件\\SIM卡入库.txt")
time.sleep(3)
driver.find_element_by_id("confirmButton").click()
time.sleep(5)
errMessa=driver.find_element_by_xpath('/html/body/div[8]/div/div[2]').text
print errMessa
def test_NumQuery(self):
u"""号码查询"""
driver = self.driver
autocase11yue.load(self)
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_def"]'))
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='客户管理'])[1]/following::div[2]").click()
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='号码管理'])[1]/following::li[1]").click()
time.sleep(3)
driver.switch_to_default_content()
driver.switch_to_frame(driver.find_element_by_xpath('//*[@id="navframe_58"]'))
driver.find_element_by_id("phone_ACCESS_NUMBER_S").click()
driver.find_element_by_id("phone_ACCESS_NUMBER_S").clear()
driver.find_element_by_id("phone_ACCESS_NUMBER_S").send_keys("18809900011")
driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='重置'])[1]/following::button[1]").click()
time.sleep(10)
NumMessa01=driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div/div/div[1]/div/table/tbody/tr').text
print NumMessa01
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
#unittest.main()#运行所有test开头的测试用例
testunit=unittest.TestSuite()
#将测试用例加入到测试容器中
# testunit.addTest(autocase12yue("test_DLLRule01"))
# testunit.addTest(autocase12yue("test_DLLRule02"))
# testunit.addTest(autocase12yue("test_DLLRule03"))
# testunit.addTest(autocase12yue("test_DLLRule04"))
# testunit.addTest(autocase12yue("test_DLLRule05"))
# testunit.addTest(autocase12yue("test_CustIdentity"))
# testunit.addTest(autocase12yue("test_YiZhengDduoMing"))
# testunit.addTest(autocase12yue("test_AccountMessageChange"))
# testunit.addTest(autocase12yue("test_SnMessageQuery"))
# testunit.addTest(autocase12yue("test_editACCESSNUMBER"))
testunit.addTest(autocase12yue("test_simEntry"))
# testunit.addTest(autocase12yue("test_NumQuery"))
#获取当前时间,这样便于下面的使用。
now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
#打开一个文件,将result写入此file中
fp=open("result"+now+".html",'wb')
runner=HTMLTestRunnerA.HTMLTestRunner(stream=fp,title='Test Report',description=u'南基五期新CRM个人业务自动化测试,test by taozhan')
runner.run(testunit)
fp.close()
| 7289edd52e360c18b190c1e8eac0eba0e55a7ff5 | [
"Python"
] | 6 | Python | ZachTao/UIAutoCases | d52e8e64c5471df48d2830cae2b8d574b6e017fc | 7cb228165d2a8f279c97a99817b4afba2cc4b289 |
refs/heads/master | <repo_name>CH3IRAT/cimabook<file_sep>/client/src/components/movie/ModalAdd.js
import React, { useEffect, useState } from "react";
import {Modal,Button} from 'react-bootstrap'
import { useDispatch, useSelector } from "react-redux";
import {Input} from 'semantic-ui-react'
import {postNew} from "../../js/actions/movie"
const ModalAdd = () => {
const [movie, setMovie] = useState({ title: "", img: "",isStream: "", rate: "", genre: "" ,trailler: "" });
const movieReducer = useSelector((state) => state.movieReducer.movie);
const dispatch = useDispatch();
const handleChange = (e) => {
e.preventDefault();
setMovie({ ...movie, [e.target.name]: e.target.value });
};
const handleMovies = () => {
dispatch(postNew(movie));
};
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<>
<Button variant="primary" onClick={handleShow}>
+
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>ADD NEW FILM </Modal.Title>
</Modal.Header>
<Modal.Body><Input onChange={handleChange} name="title" placeholder='title...' />
<Input value={movie.img} onChange={handleChange} name="img" placeholder='img...' />
<Input value={movie.src} onChange={handleChange} name="src" placeholder='src...' />
<Input value={movie.genre} onChange={handleChange} name="genre" placeholder='genre...' />
<Input value={movie.rate} onChange={handleChange} name="rate" placeholder='rate...' />
<Input value={movie.isStream} onChange={handleChange} name="isStream" placeholder='isStream?...' />
<Input value={movie.download} onChange={handleChange} name="download" placeholder='download?...' />
<Input value={movie.trailler} onChange={handleChange} name="trailler" placeholder='trailler?...' />
<Input value={movie.description} onChange={handleChange} name="description" placeholder='description?...' />
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={()=>{handleMovies();handleClose()}}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</>
);
}
export default ModalAdd
<file_sep>/client/src/js/const/movie.js
export const LOAD_MOVIE = "LOAD_MOVIE";
export const REGISTER_MOVIE = "REGISTER_MOVIE";
export const FAIL_MOVIE = "FAIL_MOVIE";
export const GET_MOVIE = "GET_MOVIE ";
export const GET_ONE_MOVIE = "GET_ONE_MOVIE ";
export const SEARCH_MOVIE = "SEARCH_MOVIE";
export const DELETE_CONTACT = "DELETE_CONTACT";
export const EDIT_MOVIE = "EDIT_MOVIE";
export const EDIT_MOVIE_FAIL = "EDIT_MOVIE_FAIL";<file_sep>/models/movie.js
const mongoose = require("mongoose");
const schema = mongoose.Schema;
const MovieSchema = new schema({
title: {
type: String,
required: true,
unique : true
},
img: {
type: String,
required: true,
},
src: {
type: String,
required: true,
},
isStream: { type: Boolean, default: false },
description: {
type: String,
},
rate: {
type: Number,
},
genre: {
type: String,
},
trailler: {
type: String,
},
download : {
type : String ,
},
});
module.exports = mongoose.model("movie", MovieSchema);
<file_sep>/client/src/components/Navbar/NavLogin.js
import { Button, Menu } from "semantic-ui-react";
import { useHistory } from "react-router-dom";
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { logout } from "../../js/actions/user";
const NavLogin = () => {
const dispatch = useDispatch();
const user = useSelector((state) => state.userReducer.user);
let history = useHistory();
function handleClick() {
if (!user) {
history.push("/login");
}
if (user) {
history.push("/movies");
}
}
function abouleClick() {
history.push("/about");
}
return (
<div>
<Menu style={{ backgroundColor: "rgb(27,28,29)" }}>
<Button
negative
onClick={handleClick}
style={{ backgroundColor: "rgb(27,28,29)", display: "flex" }}
>
Movies
</Button>
<Button
negative
onClick={handleClick}
style={{ backgroundColor: "rgb(27,28,29)", display: "flex" }}
>
IPTV
</Button>
<Button
negative
onClick={abouleClick}
style={{ backgroundColor: "rgb(27,28,29)", display: "flex" }}
>
ABOUT{" "}
</Button>
{user ? (
<Button
secondary
onClick={() => {
dispatch(logout());
history.push("/");
}}
style={{
backgroundColor: "red",
display: "flex",
marginLeft: "70%",
}}
>
logout{" "}
</Button>
) : (
<Button
secondary
onClick={handleClick}
style={{
backgroundColor: "red",
display: "flex",
marginLeft: "70%",
}}
>
Sign in{" "}
</Button>
)}
</Menu>
</div>
);
};
export default NavLogin;
<file_sep>/client/src/components/Moviecard/FilmOne.js
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router";
import { getMovie } from "../../js/actions/movie";
import "./filmone.css";
import NavLogout from "../Navbar/NavLogout";
import Footer from "../Navbar/Footer";
import teswira from "./teswira.png";
import { Button } from 'semantic-ui-react'
const FilmOne = () => {
const params = useParams();
const dispatch = useDispatch();
useEffect(() => {
dispatch(getMovie(params.id));
}, []);
const one = useSelector((state) => state.movieReducer.one);
function scrollWin() {
window.scrollTo(0, 1300);
}
return (
<div>
<NavLogout />
{one ? (
<div>
<div className="bodyou" style={{ padding: "100px" }}>
<div className="cardou">
<section className="movie_image">
<img
className="movie_poster"
src={one.img}
alt="As Above So Below"
/>
</section>
<section className="center">
<div className="about_movie">
<h1>{one.title}</h1>
<div className="movie_info">
<p>2014</p>
<p>1h 33min</p>
<p>Horror, Mystery, Thriller </p>
</div>
<div className="movie_desc">
<p>{one.description}</p>
</div>
<button
className="watch"
onClick={() => {
scrollWin();
}}
>
{" "}
<svg
viewBox="0 0 30.051 30.051"
style={{ enableBackground: "new 0 0 30.051 30.051" }}
xmlSpace="preserve"
></svg>{" "}
Watch Now!
</button>
</div>
</section>
<svg
className="wavy"
viewBox="0 0 500 500"
preserveAspectRatio="xMinYMin meet"
>
<path
d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z"
style={{ stroke: "none" }}
/>
</svg>
</div>
<div className="bg">
<img src={teswira} alt="background" />
</div>
</div>
<div style={{ marginLeft: "500px", marginTop: "100px" }}>
<h1 style={{ marginLeft: "250px", color: "white" }}>Trailler</h1>
<iframe
width="560"
height="315"
src={one.trailler}
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</div>
<div style={{ marginLeft: "250px", marginTop: "100px" }}>
<h1 style={{ marginLeft: "400px", color: "white" }}>Watch Now</h1>
<iframe
width="1000"
height="500"
src={one.src}
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen=""
></iframe>
</div>
<Button secondary
style = {{marginLeft : "650px", width : "250px" , height : "100px" , marginTop : "70px"}}
>
<a href={one.download} style={{color:"white",textDecoration:"none"}}>
<h1>DOWNLOAD</h1>
</a>
</Button>
</div>
) : (
<h1>loading.....</h1>
)}
<Footer />
</div>
);
};
export default FilmOne;
<file_sep>/client/src/components/AboErr/About.js
import React from "react";
import { useHistory } from "react-router";
import { Button } from "react-bootstrap";
export const About = () => {
const history = useHistory();
const handleClick = () => {
history.push("/");
};
return (
<div>
<h1> ABOUUUUUUT </h1>
<Button
onClick={handleClick}
style={{ width: "250", textAlign: "center" }}
>
{" "}
Home{" "}
</Button>
</div>
);
};
<file_sep>/models/user.js
const mongoose=require("mongoose");
const schema=mongoose.Schema;
const UserSchema=new schema({
name:{
type:String,
required:true,
},
lastname:{
type:String,
required:true,
},
email:{
type:String,
required:true,
unique:true
},
password:{
type:String,
required:true
},
img :{
type:String
},
isAdmin : {
type: Boolean, default: false
}
})
module.exports=mongoose.model("user",UserSchema);<file_sep>/client/src/components/Navbar/EditProfil.js
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { current, editUser } from "../../js/actions/user";
import { toggleTrue } from "../../js/actions/edit";
import NavLogout from "./NavLogout";
import { useHistory } from "react-router-dom";
import "./EditProfil.css";
import Footer from "./Footer";
const EditProfil = () => {
const edit = useSelector((state) => state.editReducer.edit);
const dispatch = useDispatch();
useEffect(() => {
dispatch(current());
}, []);
const user = useSelector((state) => state.userReducer.user);
useEffect(() => {
setNuser(user);
}, [user]);
const [nuser, setNuser] = useState();
// useEffect(() => {
// edit ? setNuser(user) : setNuser({user});
// }, [user, edit]);
//onchange
const handleChange = (e) => {
e.preventDefault();
setNuser({ ...nuser, [e.target.name]: e.target.value });
};
// handleuser
const handleuser = (user, nuser) => {
dispatch(editUser(user._id, nuser));
dispatch(toggleTrue());
};
const history = useHistory();
function redirect() {
history.push("/movies");
}
return (
<div style={{ backgroundColor: "rgb(27,28,29)" }}>
<NavLogout />
<div style={{ display: "flex", justifyContent: "center" }}>
{nuser ? (
<div className="login-space">
<div className="login">
<div className="group">
{" "}
<label htmlFor="user" className="label">
Name
</label>{" "}
<input
value={nuser.name}
name="name"
onChange={handleChange}
type="text"
className="input"
placeholder="Enter your name"
/>{" "}
</div>
<div className="group">
{" "}
<label htmlFor="user" className="label">
Lastname
</label>{" "}
<input
value={nuser.lastname}
name="lastname"
onChange={handleChange}
type="text"
className="input"
placeholder="Enter your lastname"
/>{" "}
</div>
<div className="group">
{" "}
<label htmlFor="pass" className="label">
Email
</label>{" "}
<input
value={nuser.email}
name="email"
onChange={handleChange}
type="password"
className="input"
type="text"
placeholder="Enter your email"
/>{" "}
</div>
<div className="group">
{" "}
<input
type="submit"
className="button"
defaultValue="save"
onClick={() => {
handleuser(user, nuser);
redirect();
}}
/>{" "}
</div>
<div className="hr" />
</div>
</div>
) : (
<h1>loading ...</h1>
)}
</div>
<Footer />
</div>
);
};
export default EditProfil;
<file_sep>/client/src/components/movie/EditMovie.js
import React, { useState } from "react";
import { Modal } from "react-bootstrap";
import { Input } from "semantic-ui-react";
import { useDispatch } from "react-redux";
import {
editMovie,
} from "../../js/actions/movie";
import { toggleTrue } from "../../js/actions/edit";
import { Button } from "semantic-ui-react";
const EditMovie = ({ movie }) => {
const [nmovie, setMovie] = useState(movie);
const handleChange = (e) => {
e.preventDefault();
setMovie({ ...nmovie, [e.target.name]: e.target.value });
};
function refreshPage() {
window.location.reload(false);
}
const dispatch = useDispatch();
const handleMovie = () => {
dispatch(editMovie(movie._id, nmovie));
dispatch(toggleTrue());
};
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<div>
<Button inverted color="green" type="submit" onClick={() => handleShow()}>
update{" "}
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title> update this film</Modal.Title>
</Modal.Header>
<Modal.Body>
<Input
value={nmovie.title}
name="title"
placeholder="title..."
onChange={handleChange}
/>
<Input
value={nmovie.img}
name="img"
placeholder="img..."
onChange={handleChange}
/>
<Input
value={nmovie.src}
name="src"
placeholder="src..."
onChange={handleChange}
/>
<Input
value={nmovie.genre}
name="genre"
placeholder="genre..."
onChange={handleChange}
/>
<Input
value={nmovie.rate}
name="rate"
placeholder="rate..."
onChange={handleChange}
/>
<Input
value={nmovie.isStream}
name="isStream"
placeholder="isStream?..."
onChange={handleChange}
/>
<Input
value={nmovie.description}
name="description"
placeholder="description?..."
onChange={handleChange}
/>
<Input
value={nmovie.trailler}
name="trailler"
placeholder="trailler?..."
onChange={handleChange}
/>
<Input
value={nmovie.download}
name="download"
placeholder="download?..."
onChange={handleChange}
/>
</Modal.Body>
<Modal.Footer>
<Button
variant="primary"
onClick={() => {
handleMovie();
refreshPage();
}}
>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</div>
);
};
export default EditMovie;
<file_sep>/client/src/components/Navbar/Footer.js
import React from 'react'
import { Button, Menu, Divider, List, Segment, Container, Grid, Header, Image } from 'semantic-ui-react'
const footer = () => {
return (
<div>
<Segment inverted vertical style={{ margin: '20em 0em 0em', padding: '3em 0em' }}>
<Container textAlign='center'>
<Grid divided inverted stackable>
<Grid.Column width={4} >
<Header inverted as='h2' content='THIS WEB SITE ' />
<p>
Was created by <NAME> and <NAME>
</p>
</Grid.Column>
</Grid>
<Divider inverted section />
<List horizontal inverted divided link size='small'>
<List.Item as='a' href='#'>
Site Map
</List.Item>
<List.Item as='a' href='#'>
Contact Us
</List.Item>
<List.Item as='a' href='#'>
Terms and Conditions
</List.Item>
<List.Item as='a' href='#'>
Privacy Policy
</List.Item>
</List>
</Container>
</Segment>
</div>
)
}
export default footer
<file_sep>/client/src/components/Moviecard/MovieCard.js
import { useEffect, useState } from "react";
import ReactStars from "react-rating-stars-component";
import { Link, useHistory } from "react-router-dom";
import { deleteMovie } from "../../js/actions/movie";
import { useSelector, useDispatch } from "react-redux";
import { Button } from "semantic-ui-react";
import "./MovieCard.css";
import EditMovie from "../movie/EditMovie";
export const MovieCard = ({ movie }) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(deleteMovie());
}, []);
const Movies = useSelector((state) => state.movieReducer.movie);
const user = useSelector((state) => state.userReducer.user);
let history = useHistory();
return (
<div style={{ marginLeft: "10px" }}>
<div class="cardi">
<div class="overlay">
<div class="contenu">
<Link to={`/film/${movie._id}`}>
{" "}
<span> {movie.genre} </span>{" "}
</Link>
{movie.isStream ? (
<a href={movie.src}>
<i className="far fa-play-circle" />
</a>
) : (
<Link to={`/film/${movie._id}`}>
<i className="far fa-play-circle" />
</Link>
)}
</div>
</div>
<img src={movie.img} alt="fgrgrg²" />
<h3>{movie.title}</h3>
</div>
{movie.isStream ? (
<div> </div>
) : (
<ReactStars
count={5}
value={movie.rate}
edit={false}
size={24}
activeColor="#ffd700"
/>
)}
{user && user.isAdmin ? (
<div>
{" "}
<Button
inverted
color="red"
onClick={() => dispatch(deleteMovie(movie._id))}
>
Delete
</Button>
<EditMovie movie={movie} />
</div>
) : (
<div></div>
)}
</div>
);
};
<file_sep>/client/src/components/Home page/testhome.js
import React from 'react'
export const testhome = () => {
return (
<div>
</div>
)
}
| fd02991d841288dc69c190f18f8cb1589ca69694 | [
"JavaScript"
] | 12 | JavaScript | CH3IRAT/cimabook | 1f82a21c595885acb1630bf6df261b026f11a478 | e6847113436c78df897e4f7ad26fce9bd229d636 |
refs/heads/master | <file_sep>/*
convert to pure js
save -g reactify
*/
var React=(window&&window.React)||require("react");
var E=React.createElement;
var hasksanagap=(typeof ksanagap!="undefined");
if (hasksanagap && (typeof console=="undefined" || typeof console.log=="undefined")) {
window.console={log:ksanagap.log,error:ksanagap.error,debug:ksanagap.debug,warn:ksanagap.warn};
console.log("install console output function");
}
var checkfs=function() {
return (navigator && navigator.webkitPersistentStorage) || hasksanagap;
}
var featurechecks={
"fs":checkfs
}
var checkbrowser = React.createClass({
getInitialState:function() {
var missingFeatures=this.getMissingFeatures();
return {ready:false, missing:missingFeatures};
},
getMissingFeatures:function() {
var feature=this.props.feature.split(",");
var status=[];
feature.map(function(f){
var checker=featurechecks[f];
if (checker) checker=checker();
status.push([f,checker]);
});
return status.filter(function(f){return !f[1]});
},
downloadbrowser:function() {
window.location="https://www.google.com/chrome/"
},
renderMissing:function() {
var showMissing=function(m) {
return E("div", null, m);
}
return (
E("div", {ref: "dialog1", className: "modal fade", "data-backdrop": "static"},
E("div", {className: "modal-dialog"},
E("div", {className: "modal-content"},
E("div", {className: "modal-header"},
E("button", {type: "button", className: "close", "data-dismiss": "modal", "aria-hidden": "true"}, "×"),
E("h4", {className: "modal-title"}, "Browser Check")
),
E("div", {className: "modal-body"},
E("p", null, "Sorry but the following feature is missing"),
this.state.missing.map(showMissing)
),
E("div", {className: "modal-footer"},
E("button", {onClick: this.downloadbrowser, type: "button", className: "btn btn-primary"}, "Download Google Chrome")
)
)
)
)
);
},
renderReady:function() {
return E("span", null, "browser ok")
},
render:function(){
return (this.state.missing.length)?this.renderMissing():this.renderReady();
},
componentDidMount:function() {
if (!this.state.missing.length) {
this.props.onReady();
} else {
$(this.refs.dialog1.getDOMNode()).modal('show');
}
}
});
module.exports=checkbrowser;<file_sep>var appname="installer";
if (typeof ksana=="undefined") {
window.ksana={platform:"chrome"};
if (typeof process!=="undefined" &&
process.versions && process.versions["node-webkit"]) {
window.ksana.platform="node-webkit";
}
}
var switchApp=function(path) {
var fs=require("fs");
path="../"+path;
appname=path;
document.location.href= path+"/index.html";
process.chdir(path);
}
var downloader={};
var rootPath="";
var deleteApp=function(app) {
console.error("not allow on PC, do it in File Explorer/ Finder");
}
var username=function() {
return "";
}
var useremail=function() {
return ""
}
var runtime_version=function() {
return "1.4";
}
//copy from liveupdate
var jsonp=function(url,dbid,callback,context) {
var script=document.getElementById("jsonp2");
if (script) {
script.parentNode.removeChild(script);
}
window.jsonp_handler=function(data) {
if (typeof data=="object") {
data.dbid=dbid;
callback.apply(context,[data]);
}
}
window.jsonp_error_handler=function() {
console.error("url unreachable",url);
callback.apply(context,[null]);
}
script=document.createElement('script');
script.setAttribute('id', "jsonp2");
script.setAttribute('onerror', "jsonp_error_handler()");
url=url+'?'+(new Date().getTime());
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
var loadKsanajs=function(){
if (typeof process!="undefined" && !process.browser) {
var ksanajs=require("fs").readFileSync("./ksana.js","utf8").trim();
downloader=require("./downloader");
ksana.js=JSON.parse(ksanajs.substring(14,ksanajs.length-1));
rootPath=process.cwd();
rootPath=require("path").resolve(rootPath,"..").replace(/\\/g,"/")+'/';
ksana.ready=true;
} else{
var url=window.location.origin+window.location.pathname.replace("index.html","")+"ksana.js";
jsonp(url,appname,function(data){
ksana.js=data;
ksana.ready=true;
});
}
}
loadKsanajs();
var boot=function(appId,cb) {
if (typeof appId=="function") {
cb=appId;
appId="unknownapp";
}
if (!ksana.js && ksana.platform=="node-webkit") {
loadKsanajs();
}
ksana.appId=appId;
if (ksana.ready) {
cb();
return;
}
var timer=setInterval(function(){
if (ksana.ready){
clearInterval(timer);
cb();
}
},100);
}
var ksanagap={
platform:"node-webkit",
startDownload:downloader.startDownload,
downloadedByte:downloader.downloadedByte,
downloadingFile:downloader.downloadingFile,
cancelDownload:downloader.cancelDownload,
doneDownload:downloader.doneDownload,
switchApp:switchApp,
rootPath:rootPath,
deleteApp: deleteApp,
username:username, //not support on PC
useremail:username,
runtime_version:runtime_version,
boot:boot
}
module.exports=ksanagap;<file_sep>var started=false;
var timer=null;
var bundledate=null;
var get_date=require("./html5fs").get_date;
var checkIfBundleUpdated=function() {
get_date("bundle.js",function(date){
if (bundledate &&bundledate!=date){
location.reload();
}
bundledate=date;
});
}
var livereload=function() {
if(window.location.origin.indexOf("//127.0.0.1")===-1) return;
if (started) return;
timer1=setInterval(function(){
checkIfBundleUpdated();
},2000);
started=true;
}
module.exports=livereload;<file_sep>var ksana={"platform":"remote"};
if (typeof window!="undefined") {
window.ksana=ksana;
if (typeof ksanagap=="undefined") {
window.ksanagap=require("./ksanagap"); //compatible layer with mobile
}
}
if (typeof process !="undefined") {
if (process.versions && process.versions["node-webkit"]) {
if (typeof nodeRequire!="undefined") ksana.require=nodeRequire;
ksana.platform="node-webkit";
window.ksanagap.platform="node-webkit";
var ksanajs=require("fs").readFileSync("ksana.js","utf8").trim();
ksana.js=JSON.parse(ksanajs.substring(14,ksanajs.length-1));
window.kfs=require("./kfs");
}
} else if (typeof chrome!="undefined"){//} && chrome.fileSystem){
// window.ksanagap=require("./ksanagap"); //compatible layer with mobile
window.ksanagap.platform="chrome";
window.kfs=require("./kfs_html5");
if(window.location.origin.indexOf("//1172.16.58.3")>-1) {
require("./livereload")();
}
ksana.platform="chrome";
} else {
if (typeof ksanagap!="undefined" && typeof fs!="undefined") {//mobile
var ksanajs=fs.readFileSync("ksana.js","utf8").trim(); //android extra \n at the end
ksana.js=JSON.parse(ksanajs.substring(14,ksanajs.length-1));
ksana.platform=ksanagap.platform;
if (typeof ksanagap.android !="undefined") {
ksana.platform="android";
}
}
}
var timer=null;
var React=window.React||require("react");
var boot=function(appId,opts,cb) {
if (typeof opts=="function") {
cb=opts;
opts={};
}
ksanagap.bootopts=opts;
if (typeof React!="undefined") {
if (React.initializeTouchEvents) React.initializeTouchEvents(true);
}
ksana.appId=appId;
if (ksanagap.platform=="chrome") { //need to wait for jsonp ksana.js
timer=setInterval(function(){
if (ksana.ready){
clearInterval(timer);
if ( (opts.chromeFileSystem) && ksana.js && ksana.js.files && ksana.js.files.length) {
require("./installkdb")(ksana.js,cb);
} else {
cb();
}
}
},300);
} else {
cb();
}
}
module.exports={boot:boot
,htmlfs:require("./htmlfs")
,html5fs:require("./html5fs")
,liveupdate:require("./liveupdate")
,fileinstaller:require("./fileinstaller")
,downloader:require("./downloader")
,installkdb:require("./installkdb")
};<file_sep>
var jsonp=function(url,dbid,callback,context) {
var script=document.getElementById("jsonp");
if (script) {
script.parentNode.removeChild(script);
}
if (typeof dbid=="function") {
context=callback;
callback=dbid;
dbid="";
}
window.jsonp_handler=function(data) {
//console.log("receive from ksana.js",data);
if (typeof data=="object" && dbid) {
if (typeof data.dbid=="undefined") {
data.dbid=dbid;
}
}
callback.apply(context,[data]);
}
window.jsonp_error_handler=function() {
console.error("url unreachable",url);
callback.apply(context,[null]);
}
script=document.createElement('script');
script.setAttribute('id', "jsonp");
script.setAttribute('onerror', "jsonp_error_handler()");
url=url+'?'+(new Date().getTime());
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
var runtime_version_ok=function(minruntime) {
if (!minruntime) return true;//not mentioned.
var min=parseFloat(minruntime);
var runtime=parseFloat( ksanagap.runtime_version()||"1.0");
if (min>runtime) return false;
return true;
}
var needToUpdate=function(fromjson,tojson) {
var needUpdates=[];
for (var i=0;i<fromjson.length;i++) {
var to=tojson[i];
var from=fromjson[i];
var newfiles=[],newfilesizes=[],removed=[];
if (!to || !to.files) continue; //cannot reach host
if (!runtime_version_ok(to.minruntime)) {
console.warn("runtime too old, need "+to.minruntime);
continue;
}
if (!from.filedates) {
console.warn("missing filedates in ksana.js of "+from.dbid);
continue;
}
from.filedates.map(function(f,idx){
var newidx=to.files.indexOf( from.files[idx]);
if (newidx==-1) {
//file removed in new version
removed.push(from.files[idx]);
} else {
var fromdate=Date.parse(f);
var todate=Date.parse(to.filedates[newidx]);
if (fromdate<todate) {
newfiles.push( to.files[newidx] );
newfilesizes.push(to.filesizes[newidx]);
}
}
});
if (newfiles.length) {
from.newfiles=newfiles;
from.newfilesizes=newfilesizes;
from.removed=removed;
needUpdates.push(from);
}
}
return needUpdates;
}
var getUpdatables=function(apps,cb,context) {
getRemoteJson(apps,function(jsons){
var hasUpdates=needToUpdate(apps,jsons);
cb.apply(context,[hasUpdates]);
},context);
}
var getRemoteJson=function(apps,cb,context) {
var taskqueue=[],output=[];
var makecb=function(app){
return function(data){
if (!(data && typeof data =='object' && data.__empty)) output.push(data);
if (!app.baseurl) {
taskqueue.shift({__empty:true});
} else {
var url=app.baseurl+"/ksana.js";
try {
jsonp( url ,app.dbid,taskqueue.shift(), context);
} catch(e) {
console.log(e);
taskqueue.shift({__empty:true});
}
}
};
};
apps.forEach(function(app){taskqueue.push(makecb(app))});
taskqueue.push(function(data){
output.push(data);
cb.apply(context,[output]);
});
taskqueue.shift()({__empty:true}); //run the task
}
var humanFileSize=function(bytes, si) {
var thresh = si ? 1000 : 1024;
if(bytes < thresh) return bytes + ' B';
var units = si ? ['kB','MB','GB','TB','PB','EB','ZB','YB'] : ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];
var u = -1;
do {
bytes /= thresh;
++u;
} while(bytes >= thresh);
return bytes.toFixed(1)+' '+units[u];
};
var humanDate=function(datestring) {
var d=Date.parse(datestring);
if (isNaN(d)) {
return "invalid date";
} else {
return new Date(d).toLocaleString();
}
}
var start=function(ksanajs,cb,context){
var files=ksanajs.newfiles||ksanajs.files;
var baseurl=ksanajs.baseurl|| "http://127.0.0.1:8080/"+ksanajs.dbid+"/";
var started=ksanagap.startDownload(ksanajs.dbid,baseurl,files.join("\uffff"));
cb.apply(context,[started]);
}
var status=function(){
var nfile=ksanagap.downloadingFile();
var downloadedByte=ksanagap.downloadedByte();
var done=ksanagap.doneDownload();
return {nfile:nfile,downloadedByte:downloadedByte, done:done};
}
var cancel=function(){
return ksanagap.cancelDownload();
}
var liveupdate={ humanFileSize: humanFileSize, humanDate:humanDate,
needToUpdate: needToUpdate , jsonp:jsonp,
getUpdatables:getUpdatables,
start:start,
cancel:cancel,
status:status
};
module.exports=liveupdate;<file_sep>var React=require("react");
//var mui=require("material-ui");
var E=React.createElement;
var html5fs=require("./html5fs");
var FileList = React.createClass({
getInitialState:function() {
return {downloading:false,progress:0};
},
updatable:function(f) {
var classes="btn btn-warning";
if (this.state.downloading) classes+=" disabled";
if (f.hasUpdate) return E("button", {className: classes,
"data-filename": f.filename, "data-url": f.url,
onClick: this.download
}, "Update")
else return null;
},
showLocal:function(f) {
var classes="btn btn-danger";
if (this.state.downloading) classes+=" disabled";
return E("tr", null, E("td", null, f.filename),
E("td", null),
E("td", {className: "pull-right"},
this.updatable(f), E("button", {className: classes,
onClick: this.deleteFile, "data-filename": f.filename}, "Delete")
)
)
},
showRemote:function(f) {
var classes="btn btn-warning";
if (this.state.downloading) classes+=" disabled";
return (E("tr", {"data-id": f.filename}, E("td", null,
f.filename),
E("td", null, f.desc),
E("td", null,
E("button", {"data-filename": f.filename, "data-url": f.url,
className: classes,
onClick: this.download}, "Download")
)
));
},
showFile:function(f) {
// return <span data-id={f.filename}>{f.url}</span>
return (f.ready)?this.showLocal(f):this.showRemote(f);
},
reloadDir:function() {
this.props.action("reload");
},
download:function(e) {
var url=e.target.dataset["url"];
var filename=e.target.dataset["filename"];
this.setState({downloading:true,progress:0,url:url});
this.userbreak=false;
html5fs.download(url,filename,function(){
this.reloadDir();
this.setState({downloading:false,progress:1});
},function(progress,total){
if (progress==0) {
this.setState({message:"total "+total})
}
this.setState({progress:progress});
//if user press abort return true
return this.userbreak;
}
,this);
},
deleteFile:function( e) {
var filename=e.target.attributes["data-filename"].value;
this.props.action("delete",filename);
},
allFilesReady:function(e) {
return this.props.files.every(function(f){ return f.ready});
},
abortdownload:function() {
this.userbreak=true;
},
showProgress:function() {
if (this.state.downloading) {
var progress=Math.round(this.state.progress*100);
return (
E("div", null,
"Downloading from ", this.state.url,
E("div", {key: "progress", className: "progress col-md-8"},
E("div", {className: "progress-bar", role: "progressbar",
"aria-valuenow": progress, "aria-valuemin": "0",
"aria-valuemax": "100", style: {width: progress+"%"}},
progress, "%"
)
),
E("button", {onClick: this.abortdownload,
className: "btn btn-danger col-md-4"}, "Abort")
)
);
} else {
if ( this.allFilesReady() ) {
return E("button", {onClick: this.dismiss, className: "btn btn-success"}, "Ok")
} else return null;
}
},
showUsage:function() {
var percent=this.props.remainPercent;
return E("span", null, "remaining space "+percent+"%");
},
onToggle:function(e,idx,toggle) {
console.log("toggle",idx);
}
,buildmenuitems:function(files) {
var out=[];
for (var i=0;i<files.length;i++) {
var f=files[i];
out.push({
payload:i,
text:this.showFile(f),
toggle:true, defaultToggled: f.ready
});
}
return out;
}
,render:function() {
return (
E("div", {ref: "dialog1", className: "modal fade", "data-backdrop": "static"},
E("div", {className: "modal-dialog"},
E("div", {className: "modal-content"},
E("div", {className: "modal-header"},
E("h4", {className: "modal-title"}, "File Installer")
),
E("div", {className: "modal-body"},
E("table", {className: "table"},
E("tbody", null,
this.props.files.map(this.showFile)
)
)
),
E("div", {className: "modal-footer"},
this.showUsage(),
this.showProgress()
)
)
)
)
);
},
componentDidMount:function() {
}
});
module.exports=FileList;<file_sep>/* todo , optional kdb */
var React=(window&&window.React)||require("react");
var HtmlFS=require("./htmlfs");
var html5fs=require("./html5fs");
var CheckBrowser=require("./checkbrowser");
var E=React.createElement;
var FileList=null;
/*TODO kdb check version*/
var Filemanager = React.createClass({
getInitialState:function() {
var quota=this.getQuota();
return {browserReady:false,noupdate:true, requestQuota:quota,remain:0};
},
componentWillMount:function(){
if (ksanagap.bootopts.material) FileList=require("./filelist_mui");
else FileList=require("./filelist");
},
getQuota:function() {
var q=this.props.quota||"128M";
var unit=q[q.length-1];
var times=1;
if (unit=="M") times=1024*1024;
else if (unit="K") times=1024;
return parseInt(q) * times;
},
missingKdb:function() {
if (ksanagap.platform!="chrome") return [];
var missing=this.props.needed.filter(function(kdb){
for (var i in html5fs.files) {
if (html5fs.files[i][0]==kdb.filename) return false;
}
return true;
},this);
return missing;
},
getRemoteUrl:function(fn) {
var f=this.props.needed.filter(function(f){return f.filename==fn});
if (f.length ) return f[0].url;
},
genFileList:function(existing,missing){
var out=[];
for (var i in existing) {
var url=this.getRemoteUrl(existing[i][0]);
out.push({filename:existing[i][0], url :url, ready:true });
}
for (var i in missing) {
out.push(missing[i]);
}
return out;
},
reload:function() {
html5fs.readdir(function(files){
this.setState({files:this.genFileList(files,this.missingKdb())});
},this);
},
deleteFile:function(fn) {
html5fs.rm(fn,function(){
this.reload();
},this);
},
onQuoteOk:function(quota,usage) {
if (ksanagap.platform!="chrome") {
//console.log("onquoteok");
this.setState({noupdate:true,missing:[],files:[],autoclose:true
,quota:quota,remain:quota-usage,usage:usage});
return;
}
//console.log("quote ok");
var files=this.genFileList(html5fs.files,this.missingKdb());
var that=this;
that.checkIfUpdate(files,function(hasupdate) {
var missing=this.missingKdb();
var autoclose=this.props.autoclose;
if (missing.length) autoclose=false;
that.setState({autoclose:autoclose,
quota:quota,usage:usage,files:files,
missing:missing,
noupdate:!hasupdate,
remain:quota-usage});
});
},
onBrowserOk:function() {
this.totalDownloadSize();
},
dismiss:function() {
this.props.onReady(this.state.usage,this.state.quota);
setTimeout(function(){
if (typeof $ !== "undefined") {
var modalin=$(".modal.in");
if (modalin.modal) modalin.modal('hide');
}
},500);
},
totalDownloadSize:function() {
var files=this.missingKdb();
var taskqueue=[],totalsize=0;
for (var i=0;i<files.length;i++) {
taskqueue.push(
(function(idx){
return (function(data){
if (!(typeof data=='object' && data.__empty)) totalsize+=data;
html5fs.getDownloadSize(files[idx].url,taskqueue.shift());
});
})(i)
);
}
var that=this;
taskqueue.push(function(data){
totalsize+=data;
setTimeout(function(){that.setState({requireSpace:totalsize,browserReady:true})},0);
});
taskqueue.shift()({__empty:true});
},
checkIfUpdate:function(files,cb) {
var taskqueue=[];
for (var i=0;i<files.length;i++) {
taskqueue.push(
(function(idx){
return (function(data){
if (!(typeof data=='object' && data.__empty)) files[idx-1].hasUpdate=data;
html5fs.checkUpdate(files[idx].url,files[idx].filename,taskqueue.shift());
});
})(i)
);
}
var that=this;
taskqueue.push(function(data){
if (files.length) files[files.length-1].hasUpdate=data;
var hasupdate=files.some(function(f){return f.hasUpdate});
if (cb) cb.apply(that,[hasupdate]);
});
taskqueue.shift()({__empty:true});
},
render:function(){
if (!this.state.browserReady) {
return E(CheckBrowser, {feature: "fs", onReady: this.onBrowserOk})
} if (!this.state.quota || this.state.remain<this.state.requireSpace) {
var quota=this.state.requestQuota;
if (this.state.usage+this.state.requireSpace>quota) {
quota=(this.state.usage+this.state.requireSpace)*1.5;
}
return E(HtmlFS, {quota: quota, autoclose: "true", onReady: this.onQuoteOk})
} else {
if (!this.state.noupdate || this.missingKdb().length || !this.state.autoclose) {
var remain=Math.round((this.state.usage/this.state.quota)*100);
return E(FileList, {action: this.action, files: this.state.files, remainPercent: remain})
} else {
setTimeout( this.dismiss ,0);
return E("span", null, "Success");
}
}
},
action:function() {
var args = Array.prototype.slice.call(arguments);
var type=args.shift();
var res=null, that=this;
if (type=="delete") {
this.deleteFile(args[0]);
} else if (type=="reload") {
this.reload();
} else if (type=="dismiss") {
this.dismiss();
}
}
});
module.exports=Filemanager;<file_sep>/* emulate filesystem on html5 browser */
var get_head=function(url,field,cb){
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url, true);
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
cb(xhr.getResponseHeader(field));
} else {
if (this.status!==200&&this.status!==206) {
cb("");
}
}
};
xhr.send();
}
var get_date=function(url,cb) {
get_head(url,"Last-Modified",function(value){
cb(value);
});
}
var get_size=function(url, cb) {
get_head(url,"Content-Length",function(value){
cb(parseInt(value));
});
};
var checkUpdate=function(url,fn,cb) {
if (!url) {
cb(false);
return;
}
get_date(url,function(d){
API.fs.root.getFile(fn, {create: false, exclusive: false}, function(fileEntry) {
fileEntry.getMetadata(function(metadata){
var localDate=Date.parse(metadata.modificationTime);
var urlDate=Date.parse(d);
cb(urlDate>localDate);
});
},function(){
cb(false);
});
});
}
var download=function(url,fn,cb,statuscb,context) {
var totalsize=0,batches=null,written=0;
var fileEntry=0, fileWriter=0;
var createBatches=function(size) {
var bytes=1024*1024, out=[];
var b=Math.floor(size / bytes);
var last=size %bytes;
for (var i=0;i<=b;i++) {
out.push(i*bytes);
}
out.push(b*bytes+last);
return out;
}
var finish=function() {
rm(fn,function(){
fileEntry.moveTo(fileEntry.filesystem.root, fn,function(){
setTimeout( cb.bind(context,false) , 0) ;
},function(e){
console.log("failed",e)
});
},this);
};
var tempfn="temp.kdb";
var batch=function(b) {
var abort=false;
var xhr = new XMLHttpRequest();
var requesturl=url+"?"+Math.random();
xhr.open('get', requesturl, true);
xhr.setRequestHeader('Range', 'bytes='+batches[b]+'-'+(batches[b+1]-1));
xhr.responseType = 'blob';
xhr.addEventListener('load', function() {
var blob=this.response;
fileEntry.createWriter(function(fileWriter) {
fileWriter.seek(fileWriter.length);
fileWriter.write(blob);
written+=blob.size;
fileWriter.onwriteend = function(e) {
if (statuscb) {
abort=statuscb.apply(context,[ fileWriter.length / totalsize,totalsize ]);
if (abort) setTimeout( cb.bind(context,false) , 0) ;
}
b++;
if (!abort) {
if (b<batches.length-1) setTimeout(batch.bind(context,b),0);
else finish();
}
};
}, console.error);
},false);
xhr.send();
}
get_size(url,function(size){
totalsize=size;
if (!size) {
if (cb) cb.apply(context,[false]);
} else {//ready to download
rm(tempfn,function(){
batches=createBatches(size);
if (statuscb) statuscb.apply(context,[ 0, totalsize ]);
API.fs.root.getFile(tempfn, {create: 1, exclusive: false}, function(_fileEntry) {
fileEntry=_fileEntry;
batch(0);
});
},this);
}
});
}
var readFile=function(filename,cb,context) {
API.fs.root.getFile(filename, {create: false, exclusive: false},function(fileEntry) {
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function(e) {
if (cb) cb.call(cb,this.result);
};
reader.readAsText(file,"utf8");
});
}, console.error);
}
function createDir(rootDirEntry, folders, cb) {
// Throw out './' or '/' and move on to prevent something like '/foo/.//bar'.
if (folders[0] == '.' || folders[0] == '') {
folders = folders.slice(1);
}
rootDirEntry.getDirectory(folders[0], {create: true}, function(dirEntry) {
// Recursively add the new subfolder (if we still have another to create).
if (folders.length) {
createDir(dirEntry, folders.slice(1),cb);
} else {
cb();
}
}, cb);
};
var writeFile=function(filename,buf,cb,context){
var write=function(fileEntry){
fileEntry.createWriter(function(fileWriter) {
fileWriter.write(buf);
fileWriter.onwriteend = function(e) {
if (cb) cb.apply(cb,[buf.byteLength]);
};
}, console.error);
}
var getFile=function(filename){
API.fs.root.getFile(filename, {exclusive:true}, function(fileEntry) {
write(fileEntry);
}, function(){
API.fs.root.getFile(filename, {create:true,exclusive:true}, function(fileEntry) {
write(fileEntry);
});
});
}
var slash=filename.lastIndexOf("/");
if (slash>-1) {
createDir(API.fs.root, filename.substr(0,slash).split("/"),function(){
getFile(filename);
});
} else {
getFile(filename);
}
}
var readdir=function(cb,context) {
var dirReader = API.fs.root.createReader();
var out=[],that=this;
dirReader.readEntries(function(entries) {
if (entries.length) {
for (var i = 0, entry; entry = entries[i]; ++i) {
if (entry.isFile) {
out.push([entry.name,entry.toURL ? entry.toURL() : entry.toURI()]);
}
}
}
API.files=out;
if (cb) cb.apply(context,[out]);
}, function(){
if (cb) cb.apply(context,[null]);
});
}
var getFileURL=function(filename) {
if (!API.files ) return null;
var file= API.files.filter(function(f){return f[0]==filename});
if (file.length) return file[0][1];
}
var rm=function(filename,cb,context) {
var url=getFileURL(filename);
if (url) rmURL(url,cb,context);
else if (cb) cb.apply(context,[false]);
}
var rmURL=function(filename,cb,context) {
webkitResolveLocalFileSystemURL(filename, function(fileEntry) {
fileEntry.remove(function() {
if (cb) cb.apply(context,[true]);
}, console.error);
}, function(e){
if (cb) cb.apply(context,[false]);//no such file
});
}
function errorHandler(e) {
console.error('Error: ' +e.name+ " "+e.message);
}
var initfs=function(grantedBytes,cb,context) {
webkitRequestFileSystem(PERSISTENT, grantedBytes, function(fs) {
API.fs=fs;
API.quota=grantedBytes;
readdir(function(){
API.initialized=true;
cb.apply(context,[grantedBytes,fs]);
},context);
}, errorHandler);
}
var init=function(quota,cb,context) {
if (!navigator.webkitPersistentStorage) return;
navigator.webkitPersistentStorage.requestQuota(quota,
function(grantedBytes) {
initfs(grantedBytes,cb,context);
}, errorHandler
);
}
var queryQuota=function(cb,context) {
var that=this;
navigator.webkitPersistentStorage.queryUsageAndQuota(
function(usage,quota){
initfs(quota,function(){
cb.apply(context,[usage,quota]);
},context);
});
}
var API={
init:init
,readdir:readdir
,checkUpdate:checkUpdate
,rm:rm
,rmURL:rmURL
,getFileURL:getFileURL
,writeFile:writeFile
,readFile:readFile
,download:download
,get_head:get_head
,get_date:get_date
,get_size:get_size
,getDownloadSize:get_size
,queryQuota:queryQuota
}
module.exports=API;
<file_sep>
var userCancel=false;
var files=[];
var totalDownloadByte=0;
var targetPath="";
var tempPath="";
var nfile=0;
var baseurl="";
var result="";
var downloading=false;
var startDownload=function(dbid,_baseurl,_files) { //return download id
var fs = require("fs");
var path = require("path");
files=_files.split("\uffff");
if (downloading) return false; //only one session
userCancel=false;
totalDownloadByte=0;
nextFile();
downloading=true;
baseurl=_baseurl;
if (baseurl[baseurl.length-1]!='/')baseurl+='/';
targetPath=ksanagap.rootPath+dbid+'/';
tempPath=ksanagap.rootPath+".tmp/";
result="";
return true;
}
var nextFile=function() {
setTimeout(function(){
if (nfile==files.length) {
nfile++;
endDownload();
} else {
downloadFile(nfile++);
}
},100);
}
var downloadFile=function(nfile) {
var url=baseurl+files[nfile];
var tmpfilename=tempPath+files[nfile];
var mkdirp = require("./mkdirp");
var fs = require("fs");
var http = require("http");
mkdirp.sync(path.dirname(tmpfilename));
var writeStream = fs.createWriteStream(tmpfilename);
var datalength=0;
var request = http.get(url, function(response) {
response.on('data',function(chunk){
writeStream.write(chunk);
totalDownloadByte+=chunk.length;
if (userCancel) {
writeStream.end();
setTimeout(function(){nextFile();},100);
}
});
response.on("end",function() {
writeStream.end();
setTimeout(function(){nextFile();},100);
});
});
}
var cancelDownload=function() {
userCancel=true;
endDownload();
}
var verify=function() {
return true;
}
var endDownload=function() {
nfile=files.length+1;//stop
result="cancelled";
downloading=false;
if (userCancel) return;
var fs = require("fs");
var mkdirp = require("./mkdirp");
for (var i=0;i<files.length;i++) {
var targetfilename=targetPath+files[i];
var tmpfilename =tempPath+files[i];
mkdirp.sync(path.dirname(targetfilename));
fs.renameSync(tmpfilename,targetfilename);
}
if (verify()) {
result="success";
} else {
result="error";
}
}
var downloadedByte=function() {
return totalDownloadByte;
}
var doneDownload=function() {
if (nfile>files.length) return result;
else return "";
}
var downloadingFile=function() {
return nfile-1;
}
var downloader={startDownload:startDownload, downloadedByte:downloadedByte,
downloadingFile:downloadingFile, cancelDownload:cancelDownload,doneDownload:doneDownload};
module.exports=downloader;<file_sep>
var readDir=function(cb,context){
require("./html5fs").readdir(cb,context);
}
var listApps=function(){
return "[]";
}
module.exports={readDir:readDir,listApps:listApps};<file_sep>var html5fs=require("./html5fs");
var React=(window&&window.React)||require("react");
var E=React.createElement;
var htmlfs = React.createClass({
getInitialState:function() {
return {ready:false, quota:0,usage:0,Initialized:false,autoclose:this.props.autoclose};
},
initFilesystem:function() {
var quota=this.props.quota||1024*1024*128; // default 128MB
quota=parseInt(quota);
html5fs.init(quota,function(q){
this.dialog=false;
$(this.refs.dialog1.getDOMNode()).modal('hide');
this.setState({quota:q,autoclose:true});
},this);
},
welcome:function() {
return (
E("div", {ref: "dialog1", className: "modal fade", id: "myModal", "data-backdrop": "static"},
E("div", {className: "modal-dialog"},
E("div", {className: "modal-content"},
E("div", {className: "modal-header"},
E("h4", {className: "modal-title"}, "Welcome")
),
E("div", {className: "modal-body"},
"Browser will ask for your confirmation."
),
E("div", {className: "modal-footer"},
E("button", {onClick: this.initFilesystem, type: "button",
className: "btn btn-primary"}, "Initialize File System")
)
)
)
)
);
},
renderDefault:function(){
var used=Math.floor(this.state.usage/this.state.quota *100);
var more=function() {
if (used>50) return E("button", {type: "button", className: "btn btn-primary"}, "Allocate More");
else null;
}
return (
E("div", {ref: "dialog1", className: "modal fade", id: "myModal", "data-backdrop": "static"},
E("div", {className: "modal-dialog"},
E("div", {className: "modal-content"},
E("div", {className: "modal-header"},
E("h4", {className: "modal-title"}, "Sandbox File System")
),
E("div", {className: "modal-body"},
E("div", {className: "progress"},
E("div", {className: "progress-bar", role: "progressbar", style: {width: used+"%"}},
used, "%"
)
),
E("span", null, this.state.quota, " total , ", this.state.usage, " in used")
),
E("div", {className: "modal-footer"},
E("button", {onClick: this.dismiss, type: "button", className: "btn btn-default", "data-dismiss": "modal"}, "Close"),
more()
)
)
)
)
);
},
dismiss:function() {
var that=this;
setTimeout(function(){
that.props.onReady(that.state.quota,that.state.usage);
},0);
},
queryQuota:function() {
if (ksanagap.platform=="chrome") {
html5fs.queryQuota(function(usage,quota){
this.setState({usage:usage,quota:quota,initialized:true});
},this);
} else {
this.setState({usage:333,quota:1000*1000*1024,initialized:true,autoclose:true});
}
},
render:function() {
var that=this;
if (!this.state.quota || this.state.quota<this.props.quota) {
if (this.state.initialized) {
this.dialog=true;
return this.welcome();
} else {
return E("span", null, "checking quota");
}
} else {
if (!this.state.autoclose) {
this.dialog=true;
return this.renderDefault();
}
this.dismiss();
this.dialog=false;
return null;
}
},
componentDidMount:function() {
if (!this.state.quota) {
this.queryQuota();
};
},
componentDidUpdate:function() {
if (this.dialog) $(this.refs.dialog1.getDOMNode()).modal('show');
}
});
module.exports=htmlfs;<file_sep>webruntime
==========
| 5a0ceed5548e1f87b977525611c369ef71cb9414 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | ferambot/ksana2015-webruntime | e3c8f1b721d87f3f1d288c0d7e0a9c1f8667f57d | 7853510d3ae90c70bdd0a0425b50572f99625165 |
refs/heads/master | <file_sep>var app = getApp();
Page({
data: {
mainHeight: (app.globalData.winHeight - 45) * 2 + "rpx",
now_index: 0,
active: "active",
dataOne: [{
id: "132",
type_name: "瓜果蔬菜"
}, {
id: "132",
type_name: "瓜果蔬菜"
},{
id: "132",
type_name: "瓜果蔬菜"
}, {
id: "132",
type_name: "瓜果蔬菜"
},{
id: "132",
type_name: "瓜果蔬菜"
}, {
id: "132",
type_name: "瓜果蔬菜"
},{
id: "132",
type_name: "瓜果蔬菜"
}, {
id: "132",
type_name: "瓜果蔬菜"
},{
id: "132",
type_name: "瓜果蔬菜"
}, {
id: "132",
type_name: "瓜果蔬菜"
},{
id: "132",
type_name: "瓜果蔬菜"
}, {
id: "132",
type_name: "瓜果蔬菜"
}],
dataTwo: [
[{
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
},{
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
},{
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
},{
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
},{
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/1434354240633.jpg",
type_name: "茎叶类"
}],
[{
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/143805363671.jpg",
type_name: "豆制品"
}, {
id: "133",
image_path: "https://www.shicaionline.com/image/goods_type/143805363671.jpg",
type_name: "豆制品"
}]
]
},
addActive: function(e) {
var now_index = e.target.dataset.index;
this.setData({ now_index, now_index });
},
onLoad: function() {
console.log('load-index');
},
onShow: function() {
console.log('show-index');
}
});
<file_sep>var app = getApp();
Page({
data: {
foodAll: [{
goods_describe: "大白菜(约3-5斤/棵)约3-5斤/棵,叶茎洁白、叶面嫩绿,鲜绿紧实,大小均匀,极少或无黑点",
goods_name: "大白菜(约3-5斤/棵)",
id: "2101",
image_path: "https://www.shicaionline.com/image/goods/1468664023184.jpg",
is_favorite: 0,
is_gift: "0",
is_seckill_offer: "0",
is_special_offer: "1",
max_qty: "0.00",
min_qty: "4.00",
on_sales: "1",
price: "1.48",
sales_volume: "546311",
small_image_path: "https://www.shicaionline.com/image/goods/1468664023184_150.jpg",
special_count: "305",
special_limit: "0",
special_offer_end: "1482681600",
special_offer_price: "1.33",
special_offer_start: "1482422400",
type_id: "133",
unit_id: "2",
unit_name: "斤"
},{
goods_describe: "大白菜(约3-5斤/棵)约3-5斤/棵,叶茎洁白、叶面嫩绿,鲜绿紧实,大小均匀,极少或无黑点",
goods_name: "大白菜(约3-5斤/棵)",
id: "2101",
image_path: "https://www.shicaionline.com/image/goods/1468664023184.jpg",
is_favorite: 0,
is_gift: "0",
is_seckill_offer: "0",
is_special_offer: "1",
max_qty: "0.00",
min_qty: "4.00",
on_sales: "1",
price: "1.48",
sales_volume: "546311",
small_image_path: "https://www.shicaionline.com/image/goods/1468664023184_150.jpg",
special_count: "305",
special_limit: "0",
special_offer_end: "1482681600",
special_offer_price: "1.33",
special_offer_start: "1482422400",
type_id: "133",
unit_id: "2",
unit_name: "斤"
},{
goods_describe: "大白菜(约3-5斤/棵)约3-5斤/棵,叶茎洁白、叶面嫩绿,鲜绿紧实,大小均匀,极少或无黑点",
goods_name: "大白菜(约3-5斤/棵)",
id: "2101",
image_path: "https://www.shicaionline.com/image/goods/1468664023184.jpg",
is_favorite: 0,
is_gift: "0",
is_seckill_offer: "0",
is_special_offer: "1",
max_qty: "0.00",
min_qty: "4.00",
on_sales: "1",
price: "1.48",
sales_volume: "546311",
small_image_path: "https://www.shicaionline.com/image/goods/1468664023184_150.jpg",
special_count: "305",
special_limit: "0",
special_offer_end: "1482681600",
special_offer_price: "1.33",
special_offer_start: "1482422400",
type_id: "133",
unit_id: "2",
unit_name: "斤"
},{
goods_describe: "大白菜(约3-5斤/棵)约3-5斤/棵,叶茎洁白、叶面嫩绿,鲜绿紧实,大小均匀,极少或无黑点",
goods_name: "大白菜(约3-5斤/棵)",
id: "2101",
image_path: "https://www.shicaionline.com/image/goods/1468664023184.jpg",
is_favorite: 0,
is_gift: "0",
is_seckill_offer: "0",
is_special_offer: "1",
max_qty: "0.00",
min_qty: "4.00",
on_sales: "1",
price: "1.48",
sales_volume: "546311",
small_image_path: "https://www.shicaionline.com/image/goods/1468664023184_150.jpg",
special_count: "305",
special_limit: "0",
special_offer_end: "1482681600",
special_offer_price: "1.33",
special_offer_start: "1482422400",
type_id: "133",
unit_id: "2",
unit_name: "斤"
}],
more:[{
goods_describe: "大白菜(约3-5斤/棵)约3-5斤/棵,叶茎洁白、叶面嫩绿,鲜绿紧实,大小均匀,极少或无黑点",
goods_name: "大白菜(约3-5斤/棵)",
id: "2101",
image_path: "https://www.shicaionline.com/image/goods/1468664910709.jpg",
is_favorite: 0,
is_gift: "0",
is_seckill_offer: "0",
is_special_offer: "1",
max_qty: "0.00",
min_qty: "4.00",
on_sales: "1",
price: "1.48",
sales_volume: "546311",
small_image_path: "https://www.shicaionline.com/image/goods/1468664910709_150.jpg",
special_count: "305",
special_limit: "0",
special_offer_end: "1482681600",
special_offer_price: "1.33",
special_offer_start: "1482422400",
type_id: "133",
unit_id: "2",
unit_name: "斤"
},{
goods_describe: "大白菜(约3-5斤/棵)约3-5斤/棵,叶茎洁白、叶面嫩绿,鲜绿紧实,大小均匀,极少或无黑点",
goods_name: "大白菜(约3-5斤/棵)",
id: "2101",
image_path: "https://www.shicaionline.com/image/goods/1468664910709.jpg",
is_favorite: 0,
is_gift: "0",
is_seckill_offer: "0",
is_special_offer: "1",
max_qty: "0.00",
min_qty: "4.00",
on_sales: "1",
price: "1.48",
sales_volume: "546311",
small_image_path: "https://www.shicaionline.com/image/goods/1468664910709_150.jpg",
special_count: "305",
special_limit: "0",
special_offer_end: "1482681600",
special_offer_price: "1.33",
special_offer_start: "1482422400",
type_id: "133",
unit_id: "2",
unit_name: "斤"
}],
nowNum:"0",
flag:true,
is_coll:"../../../../image/cancel-coll.png",
mainHeight:app.globalData.winHeight,
foodFlag:true
},
collection:function(e){
if(this.data.is_coll == "../../../../image/cancel-coll.png"){
this.setData({ is_coll:"../../../../image/active-coll.png" });
}else{
this.setData({ is_coll:"../../../../image/cancel-coll.png" });
}
},
addQty:function(e){
if(e.target.dataset.nowNum == "")return;
var nowNum = e.target.dataset.nowNum >= 999 ? 999 : Number(e.target.dataset.nowNum) + 1;
this.setData({ nowNum:nowNum });
},
subQty:function(e){
if(e.target.dataset.nowNum == "")return;
var nowNum = e.target.dataset.nowNum <= 0 ? 0 : Number(e.target.dataset.nowNum) - 1;
this.setData({ nowNum:nowNum });
},
changeNum:function(e){
var nowNum = e.detail.value;
this.setData({ nowNum:nowNum });
},
bigShow:function(e){
var arr = e.target.dataset.bigArea.split("?");
var bigArea = {
name:arr[0],
describe:arr[1],
price:arr[2],
unit_name:arr[3],
image_path:arr[4]
}
this.setData({bigArea:bigArea,flag:false,foodFlag:false});
},
closeShow:function(e){
this.setData({flag:true,foodFlag:true});
},
onLoad: function() {
console.log("load-often");
},
onShow: function() {
console.log("show-often");
},
goBack: function() {
wx.navigateBack({ delta: 1 });
},
loadMore:function(){
let that = this;
let flag = false;
let foodAll = this.data.foodAll;
foodAll = foodAll.concat(this.data.more);
this.setData({foodAll,flag});
setTimeout(function(){
flag = true;
that.setData({flag});
},500)
}
})
<file_sep>const filter = require("../../../util/filter.js");
const app = getApp();
Page({
data: {
winWidth:app.globalData.winWidth,
goods: [{
created: "1484103768",
goods_id: "549",
goods_name: "京包菜(去外叶)",
id: "4641935",
image_path: "https://www.shicaionline.com/image/goods/1468661446479.jpg",
is_seckill_offer: "0",
is_special_offer: "0",
max_qty: "0.00",
min_qty: "2.00",
modi_time: "1484103768",
on_sales: "1",
price: "2.28",
qty: "2",
small_image_path: "https://www.shicaionline.com/image/goods/1468661446479_150.jpg",
special_count: "588",
special_limit: "0",
special_offer_end: "1483718400",
special_offer_price: "2.28",
special_offer_start: "1483459200",
type_id: "133",
unit_name: "斤",
user_id: "16082"
},{
created: "1484103768",
goods_id: "539",
goods_name: "包菜(去外叶)",
id: "4641934",
image_path: "https://www.shicaionline.com/image/goods/1468661446479.jpg",
is_seckill_offer: "0",
is_special_offer: "0",
max_qty: "0.00",
min_qty: "2.00",
modi_time: "1484103768",
on_sales: "1",
price: "1.28",
qty: "2",
small_image_path: "https://www.shicaionline.com/image/goods/1468661446479_150.jpg",
special_count: "588",
special_limit: "0",
special_offer_end: "1483718400",
special_offer_price: "2.28",
special_offer_start: "1483459200",
type_id: "133",
unit_name: "斤",
user_id: "16082"
}],
flag: true,
arrTotal: [],
arrQty: [],
arrPrice:[],
isSelect:[],
allSelect:false,
allRemove:[],
allNoRemove:[],
noRemoveUrl:'../../../image/car-circle.png',
removeUrl:'../../../image/pay-select.png'
},
addQty: function(e) {
let qty = e.target.dataset.qty >= 999 ? 999 : Number(e.target.dataset.qty) + 1;
this.changeQty(e,qty);
},
subQty:function(e) {
let qty = e.target.dataset.qty <= 0 ? 0 : Number(e.target.dataset.qty) - 1;
this.changeQty(e,qty);
},
changeQty:function(e,qty){
let index = e.target.dataset.index;
let arrQty = this.data.arrQty;
let arrTotal = this.data.arrTotal;
arrQty[index] = qty;
arrTotal[index] = filter.addzero(filter.accMul(this.data.arrPrice[index],qty));
this.setData({ arrQty ,arrTotal});
},
edit: function() {
this.setData({ flag: false });
},
finish: function() {
this.setData({ flag: true });
},
removeSelf:function(e){
let isRemove = !e.target.dataset.isRemove;
let index = e.target.dataset.index;
let isSelect = this.data.isSelect;
isSelect[index] = isRemove;
this.setData({ isSelect});
},
removeAll:function(e){
let allSelect = !this.data.allSelect;
let isSelect = this.data.allSelect?this.data.allRemove:this.data.allNoRemove;
this.setData({isSelect,allSelect});
},
removeGoods:function(e){
let allIndex = [];
let goods = this.data.goods;
let arrTotal = this.data.arrTotal;
let arrQty = this.data.arrQty;
let arrPrice = this.data.arrPrice;
let isSelect = this.data.isSelect;
let allRemove = this.data.allRemove;
let allNoRemove = this.data.allNoRemove;
let flag = true;
this.data.isSelect.forEach((item,index)=>{item&&allIndex.push(index)});
allIndex.forEach((item,index)=>{
goods.splice(item-index,1);
arrTotal.splice(item-index,1);
arrQty.splice(item-index,1);
arrPrice.splice(item-index,1);
isSelect.splice(item-index,1);
allRemove.splice(item-index,1);
allNoRemove.splice(item-index,1);
});
console.log(goods);
this.setData({goods,arrTotal,arrQty,arrPrice,isSelect,allRemove,allNoRemove,flag});
},
onLoad: function() {
let arrTotal = [];
let arrQty = [];
let arrPrice = [];
let isSelect = [];
let allRemove = [];
let allNoRemove = [];
this.data.goods.forEach(function(item, index) {
arrTotal.push(filter.addzero(filter.accMul(item.price, item.qty)));
arrQty.push(item.qty);
arrPrice.push(item.price);
isSelect.push(false);
allRemove.push(false);
allNoRemove.push(true);
});
this.setData({ arrTotal,arrQty,arrPrice,isSelect ,allRemove,allNoRemove});
},
onShow: function() {
}
});
<file_sep>var app = getApp();
Page({
data: {
mainWidth:app.globalData.winWidth,
imgUrl: ["https://gz.shicaionline.com/uploads/images/mobile/ad/20170118_1484732314_706243.jpg",
"https://gz.shicaionline.com/uploads/images/mobile/ad/20170117_1484619713_836307.jpg"
],
mainList: [{
url: "../../image/often-buy.png",
text: "我常买",
toUrl:"activity-pages/often-buy/often-buy"
}, {
url: "../../image/my-order.png",
text: "我的订单",
toUrl:""
}, {
url: "../../image/special-mai.png",
text: "限量特价",
toUrl:""
}, {
url: "../../image/index-coll.png",
text: "我的收藏",
toUrl:""
}],
special: {
specialFlag: false,
specialImg: "https://gz.shicaionline.com/uploads/images/mobile/activity/95fd33f9853f812e3b7aba426fb570c1/1480563644_868789.jpg"
},
hotGoods: [{
url: "https://gz.shicaionline.com/image/goods/148204670426_150.jpg",
name: "莴笋(青皮...",
price: "2.28"
}, {
url: "https://gz.shicaionline.com/image/goods/148204670426_150.jpg",
name: "莴笋(青皮...",
price: "2.28"
}, {
url: "https://gz.shicaionline.com/image/goods/148204670426_150.jpg",
name: "莴笋(青皮...",
price: "2.28"
}, {
url: "https://gz.shicaionline.com/image/goods/148204670426_150.jpg",
name: "莴笋(青皮...",
price: "2.28"
}]
},
onLoad: function() {
console.log('load-index');
},
onShow: function() {
console.log('show-index');
}
})
<file_sep>var winHeight,winWidth;
wx.getSystemInfo({
success: function(res) {
/*console.log(res.model)
console.log(res.pixelRatio)
console.log(res.windowWidth)
console.log(res.windowHeight)
console.log(res.language)
console.log(res.version);*/
winWidth = res.windowWidth;
winHeight = res.windowHeight;
}
});
App({
onLaunch: function () {
//console.log('食材在线')
},
onShow: function () {
//console.log('App Show')
},
onHide: function () {
//console.log('App Hide')
},
globalData: {
winWidth,
winHeight,
hasLogin: false
}
})
| 8b6148b8f1db1130eee23e50971fda7d9949959d | [
"JavaScript"
] | 5 | JavaScript | sssLong/lianxi | 71f8ac56e3f0212bf91df23d17f5458eb344b939 | 60e12a9995256e0304c14f5a02b8314fdf1b3fba |
refs/heads/master | <file_sep>import socket
import sys
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('',10000))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print 'received data: ', data
conn.send(data)
conn.close
<file_sep>import cv
import cv2
import GlobalSettings
from camera import Uncalibrated
def CompositeShow(windowName, camera, image, pts=[]):
global Uncalibrated
if not GlobalSettings.imdebug:
return image
cv2.namedWindow(windowName)
comp = image.copy() #cv.CloneImage(image)
if(Uncalibrated):
CalibrateCameras(comp)
Uncalibrated = False
if(GlobalSettings.showGrid):
#draw lines
#p1 - p2
cv2.line(comp, tuple(camera.calibrationmarkers[0].pos), \
tuple(camera.calibrationmarkers[1].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)
#p1 - p4
cv2.line(comp, tuple(camera.calibrationmarkers[0].pos), \
tuple(camera.calibrationmarkers[3].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)
#p3 - p4
cv2.line(comp, tuple(camera.calibrationmarkers[2].pos), \
tuple(camera.calibrationmarkers[3].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)
#p2 - p3
cv2.line(comp, tuple(camera.calibrationmarkers[1].pos), \
tuple(camera.calibrationmarkers[2].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)
for pt in pts:
cv2.circle(comp, (int(pt[0]), int(pt[1])), 10, cv.Scalar(0, 0, 255), thickness=-1)
cv2.imshow(windowName, comp)
return cv2.resize(comp, (640, 480))
<file_sep>import curses, math, time, traceback
from curses import wrapper
amplitude = 2
#stdscr = curses.initscr()
current_milli_time = lambda: time.time()
def wavePtAt(t, amplitude, offset):
return amplitude*math.sin(t+offset)
def nextN(t, n=10, phase=1.5):
global amplitude
vals = []
for i in range(n):
vals.append(wavePtAt(t, amplitude, (phase*i)))
return vals
#screen = None
def curses_main(stdscr):
# Frame the interface area at fixed VT100 size
#global screen
#screen = stdscr.subwin(7, 12, 30, 12)
stdscr.resize(7, 12)
#stdscr.mvwin(30, 12)
stdscr.box()
stdscr.refresh();
stdscr.addstr(1, 1, "hello")
stdscr.addstr(2, 1, "world")
while(True):
t = current_milli_time()
dat = nextN(t)
lines = printWave(dat)
i = 1
for line in lines:
stdscr.addstr(i, 1, line)
i = i + 1
stdscr.refresh()
#stdscr.getkey()
# Define the topbar menus
# file_menu = ("File", "file_func()")
# proxy_menu = ("Proxy Mode", "proxy_func()")
# doit_menu = ("Do It!", "doit_func()")
# help_menu = ("Help", "help_func()")
# exit_menu = ("Exit", "EXIT")
# # Add the topbar menus to screen object
# topbar_menu((file_menu, proxy_menu, doit_menu,
# help_menu, exit_menu))
# # Enter the topbar menu loop
# while topbar_key_handler():
# draw_dict()
def printWave(arr, amplitude=2):
lines = []
arr2 = map(int, map(round, arr))
#print arr2
amplitude_i = amplitude
while(amplitude_i >= -amplitude):
s= ""
indices = [i for i, x in enumerate(arr2) if x == amplitude_i]
#print indices
if len(indices) > 0:
ind = indices[0]
s = s + (" "*ind) + "*"
i = 1
while i < len(indices):
next_ind = indices[i]
spcs = next_ind-ind-1 #extra -1 is for the star we just placed
s = s + (" "*spcs) + "*"
ind = next_ind
i = i + 1
lines.append(s.ljust(len(arr)))
amplitude_i = amplitude_i - 1
#convert to ints
return lines
def main(stdscr):
# Clear screen
stdscr.clear()
# This raises ZeroDivisionError when i == 10.
for i in range(1, 9):
v = i-10
stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))
stdscr.refresh()
stdscr.getkey()
if __name__ == "__main__":
wrapper(curses_main)
<file_sep>import smbus
import time
import datetime
import math
#This program takes an x,y coordinate and updates the point on a .txt file
#along with a timestamp from the Raspberry Pi clock (synced with RTC module)
def main():
log()
def log(x,y):
file = open('Coordinates.txt','a')
now = datetime.datetime.now()
timestamp = now.strftime('%Y%m/%d %H:%M')
data = 'point: ' + str(x) + ',' +str(y) + ' time: ' + str(timestamp)
file.write(data)
file.close
print data
if __name__ == "main":
main()
<file_sep>Definition
This project is a product of a collaboration between researchers at the MIT Media Lab for the Venice Biennale.
Computer vision code for doing multiview geometry for 3D point reconstruction and tracking.
<file_sep>class TCPClient:
def __init__(self, Address, Port):
self.Address = Address
self.Port = Port
self.open_server()
def open_server(self):
# Create a TCP/IP socket
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = (self.Address, self.Port)
print >>sys.stderr, 'connecting to %s port %s' % server_address
self.sock.connect(server_address)
def send(self, pts):
try:
i = 0
for pt in pts:
# the data should be sent as 3 comma separated values with a total length of 19 characters.
# 1 for id, 8 for x, 8 for y
# [ i,xxxxxxxx,yyyyyyyy ]
message = '' + str(i) + ',' + ("%8f" % pt[0]) + ',' + ("%8f" % pt[1])
# Send data
sock.sendall(message)
i = i + 1
if(i == 10):
break
except:
pass
#tcpc = TCPClient('localhost', 4558)
<file_sep>import cv
import cv2
import numpy
import numpy.linalg
import math
import re
import socket
import sys
import io
import time
import picamera
import picamera.array
import motioncontrol
current_milli_time = lambda: round(time.time() * 1000)
class CalibrationMarker:
def __init__(self, UID):
self.UID = UID
self.mon = "CALIB"+str(UID)
self.pos = [0, 0]
def Save(self, f, prefix):
stng = prefix+self.mon+"="+str(self.pos)+"\n"
f.write(stng)
def Load(self, line, prefix):
stng = prefix+self.mon
if(line.startswith(stng)):
self.pos = eval(line[line.rfind("=")+1:])
#print "got: "+ line + " ---> " + str(self.pos)
return True
return False
calibCap = None
def MouseCalibrate(image, markers):
windowName = "Choose Point";
cv.NamedWindow(windowName)
gotPoint = [False]*len(markers);
ind = [0]
pt = [0,0]
def mouseback(event,x,y,flags,param):
if event==cv.CV_EVENT_LBUTTONUP: # here event is left mouse button double-clicked
print x,y
pt[0] = x
pt[1] = y
gotPoint[ind[0]] = True
cv.SetMouseCallback(windowName, mouseback);
for i in range(0, len(markers)):
#redisplay image and title
cv.ShowImage(windowName, image);
ind[0] = i
#ask for pt
while not gotPoint[ind[0]]:
ret, calibImage = calibCap.retrieve()
cv2.imshow(windowName, calibImage);
cv.WaitKey(1);
#add point to matrix
markers[i].pos = [pt[0], pt[1]];
cv.DestroyWindow(windowName)
def AutoCalibrate(image):
pass
def Save(filename, cameras):
f = open(filename, "w")
for camera in cameras:
camera.Save(f)
class Camera:
pos = [0,0,0];
cur = None
def __init__(self, id):
self.red = CalibrationMarker("RED");
self.blue = CalibrationMarker("BLUE");
self.green = CalibrationMarker("GREEN");
self.yellow = CalibrationMarker("YELLOW");
self.calibrationmarkers = [self.red, self.blue, self.green, self.yellow]
if(type(id) == type('imastring')):
self.capture = cv.CaptureFromFile(id);
id = int(id[-5])
else: #i'm a numeric id
self.capture = cv.CaptureFromFile("../cam1.mov")
#self.capture = cv2.VideoCapture(id);
self.calibrated = False
self.id = id;
def next(self):
#self.cur = self.capture.retrieve()
self.cur = None
return self.cur;
def Save(self, f, prefix=""):
for calib in self.calibrationmarkers:
calib.Save(f, "CAM"+str(self.id))
def Load(self, line, prefix=""):
iscalib = [calib.Load(line, "CAM"+str(self.id)) for calib in self.calibrationmarkers]
self.LdCounter += iscalib.count(True)
self.calibrated = self.calibrated or self.LdCounter == len(self.calibrationmarkers)
def Calibrate(self, withMouse, imageOverride = None):
if(imageOverride == None):
imageOverride = self.cur
if(withMouse):
MouseCalibrate(imageOverride, self.calibrationmarkers);
else:
AutoCalibrate(imageOverride, self.calibrationmarkers);
self.CalibrateFunc()
self.calibrated = True
def CalibrateFunc(self):
#for each calibration marker, construct matrix to do least squares with
numrows = 2*len(self.calibrationmarkers)
A = numpy.zeros((numrows, 9))
B = numpy.zeros((numrows, 1))
# marker 1: 0,0
# marker 2: 1,0
# marker 3: 1,1
# marker 4: 0,1
#B(0),B(1) = 0 #marker 1
B[2] = 1; B[5]=1 #marker 2,3
B[4] = 1;
B[6] = 0; B[7]=1
#B[3] = 1; B[4]=1 #marker 2,3
#B[6] = 1; B[7]=1 #marker 4
#create our polygon
self.px = numpy.array([-1, 8, 13, -4])
self.py = numpy.array([-1, 3, 11, 8])
i = 0
for calib in self.calibrationmarkers:
self.px[(3+i)%4] = calib.pos[0]
self.py[(3+i)%4] = -calib.pos[1]
i = i + 1
print "PX: \n", str(self.px)
print "PY: \n", str(self.py)
#compute coefficients
#A=numpy.mat('1 0 0 0;1 1 0 0;1 1 1 1;1 0 1 0')
#print "A: \n", str(A)
#AI = numpy.invert(A)
AI = numpy.mat('1 0 0 0;-1 1 0 0;-1 0 0 1;1 -1 1 -1')
#print "AI: \n", str(AI)
#print "shapes: ", str(AI.shape), " and ", str(self.px.T.shape)
self.a = numpy.dot(AI, self.px)
self.a = numpy.squeeze(self.a)
print "a: \n", str(self.a)
self.b = numpy.dot(AI, self.py)
self.b = numpy.squeeze(self.b)
print "b: \n", str(self.b)
#classify points as internal or external
#plot_internal_and_external_points(px,py,a,b);
return self.a, self.b
# converts physical (x,y) to logical (l,m)
def FrameCorrect(self, x, y):
#quadratic equation coeffs, aa*mm^2+bb*m+cc=0
#y = 240 - y
y = -y
a = self.a
b = self.b
aa = a[0,3]*b[0,2] - a[0,2]*b[0,3]
bb = a[0,3]*b[0,0] -a[0,0]*b[0,3] + a[0,1]*b[0,2] - a[0,2]*b[0,1] + x*b[0,3] - y*a[0,3]
cc = a[0,1]*b[0,0] -a[0,0]*b[0,1] + x*b[0,1] - y*a[0,1]
#compute m = (-b+sqrt(b^2-4ac))/(2a)
det = math.sqrt(bb*bb - 4*aa*cc);
m = (-bb+det)/(2*aa);
#compute l
l = (x-a[0,0]-a[0,2]*m)/(a[0,1]+a[0,3]*m)
return l,m
#point in quad
def PointInQuad(m,l):
#is the point outside the quad?
if (m<0 or m>1 or l<0 or l>1):
return True
return False
def Load(filename, cameras):
f = open(filename, "r")
for camera in cameras:
camera.LdCounter = 0
line = f.readline()
while(len(line) != 0):
#test line on all cameras
for camera in cameras:
camera.Load(line)
line = f.readline()
def CompositeShow(windowName, camera, image, settings, pts=[]):
global Uncalibrated
# cv.NamedWindow(windowName)
comp = cv.CloneImage(image)
if(Uncalibrated):
CalibrateCameras(comp)
Uncalibrated = False
if(settings.showGrid):
#draw lines
#p1 - p2
cv.Line(comp, tuple(camera.calibrationmarkers[0].pos), \
tuple(camera.calibrationmarkers[1].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)
#p1 - p4
cv.Line(comp, tuple(camera.calibrationmarkers[0].pos), \
tuple(camera.calibrationmarkers[3].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)
#p3 - p4
cv.Line(comp, tuple(camera.calibrationmarkers[2].pos), \
tuple(camera.calibrationmarkers[3].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)
#p2 - p3
cv.Line(comp, tuple(camera.calibrationmarkers[1].pos), \
tuple(camera.calibrationmarkers[2].pos), cv.Scalar(0, 255, 0), 1, cv.CV_AA)
for pt in pts:
cv.Circle(comp, (int(pt[0]), int(pt[1])), 3, cv.Scalar(255, 0, 0))
cv.ShowImage(windowName, comp)
cam1 = Camera(-1);
cam2 = Camera("../cam2.mov");
cam3 = Camera("../cam3.mov");
cam4 = Camera("../cam4.mov");
cameras = [cam1]#,cam2,cam3,cam4]
im1 = cam1.next()
#cv.SaveImage("test.jpg", im1)
#im2 = cam2.next()
#im3 = cam3.next()
#im4 = cam4.next()
Load("prefs.txt", cameras);
ManualCalibrate = True;
#print "calibs: " + str([x.calibrated for x in cameras])
NeedsToSave = False
Uncalibrated = not reduce(lambda a,b: a and b, [x.calibrated for x in cameras])
if(not Uncalibrated):
[cam.CalibrateFunc() for cam in cameras]
def CalibrateCameras(imageOverRide = None):
global NeedsToSave, cameras, Uncalibrated
if(Uncalibrated):
#recalibrate
NeedsToSave = True
Uncalibrated = True
[cam.Calibrate(ManualCalibrate, imageOverRide) for cam in cameras]
g_a = None
g_b = None
#Calibrate unit->world
#lightblue/pink/green/darkblue
g_px = numpy.array([0.4, 2.3, 4.2, 2.3])
g_py = numpy.array([2.44, 0.4, 2.44, 4.48])
#g_px = numpy.array([2.3, 0.4, 2.3, 4.2])
#g_py = numpy.array([4.48, 2.44, 0.4, 2.44])
#compute coefficients
AI = numpy.mat('1 0 0 0;-1 1 0 0;-1 0 0 1;1 -1 1 -1')
g_a = numpy.dot(AI, g_px)
g_a = numpy.squeeze(g_a)
#print "g_a: \n", str(g_a)
g_b = numpy.dot(AI, g_py)
g_b = numpy.squeeze(g_b)
#print "g_b: \n", str(g_b)
def unit2world(pos):
g = pos[0]
h = pos[1]
k = g*h
unit = numpy.bmat([[[1], [g], [h], [k]]])
world_x = numpy.asscalar(numpy.dot(g_a, unit.T))
world_y = numpy.asscalar(numpy.dot(g_b, unit.T))
return (world_x, world_y)
#test
#print "unit2world 0,0: \n", str(unit2world([0,0]))
#print "unit2world 1,0: \n", str(unit2world([1,0]))
#print "unit2world 0 1: \n", str(unit2world([0,1]))
#print "unit2world 1 1: \n", str(unit2world([1,1]))
# 4 different colors, find those, autocalibrate
# -> calib per camera
class Settings:
def __init__(self):
self.showGrid = True
settings = Settings()
#Test 1
##CompositeShow("Camera 1", cam1, settings)
##def mouseback_rect(event,x,y,flags,param):
## if event==cv.CV_EVENT_LBUTTONUP: # here event is left mouse button double-clicked
## new = cam1.FrameCorrect(x,y)
## print x,y, "->", new
##
##
##
##cv.SetMouseCallback("Camera 1", mouseback_rect);
##cv.WaitKey()
#cv.NamedWindow("Image window", 1)
FilterWindowName = "Filter Window "
def nothing(da):
pass
def setupGUI(tag, min_default=128, max_default=128):
global FilterWindowName
# cv2.namedWindow(FilterWindowName+tag, 2)
# cv2.createTrackbar(tag+" Min", FilterWindowName+tag, min_default, 255, nothing)
# cv2.createTrackbar(tag+" Max", FilterWindowName+tag, max_default, 255, nothing)
def FindBall(im2):
global FilterWindowName
hsv = cv2.cvtColor(im2, cv.CV_RGB2HSV)
[h, s, v] = cv2.split(hsv)
#---------------------
#high_bnd = cv2.getTrackbarPos("Hue Max", FilterWindowName+"Hue")
#low_bnd = cv2.getTrackbarPos("Hue Min", FilterWindowName+"Hue")
high_bnd = 51
low_bnd = 0
ret, hi1 = cv2.threshold(h, high_bnd, 255, cv2.THRESH_BINARY_INV)
ret, hi2 = cv2.threshold(h, low_bnd, 255, cv2.THRESH_BINARY)
hi = cv2.bitwise_and(hi1, hi2)
# cv2.imshow(FilterWindowName+"Hue", hi);
#---------------------
#high_bnd = cv2.getTrackbarPos("Value Max", FilterWindowName+"Value")
#low_bnd = cv2.getTrackbarPos("Value Min", FilterWindowName+"Value")
high_bnd = 205
low_bnd = 130
ret, vi1 = cv2.threshold(v, high_bnd, 255, cv2.THRESH_BINARY_INV)
ret, vi2 = cv2.threshold(v, low_bnd, 255, cv2.THRESH_BINARY)
vi = cv2.bitwise_and(vi1, vi2)
# cv2.imshow(FilterWindowName+"Value", vi);
#---------------------
out = cv2.bitwise_and(vi, hi)
return out
def ErodeTrick(im):
cv2.erode(im, im, None, 3)
cv2.dilate(im, im, None, 3)
cv2.dilate(im, im, None, 3)
cv2.erode(im, im, None, 3)
return im
cntrs = None
hier = None
def PickBlob(im):
global cntrs, hier
[cnters, hier] = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE, cntrs, hier)
# high_bnd = cv2.getTrackbarPos(" Max", FilterWindowName)
# low_bnd = cv2.getTrackbarPos(" Min", FilterWindowName)
high_bnd = 255
low_bnd = 0
cntrs = []
for cntr in cnters:
ara = cv2.contourArea(cntr)
# print "Area: ", ara
if(low_bnd < ara < high_bnd):
cntrs.append(cntr)
centroids = []
for cntr in cntrs:
mu = cv2.moments(cntr)
#print "MU: " + str(mu)
mx = mu['m10']/mu['m00']
my = mu['m01']/mu['m00']
centroids.append( (mx,my) )
return centroids
#cap = cv2.VideoCapture(-1)
#cap.set(cv.CV_CAP_PROP_FRAME_WIDTH , 320);
#cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT , 240);
#cap.set(cv.CV_CAP_PROP_FPS, 20);
#cap.set(cv.CV_CAP_PROP_FOURCC, cv.CV_FOURCC('R', 'G', 'B', '3'))
#for i in range(0,20):
# ret, cv_image = cap.retrieve()
# cv.WaitKey(100)
class TCP:
def __init__(self,Address,Port,SoC):
self.Address = Address
self.Port = Port
self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.buffer_size = 1024
if SoC == 'Client':
pass
# self.client()
elif SoC == 'Server':
self.s.bind((self.Address,self.Port))
else:
print 'error in TCP assingment'
# no longer called
def open_socket(self):
# Create a TCP/IP socket
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set buffer size
self.buffer_size = 1024
# Connect the socket to the port where the server is listening
# server_address = (self.Address, self.Port)
# print >>sys.stderr, 'connecting to %s port %s' % server_address
# self.sock.connect(server_address)
def server(self):
# self.s.bind((self.Address,self.Port))
# self.s.settimeout(1)
self.s.listen(1)
conn,addr = self.s.accept()
data = conn.recv(self.buffer_size)
# if not data: break
# print 'received_data: ', data
(x1,y1) = re.findall('\d+.\d+',data)
return (float(x1),float(y1))
# self.s.close()
def client(self):
message = str(new[0]) + ',' + str(new[1])
self.s.connect((self.Address,self.Port))
self.s.send(message)
data = self.s.serv(self.buffer_size)
self.s.close()
# ignore this
def receive(self):
data = self.conn.recv(self.buffer_size)
print 'received_data: ',data
# no longer called
def send(self, pts):
try:
i = 0
for pt in pts:
# the data should be sent as 3 comma separated values with a total length of 19 characters.
# 1 for id, 8 for x, 8 for y
# [ i,xxxxxxxx,yyyyyyyy ]
message = '' + str(i) + ',' + ("%8f" % pt[0]) + ',' + ("%8f" % pt[1])
# Send data
sock.sendall(message)
i = i + 1
if(i == 10):
break
except:
pass
#tcpc = TCP('',10000,"Server")
class RaspiCap:
def __init__(self):
camera = self.camera = picamera.PiCamera()
#camera.resolution = (320, 240)
#camera.framerate = 20
#camera.start_preview()
time.sleep(2)
stream = self.stream = picamera.array.PiRGBArray(camera)
camera.capture(stream, format='bgr')
def retrieve(self):
# Construct a numpy array from the stream
stream = self.stream = picamera.array.PiRGBArray(self.camera)
self.camera.capture(self.stream, format='bgr')
image = self.stream.array
#image = None
#return 1, image
return 1,image
cap = RaspiCap()
calibCap = cap
def image_call():
global FilterWindowName
ret, cv_image = cap.retrieve()
if(ret):
filtered = FindBall(cv_image)
# cv2.imshow(FilterWindowName, filtered)
mcs = PickBlob(filtered)
for mc in mcs:
cv2.circle(cv_image, (int(mc[0]), int(mc[1])), 3, cv.Scalar(255, 0, 0))
#cv_image = cv2.cvtColor(cv_image, cv.CV_BGR2RGB)
#cvIm = cv.CreateImageHeader((cv_image.shape[1], cv_image.shape[0]), cv.IPL_DEPTH_8U, 3)
#cv.SetData(cvIm, cv_image.tostring(),
# cv_image.dtype.itemsize * 3 * cv_image.shape[1])
#CompositeShow("Image window", cam1, cvIm, settings)
#correct the frame
#tosend = []
for mc in mcs:
new = cam1.FrameCorrect(mc[0],mc[1])
# motioncontrol.control(int(mcs[0]), int(mcs[1]))
# rectified = unit2world(new)
# print "Ball: ", str(mc), " -> ", str(new)
(x1,y1) = (0.25,0.25)#tcpc.server()
(x2,y2) = (new[0],new[1])
(xCoord,yCoord) = chooseCoord(x1,x2,y1,y2)
# print (x1,y1)
# print (x2,y2)
print (xCoord,yCoord)
motioncontrol.control(xCoord,yCoord)
# print "Ball: ", str(mc), " -> ", str(rectified)
# tosend.append(rectified)
#now send it!
#tcpc.server()
cv.WaitKey(3)
def chooseCoord(x1,y1,x2,y2):
if(x1=='None' and y1=='None'):
return (x2,y2)
elif(x2=='None' and y2=='None'):
return (x1,y1)
else:
#(xCoord,yCoord) = ((x1+x2)/2,(y1+y2)/2)
# print (xCoord,yCoord)
return (0.6,1.0)
#set up with sane defaults
setupGUI("Hue", 115, 128)
#setupGUI("Hue")
setupGUI("Value", 218, 255)
# setupGUI("Value")
setupGUI("", 218, 1000)
if(NeedsToSave):
Save("prefs.txt", cameras);
start_time = current_milli_time()
frames = 0
motioncontrol.setup()
while(True):
image_call()
frames = frames + 1
diff = current_milli_time() - start_time
if diff > 0:
# pass
print "Frames Per Second: ", str(frames / (float(diff)/1000))
if(NeedsToSave):
Save("prefs.txt", cameras);
NeedsToSave = False
cv.DestroyAllWindows()
#play all until one dies
#while(im1 != None and im2 != None and
# im3 != None and im4 != None):
# color thresh video
# -overlay transparent
# + mask
# +erode, dilate, flip
# + overlay tracking transparent
# + all of these filters as GUI
# + all of these layers as GUI
# + affine - two cameras
# fake distances to get cm accuracy
<file_sep>imdebug=True
capvideo=False
cappi=False
showGrid = True
FilterWindowName = "Filter Window "
# quickly set which times the arrays will run which methods
trackingTime = '18:00:00'
waveTime = '17:30:00'
spotsTime = '17:00:00'
# set whether pi is client or server
TCPServer = True
TCPClient = False
# set IP adress and partner IP adress
IP_Address = '192.168.1.1'
<file_sep>import cv2
import numpy
from GlobalSettings import FilterWindowName, imdebug
#point in quad
def PointInQuad(m,l):
#is the point outside the quad?
if (m<0 or m>1 or l<0 or l>1):
return True
return False
#Test 1
##CompositeShow("Camera 1", cam1, settings)
##def mouseback_rect(event,x,y,flags,param):
## if event==cv.CV_EVENT_LBUTTONUP: # here event is left mouse button double-clicked
## new = cam1.FrameCorrect(x,y)
## print x,y, "->", new
##
##
##
##cv.SetMouseCallback("Camera 1", mouseback_rect);
##cv.WaitKey()
#cv.NamedWindow("Image window", 1)
def nothing(da):
pass
tracks = {}
def setupGUI(tag, min_default=128, max_default=128):
global FilterWindowName
if imdebug:
cv2.namedWindow(FilterWindowName+tag, 2)
cv2.createTrackbar(tag+" Min", FilterWindowName+tag, min_default, 255, nothing)
cv2.createTrackbar(tag+" Max", FilterWindowName+tag, max_default, 255, nothing)
else:
tracks[tag+" Min"] = min_default
tracks[tag+" Max"] = max_default
def ErodeTrick(im):
kernel = numpy.ones((3,3),numpy.uint8)
im = cv2.erode(im, kernel, iterations=1)
im = cv2.dilate(im, kernel, iterations = 1)
#kernel = numpy.ones((10,10),numpy.uint8)
#im = cv2.erode(im, kernel, iterations=2)
#im = cv2.dilate(im, kernel, iterations = 2)
#cv2.dilate(im, im, None, 3)
#cv2.erode(im, im, None, 3)
return im
def getTrack(name, window):
if imdebug:
high_bnd = cv2.getTrackbarPos(name, window)
low_bnd = cv2.getTrackbarPos(name, window)
else:
high_bnd = tracks[name+" Max"]
low_bnd = tracks[name+" Min"]
return high_bnd, low_bnd
<file_sep>import collections
import copy
import numpy
import cv2.cv as cv
import cv2
def pt_dist_L1(pt1, pt2):
return (pt2[0]-pt1[0])+(pt2[1]-pt1[1]);
def recurTrack(filt, history, trace=[], meanerror=0):
#returns path through history given filter, along with the mean-sq error
#first get prediction
next_pt = filt.predict()
#next find its nearest neighbor
pts_t = history.pop(0)
min_dist = float("inf")
nn = None
for q in pts_t:
if not type(q) == PtKalman:
# is a point - see if its closest
dist = pt_dist_L1(q, next_pt)
if dist < min_dist:
min_dist = dist;
nn = q
#if neighbor, update and recur
if nn != None:
filt.correct(nn)
trace.append(nn)
meanerror = meanerror + (min_dist*min_dist)
#check for termination
if(len(history) == 0):
return [filt, trace, meanerror/len(trace)]
#iterate
recurTrack(filt, history, trace, meanerror)
class PtKalman:
def __init__(self, pt):
self.pt = pt
self.history = [pt]
self.mse = 0.0
self.ns = 1
self.lifespan = 1
self.kalman = cv.CreateKalman(4, 2, 0)
self.kalman_state = cv.CreateMat(4, 1, cv.CV_32FC1)
self.kalman_process_noise = cv.CreateMat(4, 1, cv.CV_32FC1)
self.kalman_measurement = cv.CreateMat(2, 1, cv.CV_32FC1)
# set previous state for prediction
self.kalman.state_pre[0,0] = pt[0]
self.kalman.state_pre[1,0] = pt[1]
self.kalman.state_pre[2,0] = 0
self.kalman.state_pre[3,0] = 0
# set kalman transition matrix
self.kalman.transition_matrix[0,0] = 1
self.kalman.transition_matrix[0,1] = 0
self.kalman.transition_matrix[0,2] = 0
self.kalman.transition_matrix[0,3] = 0
self.kalman.transition_matrix[1,0] = 0
self.kalman.transition_matrix[1,1] = 1
self.kalman.transition_matrix[1,2] = 0
self.kalman.transition_matrix[1,3] = 0
self.kalman.transition_matrix[2,0] = 0
self.kalman.transition_matrix[2,1] = 0
self.kalman.transition_matrix[2,2] = 0
self.kalman.transition_matrix[2,3] = 1
self.kalman.transition_matrix[3,0] = 0
self.kalman.transition_matrix[3,1] = 0
self.kalman.transition_matrix[3,2] = 0
self.kalman.transition_matrix[3,3] = 1
# set Kalman Filter
cv.SetIdentity(self.kalman.measurement_matrix, cv.RealScalar(1))
cv.SetIdentity(self.kalman.process_noise_cov, cv.RealScalar(1e-5))
cv.SetIdentity(self.kalman.measurement_noise_cov, cv.RealScalar(1e-1))
cv.SetIdentity(self.kalman.error_cov_post, cv.RealScalar(1))
self.assignObs(pt, 3)
def getHistory(self):
return self.history
def assignObs(self, pt, err):
#update the kalman
self.kalman_measurement[0, 0] = float(pt[0])
self.kalman_measurement[1, 0] = float(pt[1])
kalman_estimated = cv.KalmanCorrect(self.kalman, self.kalman_measurement)
state_pt = (kalman_estimated[0,0], kalman_estimated[1,0])
#print "State estimate: ", state_pt
print "Adding pt, ", pt, " to history: ", self.history
#self.kalman.correct(pt)
self.history.append(pt)
self.mse = self.mse + err*err
self.ns = self.ns + 1
def one_up(self):
#print "Filter lifespan before: ", self.lifespan
self.lifespan = self.lifespan + 1
#print "Filter lifespan after: ", self.lifespan
def drawOnImage(self, im, color):
# go through history and make a line
#only pick 10 - will make a snake like trace
li = len(self.history) -1
prev = self.history[li]
li = li -1
scolor = cv.Scalar(color[0], color[1], color[2])
for i in range(10):
if(li > 0):
nextl = self.history[li]
#print "", prev, " -> ", nextl, " in ", color
cv2.line(im, tuple((int(prev[0]), int(prev[1]))), tuple((int(nextl[0]), int(nextl[1]))), scolor, 1, cv.CV_AA)
prev = nextl
li = li -1
def predict(self):
kalman_prediction = cv.KalmanPredict(self.kalman)
predict_pt = (kalman_prediction[0,0], kalman_prediction[1,0])
return predict_pt
def getMSE(self):
return self.mse / self.ns
class HumanTracker:
def __init__(self):
self.initialize(conf_freq=10, conf_thresh=10)
def initialize(self, conf_freq, conf_thresh):
self.confidence_freq = conf_freq
self.confidence_thresh = conf_thresh
self.history = collections.deque(maxlen=self.confidence_freq)
self.filters = []
def update(self, mcs):
min_dist_g = 15
num_updates = 20
#go through points, absorb the ones that already have tracks
for filt in self.filters:
#predict
next_pt = filt.predict()
#you only get one
min_dist = float("inf")
min_ind = -1
min_pt = None
ind = 0
for mc in mcs:
# is a point - see if its closest
dist = abs(pt_dist_L1(mc, next_pt))
#print "Dist: ", dist, " -> ", mc, " - ", next_pt
if dist < min_dist:
min_pt = mc
min_dist = dist
min_ind = ind
ind = ind + 1
#print "checking out dist: ", min_dist
#if meets criteria, then remove from history and move on to next filter
if min_dist < min_dist_g:
#print "the min dist: ", min_dist
filt.assignObs(min_pt, min_dist)
mcs.pop(min_ind)
filt.one_up()
#go through remaining - create temp kalmans for them
for mc in mcs:
self.filters.append(PtKalman(mc))
#clear out kalmans that were updated more than x times and
# have less than y confidence
# history, mse, lifespan
toclear = []
ind = 0
for filt in self.filters:
if (len(filt.history) > num_updates and filt.getMSE() > self.confidence_thresh) or (filt.lifespan > 30 and filt.lifespan / len(filt.history) > 0.80):
toclear.append(ind)
ind = ind + 1
#print "TOCLEAR: ", toclear
#go through indices and clear them out of the filter list
toclear.reverse()
for index in toclear:
self.filters.pop(index)
print "Num Filters: ", str(self.countConfidentFilters())
def calcColor(self, indnum):
r = indnum & 0x1
g = indnum & 0x2
b = indnum & 0x4
return (255*r, 255*g, 255*b)
def drawFirstEight(self, im):
ind = 0
for filt in self.filters:
filt.drawOnImage(im, self.calcColor(ind))
ind = ind + 1
return im
def countConfidentFilters(self):
conf = []
for filt in self.filters: #and filt.getMSE() < self.confidence_thresh
if (len(filt.history) > 8 ):
conf.append(filt)
return conf
def getConfidentPts(self):
mcs = []
for filt in self.countConfidentFilters():
hlen = len(filt.history)
mc = filt.history[hlen-1]
mcs.append(mc)
return mcs
<file_sep>import cv
import cv2
from GlobalSettings import FilterWindowName, imdebug
from utils import getTrack
def FindBall(im2):
global FilterWindowName, imdebug
hsv = cv2.cvtColor(im2, cv.CV_RGB2HSV)
[h, s, v] = cv2.split(hsv)
#---------------------
high_bnd, low_bnd = getTrack("Hue", FilterWindowName+"Hue")
ret, hi1 = cv2.threshold(h, high_bnd, 255, cv2.THRESH_BINARY_INV)
ret, hi2 = cv2.threshold(h, low_bnd, 255, cv2.THRESH_BINARY)
hi = cv2.bitwise_and(hi1, hi2)
if imdebug:
cv2.imshow(FilterWindowName+"Hue", hi);
#---------------------
high_bnd, low_bnd = getTrack("Value", FilterWindowName+"Value")
ret, vi1 = cv2.threshold(v, high_bnd, 255, cv2.THRESH_BINARY_INV)
ret, vi2 = cv2.threshold(v, low_bnd, 255, cv2.THRESH_BINARY)
vi = cv2.bitwise_and(vi1, vi2)
if imdebug:
cv2.imshow(FilterWindowName+"Value", vi);
#---------------------
out = cv2.bitwise_and(vi, hi)
return out
cntrs = None
hier = None
def PickBlob(im):
global cntrs, hier
[conts, hier] = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
high_bnd, low_bnd = getTrack("", FilterWindowName)
cntrs = []
max_area = 0
max_ind = -1
i = 0
for cntr in conts:
ara = cv2.contourArea(cntr)
if(1000 < ara):
if ara > max_area:
max_area = ara
max_ind = i
#print "fnd: ", str(ara)
cntrs.append(cntr)
i = i + 1
centroids = []
for cntr in cntrs:
mu = cv2.moments(cntr)
#print "MU: " + str(mu)
mx = mu['m10']/mu['m00']
my = mu['m01']/mu['m00']
centroids.append( (mx,my) )
if max_ind != -1:
mu = cv2.moments(conts[max_ind])
#print "MU: " + str(mu)
mx = mu['m10']/mu['m00']
my = mu['m01']/mu['m00']
return [ (mx, my) ]
return []
#return centroids
<file_sep>
# Motion Control Code
from Adafruit_PWM_Servo_Driver import PWM
import math
import time
servoPins = [1,2,3,4,5,6]
bulbPins = [8,9,10,12,13,14]
numServos = len(servoPins)
numBulbs = len(bulbPins)
angles = [45,135]
pwm = PWM(0x40, debug=True)
def main():
setup()
# test4545()
control(0.4,0)
time.sleep(1)
control(0.4,0.2)
time.sleep(1)
control(0.4,0.4)
time.sleep(1)
control(0.4,0.6)
time.sleep(1)
control(0.4,0.8)
time.sleep(1)
control(0.4,1.0)
time.sleep(1)
control(0.4,0.8)
time.sleep(1)
control(0.4,0.6)
time.sleep(1)
control(0.4,0.4)
time.sleep(1)
control(0.4,0.2)
time.sleep(1)
control(0.4,0)
#def __init__(self):
# setup()
# for i in range(0,2000):
# control(0,0)
def coordToDist(coord,length):
dist = (coord*length)
return dist
def distToAngle(dist,height):
angle = (math.atan2(dist,height)*57.0)
return angle
# returns the pulse width in milliseconds for a given servo angle
def angleToPulse(angle):
minimumPulse = 150.0 #0.5 milliseconds pulse - angle 0
maximumPulse = 600.0 #2.5 milliseconds pulse - angle 180
pulse = minimumPulse+(((maximumPulse-minimumPulse)/180)*angle)
return pulse
# write an angle to a given servo
def servoWrite(number,angle):
pulseWidth = angleToPulse(angle)
pwm.setPWM(number,0,int(pulseWidth))
def bulbWrite(number,status):
if status == 'HIGH':
pwm.setPWM(number,0,4096)
else:
pwm.setPWM(number,0,0)
def setup():
pwm.setPWMFreq(60)
for i in range(0,numServos):#(int i=0; i<numServos; i++)
servoWrite(i,90)#servos[i].write(pos);
time.sleep(.01)
def test4545():
for i in range(0,10):
for j in range(0,2):
for k in range(0,numServos):
servoWrite(servoPins[k],angles[j])
time.sleep(1)
def control(x,y):
#set height of array and length of coordinate grid in meters
height = 3.5
length = height*(3.0/4.0)
#choose array offset depending on array y position
arrayOffset = length/2
#determine x coordiante by diving x plane into sixths
num = int(x/0.1666666)
#determine y coordinate
yDist = coordToDist(y,length)
yDist = yDist - arrayOffset
#print yDist
#if coordinate within range of array
if (yDist>=-(length/2) and yDist<=(length/2)):#or x<0 or x>1:
theta = distToAngle(yDist,height)
print 90-theta
#print 90-theta+(theta/2)
#print servoPins[num]
#print servoPins[num+1]
#print servoPins[abs(num-1)]
print str(num)+' , ',str(theta)
servoWrite(servoPins[num],90-theta)#servos[num].write(90-theta)
servoWrite(servoPins[abs(num+1)],90-theta+(theta/2))#servos[num+1].write(90-theta+(theta/2))
servoWrite(servoPins[abs(num-1)],90-theta+(theta/2))#servos[num-1].write(90-theta+(theta/2))
bulbWrite(num,'HIGH')#digitalWrite(lightPins[num],HIGH)
for i in range(0,numServos):#for int i=0; i<numServos; i++)
if i==num or i==num+1 or num==i-1:
#currently code does not turn off adjacent bulbs
#occasionally leaving two bulbs on, this can be changed here
pass
else:
servoWrite(servoPins[i],90)#servos[i].write(90); # tell servo to go to 90
bulbWrite(bulbPins[i],'LOW')#digitalWrite(lightPins[i], LOW) # make sure they are all off
time.sleep(.01)
# pass
else:
for i in range(0,numBulbs):#for (int i=0; i<numLights; i++)
# pass
bulbWrite(bulbPins[i],'LOW')#digitalWrite(lightPins[i], LOW) #make sure they are all off
for i in range(0,numServos):#for (int i=0; i<numServos; i++)
servoWrite(servoPins[i],90) #tell servo to go to 90
time.sleep(.01)
# pass
if __name__ == "__main__":
main()
<file_sep>import GlobalSettings
import cv2
import cv
if GlobalSettings.capvideo:
cap = cv2.VideoCapture(-1)
else:
cap = cv2.VideoCapture("/home/nd/Downloads/video.avi")
if not cap.isOpened():
print "AHH NOT OPEN"
else:
print "OPEN!"
if GlobalSettings.cappi:
import picamera
class RaspiCap:
def __init__(self):
stream = self.stream = io.BytesIO()
camera = self.camera = picamera.PiCamera()
camera.resolution = (320, 240)
camera.framerate = 20
#camera.start_preview()
time.sleep(2)
camera.capture(stream, format='bmp')
def retrieve(self):
# Construct a numpy array from the stream
data = numpy.fromstring(self.stream.getvalue(), dtype=numpy.uint8)
# "Decode" the image from the array, preserving colour
image = cv2.imdecode(data, 1)
#image = None
return 1, image
cap = RaspiCap()
else:
cap.set(cv.CV_CAP_PROP_FRAME_WIDTH , 320);
cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT , 240);
cap.set(cv.CV_CAP_PROP_FPS, 20);
cap.set(cv.CV_CAP_PROP_FOURCC, cv.CV_FOURCC('R', 'G', 'B', '3'))
if GlobalSettings.capvideo:
for i in range(0,20):
ret, cv_image = cap.retrieve()
cv.WaitKey(100)
def GetCaptureDevice():
return cap
<file_sep>import cv2
import cv
import numpy
import numpy.linalg
calibCap = None
def MouseCalibrate(image, markers):
windowName = "Choose Point";
cv2.namedWindow(windowName)
gotPoint = [False]*len(markers);
ind = [0]
pt = [0,0]
def mouseback(event,x,y,flags,param):
if event==cv.CV_EVENT_LBUTTONUP: # here event is left mouse button double-clicked
print x,y
pt[0] = x
pt[1] = y
gotPoint[ind[0]] = True
cv.SetMouseCallback(windowName, mouseback);
for i in range(0, len(markers)):
#redisplay image and title
cv2.imshow(windowName, image);
ind[0] = i
#ask for pt
while not gotPoint[ind[0]]:
ret, calibImage = calibCap.retrieve()
cv2.imshow(windowName, calibImage);
cv.WaitKey(1);
#add point to matrix
markers[i].pos = [pt[0], pt[1]];
cv.DestroyWindow(windowName)
def AutoCalibrate(image):
pass
g_a = None
g_b = None
#Calibrate unit->world
#lightblue/pink/green/darkblue
g_px = numpy.array([0.4, 2.3, 4.2, 2.3])
g_py = numpy.array([2.44, 0.4, 2.44, 4.48])
#g_px = numpy.array([2.3, 0.4, 2.3, 4.2])
#g_py = numpy.array([4.48, 2.44, 0.4, 2.44])
#compute coefficients
AI = numpy.mat('1 0 0 0;-1 1 0 0;-1 0 0 1;1 -1 1 -1')
g_a = numpy.dot(AI, g_px)
g_a = numpy.squeeze(g_a)
#print "g_a: \n", str(g_a)
g_b = numpy.dot(AI, g_py)
g_b = numpy.squeeze(g_b)
#print "g_b: \n", str(g_b)
def unit2world(pos):
g = pos[0]
h = pos[1]
k = g*h
unit = numpy.bmat([[[1], [g], [h], [k]]])
world_x = numpy.asscalar(numpy.dot(g_a, unit.T))
world_y = numpy.asscalar(numpy.dot(g_b, unit.T))
return (world_x, world_y)
#test
#print "unit2world 0,0: \n", str(unit2world([0,0]))
#print "unit2world 1,0: \n", str(unit2world([1,0]))
#print "unit2world 0 1: \n", str(unit2world([0,1]))
#print "unit2world 1 1: \n", str(unit2world([1,1]))
# 4 different colors, find those, autocalibrate
<file_sep>import time
import datetime
def main():
print clock()
# return a date and time from the computer clock
def timestamp():
t = time.time()
stamp = datetime.datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
return stamp
# parse a time stamp first into the time, and then into the hour
# split(" ",1) will split a string into an array containing the strings
# before the selected character and after the character
def clock():
stamp = timestamp()
stamp_list = stamp.split(" ",1)
time = stamp_list[1]
return time
def hour():
stamp = timestamp()
stamp_list = stamp.split(" ",1)
time = stamp_list[1]
hour = time.split(":",1)
return hour[0]
# parse a time stamp first into the time, and then into the hour
def minute():
stamp = timestamp()
stamp_list = stamp.split(" ",1)
time = stamp_list[1]
minsec = time.split(":",1)
minute = minsec[1].split(":",1)
return minute[0]
def second():
stamp = timestamp()
stamp_list = stamp.split(" ",1)
time = stamp_list[1]
minsec = time.split(":",1)
second = minsec[1].split(":",1)
return second[1]
if __name__ == "__main__":
main()
<file_sep>import picamera
import picamera.array
import socket
from time import sleep
import numpy as np
import cv2 as cv2
import cv as cv
import re
import io
import sys
camera = picamera.PiCamera()
camera.start_preview()
sleep(120)
class RaspiCap:
def __init__(self):
camera = self.camera = picamera.PiCamera()
stream = self.stream = picamera.array.PiRGBArray(camera)
camera.capture(stream,format='bgr')
def retrieve(self):
stream = self.stream = picamera.array.PiRGBArray(self.camera)
self.camera.capture(self.stream,format='bgr')
image = self.stream.array
return 1,image
#cap = RaspiCap()
#fgbg = cv2.BackgroundSubtractorMOG()
#fgbg = cv2.imread('image.jpg')
#image = fgbg.array
#cv.NamedWindow('frame')
#cv.ShowImage('frame',fgbg)
#while(1):
#ret,frame = cap.retrieve()
#fgmask = fgbg.apply(frame)
#fgmask2 = cv.fromarray(fgmask)
#cv.ShowImage('frame',fgbg)
#k = cv2.waitKey(30) & 0xFF
#if k == 27:
# break
#cap.release()
#cv2.destroyAllWindows()
<file_sep>from markers import CalibrationMarker
from calibration import MouseCalibrate, AutoCalibrate
import os
import cv
import numpy
class Camera:
pos = [0,0,0];
cur = None
def __init__(self, id):
self.red = CalibrationMarker("RED");
self.blue = CalibrationMarker("BLUE");
self.green = CalibrationMarker("GREEN");
self.yellow = CalibrationMarker("YELLOW");
self.calibrationmarkers = [self.red, self.blue, self.green, self.yellow]
if(type(id) == type('imastring')):
self.capture = cv.CaptureFromFile(id);
id = int(id[-5])
else: #i'm a numeric id
self.capture = cv.CaptureFromFile("../cam1.mov")
#self.capture = cv2.VideoCapture(id);
self.calibrated = False
self.id = id;
def next(self):
#self.cur = self.capture.retrieve()
self.cur = None
return self.cur;
def Save(self, f, prefix=""):
for calib in self.calibrationmarkers:
calib.Save(f, "CAM"+str(self.id))
def Load(self, line, prefix=""):
iscalib = [calib.Load(line, "CAM"+str(self.id)) for calib in self.calibrationmarkers]
self.LdCounter += iscalib.count(True)
self.calibrated = self.calibrated or self.LdCounter == len(self.calibrationmarkers)
def Calibrate(self, withMouse, imageOverride = None):
if(imageOverride == None):
imageOverride = self.cur
if(withMouse):
MouseCalibrate(imageOverride, self.calibrationmarkers);
else:
AutoCalibrate(imageOverride, self.calibrationmarkers);
self.CalibrateFunc()
self.calibrated = True
def CalibrateFunc(self):
#for each calibration marker, construct matrix to do least squares with
numrows = 2*len(self.calibrationmarkers)
A = numpy.zeros((numrows, 9))
B = numpy.zeros((numrows, 1))
# marker 1: 0,0
# marker 2: 1,0
# marker 3: 1,1
# marker 4: 0,1
#B(0),B(1) = 0 #marker 1
B[2] = 1; B[5]=1 #marker 2,3
B[4] = 1;
B[6] = 0; B[7]=1
#B[3] = 1; B[4]=1 #marker 2,3
#B[6] = 1; B[7]=1 #marker 4
#create our polygon
self.px = numpy.array([-1, 8, 13, -4])
self.py = numpy.array([-1, 3, 11, 8])
i = 0
for calib in self.calibrationmarkers:
self.px[(3+i)%4] = calib.pos[0]
self.py[(3+i)%4] = -calib.pos[1]
i = i + 1
print "PX: \n", str(self.px)
print "PY: \n", str(self.py)
#compute coefficients
#A=numpy.mat('1 0 0 0;1 1 0 0;1 1 1 1;1 0 1 0')
#print "A: \n", str(A)
#AI = numpy.invert(A)
AI = numpy.mat('1 0 0 0;-1 1 0 0;-1 0 0 1;1 -1 1 -1')
#print "AI: \n", str(AI)
#print "shapes: ", str(AI.shape), " and ", str(self.px.T.shape)
self.a = numpy.dot(AI, self.px)
self.a = numpy.squeeze(self.a)
print "a: \n", str(self.a)
self.b = numpy.dot(AI, self.py)
self.b = numpy.squeeze(self.b)
print "b: \n", str(self.b)
#classify points as internal or external
#plot_internal_and_external_points(px,py,a,b);
return self.a, self.b
# converts physical (x,y) to logical (l,m)
def FrameCorrect(self, x, y):
#quadratic equation coeffs, aa*mm^2+bb*m+cc=0
#y = 240 - y
y = -y
a = self.a
b = self.b
aa = a[0,3]*b[0,2] - a[0,2]*b[0,3]
bb = a[0,3]*b[0,0] -a[0,0]*b[0,3] + a[0,1]*b[0,2] - a[0,2]*b[0,1] + x*b[0,3] - y*a[0,3]
cc = a[0,1]*b[0,0] -a[0,0]*b[0,1] + x*b[0,1] - y*a[0,1]
#compute m = (-b+sqrt(b^2-4ac))/(2a)
det = math.sqrt(bb*bb - 4*aa*cc);
m = (-bb+det)/(2*aa);
#compute l
l = (x-a[0,0]-a[0,2]*m)/(a[0,1]+a[0,3]*m)
return l,m
def Save(filename, cameras):
f = open(filename, "w")
for camera in cameras:
camera.Save(f)
def Load(filename, cameras):
if(not os.path.isfile(filename)):
f = open(filename, "w")
f.close()
f = open(filename, "r")
for camera in cameras:
camera.LdCounter = 0
line = f.readline()
while(len(line) != 0):
#test line on all cameras
for camera in cameras:
camera.Load(line)
line = f.readline()
cam1 = Camera(-1);
cam2 = Camera("../cam2.mov");
cam3 = Camera("../cam3.mov");
cam4 = Camera("../cam4.mov");
cameras = [cam1]#,cam2,cam3,cam4]
im1 = cam1.next()
#cv.SaveImage("test.jpg", im1)
#im2 = cam2.next()
#im3 = cam3.next()
#im4 = cam4.next()
Load("prefs.txt", cameras);
ManualCalibrate = True;
#print "calibs: " + str([x.calibrated for x in cameras])
NeedsToSave = False
Uncalibrated = not reduce(lambda a,b: a and b, [x.calibrated for x in cameras])
if(not Uncalibrated):
[cam.CalibrateFunc() for cam in cameras]
def CalibrateCameras(imageOverRide = None):
global NeedsToSave, cameras, Uncalibrated
if(Uncalibrated):
#recalibrate
NeedsToSave = True
Uncalibrated = True
[cam.Calibrate(ManualCalibrate, imageOverRide) for cam in cameras]
<file_sep>import math
import re
import socket
import sys
import io
import time
import GlobalSettings
from GlobalSettings import TCPServer
from GlobalSettings import TCPClient
from GlobalSettings import IP_Address
class TCP:
def __init__(self):
self.Address = IP_Address
self.Port = 10000
self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.buffer_size = 1024
if TCPServer:
self.s.bind((self.Address,self.Port))
def server(self):
# self.s.bind((self.Address,self.Port))
# self.s.settimeout(1)
self.s.listen(1)
conn,addr = self.s.accept()
data = conn.recv(self.buffer_size)
# if not data: break
# print 'received_data: ', data
(x1,y1) = re.findall('\d+.\d+',data)
return (float(x1),float(y1))
# self.s.close()
def client(self):
message = str(new[0]) + ',' + str(new[1])
self.s.connect((self.Address,self.Port))
self.s.send(message)
data = self.s.serv(self.buffer_size)
self.s.close()
def talk(self):
if TCPServer:
self.server()
else:
self.client()
<file_sep>def CalibrateFunc(self):
#for each calibration marker, construct matrix to do least squares with
numrows = 2*len(self.calibrationmarkers)
A = numpy.zeros((numrows, 9))
B = numpy.zeros((numrows, 1))
# marker 1: 0,0
# marker 2: 1,0
# marker 3: 0,1
# marker 4: 1,1
#B(0),B(1) = 0 #marker 1
B[2] = 1; B[5]=1 #marker 2,3
B[4] = 1;
B[6] = 0; B[7]=1
#B[3] = 1; B[4]=1 #marker 2,3
#B[6] = 1; B[7]=1 #marker 4
i = 0
for calib in self.calibrationmarkers:
A[2*i, 0] = calib.pos[0]; A[2*i, 1] = calib.pos[1]
A[2*i+1, 3] = calib.pos[0]; A[2*i+1, 4] = calib.pos[1]
A[2*i,2] = 1; A[2*i+1,5] = 1
A[2*i,6] = -B[2*i]*calib.pos[0]
A[2*i,7] = -B[2*i]*calib.pos[1]
A[2*i,8] = -B[2*i]
A[2*i+1,6] = -B[2*i+1]*calib.pos[0]
A[2*i+1,7] = -B[2*i+1]*calib.pos[1]
A[2*i+1,8] = -B[2*i+1]
i = i + 1
#create our polygon
px = numpy.array([-1, 8, 13, -4])
py = numpy.array([-1, 3, 11, 8])
#compute coefficients
A=numpy.bmat('1 0 0 0;1 1 0 0;1 1 1 1;1 0 1 0')
AI = numpy.invert(A)
a = AI*px';
b = AI*py';
%plot random internal points
plot_points_in_poly(px,py,a,b);
%classify points as internal or external
plot_internal_and_external_points(px,py,a,b);
#print "A shape: " + str(A.shape) + " and B shape: " + str(B.shape)
#find pseudoinverse to unit frame -- least squares
#ata = A.T*A
U, s, V = numpy.linalg.svd(A, full_matrices=True)
#sh = s
#print "USV: \n" + str(U) + "\n" + str(s) + "\n" + str(V)
#n = min(s.shape)
#print "got n: ", str(n), " and ", str(s.shape)
#print "U shape: " + str(U.shape) + " and V shape: " + str(V.shape)
#for i in range(0, n):
# if(sh[i] != 0):
# sh[i] = 1.0/sh[i]
#ata_inv = V.conj().T*numpy.diag(sh)*U.conj().T
# get eigenvalues
#L = numpy.dot(A.T,B)
#L = numpy.dot(ata_inv, B)
#print "Here we are: ", str(L.shape)
#affine is reconstruction of lambda
L = V[8,:].T
#L = L / numpy.linalg.norm(L)
H = numpy.zeros((3,3))
for i in range(0,9):
H[i/3,i%3] = L[i]
#H[2,2] = 1
self.homography = H
print "Got Homography: \n", H
print "Got L: \n", L
print "From: \n", A
self.W = numpy.array([H[2,0], H[2,1], 1])
return H<file_sep>class CalibrationMarker:
def __init__(self, UID):
self.UID = UID
self.mon = "CALIB"+str(UID)
self.pos = [0, 0]
def Save(self, f, prefix):
stng = prefix+self.mon+"="+str(self.pos)+"\n"
f.write(stng)
def Load(self, line, prefix):
stng = prefix+self.mon
if(line.startswith(stng)):
self.pos = eval(line[line.rfind("=")+1:])
#print "got: "+ line + " ---> " + str(self.pos)
return True
return False
<file_sep>def PointOnLine(x1, x2, x0):
n = math.sqrt(numpy.dot(x2-x1,x2-x1))
#print "n: ", str(n)
detmat = numpy.zeros((2,2))
detmat[:,0] = x2-x1
detmat[:,1] = x1-x0
d = numpy.linalg.det(detmat)/n
#print "d: ", str(d)
v = numpy.zeros(2)
v[0] = x2[1]-x1[1]
v[1] = -(x2[0]-x1[0])
#print "v: ", str(v)
v = v / math.sqrt(numpy.dot(v,v));
ot = x0-v*d
#print "OT: ", str(ot)
return ot
#normalized coords
nc = (ot-x1) / n
#print "nc: ", str(nc)
p = math.sqrt(numpy.dot(nc*nc))
#print "p: ", str(p)
return p
def GetFourPoints(camera, pt):
#p1 - p2
pt12 = PointOnLine(numpy.array(camera.calibrationmarkers[0].pos), \
numpy.array(camera.calibrationmarkers[1].pos), pt)
#p1 - p4
pt14 = PointOnLine(numpy.array(camera.calibrationmarkers[3].pos), \
numpy.array(camera.calibrationmarkers[0].pos), pt)
#p3 - p4
pt34 = PointOnLine(numpy.array(camera.calibrationmarkers[2].pos), \
numpy.array(camera.calibrationmarkers[3].pos), pt)
#p2 - p3
pt23 = PointOnLine(numpy.array(camera.calibrationmarkers[1].pos), \
numpy.array(camera.calibrationmarkers[2].pos), pt)
return [pt12, pt14]#, pt34, pt23]
#Test 2
ptsyu = []
CompositeShow("Camera 1", cam1, settings)
def mouseback_rect(event,x,y,flags,param):
global ptsyu
if event==cv.CV_EVENT_LBUTTONUP: # here event is left mouse button double-clicked
#x1 = [77, 92]
#x2 = [147, 74]
#new = PointOnLine(numpy.array(x1), numpy.array(x2), numpy.array([110, 96]))
#print x,y, "->", new
ptsyu = GetFourPoints(cam1, numpy.array([x, y]))
cv.SetMouseCallback("Camera 1", mouseback_rect);
cv.WaitKey(1)
while(True):
CompositeShow("Camera 1", cam1, settings, ptsyu)
cv.WaitKey(1)<file_sep>import cv
vidFile = cv.CaptureFromFile( '../cam1.mov' )
nFrames = int( cv.GetCaptureProperty( vidFile, cv.CV_CAP_PROP_FRAME_COUNT ) )
fps = cv.GetCaptureProperty( vidFile, cv.CV_CAP_PROP_FPS )
waitPerFrameInMillisec = int( 1/fps * 1000/1 )
print 'Num. Frames = ', nFrames
print 'Frame Rate = ', fps, ' frames per sec'
for f in xrange( nFrames ):
frameImg = cv.QueryFrame( vidFile )
cv.ShowImage( "My Video Window", frameImg )
cv.WaitKey( waitPerFrameInMillisec )
# When playing is done, delete the window
# NOTE: this step is not strictly necessary,
# when the script terminates it will close all windows it owns anyways
cv.DestroyWindow( "My Video Window" ) | b5a73191fdd56e08c78d6d58f289d27575fc8070 | [
"Markdown",
"Python"
] | 22 | Python | localwarming-mit/local-warming | 70830a9759f1fb9b29c372547cfa6ccd3d277a89 | 89125905ef0c5a06c1e83acdc944551a34ce2f19 |
refs/heads/master | <file_sep>package test;
import static org.junit.Assert.assertEquals;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import backendapi.AdminModeApi;
import interfaces.AdminMode;
import interfaces.Song;
public class AdminModeTest
{
/**
* Testet das generieren von Songs aus der Textdatei
*
* @throws FileNotFoundException
*/
@Test
public void generateSongList( ) throws FileNotFoundException
{
String filepathForPersistence = new String();
filepathForPersistence = "/home/richard/musikdatenbank/penelope.txt";
initFileList( );
ArrayList<Song> songs = new ArrayList<Song>( );
songs=AdminModeApi.generateSongList(filepathForPersistence );
assertEquals( 3, songs.size( ) );
}
private void initFileList () throws FileNotFoundException
{
//Datei neu anlegen
// File songFile = new File ("/home/richard/musikdatenbank/penelope.txt");
// songFile.createNewFile( );
String filepathForPersistence = new String();
filepathForPersistence = "/home/richard/musikdatenbank/penelope.txt";
ArrayList<String> filepathes = new ArrayList<String>( );
//filepathes.add( "/home/richard/musikdatenbank/song4.mp3" );
filepathes.add( "/home/richard/musikdatenbank/song2.mp3" );
filepathes.add( "/home/richard/musikdatenbank/song.mp3" );
AdminMode.addSong( "/home/richard/musikdatenbank/song4.mp3", "/home/richard/musikdatenbank/penelope.txt", false );
for (String songPath : filepathes)
{
AdminMode.addSong( songPath, "/home/richard/musikdatenbank/penelope.txt", true );
}
//Songs reinschreiben z.B. 5
ArrayList<Song> songs=AdminModeApi.generateSongList(filepathForPersistence );
assertEquals( 3, songs.size( ) );
}
//
// /**
// * Testet die Ausgabe der in der Textdatei gespeicherten Songs
// *
// * @throws FileNotFoundException
// */
// @Test
// public void showAllExistingSongs( ) throws FileNotFoundException
// {
// AdminModeApi adminModeApi = new AdminModeApi( );
// adminModeApi.showAllExistingSongs( );
// }
/**
* Testet das Hinzufügen von Songs
*
* @throws FileNotFoundException
*/
@Test
public void addSongs( ) throws FileNotFoundException
{
initFileList( );
String filepathForPersistence = new String();
filepathForPersistence = "/home/richard/musikdatenbank/penelope.txt";
ArrayList<String> filepathes = new ArrayList<String>( );
filepathes.add( "/home/richard/musikdatenbank/song.mp3" );
filepathes.add( "/home/richard/musikdatenbank/song2.mp3" );
filepathes.add( "/home/richard/musikdatenbank/song.mp3" );
AdminModeApi adminModeApi = new AdminModeApi( );
adminModeApi.addSongs( filepathes,filepathForPersistence,true );
ArrayList<Song> songs = new ArrayList<Song>( );
songs=AdminModeApi.generateSongList(filepathForPersistence );
assertEquals( 6, songs.size( ) );
//showAllExistingSongs( );
}
// public void printSongList() throws FileNotFoundException
// {
// String filepathForPersistence = new String();
// filepathForPersistence = "/home/richard/musikdatenbank/penelope.txt";
// initFileList( );
// ArrayList<Song> songs = new ArrayList<Song>( );
// songs=AdminModeApi.generateSongList(filepathForPersistence );
// AdminMode.printSongs(songs);
// }
@Test
public void deleteSongsLowerThanFileEntries( ) throws FileNotFoundException
{
initFileList( );
String filepathForPersistence = new String();
filepathForPersistence = "/home/richard/musikdatenbank/penelope.txt";
//lösche 2 files
ArrayList<String> filepathesToDelete = new ArrayList<String>( );
filepathesToDelete.add( "/home/richard/musikdatenbank/song.mp3" );
//filepathesToDelete.add( "/home/richard/musikdatenbank/song2.mp3" );
AdminModeApi adminModeApi = new AdminModeApi( );
adminModeApi.deleteSongs( filepathForPersistence, filepathesToDelete );
List <String> actualEntries = AdminMode.generateFilepathList(filepathForPersistence );
assertEquals( 1, actualEntries.size( ) );
}
@Test
public void deleteSongsHigherThanFileEntries( ) throws FileNotFoundException
{
initFileList( );
String filepathForPersistence = new String();
filepathForPersistence = "/home/richard/musikdatenbank/penelope.txt";
//lösche 2 files
ArrayList<String> filepathesToDelete = new ArrayList<String>( );
filepathesToDelete.add( "/home/richard/musikdatenbank/song.mp3" );
filepathesToDelete.add( "/home/richard/musikdatenbank/song2.mp3" );
filepathesToDelete.add( "/home/richard/musikdatenbank/song.mp3" );
filepathesToDelete.add( "/home/richard/musikdatenbank/song4.mp3" );
//filepathesToDelete.add( "/home/richard/musikdatenbank/song2.mp3" );
AdminModeApi adminModeApi = new AdminModeApi( );
adminModeApi.deleteSongs( filepathForPersistence, filepathesToDelete );
List <String> actualEntries = AdminMode.generateFilepathList(filepathForPersistence );
assertEquals( 0, actualEntries.size( ) );
}
// private List<String> readFilePathForPersistenceEntries (String filepathForPersistence)
// {
// List <String> entries = new ArrayList<String>( );
//
// return entries;
// }
// @Test
// public void deleteSongsEqualsThanFileEntrys( ) throws FileNotFoundException
// {
// initFileList( );
// //lösche 2 files
// ArrayList<String> filepathes = new ArrayList<String>( );
//
// // List<String> filepathes = Arrays.asList("/home/richard/musikdatenbank/song4.mp3",
// // "/home/richard/musikdatenbank/song2.mp3", "/home/richard/musikdatenbank/song.mp3");
// filepathes.add( "/home/richard/musikdatenbank/song.mp3" );
// filepathes.add( "/home/richard/musikdatenbank/song2.mp3" );
// // checkfilepath
// for ( int j = 0; j < filepathes.size( ); j++ )
// {
// String filepathToDelete = new String();
// filepathToDelete = filepathes.get( j );
// AdminMode.deleteSong( filepathToDelete, filepathes );
// }
// // Ausgabe der neuen Songs
// // showAllExistingSongs( );
// }
//
// @Test//( expected = IllegalArgumentException.class )
// public void deleteSongsMoreThanFileEntrys( ) throws FileNotFoundException
// {
// //init
// //lösche 2 files
// ArrayList<String> filepathes = new ArrayList<String>( );
//
// // List<String> filepathes = Arrays.asList("/home/richard/musikdatenbank/song4.mp3",
// // "/home/richard/musikdatenbank/song2.mp3", "/home/richard/musikdatenbank/song.mp3");
// filepathes.add( "/home/richard/musikdatenbank/song.mp3" );
// filepathes.add( "/home/richard/musikdatenbank/song2.mp3" );
// // checkfilepath
// for ( int j = 0; j < filepathes.size( ); j++ )
// {
// String filepathToDelete = new String();
// filepathToDelete = filepathes.get( j );
// AdminMode.deleteSong( filepathToDelete, filepathes );
// }
// // Ausgabe der neuen Songs
// // showAllExistingSongs( );
// }
//
// //bearbeiten
// public void sortSongs( ) throws FileNotFoundException
// {
// ArrayList<Song> songs = new ArrayList<Song>( );
// songs = generateSongList( );
//
// ArrayList<String> songtitles = new ArrayList<String>( );
// songs = generateSongList( );
//
// for ( int j = 0; j < songs.size( ); j++ )
// {
//
// }
// }
//
}
<file_sep>package interfaces;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class DeleteFilepathTest
{
public static void main( String[ ] args ) throws FileNotFoundException
{
//TEST FilepathList wird erstellt
File f = new File( "/home/richard/musikdatenbank/songtitel.txt" );
List<String> filepathList = new ArrayList<String>( );
InputStream istream = new FileInputStream( f );
Scanner reader = new Scanner( istream );
while ( reader.hasNextLine( ) == true )
{
filepathList.add( reader.nextLine( ) );
}
//Zeichen wird aus FilepahtList gelöscht
String filepathToDelete = new String( );
System.out.print( "Welchen Dateipfad möchten sie löschen? > " );
Scanner input = new Scanner( System.in );
filepathToDelete = input.next( );
//lösche Zeichen Filepath aus FilepathList
for ( int i = 0; i < filepathList.size( ); i++ )
{
String filepath = filepathList.get( i );
System.out.println( "Element Filepatlist: "+filepath );
System.out.println( " zu löschen: "+filepathToDelete );
if ( filepath.equals( filepathToDelete ) )
{
System.out.println( "wird entfernt!");
filepathList.remove( i );
}
}
//lösche gesamten Inhalt von songtitel.txt und füge alle Dateipfade aus FilepathList ein
OutputStream ostream = new FileOutputStream( f);
//ohne true: neuer Inhalt überschreibt alten Inhalt
PrintStream writer = new PrintStream( ostream);
for ( int i = 0; i < (filepathList.size( ) ); i++ )
{
String eingabeInDatei = filepathList.get( i );
//Text wird in ostream und in Datei geschrieben
writer.print( eingabeInDatei + '\n' );
//ostream wird geleert
writer.flush( );
}
//TEST Ausgabe der neuen Liste
for ( int j = 0; j < filepathList.size( ); j++ )
{
System.out.println( filepathList.get( j ) );
}
}
}
<file_sep>package interfaces;
import java.util.Collection;
public interface AdminmodeInterface
{
// in Liste aller Songs aus Adminmode suchen
public Song searchSong( Collection<Song> songs );
// irgendeinen Sortieralg vom Karsten
public Collection<Song> sortSongs( Collection<Song> songs );
// vorher: checkFilepath
//addSong und vorher addFilepath
public Collection<Song> addSong( Song song );
//generateFilepathList
//public Collection<Song> generateSongsFromFilepathList()
//deleteSong
public Collection<Song> deleteSong( Song song );
//printAllSongs
}
<file_sep>package interfaces;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class AddFilepathTest
{
public static void main( String[ ] args ) throws FileNotFoundException
{
/**
* File Objekt ausgeben zum bearbeiten
* Dateipfad in txt speichern
*/
File f = new File( "/home/richard/musikdatenbank/songtitel.txt" ); // Dateipfad
OutputStream ostream = new FileOutputStream( f, true );
//falls die Datei bereits existiert wrd der Text an das Ende der Datei geschrieben
Scanner input = new Scanner( System.in );
System.out.print( "Wieviele Dateipfade in Datei schreiben? >");
//exception abfangen --> nur zahleneingabe erlaubt
int wortanzahl = input.nextInt( );
PrintStream writer = new PrintStream( ostream);
for ( int i = 0; i < (wortanzahl ); i++ )
{
System.out.print( "Eingabe des Dateipfades ohne Leerzeichen >" );
String eingabeInDatei = input.next( );
//Text wird in ostream und in Datei geschrieben
writer.print( eingabeInDatei + '\n' );
//ostream wird geleert
writer.flush( );
}
}
}
<file_sep>package interfaces;
import java.util.Collection;
public interface UserModeInterface
{
public Playlist editPlaylist( Playlist playlist1 );
public Collection<Playlist> addPlaylist( Playlist playlist );
public Collection<Playlist> deletePlaylist( Playlist playlist );
public void playPlaylist( Playlist playlist );
public void printPlaylist( Playlist playlist );
public Collection<Song> addSong( Song song );
public Collection<Song> deleteSong( Song song );
public void playSong( Song song );
public void printSong( Song song );
public void breakSong( Song song1 );
public void skipSong( Song song1 );
}
<file_sep>package interfaces;
import java.util.ArrayList;
import java.util.Collections;
public class SortTest
{
public static void main( String[ ] args )
{
ArrayList<String> filepathesToDelete = new ArrayList<String>( );
filepathesToDelete.add( "a" );
filepathesToDelete.add( "b" );
filepathesToDelete.add( "e" );
filepathesToDelete.add( "d" );
filepathesToDelete.add( "g" );
filepathesToDelete.add( "c" );
Collections.sort(filepathesToDelete );
for ( int i = 0; i < ( filepathesToDelete.size( ) ); i++ )
{
System.out.println(filepathesToDelete.get( i ));
}
}
}
<file_sep>//package interfaces;
///**
// * struktur und methoden adminmode klasse
// * warum leerzeile beim einfügen nach neustart
// * bei welchen songs gibt es probleme und warum
// * reguläre ausdrücke
// * textdatei erstellen über programm
// */
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.io.PrintStream;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Scanner;
//
//import org.farng.mp3.TagException;
//
//public class Main
//{
//
// public static void main( String[ ] args ) throws IOException, TagException
// {
// /**
// * 1.) Adminmode
// */
// // 1.1. Ausgabe aller Songs
// ArrayList<String> filepathes = new ArrayList<String>();
// filepathes = AdminMode.generateFilepathList( );
// AdminMode am = new AdminMode();
// ArrayList<Song> songs = new ArrayList<Song>();
// songs = am.generateSongsFromFilepathList( filepathes );
// am.printSongs( songs );
//
// // 1.2. Song hinzufügen
// Scanner input = new Scanner( System.in );
// System.out.println( "Wieviele Songs hinzufügen?" );
// //exception abfangen
// int number = input.nextInt( );
//
// for ( int j = 0; j < number; j++ )
// {
// System.out.println( "Fügen sie einen Dateipfad hinzu, aus welchem ein Song erstellt wird (ohne Leerzeichen) >" );
// //checkfilepath
// String filepath = input.next( );
// AdminMode.addSong(filepath, "/home/richard/musikdatenbank/songtitel.txt", true);
// }
// // neu laden der Dateipfade, neu laden der Songs und ausgeben
// filepathes = AdminMode.generateFilepathList( );
// songs = am.generateSongsFromFilepathList( filepathes );
// am.printSongs( songs );
//
// // 1.3. Song löschen
// System.out.println( "Wieviele Songs löschen?" );
// //exception abfangen
// int number2 = input.nextInt( );
// for ( int j = 0; j < number2; j++ )
// {
// System.out.println( "Fügen sie einen Dateipfad hinzu, um einen Song zu löschen" );
// // Admin kennt Dateipfad nicht mehr: über Titel an Dateipfad
// //checkfilepath
// String filepathToDelete = input.next( );
// AdminMode.deleteSong( filepathToDelete, filepathes );
//
// // neu generieren und ausgeben
// filepathes = AdminMode.generateFilepathList( );
// songs = am.generateSongsFromFilepathList( filepathes );
// am.printSongs( songs );
// }
//
// // 1.4. Songs sortieren
//
//
// // 1.5. Auswählen eines Songs
//
// /*Song song = new Song (filepath);
//
// String genre = new String( );
// String title = new String( );
// String interpret = new String( );
// String dateipfad = new String();
//
// genre = song.getGenre( );
// title = song.getTitle( );
// interpret = song.getInterpret( );
// dateipfad = song.getFilepath( );
//
// System.out.println( "Genre: " + genre );
// System.out.println( "Titel: " + title );
// System.out.println( "Interpret: " + interpret );
// System.out.println( "Dateipfad: " + dateipfad );*/
//
//
//
//
// //Song song2 = new Song( "/home/richard/musikdatenbank/song.mp3" );
//
// //
// // Moduswahl
//
// // 2
// // switch case 1 oder 2 --> Benutzermodus oder Verwaltungsmodus
// // 1: AdminMode adminmode = new AdminMode ();
// // adminmode.setSongs(); // wie?: Titel, Genre, Interpret in Datei speichern, auslesen und an Liste übergeben?
// // printTitle(adminmode);
// // 2: UserMode usermode = new UserMode ();
// // usermode.setplaylists();
// // printTitle(usermode);
//
// // 3
// // Aktionswahl im Modus mit switch case
//
// // Adminmode Aktionen
// // 1.) Song suchen
// // Song searchedSong = new Song();
// // Collection songlist = adminmode.getSongs();
// // searchedSong = adminmode.searchSong(songlist);
// // SOngs sortieren, einfügen (String in Datei schreiben), löschen,...
//
// // Usermode AKtionen
// // Playlist bearbeiten; abspielen
//
// // Playlist abspielen
//
// // Playlist playlist = new Playlist("Name der Playlist");
// // playlist.playTitles();
//
// // playTitles
// // Collection playlist = laden
// // for ()
// // song.playTitle()
//
//
// /**
// * Setzen eines Schreibers mit Zeichencodierung
// */
//
// //File f = new File( "/home/richard/musikdatenbank/songtitel.txt" );
// // Liste oder Collection
// //List<String> filepathList = new ArrayList<String>( );
// /*
// * Auslesen
// */
//
// /*InputStream istream = new FileInputStream( f );
// Scanner reader = new Scanner( istream );
// while ( reader.hasNextLine( ) == true )
// {
// filepathList.add( reader.nextLine( ) );
// }
//
// for(int j = 0; j<filepathList.size( );j++)
// {
// System.out.println( filepathList.get( j ));
// }*/
//
// // Zeichen aus Datei löschen
// /*String filepathToDelete = new String( );
//
// OutputStream ostream = new FileOutputStream( f );
//
// Scanner input = new Scanner( System.in );
//
// System.out.print( "Welchen Buchstaben möchten sie löschen > " );
// filepathToDelete = input.next( );
//
// for ( int i = 0; i < filepathList.size( ); i++ )
// {
// if ( filepathList.get( i ) == filepathToDelete )
// {
// filepathList.remove( i );
// }
// }
//
// PrintStream writer = new PrintStream( ostream );*/
//
// /**
// * neu reinschreiben
// */
// //writer.printf( + '\n' );
// /*
// * Nochmal Auslesen
// */
//
// //InputStream istream = new FileInputStream( f );
// //Scanner reader = new Scanner( istream );
// /*while ( reader.hasNextLine( ) == true )
// {
// filepathList.add( reader.nextLine( ) );
// }*/
//
// /*for(int k = 0; k<filepathes.size( );k++)
// {
// System.out.println( filepathes.get( k )+"ende");
// }*/
// }
//
//}
| 14310f9a79b3618123717a10159869e9c32082fc | [
"Java"
] | 7 | Java | richardfiedler/musikverwaltung | 6594493960d449f6c91519cadb52a8f655f9ae90 | 26d49a6fc5b984d1fbb8035edf203de68c37a2f4 |
refs/heads/master | <repo_name>EnesHockic/Artificial-intelligence<file_sep>/TicTac/TicTac/ViewModel/AlphaBetaVM.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TicTac.ViewModel
{
public enum Player { MIN, MAX };
public class AlphaBetaVM
{
public char[] array { get; set; }
public List<SelectListItem> depths { get; set; }
public int depth { get; set; }
public bool MaxPlayer { get; set; }
public int playerScore { get; set; }
public int compScore { get; set; }
public int equalScore { get; set; }
public string isLeaf { get; set; }
public int heuristic { get; set; }
public Player player { get; set; }
}
}
<file_sep>/Algorithms/Algorithms/Controllers/HillClimbingController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Algorithms.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Algorithms.Controllers
{
public class HillClimbingController : Controller
{
private FunctionsInterface _IFunctions;
public HillClimbingController(FunctionsInterface IFunctions)
{
_IFunctions = IFunctions;
}
public IActionResult Index()
{
int[] a = new int[16] { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //For every angorithm we generate initial array 4x4
HillClimbingVM VM = new HillClimbingVM()
{
array = a,
dimension =4,
heuristic=_IFunctions.Heuristic(_IFunctions.array1Dto2D(a,4),4),
dimensions=new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
};
return View(VM);
}
public IActionResult GenerateRandomState(int dim,int stepsInSameState)
{
int[][] array = _IFunctions.GenerateArray(dim); //Generates random state
HillClimbingVM VM = new HillClimbingVM()
{
array = _IFunctions.array2Dto1D(array,dim),
dimension = dim,
heuristic = _IFunctions.Heuristic(array,dim), //Heuristic function calculates heuristic of this array
stepsInSameState= stepsInSameState,
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
};
return View("Index",VM);
}
public int[][] GetBestH(int[][] array, int dim,int startH)
{
int h = startH;
int h2;
int[][] array2 = _IFunctions.CopyRow(array,dim);
int[][] nizFinal = _IFunctions.CopyRow(array,dim);
List<int> Is = new List<int>();
List<int> Js = new List<int>();
List<int> Hs = new List<int>();
for (int i = 0; i < dim; i++)
{
for (int j = 0; j < dim; j++)
{
if (array[i][j] != 1) //searching space where the queen is not in for each column
{
array2[i][j] = 1; //setting queen in new position
for (int k = 0; k < dim; k++)
{
if (array2[k][j] == 1 && i != k)
{
array2[k][j] = 0; //remove old position for queen
break;
}
}
h2 = _IFunctions.Heuristic(array2, dim); //Calculate heurstic for array with new position of queen
if (h2 < h)
{
h = h2;
nizFinal = _IFunctions.CopyRow(array2, dim);
}
else if (h2 == h)
{
Is.Add(i);
Js.Add(j);
Hs.Add(h2);
}
array2 = _IFunctions.CopyRow(array, dim);
}
}
}
if (h >=startH) // if there are states with same heuristic we randomly pick state
{
for (int i = 0; i < Hs.Count(); i++)
{
if (Hs[i] != h)
{
Is.RemoveAt(i);
Js.RemoveAt(i);
Hs.RemoveAt(i);
}
}
int rnd = new Random().Next(0, Is.Count());
for (int i = 0; i < dim; i++)
{
if (nizFinal[i][Js[rnd]] == 1)
{
nizFinal[i][Js[rnd]] = 0;
break;
}
}
nizFinal[Is[rnd]][Js[rnd]] = 1;
}
return nizFinal;
}
public IActionResult HillClimbingA(string stringArray,int dim,int stepsInSameState)
{
int[] array = _IFunctions.StringToInt(stringArray, dim);
int[][] Array = new int[dim][];
Array = _IFunctions.array1Dto2D(array, dim);
int h = _IFunctions.Heuristic(Array,dim);
int h2 = 1000;
int[][] array2;
int brojac = 0;
int brojac2 = 0;
while (h != 0 && stepsInSameState > brojac)
{
array2 = GetBestH(Array, dim,h); //Searching for next state with the best heuristic
h2 = _IFunctions.Heuristic(array2,dim);
if(h2>=h)
{
brojac++; //if we don't have better solution we keep the state with same h for stepsInSameState number of itterations
}
if (h2 <= h)
{
h = h2;
Array = _IFunctions.CopyRow(array2,dim);
h2 = 1000;
}
brojac2++;
}
HillClimbingVM VM = new HillClimbingVM()
{
array = _IFunctions.array2Dto1D(Array, dim),
dimension = dim,
heuristic = _IFunctions.Heuristic(Array, dim),
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
counter=brojac2,
stepsInSameState=stepsInSameState
};
return PartialView("HillClimbingDone",VM);
}
}
}<file_sep>/TicTac/TicTac/Controllers/AlphaBetaController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using TicTac.Models;
using TicTac.ViewModel;
namespace TicTac.Controllers
{
public class AlphaBetaController : Controller
{
public IActionResult Index(int Depth, Player player=(Player)0, int PlayerScore=0, int EqualScore=0, int CompScore=0)
{
//char[] array;
//if (HumanOnMove)
//{
char []array = new char[9] {'0', '0', '0', '0', '0', '0', '0', '0', '0' };
Node s=new Node();
if(player==(Player)1)
{
char[][] Array = new char[3][];
Array[0] = new char[3] { '0', '0', '0' };
Array[1] = new char[3] { '0', '0', '0' };
Array[2] = new char[3] { '0', '0', '0' };
s.niz = CopyRow(Array);
s.h = Heuristic(s.niz);
List<object> result = alphabet(s, Depth, int.MinValue, int.MaxValue, (Player)1);
s = (Node)result[1];
s.h = Heuristic(s.niz);
int brojac = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
array[brojac++]=s.niz[i][j];
}
}
}
AlphaBetaVM VM = new AlphaBetaVM()
{
array = array,
depth=Depth,
player=player,
isLeaf="false",
playerScore=PlayerScore,
compScore=CompScore,
equalScore=EqualScore,
depths = new List<SelectListItem>()
{
new SelectListItem{Text="Too Easy (1)",Value="1"},
new SelectListItem{Text="Easy (2)",Value="2"},
new SelectListItem{Text="Simple (3)",Value="3"},
new SelectListItem{Text="Medium (4)",Value="4"},
new SelectListItem{Text="Harder (5)",Value="5"},
new SelectListItem{Text="Hard (6)",Value="6"},
new SelectListItem{Text="Very difficult (7)",Value="7"},
new SelectListItem{Text="Extreme (8)",Value="8"},
new SelectListItem{Text="Impossible (9)",Value="8"}
}
};
return View(VM);
}
public IActionResult NextPlayer(int Depth)
{
return View();
}
public char[][] StringToChar2D(string stringArray)
{
char[][] array = new char[3][];
int brojac = 0;
for (int i = 0; i <3; i++)
{
array[i] = new char[3];
for (int j = 0; j < 3; j++)
{
array[i][j] = stringArray[brojac++];
}
}
return array;
}
public static bool IsLeaf(Node s)
{
if (s.h == 1000 || s.h == -1000)
return true;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (s.niz[i][j] == '0')
return false;
}
}
return true;
}
static char[][] CopyRow(char[][] niz)
{
char[][] niz2 = new char[3][];
for (int i = 0; i < 3; i++)
{
niz2[i] = new char[3];
for (int j = 0; j < 3; j++)
{
niz2[i][j] = niz[i][j];
}
}
return niz2;
}
public static int Heuristic(char[][] niz)
{
int h;
int sumX = 0;
int sumO = 0;
int brojacX = 0;
int brojacO = 0;
int brojacXO = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (niz[i][j] == 'X')
{
brojacX++;
}
else if (niz[i][j] == 'O')
{
brojacO++;
}
else
{
brojacXO++;
}
}
if (brojacX == 3)
{
return 1000;
}
else if (brojacO == 3)
return -1000;
else if (brojacXO == 3)
{
sumO++;
sumX++;
}
else if (brojacX + brojacXO == 3)
sumX++;
else if (brojacO + brojacXO == 3)
sumO++;
brojacO = 0;
brojacX = 0;
brojacXO = 0;
}
for (int j = 0; j < 3; j++)
{
for (int i = 0; i < 3; i++)
{
if (niz[i][j] == 'X')
{
brojacX++;
}
else if (niz[i][j] == 'O')
{
brojacO++;
}
else
{
brojacXO++;
}
}
if (brojacX == 3)
{
return 1000;
}
else if (brojacO == 3)
return -1000;
else if (brojacXO == 3)
{
sumO++;
sumX++;
}
else if (brojacX + brojacXO == 3)
sumX++;
else if (brojacO + brojacXO == 3)
sumO++;
brojacO = 0;
brojacX = 0;
brojacXO = 0;
}
for (int i = 0; i < 3; i++)
{
if (niz[i][i] == 'X')
{
brojacX++;
}
else if (niz[i][i] == 'O')
{
brojacO++;
}
else
{
brojacXO++;
}
}
if (brojacX == 3)
{
return 1000;
}
else if (brojacO == 3)
return -1000;
else if (brojacXO == 3)
{
sumO++;
sumX++;
}
else if (brojacX + brojacXO == 3)
sumX++;
else if (brojacO + brojacXO == 3)
sumO++;
brojacO = 0;
brojacX = 0;
brojacXO = 0;
int n = 2;
for (int i = 0; i < 3; i++)
{
if (niz[i][n] == 'X')
{
brojacX++;
}
else if (niz[i][n] == 'O')
{
brojacO++;
}
else
{
brojacXO++;
}
n--;
}
if (brojacX == 3)
{
return 1000;
}
else if (brojacO == 3)
return -1000;
else if (brojacXO == 3)
{
sumO++;
sumX++;
}
else if (brojacX + brojacXO == 3)
sumX++;
else if (brojacO + brojacXO == 3)
sumO++;
h = sumX - sumO;
return h;
}
public static List<Node> PossibleMoves(Node s, Player p)
{
List<Node> possibleMoves = new List<Node>();
int brojac = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (s.niz[i][j] == '0')
{
possibleMoves.Add(new Node());
possibleMoves[brojac].niz = CopyRow(s.niz);
if (p == (Player)0)
{
possibleMoves[brojac].niz[i][j] = 'O';
}
else
{
possibleMoves[brojac].niz[i][j] = 'X';
}
possibleMoves[brojac].h = Heuristic(possibleMoves[brojac].niz);
brojac++;
}
}
}
return possibleMoves;
}
public static List<object> alphabet(Node node, int depth, int α, int ß
, Player player)
{
if (depth == 0 || IsLeaf(node)) //
return new List<object>() { node.h, node }; //if we found the Leaf or we came to the marked depth we are returning that node
if (player == (Player)1)//If the maximizing player is on move we are calculating next move with the highest heuristi(state with highest possibility of winning the game)
{
int value = int.MinValue;
List<Node> children = PossibleMoves(node, player); //Calculating all possible moves for next player
Node move = null;
foreach (var child in children)
{
List<object> result = alphabet(child, depth - 1, α, ß, (Player)0);//for every child we are looking for the one with highest heuristic
if ((int)result[0] > value)
{
value = (int)result[0];
move = child;
}
if (value > α)
{
α = value;
move = child;
}
if (α >= ß)
break;
}
return new List<object>() { value, move };
}
else
{
int value = int.MaxValue;
List<Node> children = PossibleMoves(node, player);
Node move = null;
foreach (var child in children)
{
List<object> result = alphabet(child, depth - 1, α, ß, (Player)1);
if ((int)result[0] < value)
{
value = (int)result[0];
}
if (value < ß)
{
ß = value;
move = child;
}
if (α >= ß)
break;
}
return new List<object>() { value, move };
}
}
public static char[] Char2Dto1D(char[][] Array)
{
char[] array = new char[9];
int brojac = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
array[brojac] = Array[i][j];
brojac++;
}
}
return array;
}
public IActionResult AlphaBetaA(string stringArray,int depth,Player player,int PlayerScore, int EqualScore,int CompScore)
{
char[][] array = StringToChar2D(stringArray);
Node s=new Node();
s.niz = CopyRow(array);
s.h = Heuristic(s.niz);
List<object> result = alphabet(s, depth, int.MinValue, int.MaxValue, player);
s = (Node)result[1];
s.h = Heuristic(s.niz);
if (IsLeaf(s))
{
player = (player == (Player)0 ? (Player)1 : (Player)0);
if (s.h == 1000 && player == (Player)1)
PlayerScore ++;
else if (s.h == -1000 && player == (Player)1)
CompScore ++;
else if (s.h == 1000 && player == (Player)0)
CompScore ++;
else if (s.h == -1000 && player == (Player)0)
PlayerScore ++;
else
EqualScore ++;
}
AlphaBetaVM VM = new AlphaBetaVM()
{
array = Char2Dto1D(CopyRow(s.niz)),
player = player,
heuristic = s.h,
isLeaf = (IsLeaf(s) ? "true": "false"),
depth=depth,
playerScore=PlayerScore,
compScore=CompScore,
equalScore=EqualScore,
depths = new List<SelectListItem>()
{
new SelectListItem{Text="Too Easy (1)",Value="1"},
new SelectListItem{Text="Easy (2)",Value="2"},
new SelectListItem{Text="Simple (3)",Value="3"},
new SelectListItem{Text="Medium (4)",Value="4"},
new SelectListItem{Text="Harder (5)",Value="5"},
new SelectListItem{Text="Hard (6)",Value="6"},
new SelectListItem{Text="Very difficult (7)",Value="7"},
new SelectListItem{Text="Extreme (8)",Value="8"},
new SelectListItem{Text="Impossible (9)",Value="8"}
}
};
return PartialView("AlphaBetaA",VM);
}
}//U indexu da se prihvati array kojeg vrati partial view
}<file_sep>/Algorithms/Algorithms/Controllers/SimulatedAnealingController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Algorithms.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Algorithms.Controllers
{
public class SimulatedAnealingController : Controller
{
private FunctionsInterface _IFunctions;
public SimulatedAnealingController(FunctionsInterface IFunctions)
{
_IFunctions = IFunctions;
}
public IActionResult Index()
{
int[] a = new int[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
SimulatedAnealingVM VM = new SimulatedAnealingVM()
{
array = a,
dimension = 4,
heuristic = 0,
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
};
return View(VM);
}
public IActionResult GenerateRandomState(int dim, int T0, int coolingFactor)
{
int[][] array = _IFunctions.GenerateArray(dim);
SimulatedAnealingVM VM = new SimulatedAnealingVM()
{
array =_IFunctions.array2Dto1D(array, dim),
dimension = dim,
heuristic = _IFunctions.Heuristic(array, dim),
T0=T0,
coolingFactor=coolingFactor,
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
}
};
return View("Index", VM);
}
public IActionResult SimulatedAnealingA(string stringArray, int dim, int T0,int coolingFactor)
{
int[] array = _IFunctions.StringToInt(stringArray, dim);
int[][] Array = _IFunctions.array1Dto2D(array, dim);
int[][] array2;
int deltaH;
int Hs = 1;
int counter = 0;
while (T0 > 0 && Hs != 0) //do until the temperature reaches 0, or we found state with h0
{
array2 = _IFunctions.rndSuccessor(Array,dim);//make single random move
Hs = _IFunctions.Heuristic(array2,dim);
deltaH = Hs - _IFunctions.Heuristic(Array,dim);
if (deltaH < 0) //if the random state is better than previous state we use it as current state
{
Array = _IFunctions.CopyRow(array2,dim);
}
else if (Math.Pow(2.71828, -(deltaH / T0)) > new Random().NextDouble()) //if the state is worse than previous state, we calculate propability
{ //for selecting it anyway
Array = _IFunctions.CopyRow(array2,dim);
}
T0 -= coolingFactor; //decreasing temperature
counter++;
}
SimulatedAnealingVM VM = new SimulatedAnealingVM()
{
array = _IFunctions.array2Dto1D(Array, dim),
dimension = dim,
heuristic = _IFunctions.Heuristic(Array, dim),
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
counter = counter,
T0=T0,
coolingFactor=coolingFactor
};
return PartialView("SimulatedAnealingDone", VM);
}
}
}<file_sep>/Algorithms/Algorithms/Controllers/LocalBeamSearchController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Algorithms.Models;
using Algorithms.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Algorithms.Controllers
{
public class LocalBeamSearchController : Controller
{
private FunctionsInterface _IFunctions;
public LocalBeamSearchController(FunctionsInterface IFunctions)
{
_IFunctions = IFunctions;
}
public IActionResult Index()
{
int[] a = new int[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
LocalBeamSearchVM VM = new LocalBeamSearchVM()
{
array = a,
dimension = 4,
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
}
};
return View(VM);
}
public IActionResult GenerateRandomState(int dim,int states,int maxCounter)
{
int[][] array = _IFunctions.GenerateArray(dim);
LocalBeamSearchVM VM = new LocalBeamSearchVM()
{
array = _IFunctions.array2Dto1D(array, dim),
dimension = dim,
heuristic = _IFunctions.Heuristic(array, dim),
nmbrStates=states,
maxCounter=maxCounter,
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
};
return View("Index", VM);
}
public IActionResult LocalBeamSearchA(string stringArray, int dim,int states,int maxCounter)
{
int[] array = _IFunctions.StringToInt(stringArray, dim);
int[][] Array = _IFunctions.array1Dto2D(array, dim);
State[] BestStates = new State[states];
for (int i = 0; i < states; i++) //generating k random states
{
BestStates[i] = new State(dim);
BestStates[i].niz= _IFunctions.GenerateArray(dim);
BestStates[i].h = _IFunctions.Heuristic(BestStates[i].niz,dim);
}
bool change = true;
while (change) //sort initial states
{
change = false;
for (int i = 0; i < states - 1; i++)
{
if (BestStates[i].h > BestStates[i + 1].h)
{
State s = BestStates[i];
BestStates[i] = BestStates[i + 1];
BestStates[i + 1] = s;
change = true;
}
}
}
State[] allStates = new State[states * states];
int counter2 = 0;
while (BestStates[0].h != 0 && counter2 < maxCounter) // do until we find the state with h0, or until the counter reaches final status
{
int counter = 0;
for (int i = 0; i < states; i++)
{
for (int j = 0; j < states; j++)
{
allStates[counter] = new State(dim);
allStates[counter].niz =_IFunctions.rndSuccessor(_IFunctions.CopyRow(BestStates[j].niz,dim),dim); //for k states we are making k random single moves
allStates[counter].h = _IFunctions.Heuristic(allStates[counter].niz,dim);
counter++;
}
}
change = true; //sort expanded array
while (change)
{
change = false;
for (int i = 0; i < states * states - 1; i++)
{
if (allStates[i].h > allStates[i + 1].h)
{
State s = allStates[i];
allStates[i] = allStates[i + 1];
allStates[i + 1] = s;
change = true;
}
}
}
for (int i = 0; i < states; i++) //selecting k best states
{
BestStates[i].niz = _IFunctions.CopyRow(allStates[i].niz,dim);
BestStates[i].h = _IFunctions.Heuristic(allStates[i].niz,dim);
}
counter2++;
}
LocalBeamSearchVM VM = new LocalBeamSearchVM()
{
array = _IFunctions.array2Dto1D(BestStates[0].niz, dim),
dimension = dim,
heuristic = _IFunctions.Heuristic(BestStates[0].niz, dim),
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
counter = counter2,
nmbrStates=states,
maxCounter=maxCounter
};
return PartialView("LocalBeamSearchDone", VM);
}
}
}<file_sep>/Algorithms/Algorithms/FuntionsDefinition.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Algorithms
{
public class FuntionsDefinition : FunctionsInterface
{
public int[][] array1Dto2D(int[] array1D, int dim)
{
int[][] array2D = new int[dim][];
int counter = 0;
for (int i = 0; i < dim; i++)
{
array2D[i] = new int[dim];
for (int j = 0; j < dim; j++)
{
array2D[i][j] = array1D[counter++];
}
}
return array2D;
}
public int[] array2Dto1D(int[][] array2D, int dim)
{
int[] array1D = new int[dim * dim];
int counter = 0;
for (int i = 0; i < dim; i++)
{
for (int j = 0; j < dim; j++)
{
array1D[counter++] = array2D[i][j];
}
}
return array1D;
}
public int Heuristic(int[][] niz, int dim)
{
int h = 0;
for (int i = 0; i < dim; i++)
{
for (int j = 0; j < dim; j++)
{
if (niz[i][j] == 1)
{
for (int k = 0; k < dim; k++)
{
for (int n = j + 1; n < dim; n++)
{
if (k == i)
{
if (niz[k][n] == 1)
{
h++;
}
}
else if (k + n == i + j)
{
if (niz[k][n] == 1)
{
h++;
}
}
else if (k - i == n - j)
{
if (niz[k][n] == 1)
{
h++;
}
}
}
}
}
}
}
return h;
}
public int[][] CopyRow(int[][] array, int dim)
{
int[][] array2 = new int[dim][];
for (int i = 0; i < dim; i++)
{
array2[i] = new int[dim];
for (int j = 0; j < dim; j++)
{
array2[i][j] = array[i][j];
}
}
return array2;
}
public int[][] rndSuccessor(int[][] array, int dim)
{
int row = new Random().Next(0, dim);
int column = new Random().Next(0, dim);
while (array[row][column] == 1)
{
row = new Random().Next(0, dim);
column = new Random().Next(0, dim);
}
for (int i = 0; i < dim; i++)
{
if (array[i][column] == 1)
{
array[i][column] = 0;
break;
}
}
array[row][column] = 1;
return array;
}
public int[][] GenerateArray(int dim)
{
int[][] array = new int[dim][];
Array.Clear(array, 0, array.Length);
Random rnd = new Random();
int[] rndnNiz = new int[dim];
for (int i = 0; i < dim; i++)
{
array[i] = new int[dim];
rndnNiz[i] = rnd.Next(0, dim);
}
for (int i = 0; i < dim; i++)
{
for (int j = 0; j < dim; j++)
{
if (j == rndnNiz[i])
{
array[j][i] = 1;
break;
}
}
}
return array;
}
public int[] StringToInt(string stringArray, int dim)
{
int[] array = new int[dim * dim];
for (int i = 0; i < dim * dim; i++)
{
array[i] = (int)Char.GetNumericValue(stringArray, i);
}
return array;
}
}
}
<file_sep>/Algorithms/Algorithms/Controllers/GeneticController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Algorithms.Models;
using Algorithms.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Algorithms.Controllers
{
public class GeneticController : Controller
{
private FunctionsInterface _IFunctions;
public GeneticController(FunctionsInterface IFunctions)
{
_IFunctions = IFunctions;
}
public IActionResult Index()
{
int[] a = new int[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
GeneticVM VM = new GeneticVM()
{
array = a,
dimension = 4,
heuristic =_IFunctions.Heuristic(_IFunctions.array1Dto2D(a, 4), 4),
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
};
return View(VM);
}
public IActionResult GenerateRandomState(int dim, int populationSize, int elitism, int crossoverProb, int mutationProb, int nmbrGenerations)
{
int[][] Array = (_IFunctions.GenerateArray(dim));
GeneticVM VM = new GeneticVM()
{
array = _IFunctions.array2Dto1D(Array, dim),
dimension = dim,
heuristic = _IFunctions.Heuristic(Array, dim),
crossoverProb = crossoverProb,
elitism = elitism,
mutationProb = mutationProb,
nmbrGenerations = nmbrGenerations,
populationSize = populationSize,
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
}
};
return View("Index", VM);
}
static int rouletteSelection(List<State> chromosomes, int k)
{
int i = -1;
int sum = 0;
for (int j = 0; j < k; j++)
{
sum += chromosomes[j].h;
}
int a = new Random().Next(0, sum);
sum = 0;
do
{
i++;
sum += chromosomes[i].h;
} while (sum < a);
return i;
}
public void Crossover(State C1, State C2, int dim)
{
int x = new Random().Next(0, dim);
int y = new Random().Next(0, dim);
if (y < x)
{
int temp = y;
y = x;
x = temp;
}
for (int i = x; i < y + 1; i++)
{
for (int j = 0; j < dim; j++)
{
if (C1.niz[j][i] == 1 || C2.niz[j][i] == 1)
{
int temp = C1.niz[j][i];
C1.niz[j][i] = C2.niz[j][i];
C2.niz[j][i] = temp;
}
}
}
C1.h = _IFunctions.Heuristic(C1.niz, dim);
C2.h = _IFunctions.Heuristic(C2.niz, dim);
}
public void Mutation(State Cm, int dim)
{
int col1 = new Random().Next(0, dim);
int col2;
do
{
col2 = new Random().Next(0, dim);
} while (col2 == col1);
int temp;
for (int i = 0; i < dim; i++)
{
temp = Cm.niz[i][col1];
Cm.niz[i][col1] = Cm.niz[i][col2];
Cm.niz[i][col2] = temp;
}
Cm.h = _IFunctions.Heuristic(Cm.niz, dim);
}
public IActionResult GeneticA(string stringArray, int dim, int populationSize, int elitism, double crossoverProb, double mutationProb, int nmbrGenerations)
{
int[] array = _IFunctions.StringToInt(stringArray, dim);
int[][] Array = _IFunctions.array1Dto2D(array,dim);
List<State> chromosomes = new List<State>();
chromosomes.Add(new State(dim)); //adding initial state to chromosomes/random states
chromosomes[0].niz = Array;
chromosomes[0].h = _IFunctions.Heuristic(Array, dim);
for (int i = 1; i < populationSize; i++) //adding rest of random chromosomes/random states
{
chromosomes.Add(new State(dim));
chromosomes[i].niz = _IFunctions.GenerateArray(dim);
chromosomes[i].h = _IFunctions.Heuristic(chromosomes[i].niz, dim);
}
bool promjena;
State bestChromosome;
int brojac = 0;
while (nmbrGenerations > 0)//do until we go through all generations
{
promjena = true;
while (promjena) //sort chromosomes by h
{
promjena = false;
for (int i = 0; i < populationSize - 1; i++)
{
if (chromosomes[i].h > chromosomes[i + 1].h)
{
State s = chromosomes[i];
chromosomes[i] = chromosomes[i + 1];
chromosomes[i + 1] = s;
promjena = true;
}
}
}
bestChromosome = chromosomes[0];
if (bestChromosome.h == 0) //if we find solution
break;
List<State> chromsToAdd = new List<State>();
for (int i = 0; i < populationSize * elitism / 100; i++)
{
chromsToAdd.Add(chromosomes[i]); //adding elite chromosomes to the next generation
}
for (int i = chromsToAdd.Count() / 2; i < populationSize / 2; i++)//adding the rest of chromosomes to the next generation
{
int k = rouletteSelection(chromosomes, populationSize);//roulette Selection- select a parent
State C1 = chromosomes[k];
int n;
do
{
n = rouletteSelection(chromosomes, populationSize);//select second parent
} while (n == k);//restriction not to have same chromosome as two parents
State C2 = chromosomes[n];
State C1c = C1;
State C2c = C2;
if (new Random().NextDouble() < crossoverProb)//if the propability is high enough we do the crossover between two parents
{
Crossover(C1c, C2c, dim);
}
State C1m = C1c;
State C2m = C2c;
if (new Random().NextDouble() < mutationProb)//if the propability is high enough we do the mutation of each of the parents
{
Mutation(C1m, dim);
Mutation(C2m, dim);
}
chromsToAdd.Add(C1m);
chromsToAdd.Add(C2m);
}
brojac++;
chromosomes = chromsToAdd;
nmbrGenerations--;
}
if (chromosomes[0].h != 0)
{
promjena = true;
while (promjena) //because on the end of while loop we don't sort the final generation, so we do it here to
{
promjena = false;
for (int i = 0; i < populationSize - 1; i++)
{
if (chromosomes[i].h > chromosomes[i + 1].h)
{
State s = chromosomes[i];
chromosomes[i] = chromosomes[i + 1];
chromosomes[i + 1] = s;
promjena = true;
}
}
}
}
GeneticVM VM = new GeneticVM()
{
array = _IFunctions.array2Dto1D(chromosomes[0].niz, dim),
dimension = dim,
heuristic = chromosomes[0].h,
crossoverProb = crossoverProb,
elitism = elitism,
mutationProb = mutationProb,
nmbrGenerations = nmbrGenerations,
populationSize = populationSize,
dimensions = new List<SelectListItem>()
{
new SelectListItem{Text="4x4",Value="4"},
new SelectListItem{Text="5x5",Value="5"},
new SelectListItem{Text="6x6",Value="6"},
new SelectListItem{Text="7x7",Value="7"},
new SelectListItem{Text="8x8",Value="8"},
new SelectListItem{Text="9x9",Value="9"},
new SelectListItem{Text="10x10",Value="10"},
new SelectListItem{Text="11x11",Value="11"},
new SelectListItem{Text="12x12",Value="12"},
},
counter = brojac
};
return PartialView("GeneticDone", VM);
}
}
}<file_sep>/Algorithms/Algorithms/Models/State.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Algorithms.Models
{
public class State
{
public int[][] niz;
public int h;
public State(int dim)
{
niz = new int[dim][];
}
}
}
<file_sep>/Algorithms/Algorithms/ViewModel/SimulatedAnealingVM.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Algorithms.ViewModel
{
public class SimulatedAnealingVM
{
public int dimension { get; set; }
public int[] array { get; set; }
public int heuristic { get; set; }
public int counter { get; set; }
public int T0 { get; set; }
public int coolingFactor { get; set; }
public List<SelectListItem> dimensions { get; set; }
}
}
<file_sep>/Algorithms/Algorithms/ViewModel/GeneticVM.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Algorithms.ViewModel
{
public class GeneticVM
{
public int dimension { get; set; }
public int[] array { get; set; }
public int heuristic { get; set; }
public int counter { get; set; }
public List<SelectListItem> dimensions { get; set; }
public int populationSize { get; set; }
public int elitism { get; set; }
public double crossoverProb { get; set; }
public double mutationProb { get; set; }
public int nmbrGenerations { get; set; }
}
}
<file_sep>/Algorithms/Algorithms/FunctionsInterface.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Algorithms
{
public interface FunctionsInterface
{
int[][] array1Dto2D(int[] array1D, int dim);
int[] array2Dto1D(int[][] array2D, int dim);
int Heuristic(int[][] niz, int dim);
int[][] CopyRow(int[][] array, int dim);
int[] StringToInt(string stringArray, int dim);
int[][] GenerateArray(int dim);
int[][] rndSuccessor(int[][] array, int dim);
}
}
<file_sep>/Algorithms/Algorithms/Models/CommonFunctions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Algorithms.Models
{
public class CommonFunctions
{
public static int[][] array1Dto2D(int[] array1D, int dim)
{
int[][] array2D = new int[dim][];
int counter = 0;
for (int i = 0; i < dim; i++)
{
array2D[i] = new int[dim];
for (int j = 0; j < dim; j++)
{
array2D[i][j] = array1D[counter++];
}
}
return array2D;
}
}
}
<file_sep>/TicTac/TicTac/Models/Node.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TicTac.Models
{
public class Node
{
public char[][] niz;
public int h;
public Node()
{
niz = new char[3][];
for (int i = 0; i < 3; i++)
{
niz[i] = new char[3];
}
}
}
}
| f2586854e91cd8327e23cafff5dd3c012c994280 | [
"C#"
] | 13 | C# | EnesHockic/Artificial-intelligence | 88e31385d6e8785a19eb2c5c8d9e1c55df39a1b5 | 80f7bc20280c8faf4b042fed06f9a05b68833dce |
refs/heads/master | <file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
package remote
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"testing"
"github.com/golang/protobuf/proto"
"github.com/googleapis/gnostic/OpenAPIv2"
"github.com/splunk/qbec/internal/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
)
type disco struct {
Groups *metav1.APIGroupList `json:"groups"`
ResourceLists map[string]*metav1.APIResourceList `json:"resourceLists"`
}
func (d *disco) ServerGroups() (*metav1.APIGroupList, error) {
return d.Groups, nil
}
func (d *disco) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {
parts := strings.SplitN(groupVersion, "/", 2)
var group, version string
if len(parts) == 2 {
group, version = parts[0], parts[1]
} else {
version = parts[0]
}
key := fmt.Sprintf("%s:%s", group, version)
rl := d.ResourceLists[key]
if rl == nil {
return nil, fmt.Errorf("no resources for %s", groupVersion)
}
return rl, nil
}
func (d *disco) OpenAPISchema() (*openapi_v2.Document, error) {
b, err := ioutil.ReadFile(filepath.Join("testdata", "swagger-2.0.0.pb-v1"))
if err != nil {
return nil, err
}
var doc openapi_v2.Document
if err := proto.Unmarshal(b, &doc); err != nil {
return nil, err
}
return &doc, nil
}
func getServerMetadata(t *testing.T, verbosity int) *ServerMetadata {
var d disco
b, err := ioutil.ReadFile(filepath.Join("testdata", "metadata.json"))
require.Nil(t, err)
err = json.Unmarshal(b, &d)
require.Nil(t, err)
sm, err := newServerMetadata(&d, "foobar", verbosity)
require.Nil(t, err)
return sm
}
func loadObject(t *testing.T, file string) model.K8sObject {
b, err := ioutil.ReadFile(filepath.Join("testdata", file))
require.Nil(t, err)
var d map[string]interface{}
err = json.Unmarshal(b, &d)
require.Nil(t, err)
return model.NewK8sObject(d)
}
func TestMetadataCanonical(t *testing.T) {
a := assert.New(t)
sm := getServerMetadata(t, 2)
expected := schema.GroupVersionKind{Group: "extensions", Version: "v1beta1", Kind: "Deployment"}
canon, err := sm.canonicalGroupVersionKind(expected)
require.Nil(t, err)
a.EqualValues(expected, canon)
canon, err = sm.canonicalGroupVersionKind(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"})
require.Nil(t, err)
a.EqualValues(expected, canon)
canon, err = sm.canonicalGroupVersionKind(schema.GroupVersionKind{Group: "apps", Version: "v1beta1", Kind: "Deployment"})
require.Nil(t, err)
a.EqualValues(expected, canon)
}
func TestMetadataOther(t *testing.T) {
a := assert.New(t)
sm := getServerMetadata(t, 0)
n, err := sm.IsNamespaced(schema.GroupVersionKind{Group: "extensions", Version: "v1beta1", Kind: "Deployment"})
require.Nil(t, err)
a.True(n)
n, err = sm.IsNamespaced(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRole"})
require.Nil(t, err)
a.False(n)
_, err = sm.IsNamespaced(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "FooBar"})
require.NotNil(t, err)
a.Equal("server does not recognize gvk /v1, Kind=FooBar", err.Error())
name := sm.DisplayName(loadObject(t, "ns-good.json"))
a.Equal("namespaces foobar", name)
ob := loadObject(t, "ns-good.json")
name = sm.DisplayName(model.NewK8sLocalObject(ob.ToUnstructured().Object, "app1", "c1", "dev"))
a.Equal("namespaces foobar (source c1)", name)
}
func TestMetadataValidator(t *testing.T) {
a := assert.New(t)
sm := getServerMetadata(t, 0)
v, err := sm.ValidatorFor(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Namespace"})
require.Nil(t, err)
errs := v.Validate(loadObject(t, "ns-good.json").ToUnstructured())
require.Nil(t, errs)
errs = v.Validate(loadObject(t, "ns-bad.json").ToUnstructured())
require.NotNil(t, errs)
a.Equal(1, len(errs))
a.Contains(errs[0].Error(), `unknown field "foo"`)
_, err = sm.ValidatorFor(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "FooBar"})
require.NotNil(t, err)
a.Equal(ErrSchemaNotFound, err)
}
<file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
package vm
import (
"encoding/json"
"os"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type code struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}
type result struct {
TLAStr string `json:"tlaStr"`
TLACode bool `json:"tlaCode"`
ExtStr string `json:"extStr"`
ExtCode code `json:"extCode"`
LibPath1 code `json:"libpath1"`
LibPath2 code `json:"libpath2"`
InlineStr string `json:"inlineStr"`
InlineCode bool `json:"inlineCode"`
}
var evalCode = `
function (tlaStr,tlaCode) {
tlaStr: tlaStr,
tlaCode: tlaCode,
extStr: std.extVar('extStr'),
extCode: std.extVar('extCode'),
libPath1: import 'libcode1.libsonnet',
libPath2: import 'libcode2.libsonnet',
inlineStr: std.extVar('inlineStr'),
inlineCode: std.extVar('inlineCode'),
}
`
func TestVMConfig(t *testing.T) {
var fn func() (Config, error)
var cfg Config
var output string
cmd := &cobra.Command{
Use: "show",
RunE: func(c *cobra.Command, args []string) error {
var err error
cfg, err = fn()
if err != nil {
return err
}
baseVM := New(cfg)
cfg = baseVM.Config().WithLibPaths([]string{"testdata/lib2"}).
WithVars(map[string]string{"inlineStr": "ifoo"}).
WithCodeVars(map[string]string{"inlineCode": "true"})
jvm := New(cfg)
output, err = jvm.EvaluateSnippet("test.jsonnet", evalCode)
return err
},
}
cmd.SilenceUsage = true
cmd.SilenceErrors = true
fn = ConfigFromCommandParams(cmd, "vm:")
cmd.SetArgs([]string{
"show",
"--vm:ext-str=extStr",
"--vm:ext-code-file=extCode=testdata/extCode.libsonnet",
"--vm:tla-str=tlaStr=tlafoo",
"--vm:tla-code=tlaCode=true",
"--vm:jpath=testdata/lib1",
})
os.Setenv("extStr", "envFoo")
defer os.Setenv("extStr", "")
err := cmd.Execute()
require.Nil(t, err)
var r result
err = json.Unmarshal([]byte(output), &r)
require.Nil(t, err)
assert.EqualValues(t, result{
TLAStr: "tlafoo",
TLACode: true,
ExtStr: "envFoo",
ExtCode: code{Foo: "ec1foo", Bar: "ec1bar"},
LibPath1: code{Foo: "lc1foo", Bar: "lc1bar"},
LibPath2: code{Foo: "lc2foo", Bar: "lc2bar"},
InlineStr: "ifoo",
InlineCode: true,
}, r)
}
func TestVMNegative(t *testing.T) {
execInVM := func(code string, args []string) error {
var fn func() (Config, error)
cmd := &cobra.Command{
Use: "show",
RunE: func(c *cobra.Command, args []string) error {
var err error
cfg, err := fn()
if err != nil {
return err
}
jvm := New(cfg)
if code == "" {
code = "{}"
}
_, err = jvm.EvaluateSnippet("test.jsonnet", code)
return err
},
}
fn = ConfigFromCommandParams(cmd, "vm:")
cmd.SetArgs(args)
cmd.SilenceUsage = true
cmd.SilenceErrors = true
return cmd.Execute()
}
tests := []struct {
name string
code string
args []string
asserter func(a *assert.Assertions, err error)
}{
{
name: "ext-str-undef",
args: []string{"show", "--vm:ext-str=undef_foo"},
asserter: func(a *assert.Assertions, err error) {
require.NotNil(t, err)
a.Contains(err.Error(), "no value found from environment for undef_foo")
},
},
{
name: "ext-code-undef",
args: []string{"show", "--vm:ext-code=undef_foo"},
asserter: func(a *assert.Assertions, err error) {
require.NotNil(t, err)
a.Contains(err.Error(), "no value found from environment for undef_foo")
},
},
{
name: "tla-str-undef",
args: []string{"show", "--vm:tla-str=undef_foo"},
asserter: func(a *assert.Assertions, err error) {
require.NotNil(t, err)
a.Contains(err.Error(), "no value found from environment for undef_foo")
},
},
{
name: "tla-code-undef",
args: []string{"show", "--vm:tla-code=undef_foo"},
asserter: func(a *assert.Assertions, err error) {
require.NotNil(t, err)
a.Contains(err.Error(), "no value found from environment for undef_foo")
},
},
{
name: "ext-file-undef",
args: []string{"show", "--vm:ext-str-file=foo"},
asserter: func(a *assert.Assertions, err error) {
require.NotNil(t, err)
a.Contains(err.Error(), "ext-str-file no filename specified for foo")
},
},
{
name: "tla-file-undef",
args: []string{"show", "--vm:tla-str-file=foo=bar"},
asserter: func(a *assert.Assertions, err error) {
require.NotNil(t, err)
a.Contains(err.Error(), "open bar: no such file or directory")
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
a := assert.New(t)
err := execInVM(test.code, test.args)
test.asserter(a, err)
})
}
}
func TestVMFromScratch(t *testing.T) {
cfg := Config{}.
WithVars(map[string]string{"foo": "bar"}).
WithCodeVars(map[string]string{"bar": "true"})
jvm := New(cfg)
out, err := jvm.EvaluateSnippet("test.jsonnet", `std.extVar('foo') + std.toString(std.extVar('bar'))`)
require.Nil(t, err)
assert.Equal(t, `"bartrue"`+"\n", out)
}
<file_sep>---
title: Application YAML
weight: 10
---
The app configuration is a file called `qbec.yaml` and needs to be at the root of the directory tree.
```yaml
apiVersion: qbec.io/v1alpha1 # only supported version currently
kind: App # must always be "App"
metadata:
name: my-app # app name. Allows multiple qbec apps to deploy different objects to the same namespace without GC collisions
spec:
componentsDir: components # directory where component files can be found. Not recursive. default: components
paramsFile: params.libsonnet # file to load for `param list` and `param diff` commands. Not otherwise used.
libPaths: # additional library paths when executing jsonnet, no support currently for `http` URLs.
- additional
- local
- library
- paths
excludes: # list of components to exclude by default
- components
- to
- exclude
- by
- default
environments: # map of environment names to environment objects
minikube:
server: https://minikube:8443 # server end point
defaultNamespace: my-ns # the namespace to use when namespaced object does not define it.
includes: # components to include, subset of global exclusion list
- components
- to
- include
excludes: # additional components to exclude
- more
- exclusions
dev:
server: https://dev-server
```
### Notes
* The list of components is loaded from the `componentsDir` directory. Components may be `.jsonnet`, `.json` or `.yaml`
files. The name of the component is the name of the file without the extension. You may not create two files with the
same name and different extensions.
* Once the list is loaded, all exclusion and inclusion lists are checked to ensure that they refer to valid components.
* The global exclusion list allows you to introduce a new component gradually by only including it in a dev environment.
<file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
package eval
import (
"testing"
"github.com/splunk/qbec/internal/model"
"github.com/splunk/qbec/internal/vm"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEvalParams(t *testing.T) {
paramsMap, err := Params("testdata/params.libsonnet", Context{
Env: "dev",
Verbose: true,
})
require.Nil(t, err)
a := assert.New(t)
comps, ok := paramsMap["components"].(map[string]interface{})
require.True(t, ok)
base, ok := comps["base"].(map[string]interface{})
require.True(t, ok)
a.EqualValues("dev", base["env"])
}
func TestEvalParamsNegative(t *testing.T) {
_, err := Params("testdata/params.invalid.libsonnet", Context{Env: "dev"})
require.NotNil(t, err)
require.Contains(t, err.Error(), "end of file")
_, err = Params("testdata/params.non-object.libsonnet", Context{Env: "dev"})
require.NotNil(t, err)
require.Contains(t, err.Error(), "cannot unmarshal array")
}
func TestEvalComponents(t *testing.T) {
objs, err := Components([]model.Component{
{
Name: "b",
File: "testdata/components/b.yaml",
},
{
Name: "c",
File: "testdata/components/c.jsonnet",
},
{
Name: "a",
File: "testdata/components/a.json",
},
}, Context{Env: "dev", Verbose: true})
require.Nil(t, err)
require.Equal(t, 3, len(objs))
a := assert.New(t)
obj := objs[0]
a.Equal("a", obj.Component())
a.Equal("dev", obj.Environment())
a.Equal("", obj.GetObjectKind().GroupVersionKind().Group)
a.Equal("v1", obj.GetObjectKind().GroupVersionKind().Version)
a.Equal("ConfigMap", obj.GetObjectKind().GroupVersionKind().Kind)
a.Equal("", obj.GetNamespace())
a.Equal("json-config-map", obj.GetName())
obj = objs[1]
a.Equal("b", obj.Component())
a.Equal("dev", obj.Environment())
a.Equal("yaml-config-map", obj.GetName())
obj = objs[2]
a.Equal("c", obj.Component())
a.Equal("dev", obj.Environment())
a.Equal("jsonnet-config-map", obj.GetName())
}
func TestEvalComponentsBadJson(t *testing.T) {
_, err := Components([]model.Component{
{
Name: "bad",
File: "testdata/components/bad.json",
},
}, Context{Env: "dev", VM: vm.New(vm.Config{})})
require.NotNil(t, err)
require.Contains(t, err.Error(), "invalid character")
}
func TestEvalComponentsBadYaml(t *testing.T) {
_, err := Components([]model.Component{
{
Name: "bad",
File: "testdata/components/bad.yaml",
},
}, Context{Env: "dev", VM: vm.New(vm.Config{})})
require.NotNil(t, err)
require.Contains(t, err.Error(), "did not find expected node content")
}
func TestEvalComponentsBadObjects(t *testing.T) {
_, err := Components([]model.Component{
{
Name: "bad",
File: "testdata/components/bad-objects.yaml",
},
}, Context{Env: "dev", VM: vm.New(vm.Config{})})
require.NotNil(t, err)
require.Contains(t, err.Error(), `unexpected type for object (string) at path "$.bad[0].foo"`)
}
<file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
// Package commands contains the implementation of all qbec commands.
package commands
import (
"fmt"
"io"
"strings"
"sync"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/splunk/qbec/internal/model"
"github.com/splunk/qbec/internal/objsort"
"github.com/splunk/qbec/internal/remote"
"github.com/splunk/qbec/internal/sio"
"github.com/splunk/qbec/internal/vm"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// usageError indicates that the user supplied incorrect arguments or flags to the command.
type usageError struct {
error
}
// newUsageError returns a usage error
func newUsageError(msg string) error {
return &usageError{
error: errors.New(msg),
}
}
// isUsageError returns if the supplied error was caused due to incorrect command usage.
func isUsageError(err error) bool {
_, ok := err.(*usageError)
return ok
}
// runtimeError indicates that there were runtime issues with execution.
type runtimeError struct {
error
}
// newRuntimeError returns a runtime error
func newRuntimeError(err error) error {
return &runtimeError{
error: err,
}
}
// IsRuntimeError returns if the supplied error was a runtime error as opposed to an error arising out of user input.
func IsRuntimeError(err error) bool {
_, ok := err.(*runtimeError)
return ok
}
// wrapError passes through usage errors and wraps all other errors with a runtime marker.
func wrapError(err error) error {
if err == nil {
return nil
}
if isUsageError(err) {
return err
}
return newRuntimeError(err)
}
// StdOptions provides standardized access to information available to every command.
type StdOptions interface {
App() *model.App // the app loaded for the command
VM() *vm.VM // the base VM constructed out of command line args and potentially app information
Colorize() bool // returns if colorized output is needed
Verbosity() int // returns the verbosity level
SortConfig(provider objsort.Namespaced) objsort.Config // returns the apply sort config potentially using hints from the app
Stdout() io.Writer // output to write to
DefaultNamespace(env string) string // the default namespace for the supplied environment
Confirm(context string) error // confirmation function for dangerous operations
}
// Client encapsulates all remote operations needed for the superset of all commands.
type Client interface {
DisplayName(o model.K8sMeta) string
IsNamespaced(kind schema.GroupVersionKind) (bool, error)
Get(obj model.K8sMeta) (*unstructured.Unstructured, error)
Sync(obj model.K8sLocalObject, opts remote.SyncOptions) (*remote.SyncResult, error)
ValidatorFor(gvk schema.GroupVersionKind) (remote.Validator, error)
ListExtraObjects(ignore []model.K8sQbecMeta, scope remote.ListQueryConfig) ([]model.K8sQbecMeta, error)
Delete(obj model.K8sMeta, dryRun bool) (*remote.SyncResult, error)
}
// StdOptionsWithClient provides a remote client in addition to standard options.
type StdOptionsWithClient interface {
StdOptions // base options
Client(env string) (Client, error) // a client valid for the supplied environment
}
// OptionsProvider provides standard configuration available to all commands
type OptionsProvider func() StdOptionsWithClient
// Setup sets up all subcommands for the supplied root command.
func Setup(root *cobra.Command, op OptionsProvider) {
root.AddCommand(newApplyCommand(op))
root.AddCommand(newValidateCommand(op))
root.AddCommand(newShowCommand(op))
root.AddCommand(newDiffCommand(op))
root.AddCommand(newDeleteCommand(op))
root.AddCommand(newComponentCommand(op))
root.AddCommand(newParamCommand(op))
root.AddCommand(newInitCommand())
}
type worker func(object model.K8sLocalObject) error
func runInParallel(objs []model.K8sLocalObject, worker worker, parallel int) error {
if parallel <= 0 {
parallel = 1
}
ch := make(chan model.K8sLocalObject, len(objs))
for _, o := range objs {
ch <- o
}
close(ch)
var wg sync.WaitGroup
errs := make(chan error, parallel)
for i := 0; i < parallel; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for o := range ch {
err := worker(o)
if err != nil {
errs <- errors.Wrap(err, fmt.Sprint(o))
return
}
}
}()
}
wg.Wait()
close(errs)
errMsgs := []string{}
for e := range errs {
errMsgs = append(errMsgs, e.Error())
}
if len(errMsgs) > 0 {
return errors.New(strings.Join(errMsgs, "\n"))
}
return nil
}
func printStats(w io.Writer, stats interface{}) {
summary := struct {
Stats interface{} `json:"stats"`
}{stats}
b, err := yaml.Marshal(summary)
if err != nil {
sio.Warnln("unable to print summary stats", err)
}
fmt.Fprintf(w, "---\n%s\n", b)
}
type lockWriter struct {
io.Writer
l sync.Mutex
}
func (lw *lockWriter) Write(buf []byte) (int, error) {
lw.l.Lock()
n, err := lw.Writer.Write(buf)
lw.l.Unlock()
return n, err
}
<file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
package model
//go:generate gen-qbec-swagger swagger.yaml swagger-schema.go
// Environment points to a specific destination and has its own set of runtime parameters.
type Environment struct {
DefaultNamespace string `json:"defaultNamespace"` // default namespace to set for k8s context
Server string `json:"server"` // server URL of server
Includes []string `json:"includes,omitempty"` // components to be included in this env even if excluded at the app level
Excludes []string `json:"excludes,omitempty"` // additional components to exclude for this env
}
// AppMeta is the simplified metadata object for a qbec app.
type AppMeta struct {
// required: true
Name string `json:"name"`
}
// AppSpec is the user-supplied configuration of the qbec app.
type AppSpec struct {
// directory containing component files, default to components/
ComponentsDir string `json:"componentsDir,omitempty"`
// standard file containing parameters for all environments returning correct values based on qbec.io/env external
// variable, defaults to params.libsonnet
ParamsFile string `json:"paramsFile,omitempty"`
// set of environments for the app
// required: true
Environments map[string]Environment `json:"environments"`
// list of components to exclude by default for every environment
Excludes []string `json:"excludes,omitempty"`
// list of library paths to add to the jsonnet VM at evaluation
LibPaths []string `json:"libPaths,omitempty"`
}
// QbecApp is a set of components that can be applied to multiple environments with tweaked runtime configurations.
// The list of all components for the app is derived as all the supported (jsonnet, json, yaml) files in the components subdirectory.
// swagger:model App
type QbecApp struct {
// object kind
// required: true
// pattern: ^App$
Kind string `json:"kind"`
// requested API version
// required: true
APIVersion string `json:"apiVersion"`
// app metadata
// required: true
Metadata AppMeta `json:"metadata,omitempty"`
// app specification
// required: true
Spec AppSpec `json:"spec"`
}
<file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
// Package model contains the app definition and interfaces for dealing with K8s objects.
package model
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"github.com/splunk/qbec/internal/sio"
)
// Baseline is a special environment name that represents the baseline environment with no customizations.
const Baseline = "_"
// Default values
const (
DefaultComponentsDir = "components" // the default components directory
DefaultParamsFile = "params.libsonnet" // the default params files
)
var supportedExtensions = map[string]bool{
".jsonnet": true,
".yaml": true,
".json": true,
}
// Component is a file that contains objects to be applied to a cluster.
type Component struct {
Name string // component name
File string // path to component file
}
// App is a qbec application wrapped with some runtime attributes.
type App struct {
QbecApp
root string // derived root directory of the app
allComponents map[string]Component // all components whether or not included anywhere
defaultComponents map[string]Component // all components enabled by default
}
// NewApp returns an app loading its details from the supplied file.
func NewApp(file string) (*App, error) {
b, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
var qApp QbecApp
if err := yaml.Unmarshal(b, &qApp); err != nil {
return nil, errors.Wrap(err, "unmarshal YAML")
}
// validate YAML against schema
v, err := newValidator()
if err != nil {
return nil, errors.Wrap(err, "create schema validator")
}
errs := v.validateYAML(b)
if len(errs) > 0 {
var msgs []string
for _, err := range errs {
msgs = append(msgs, err.Error())
}
return nil, fmt.Errorf("%d schema validation error(s): %s", len(errs), strings.Join(msgs, "\n"))
}
app := App{QbecApp: qApp}
dir := filepath.Dir(file)
if !filepath.IsAbs(dir) {
var err error
dir, err = filepath.Abs(dir)
if err != nil {
return nil, errors.Wrap(err, "abs path for "+dir)
}
}
app.root = dir
app.setupDefaults()
app.allComponents, err = app.loadComponents()
if err != nil {
return nil, errors.Wrap(err, "load components")
}
if err := app.verifyEnvAndComponentReferences(); err != nil {
return nil, err
}
app.defaultComponents = make(map[string]Component, len(app.allComponents))
for k, v := range app.allComponents {
app.defaultComponents[k] = v
}
for _, k := range app.Spec.Excludes {
delete(app.defaultComponents, k)
}
return &app, nil
}
func (a *App) setupDefaults() {
if a.Spec.ComponentsDir == "" {
a.Spec.ComponentsDir = DefaultComponentsDir
}
if a.Spec.ParamsFile == "" {
a.Spec.ParamsFile = DefaultParamsFile
}
}
// Name returns the name of the application.
func (a *App) Name() string {
return a.Metadata.Name
}
// ComponentsForEnvironment returns a slice of components for the specified
// environment, taking intrinsic as well as specified inclusions and exclusions into account.
// All names in the supplied subsets must be valid component names. If a specified component is valid but has been excluded
// for the environment, it is simply not returned. The environment can be specified as the baseline
// environment.
func (a *App) ComponentsForEnvironment(env string, includes, excludes []string) ([]Component, error) {
toList := func(m map[string]Component) []Component {
var ret []Component
for _, v := range m {
ret = append(ret, v)
}
sort.Slice(ret, func(i, j int) bool {
return ret[i].Name < ret[j].Name
})
return ret
}
cf, err := NewComponentFilter(includes, excludes)
if err != nil {
return nil, err
}
if err := a.verifyComponentList("specified components", includes); err != nil {
return nil, err
}
if err := a.verifyComponentList("specified components", excludes); err != nil {
return nil, err
}
ret := map[string]Component{}
if env == Baseline {
for k, v := range a.defaultComponents {
ret[k] = v
}
} else {
e, ok := a.Spec.Environments[env]
if !ok {
return nil, fmt.Errorf("invalid environment %q", env)
}
for k, v := range a.defaultComponents {
ret[k] = v
}
for _, k := range e.Excludes {
if _, ok := ret[k]; !ok {
sio.Warnf("component %s excluded from %s is already excluded by default\n", k, env)
}
delete(ret, k)
}
for _, k := range e.Includes {
if _, ok := ret[k]; ok {
sio.Warnf("component %s included from %s is already included by default\n", k, env)
}
ret[k] = a.allComponents[k]
}
}
if !cf.HasFilters() {
return toList(ret), nil
}
for _, k := range includes {
if _, ok := ret[k]; !ok {
sio.Noticef("not including component %s since it is not part of the component list for %s\n", k, env)
}
}
subret := map[string]Component{}
for k, v := range ret {
if cf.ShouldInclude(v.Name) {
subret[k] = v
}
}
return toList(subret), nil
}
// loadComponents loads metadata for all components for the app.
// The data is returned as a map keyed by component name. It does _not_ recurse
// into subdirectories.
func (a *App) loadComponents() (map[string]Component, error) {
var list []Component
dir := strings.TrimSuffix(filepath.Clean(a.Spec.ComponentsDir), "/")
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if path == dir {
return nil
}
if info.IsDir() {
return filepath.SkipDir
}
extension := filepath.Ext(path)
if supportedExtensions[extension] {
list = append(list, Component{
Name: strings.TrimSuffix(filepath.Base(path), extension),
File: path,
})
}
return nil
})
if err != nil {
return nil, err
}
m := make(map[string]Component, len(list))
for _, c := range list {
if old, ok := m[c.Name]; ok {
return nil, fmt.Errorf("duplicate component %s, found %s and %s", c.Name, old.File, c.File)
}
m[c.Name] = c
}
return m, nil
}
func (a *App) verifyComponentList(src string, comps []string) error {
var bad []string
for _, c := range comps {
if _, ok := a.allComponents[c]; !ok {
bad = append(bad, c)
}
}
if len(bad) > 0 {
return fmt.Errorf("%s: bad component reference(s): %s", src, strings.Join(bad, ","))
}
return nil
}
var reEnvName = regexp.MustCompile(`^(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$`) // XXX: duplicated in swagger
func (a *App) verifyEnvAndComponentReferences() error {
var errs []string
localVerify := func(src string, comps []string) {
if err := a.verifyComponentList(src, comps); err != nil {
errs = append(errs, err.Error())
}
}
localVerify("default exclusions", a.Spec.Excludes)
for e, env := range a.Spec.Environments {
if e == Baseline {
return fmt.Errorf("cannot use _ as an environment name since it has a special meaning")
}
if !reEnvName.MatchString(e) {
return fmt.Errorf("invalid environment %s, must match %s", e, reEnvName)
}
localVerify(e+" inclusions", env.Includes)
localVerify(e+" exclusions", env.Excludes)
includeMap := map[string]bool{}
for _, inc := range env.Includes {
includeMap[inc] = true
}
for _, exc := range env.Excludes {
if includeMap[exc] {
errs = append(errs, fmt.Sprintf("env %s: component %s present in both include and exclude sections", e, exc))
}
}
}
if len(errs) > 0 {
return fmt.Errorf("invalid component references\n:\t%s", strings.Join(errs, "\n\t"))
}
return nil
}
<file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/chzyer/readline"
"github.com/mattn/go-isatty"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/splunk/qbec/internal/commands"
"github.com/splunk/qbec/internal/model"
"github.com/splunk/qbec/internal/objsort"
"github.com/splunk/qbec/internal/remote"
"github.com/splunk/qbec/internal/sio"
"github.com/splunk/qbec/internal/vm"
"k8s.io/apimachinery/pkg/runtime/schema"
)
type gOpts struct {
verbose int // verbosity level
app *model.App // app loaded from file
config vm.Config // jsonnet VM config
k8sConfig *remote.Config // remote config for k8s, when needed
colors bool // colorize output
yes bool // auto-confirm
}
func (g gOpts) App() *model.App {
return g.app
}
func (g gOpts) VM() *vm.VM {
cfg := g.config.WithLibPaths(g.app.Spec.LibPaths)
return vm.New(cfg)
}
func (g gOpts) Colorize() bool {
return g.colors
}
func (g gOpts) Verbosity() int {
return g.verbose
}
type client struct {
*remote.Client
}
func (c *client) ValidatorFor(gvk schema.GroupVersionKind) (remote.Validator, error) {
return c.ServerMetadata().ValidatorFor(gvk)
}
func (c *client) DisplayName(o model.K8sMeta) string {
return c.ServerMetadata().DisplayName(o)
}
func (c *client) IsNamespaced(kind schema.GroupVersionKind) (bool, error) {
return c.ServerMetadata().IsNamespaced(kind)
}
func (g gOpts) DefaultNamespace(env string) string {
envObj := g.app.Spec.Environments[env]
ns := envObj.DefaultNamespace
if ns == "" {
ns = "default"
}
return ns
}
func (g gOpts) Client(env string) (commands.Client, error) {
envObj, ok := g.app.Spec.Environments[env]
if !ok {
return nil, fmt.Errorf("get client: invalid environment %q", env)
}
ns := envObj.DefaultNamespace
if ns == "" {
ns = "default"
}
rem, err := g.k8sConfig.Client(remote.ConnectOpts{
EnvName: env,
ServerURL: envObj.Server,
Namespace: ns,
Verbosity: g.verbose,
})
if err != nil {
return nil, err
}
return &client{Client: rem}, nil
}
func (g gOpts) SortConfig(provider objsort.Namespaced) objsort.Config {
return objsort.Config{
NamespacedIndicator: func(gvk schema.GroupVersionKind) (bool, error) {
ret, err := provider(gvk)
if err != nil {
return false, err
}
return ret, nil
},
}
}
func (g gOpts) Stdout() io.Writer {
return os.Stdout
}
func (g gOpts) Confirm(context string) error {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, context)
fmt.Fprintln(os.Stderr)
if g.yes {
return nil
}
inst, err := readline.New("Do you want to continue [y/n]: ")
if err != nil {
return err
}
for {
s, err := inst.Readline()
if err != nil {
return err
}
if s == "y" {
return nil
}
if s == "n" {
return errors.New("canceled")
}
}
}
func envOrDefault(name, def string) string {
v := os.Getenv(name)
if v != "" {
return v
}
return def
}
func defaultRoot() string {
return envOrDefault("QBEC_ROOT", "")
}
func usageTemplate(rootCmd string) string {
return fmt.Sprintf(`Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
Use "%s options" for a list of global options available to all commands.
`, rootCmd)
}
var expectedFiles = []string{"qbec.yaml"}
// setWorkDir sets the working dir of the current process as the top-level
// directory of the source tree. The current working directory of the process
// must be somewhere at or under this tree. If the specified argument is non-empty
// then it is returned provided it is a valid root.
func setWorkDir(specified string) error {
isRootDir := func(dir string) bool {
for _, f := range expectedFiles {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil {
return false
}
}
return true
}
cwd, err := os.Getwd()
if err != nil {
return errors.Wrap(err, "os.Getwd")
}
orig := cwd
doChdir := func(dir string) error {
if orig != dir {
sio.Debugln(fmt.Sprintf("cd %s", dir))
if err := os.Chdir(dir); err != nil {
return err
}
}
return nil
}
if specified != "" {
abs, err := filepath.Abs(specified)
if err != nil {
return err
}
if !isRootDir(abs) {
return fmt.Errorf("specified root %q not valid, does not contain expected files", abs)
}
return doChdir(abs)
}
for {
if isRootDir(cwd) {
return doChdir(cwd)
}
old := cwd
cwd = filepath.Dir(cwd)
if cwd == "" || old == cwd {
return fmt.Errorf("unable to find source root at or above %s", orig)
}
}
}
// setup sets up all sub-commands for the supplied root command and adds facilities for commands
// to access common options.
func setup(root *cobra.Command) {
var opts gOpts
var rootDir string
vmConfigFn := vm.ConfigFromCommandParams(root, "vm:")
cfg := remote.NewConfig(root, "k8s:")
root.SetUsageTemplate(usageTemplate(root.CommandPath()))
root.PersistentFlags().StringVar(&rootDir, "root", defaultRoot(), "root directory of repo (from QBEC_ROOT or auto-detect)")
root.PersistentFlags().IntVarP(&opts.verbose, "verbose", "v", 0, "verbosity level")
root.PersistentFlags().BoolVar(&opts.colors, "colors", false, "colorize output (set automatically if not specified)")
root.PersistentFlags().BoolVar(&opts.yes, "yes", false, "do not prompt for confirmation")
root.AddCommand(newOptionsCommand(root))
root.AddCommand(newVersionCommand())
root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if cmd.Name() == "version" || cmd.Name() == "init" { // don't make the version command dependent on work dir
return nil
}
if !cmd.Flags().Changed("colors") {
opts.colors = isatty.IsTerminal(os.Stdout.Fd())
}
sio.EnableColors = opts.colors
if err := setWorkDir(rootDir); err != nil {
return err
}
c, err := model.NewApp("qbec.yaml")
if err != nil {
return err
}
opts.app = c
conf, err := vmConfigFn()
if err != nil {
return err
}
opts.config = conf
opts.k8sConfig = cfg
return nil
}
commands.Setup(root, func() commands.StdOptionsWithClient {
return opts
})
}
<file_sep>package model
// generated by gen-qbec-swagger from internal/model/swagger.yaml at 2019-02-23 05:19:18.686016829 +0000 UTC
// Do NOT edit this file by hand
var swaggerJSON = `
{
"definitions": {
"qbec.io.v1alpha1.App": {
"additionalProperties": false,
"description": "The list of all components for the app is derived as all the supported (jsonnet, json, yaml) files in the components subdirectory.",
"properties": {
"apiVersion": {
"description": "requested API version",
"type": "string"
},
"kind": {
"description": "object kind",
"pattern": "^App$",
"type": "string"
},
"metadata": {
"$ref": "#/definitions/qbec.io.v1alpha1.AppMeta"
},
"spec": {
"$ref": "#/definitions/qbec.io.v1alpha1.AppSpec"
}
},
"required": [
"kind",
"apiVersion",
"metadata",
"spec"
],
"title": "QbecApp is a set of components that can be applied to multiple environments with tweaked runtime configurations.",
"type": "object"
},
"qbec.io.v1alpha1.AppMeta": {
"additionalProperties": false,
"properties": {
"name": {
"pattern": "^(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$",
"type": "string"
}
},
"required": [
"name"
],
"title": "AppMeta is the simplified metadata object for a qbec app.",
"type": "object"
},
"qbec.io.v1alpha1.AppSpec": {
"additionalProperties": false,
"properties": {
"componentsDir": {
"description": "directory containing component files, default to components/",
"type": "string"
},
"environments": {
"additionalProperties": {
"$ref": "#/definitions/qbec.io.v1alpha1.Environment"
},
"description": "set of environments for the app",
"minProperties": 1,
"type": "object"
},
"excludes": {
"description": "list of components to exclude by default for every environment",
"items": {
"type": "string"
},
"type": "array"
},
"libPaths": {
"description": "list of library paths to add to the jsonnet VM at evaluation",
"items": {
"type": "string"
},
"type": "array"
},
"paramsFile": {
"description": "standard file containing parameters for all environments returning correct values based on qbec.io/env external\nvariable, defaults to params.libsonnet",
"type": "string"
}
},
"required": [
"environments"
],
"title": "AppSpec is the user-supplied configuration of the qbec app.",
"type": "object"
},
"qbec.io.v1alpha1.Environment": {
"additionalProperties": false,
"properties": {
"defaultNamespace": {
"type": "string"
},
"excludes": {
"items": {
"type": "string"
},
"type": "array"
},
"includes": {
"items": {
"type": "string"
},
"type": "array"
},
"server": {
"type": "string"
}
},
"title": "Environment points to a specific destination and has its own set of runtime parameters.",
"type": "object"
}
},
"paths": {},
"swagger": "2.0"
}
`
<file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
package remote
import (
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/googleapis/gnostic/OpenAPIv2"
"github.com/pkg/errors"
"github.com/splunk/qbec/internal/model"
"github.com/splunk/qbec/internal/sio"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kube-openapi/pkg/util/proto"
"k8s.io/kube-openapi/pkg/util/proto/validation"
"k8s.io/kubernetes/pkg/kubectl/cmd/util/openapi"
)
// Validator validates documents of a specific type.
type Validator interface {
// Validate validates the supplied object and returns a slice of validation errors.
Validate(obj *unstructured.Unstructured) []error
}
// vsSchema implements Validator
type vsSchema struct {
proto.Schema
}
func (v *vsSchema) Validate(obj *unstructured.Unstructured) []error {
gvk := obj.GroupVersionKind()
return validation.ValidateModel(obj.UnstructuredContent(), v.Schema, fmt.Sprintf("%s.%s", gvk.Version, gvk.Kind))
}
type schemaResult struct {
validator Validator
err error
}
// validators produces Validator instances for k8s types.
type validators struct {
res openapi.Resources
l sync.Mutex
cache map[schema.GroupVersionKind]*schemaResult
}
func (v *validators) validatorFor(gvk schema.GroupVersionKind) (Validator, error) {
v.l.Lock()
defer v.l.Unlock()
sr := v.cache[gvk]
if sr == nil {
var err error
valSchema := v.res.LookupResource(gvk)
if valSchema == nil {
err = ErrSchemaNotFound
}
sr = &schemaResult{
validator: &vsSchema{valSchema},
err: err,
}
v.cache[gvk] = sr
}
return sr.validator, sr.err
}
// openapiResourceResult is the cached result of retrieving an openAPI doc from the server.
type openapiResourceResult struct {
res openapi.Resources
validators *validators
err error
}
// gvkInfo is all the information we need for k8s types as represented by group-version-kind.
type gvkInfo struct {
canonical schema.GroupVersionKind // the preferred gvk that includes aliasing (e.g. extensions/v1beta1 => apps/v1)
resource metav1.APIResource // the API resource for the gvk
}
type minimalDiscovery interface {
ServerGroups() (*metav1.APIGroupList, error)
ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error)
OpenAPISchema() (*openapi_v2.Document, error)
}
// ServerMetadata provides metadata information for a K8s cluster.
type ServerMetadata struct {
disco minimalDiscovery
registry map[schema.GroupVersionKind]*gvkInfo
defaultNs string
ol sync.Mutex
oResult *openapiResourceResult
verbosity int
}
func newServerMetadata(disco minimalDiscovery, defaultNs string, verbosity int) (*ServerMetadata, error) {
sm := &ServerMetadata{
disco: disco,
registry: map[schema.GroupVersionKind]*gvkInfo{},
defaultNs: defaultNs,
verbosity: verbosity,
}
if err := sm.init(); err != nil {
return nil, err
}
return sm, nil
}
func (sm *ServerMetadata) infoFor(gvk schema.GroupVersionKind) (*gvkInfo, error) {
res, ok := sm.registry[gvk]
if !ok {
return nil, fmt.Errorf("server does not recognize gvk %s", gvk)
}
return res, nil
}
// ValidatorFor returns a validator for the supplied GroupVersionKind.
func (sm *ServerMetadata) ValidatorFor(gvk schema.GroupVersionKind) (Validator, error) {
_, v, err := sm.openAPIResources()
if err != nil {
return nil, err
}
return v.validatorFor(gvk)
}
// DisplayName returns a display name for the supplied object in a format that mimics
// phrases that can be pasted into kubectl commands.
func (sm *ServerMetadata) DisplayName(o model.K8sMeta) string {
gvk := o.GetObjectKind().GroupVersionKind()
info := sm.registry[gvk]
displayType := func() string {
if info != nil {
return info.resource.Name
}
return strings.ToLower(gvk.Kind)
}
displayName := func() string {
ns := o.GetNamespace()
name := o.GetName()
if info != nil {
if info.resource.Namespaced {
if ns == "" {
ns = sm.defaultNs
}
} else {
ns = ""
}
}
if ns == "" {
return name
}
return name + " -n " + ns
}
name := fmt.Sprintf("%s %s", displayType(), displayName())
if l, ok := o.(model.K8sLocalObject); ok {
comp := l.Component()
if comp != "" {
name += fmt.Sprintf(" (source %s)", comp)
}
}
return name
}
// IsNamespaced returns true if the resource corresponding to the supplied
// GroupVersionKind is namespaced.
func (sm *ServerMetadata) IsNamespaced(gvk schema.GroupVersionKind) (bool, error) {
info, err := sm.infoFor(gvk)
if err != nil {
return false, err
}
return info.resource.Namespaced, nil
}
func (sm *ServerMetadata) collectTypes(filter func(*gvkInfo) bool) []schema.GroupVersionKind {
canonicalTypes := map[schema.GroupVersionKind]bool{}
for _, t := range sm.registry {
canonicalTypes[t.canonical] = true
}
var ret []schema.GroupVersionKind
for t := range canonicalTypes {
info := sm.registry[t]
if info == nil {
panic(fmt.Errorf("no info for %s", t))
}
if filter(info) {
ret = append(ret, t)
}
}
return ret
}
func (sm *ServerMetadata) namespacedTypes() []schema.GroupVersionKind {
return sm.collectTypes(func(info *gvkInfo) bool { return info.resource.Namespaced })
}
func (sm *ServerMetadata) clusterTypes() []schema.GroupVersionKind {
return sm.collectTypes(func(info *gvkInfo) bool { return !info.resource.Namespaced })
}
// canonicalGroupVersionKind provides the preferred/ canonical group version kind for the supplied input.
// It takes aliases into account (e.g. extensions/Deployment same as apps/Deployment) for doing so.
func (sm *ServerMetadata) canonicalGroupVersionKind(gvk schema.GroupVersionKind) (schema.GroupVersionKind, error) {
info, err := sm.infoFor(gvk)
if err != nil {
return gvk, err
}
return info.canonical, nil
}
type equivalence struct {
gk1 schema.GroupKind
gk2 schema.GroupKind
}
// equivalences from https://github.com/kubernetes/kubernetes/blob/master/pkg/kubeapiserver/default_storage_factory_builder.go
var equivalences = []equivalence{
{
gk1: schema.GroupKind{Group: "networking.k8s.io", Kind: "NetworkPolicy"},
gk2: schema.GroupKind{Group: "extensions", Kind: "NetworkPolicy"},
},
{
gk1: schema.GroupKind{Group: "apps", Kind: "Deployment"},
gk2: schema.GroupKind{Group: "extensions", Kind: "Deployment"},
},
{
gk1: schema.GroupKind{Group: "apps", Kind: "DaemonSet"},
gk2: schema.GroupKind{Group: "extensions", Kind: "DaemonSet"},
},
{
gk1: schema.GroupKind{Group: "", Kind: "Event"},
gk2: schema.GroupKind{Group: "events.k8s.io", Kind: "Event"},
},
{
gk1: schema.GroupKind{Group: "policy", Kind: "PodSecurityPolicy"},
gk2: schema.GroupKind{Group: "extensions", Kind: "PodSecurityPolicy"},
},
}
func eligibleResource(r metav1.APIResource) bool {
needed := []string{"create", "delete", "get", "list"}
for _, n := range needed {
found := false
for _, v := range r.Verbs {
if n == v {
found = true
break
}
}
if !found {
return false
}
}
return true
}
type resolver struct {
group string
version string
groupVersion string
preferredVersion string
registry map[schema.GroupVersionKind]*gvkInfo
tracker map[schema.GroupKind][]schema.GroupVersionKind
err error
}
func (r *resolver) resolve(disco minimalDiscovery) {
reg := map[schema.GroupVersionKind]*gvkInfo{}
tracker := map[schema.GroupKind][]schema.GroupVersionKind{}
list, err := disco.ServerResourcesForGroupVersion(r.groupVersion)
if err != nil {
sio.Warnln("error getting resources for type", r.groupVersion, ":", err)
}
if list != nil {
for _, res := range list.APIResources {
if strings.Contains(res.Name, "/") { // ignore sub-resources
continue
}
if !eligibleResource(res) { // remove stuff we cannot create and delete
continue
}
kindName := res.Kind
gvk := schema.GroupVersionKind{Group: r.group, Version: r.version, Kind: kindName}
// the canonical version of the type may not be correct at this stage if the preferred group version
// does not have the specific kind. We will fix these anomalies later when all objects have been loaded
// and are known.
reg[gvk] = &gvkInfo{
canonical: schema.GroupVersionKind{Group: r.group, Version: r.preferredVersion, Kind: kindName},
resource: res,
}
gk := schema.GroupKind{Group: r.group, Kind: kindName}
tracker[gk] = append(tracker[gk], gvk)
}
}
r.registry = reg
r.tracker = tracker
}
func (sm *ServerMetadata) init() error {
start := time.Now()
groups, err := sm.disco.ServerGroups()
if err != nil {
return errors.Wrap(err, "get server groups")
}
order := 0
groupOrderMap := map[string]int{}
var resolvers []*resolver
for _, group := range groups.Groups {
groupName := group.Name
order++
groupOrderMap[groupName] = order
preferredVersionName := group.PreferredVersion.Version
for _, gv := range group.Versions {
versionName := gv.Version
resolvers = append(resolvers, &resolver{
group: groupName,
version: versionName,
preferredVersion: preferredVersionName,
groupVersion: gv.GroupVersion,
})
}
}
var wg sync.WaitGroup
wg.Add(len(resolvers))
for _, r := range resolvers {
go func(resolver *resolver) {
defer wg.Done()
resolver.resolve(sm.disco)
}(r)
}
wg.Wait()
reg := map[schema.GroupVersionKind]*gvkInfo{}
// tracker tracks all known versions for a given group kind for the purposes of updating
// the canonical versions for equivalences.
tracker := map[schema.GroupKind][]schema.GroupVersionKind{}
for _, r := range resolvers {
if r.err != nil {
return r.err
}
for k, v := range r.registry {
reg[k] = v
}
for k, v := range r.tracker {
tracker[k] = append(tracker[k], v...)
}
}
// now deal with incorrect preferred versions when specific types do not exist for those
var fixTypes []schema.GroupVersionKind // collect list of types to be fixed
for k, v := range reg {
canon := v.canonical
if reg[canon] == nil {
fixTypes = append(fixTypes, k)
}
}
for _, k := range fixTypes {
v := reg[k]
reg[k] = &gvkInfo{
canonical: k,
resource: v.resource,
}
}
// then process aliases
for _, eq := range equivalences {
gk1 := eq.gk1
gk2 := eq.gk2
_, gk1Present := tracker[gk1]
_, gk2Present := tracker[gk2]
if !(gk1Present && gk2Present) {
continue
}
g1Order := groupOrderMap[gk1.Group]
g2Order := groupOrderMap[gk2.Group]
var canonicalGK, aliasGK schema.GroupKind
if g1Order < g2Order {
canonicalGK, aliasGK = eq.gk1, eq.gk2
} else {
canonicalGK, aliasGK = eq.gk2, eq.gk1
}
anyGKV := tracker[canonicalGK][0]
canonicalGKV := reg[anyGKV].canonical
for _, gkv := range tracker[aliasGK] {
reg[gkv] = &gvkInfo{
canonical: canonicalGKV,
resource: reg[gkv].resource,
}
}
}
sm.registry = reg
if sm.verbosity > 0 {
var display []string
for k, v := range reg {
l := fmt.Sprintf("%s/%s:%s", k.Group, k.Version, k.Kind)
r := fmt.Sprintf("%s/%s:%s", v.canonical.Group, v.canonical.Version, v.canonical.Kind)
ns := "cluster scoped"
if v.resource.Namespaced {
ns = "namespaced"
}
display = append(display, fmt.Sprintf("\t%-70s => %s (%s)", l, r, ns))
}
sort.Strings(display)
sio.Debugln()
sio.Debugln("group version kind map:")
for _, line := range display {
sio.Debugln(line)
}
sio.Debugln()
}
duration := time.Now().Sub(start).Round(time.Millisecond)
sio.Debugln("cluster metadata load took", duration)
return nil
}
func (sm *ServerMetadata) openAPIResources() (openapi.Resources, *validators, error) {
sm.ol.Lock()
defer sm.ol.Unlock()
ret := sm.oResult
if ret != nil {
return ret.res, ret.validators, ret.err
}
handle := func(r openapi.Resources, err error) (openapi.Resources, *validators, error) {
sm.oResult = &openapiResourceResult{res: r, err: err}
if err == nil {
sm.oResult.validators = &validators{
res: r,
cache: map[schema.GroupVersionKind]*schemaResult{},
}
}
return sm.oResult.res, sm.oResult.validators, sm.oResult.err
}
doc, err := sm.disco.OpenAPISchema()
if err != nil {
return handle(nil, errors.Wrap(err, "Open API doc from server"))
}
res, err := openapi.NewOpenAPIData(doc)
if err != nil {
return handle(nil, errors.Wrap(err, "get resources from validator"))
}
return handle(res, nil)
}
<file_sep>---
title: Component evaluation
weight: 20
---
How qbec evaluates component code using jsonnet and what it expects the output to look like.
## Jsonnet evaluation
This works as follows:
* Collect the list of files to be evaluated for the environment. This takes into account all components in the directory,
inclusion and exclusion lists for the current environment and component filters specified on the command line.
* Assuming this leads to 3 files, say, `c1.jsonnet`, `c2.json`, and `c3.yaml` create a jsonnet snippet as follows:
```
local parseYaml = std.native('parseYaml');
local parseJson = std.native('parseJson');
{
'c1': import '/path/to/c1.jsonnet',
'c2': parseJson(importstr '/path/to/c2.json'),
'c3': parseYaml(importstr '/path/to/c3.yaml'),
}
```
* Evaluate this snippet after setting the `qbec.io/env` extension variable to the environment name in question.
## Converting component output to Kubernetes objects
The evaluation above creates a map of component names to outputs returned by the jsonnet, json and yaml files.
The output is allowed to be:
* A single Kubernetes object (identified as such by virtue of having a `kind` and `apiVersion`
fields, where `kind` is not `List`).
* A Kubernetes list object where `kind` is `List` and it has an `items` array attribute
containing an array of outputs.
* A map of string keys to outputs
* An array of outputs
In the latter 3 cases, the output is processed recursively to get to the leaf k8s objects.
<file_sep>/*
Copyright 2019 Splunk Inc.
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.
*/
// Package eval encapsulates the manner in which components and parameters are evaluated for qbec.
package eval
import (
"encoding/json"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/splunk/qbec/internal/model"
"github.com/splunk/qbec/internal/sio"
"github.com/splunk/qbec/internal/vm"
)
// Context is the evaluation context
type Context struct {
App string // the application for which the evaluation is done
Env string // the environment for which the evaluation is done
VM *vm.VM // the base VM to use for eval
Verbose bool // show generated code
}
// Components evaluates the specified components using the specific runtime
// parameters file and returns the result.
func Components(components []model.Component, ctx Context) ([]model.K8sLocalObject, error) {
if ctx.VM == nil {
ctx.VM = vm.New(vm.Config{})
}
cCode, err := evalComponents(components, ctx)
if err != nil {
return nil, errors.Wrap(err, "evaluate components")
}
objs, err := k8sObjectsFromJSONString(cCode, ctx.App, ctx.Env)
if err != nil {
return nil, errors.Wrap(err, "extract objects")
}
return objs, nil
}
// Params evaluates the supplied parameters file in the supplied VM and
// returns it as a JSON object.
func Params(file string, ctx Context) (map[string]interface{}, error) {
baseVM := ctx.VM
if baseVM == nil {
baseVM = vm.New(vm.Config{})
}
cfg := baseVM.Config().WithVars(map[string]string{model.QbecNames.EnvVarName: ctx.Env})
jvm := vm.New(cfg)
code := fmt.Sprintf("import '%s'", file)
if ctx.Verbose {
sio.Debugln("Eval params:\n" + code)
}
output, err := jvm.EvaluateSnippet("param-loader.jsonnet", code)
if err != nil {
return nil, err
}
if ctx.Verbose {
sio.Debugln("Eval params output:\n" + prettyJSON(output))
}
var ret map[string]interface{}
if err := json.Unmarshal([]byte(output), &ret); err != nil {
return nil, err
}
return ret, nil
}
func evalComponents(list []model.Component, ctx Context) (string, error) {
cfg := ctx.VM.Config().WithVars(map[string]string{model.QbecNames.EnvVarName: ctx.Env})
jvm := vm.New(cfg)
var lines []string
for _, c := range list {
switch {
case strings.HasSuffix(c.File, ".yaml"):
lines = append(lines, fmt.Sprintf("'%s': parseYaml(importstr '%s')", c.Name, c.File))
case strings.HasSuffix(c.File, ".json"):
lines = append(lines, fmt.Sprintf("'%s': parseJson(importstr '%s')", c.Name, c.File))
default:
lines = append(lines, fmt.Sprintf("'%s': import '%s'", c.Name, c.File))
}
}
preamble := []string{
"local parseYaml = std.native('parseYaml');",
"local parseJson = std.native('parseJson');",
}
code := strings.Join(preamble, "\n") + "\n{\n " + strings.Join(lines, ",\n ") + "\n}"
if ctx.Verbose {
sio.Debugln("Eval components:\n" + code)
}
ret, err := jvm.EvaluateSnippet("component-loader.jsonnet", code)
if err != nil {
return "", err
}
if ctx.Verbose {
sio.Debugln("Eval components output:\n" + prettyJSON(ret))
}
return ret, nil
}
func prettyJSON(s string) string {
var data interface{}
if err := json.Unmarshal([]byte(s), &data); err == nil {
b, err := json.MarshalIndent(data, "", " ")
if err == nil {
return string(b)
}
}
return s
}
| 75bc7f103314478ddbced55d81496edd850de343 | [
"Markdown",
"Go"
] | 12 | Go | cspargo/qbec | 0aa6ea1a85fed577746a11768e6facc53c89787f | 1e245be2aa31000bd9861781a2b2459a9219dfc2 |
refs/heads/master | <file_sep># %% [md]
# # Overview
#
# We cover how to model relationships and behaviors in this class.
# * Is A = Inheritance
# * Has A = Composition
#
# %% [md]
# # Example
# Requirements:
# * Albums have Songs
# * Albums have Artists
# * Bands have more than one artist
# * Bands, Artists, Songs, and Albums have Names
# * Albums are sold
# * Albums that sell 100,000 copies are Gold
# %% [md]
# ## Step 1 - Model Entities
# Tackle modeling the major actors in this system
# * Album
# * Song
# * Artist
# * Band
# %% codecell
class Album():
pass
class Song():
pass
class Artist():
pass
class Band():
pass
# %% [md]
# ## Step 2 - Model Compositions
# We assign variables to model compositions
# * Albums have Songs
# * Albums have Artists
# * Bands have Artists
# %% codecell
class Album():
def __init__(self):
self.songs = []
self.artists = []
class Song():
pass
class Artist():
pass
class Band():
def __init__(self):
self.artists = []
<file_sep># %% [md]
# # Abstract Base Classes
# Abstract base classes enforces rules in inheritence
# %% codecell
from abc import ABC
from abc import abstractmethod
# %% [md]
# # Abstract Base Class
# * You can inherit from an ABC, but you can't create an instance of one
# * It can define abstract methods, that derived classes must implment
# * It can have concrete methods (and properties) that derived methods inherit
# %% codecell
class Vehicle(ABC):
@abstractmethod
def move(self):
pass
@abstractmethod
def park(self):
pass
# %% codecell
vehicle = Vehicle()
# %% [md]
# # Derived Classes
# * Car
# * Airplane
# %% codecell
class Car(Vehicle):
def move(self):
print('Driving')
def park(self):
print('Garage')
class Airplane(Vehicle):
def move(self):
print('Flying')
def park(self):
print('Hangar')
# %% codecell
car = Car()
car.move()
car.park()
airplane = Airplane()
airplane.move()
airplane.park()
# %% [md]
# # Abstract Methods must have a concrete implementation
# * Let's create a ship, with only move implemented
# * We get an exception - park isn't implemented
# %% codecell
class Ship(Vehicle):
def move(self):
print('Sailing')
# %% codecell
ship = Ship()
# %% [md]
# # Behavior in Abstract Classes
# * Our Vehicle class keeps a speed int
# * We can accelerate and stop
# %% codecell
class Vehicle(ABC):
def __init__(self):
self._speed = 0
@abstractmethod
def move(self):
pass
@abstractmethod
def park(self):
pass
def accelerate(self, amount):
self._speed += amount
def stop(self):
self._speed = 0
# %% [md]
# # Derived Classes
# %% codecell
class Car(Vehicle):
def move(self):
print(f'Driving {self._speed} miles')
def park(self):
print('Garage')
class Airplane(Vehicle):
def move(self):
print(f'Flying {self._speed} miles')
def park(self):
print('Hangar')
# %% codecell
car = Car()
car.accelerate(60)
car.move()
car.park()
car.stop()
airplane = Airplane()
airplane.accelerate(450)
airplane.move()
airplane.park()
airplane.stop()
# %% codecell
fleet = []
fleet.append(Car())
fleet.append(Airplane())
fleet.append(Car())
for vehicle in fleet:
vehicle.accelerate(50)
vehicle.move()<file_sep># %% [md]
# # Polymorphism
# * Polymorphism simply means to change.
# * In the context of OOP, it means that a derived class can change the behavior of a base class
# %% [md]
# # Derived Class
# Example of defining a base and derived class
# * In this example, class Birds and Sloths derive from Animal
# * In other words, Bird is an Animal and Sloth is an Animal
# %% codecell
class Animal():
pass
class Bird(Animal):
pass
class Sloth(Animal):
pass
# %% [md]
# # Behavior
# * We give animals the ability to move
# * This is defined in the base class
# * Therefore all animals, including Birds and Sloths can move
# %% codecell
class Animal():
def move(self):
print('Moving')
class Bird(Animal):
pass
class Sloth(Animal):
pass
# %% codecell
a = Animal()
a.move()
b = Bird()
b.move()
s = Sloth()
s.move()
# %% [md]
# # Polymorphism
# * Birds and Sloths move differently
# * We can override or change behavior for specific animals using polymorphism
# %% codecell
class Animal():
def move(self):
print('Moving')
class Bird(Animal):
def move(self):
print('Flying')
class Sloth(Animal):
def move(self):
raise Exception('Not Happening')
# %% codecell
a = Animal()
a.move()
b = Bird()
b.move()
s = Sloth()
s.move()
# %% [md]
# # Recall Aminals, Dogs & Cats
# %% codecell
class Animal():
def __init__(self, lives=1):
self.lives = lives
class Dog(Animal):
def __init__(self):
super().__init__(lives=1)
def sound(self):
return "Bark"
class Cat(Animal):
def __init__(self):
super().__init__(lives=9)
def sound(self):
return "Meow"
# %% [md]
# # Refactor Aminals, Dogs & Cats
# We want to push the definition of sound into our base class since it
# pertains to both cats and dogs (and presumably any animal)
# We want ot override the behavior in our derived classes.
# %% codecell
class Animal():
def __init__(self, lives=1):
self.lives = lives
def sound(self):
return "Sound"
class Dog(Animal):
def __init__(self):
super().__init__(lives=1)
def sound(self):
return "Bark"
class Cat(Animal):
def __init__(self):
super().__init__(lives=9)
def sound(self):
return "Meow"
# %% codecell
animal = Animal()
print(animal.sound())
dog = Dog()
print(dog.sound())
cat = Cat()
print(cat.sound())
<file_sep># %% [md]
# # Constructors
# When we construct an object we initialize our class
# with the dunder init (__init__) method.
# %% codecell
class Example():
def __init__(self):
print('Running init')
self.some_variable = 1
# %% codecell
e = Example()
print(f'Value {e.some_variable}')
# %% [md]
# # Constructors & Inheritance
# If you don't initiatlize your base class it's
# dunder init will not run. Any initialization
# that would occur there does not run.
# %% codecell
class Example():
def __init__(self):
print('Running Example Init')
self.example_variable = 1
class Derived(Example):
def __init__(self):
print('Running Derived Init')
self.derived_variable = 2
# %% codecell
d = Derived()
print(f'Example Variable {d.example_variable}')
print(f'Derived Variable {d.derived_variable}')
# %% [md]
# # Super
# You can initialize your base class with a call to super().__init__()
# %% codecell
class Example():
def __init__(self):
print('Running Example Init')
self.example_variable = 1
class Derived(Example):
def __init__(self):
super().__init__()
print('Running Derived Init')
self.derived_variable = 2
# %% codecell
d = Derived()
print(f'Example Variable {d.example_variable}')
print(f'Derived Variable {d.derived_variable}')
# %% [md]
# # Super
# You can pass parameters as defined in __init__ to super's dunder init (constructor)
# %% codecell
class Example():
def __init__(self, value):
print('Running Example Init')
self.example_variable = value
class Derived(Example):
def __init__(self, value):
super().__init__(value ** 2)
print('Running Derived Init')
self.derived_variable = value
# %% codecell
d = Derived(4)
print(f'Example Variable {d.example_variable}')
print(f'Derived Variable {d.derived_variable}')
# %% [md]
# # Recall Aminals, Dogs & Cats
# %% codecell
class Animal():
pass
class Dog(Animal):
def __init__(self):
self.lives = 1
def sound(self):
return "Bark"
class Cat(Animal):
def __init__(self):
self.lives = 9
def sound(self):
return "Meow"
# %% [md]
# # Refactor Aminals, Dogs & Cats
# We want to push the definition of lives into our base class since it
# pertains to both cats and dogs (and presumably any animal)
# %% codecell
class Animal():
def __init__(self, lives=1):
self.lives = lives
class Dog(Animal):
def __init__(self):
super().__init__(lives=1)
def sound(self):
return "Bark"
class Cat(Animal):
def __init__(self):
super().__init__(lives=9)
def sound(self):
return "Meow"
# %% codecell
animal = Animal()
print(animal.lives)
dog = Dog()
print(dog.lives)
cat = Cat()
print(cat.lives)<file_sep># %% [md]
# # Inheritance
# In this inheritance example we want to design a set of functionality.
# To accomplish that we'll build some classes that will
# be remniscent of sklearn.
#
# Our requirements:
# * Transformations
# * Transformations are fit to data
# * Transformations transform data
# * Normalizing data is a transformation
# * Models
# * Models are fit to data
# * Fitted Models predict given data
# * Linear is a type of Model
# * Logistic is a type of Model
# * PCA
# * PCA is a Transformations
# * PCA is a Model
# * Pipeline
# * Pipelines are a serial list of Transforms or Models
# %% [md]
# # Learning Objects Fit
# * Transformatations are fit to data
# * Models are fit to data
# * Good candidate for a base class!
# %% codecell
class Base():
"""
A Base class models functionality that can learn from data.
We use a fit method to handle learning.
"""
def __init__(self):
pass
def fit(self, X, y):
pass
# %% [md]
# # Transformations
# * Transformations transform data
# * Normalizing is a transformation
# * Good candidate for an is - a (base - derived class)
# %% codecell
class BaseTransform(Base):
"""
The BaseTransform method performs a transformation of data.
It can learn parameters it needs from data.
It derives from Base, giving it a fit method.
"""
def __init__(self):
pass
def transform(self, X):
pass
class Normalize(BaseTransform):
def __init__(self):
pass
def fit(self, X, y):
print('Fit Normalize')
def transform(self, X):
print('Transform Normalize')
# %% [md]
# # Models
# * Fitted models can create predictions
# * Logitic is a model
# * Linear is a model
# * Another good candidate for an is - a (base - derived class)
# %% codecell
class BaseModel(Base):
"""
Our BaseModel learns from data and can make a prediction given new data.
It derives from Base giving it a fit method.
"""
def __init__(self):
pass
def predict(self, X):
pass
class LinearModel(BaseModel):
def __init__(self):
super().__init__()
def fit(self, X, y):
print('Fit Linear Model')
def predict(self, X):
print('Predict Linear Model')
class LogisticModel(BaseModel):
def __init__(self):
super().__init__()
def fit(self, X, y):
print('Fit Logistic Model')
def predict(self, X):
print('Predict Logistic Model')
# %% [md]
# # PCA
# * Models that Transform
# * Good candidate for Multiple Inheritance
# * PCA is a Model
# * PCA is a Transformer
# %% codecell
class PCA(BaseModel, BaseTransform):
def __init__(self):
pass
def fit(self, X, y):
print('Fit PCA')
def transform(self, X):
print('Transform PCA')
def predict(self, X):
print('Predict PCA')
# %% [md]
# # Pipelines are Collection
# * We want to add items to the pipeline
# * We'd like to fit the data pipeline
# * We'd like to transform the data pipeline
# * We'd like to make a prediction
# * Good plan to wrap a list with fit, transform and predict
# %% codecell
class Pipeline(Base):
def __init__(self):
self.steps = []
def add(self, step):
self.steps.append(step)
def fit(self, X, y):
for obj in self.steps:
if isinstance(obj, Base):
obj.fit(X, y)
def transform(self, X):
for obj in self.steps:
if isinstance(obj, BaseTransform):
obj.transform(X)
def predict(self, X):
for obj in self.steps:
if isinstance(obj, BaseModel):
obj.predict(X)
# %% [md]
# Running a Pipeline
# %% codecell
X = []
y = []
pipe = Pipeline()
pipe.add(Normalize())
pipe.add(PCA())
pipe.add(LinearModel())
pipe.fit(X, y)
pipe.predict(X)
pipe.transform(X)
<file_sep># %% [md]
# # Encapsulation
# * Co-locate state & behavior & Hide details
# * Bundling of data with the methods that operate on that data
# * Restricting direct access to some of an object's components
# * Two Approaches
# * Protected - Convention
# * Private - Compiler
# %% [md]
# # Protected Methods
# Use a single underscore to indicate that the method is not part of your API
# and it should be treated as private. Note, the compiler and interpreter do
# not enforce this. It's on the users of an API to respect protected members.
# %% codecell
class Base():
def public_method(self):
print('public')
def _protected_method(self):
print('protected')
# %% codecell
b = Base()
b.public_method()
b._protected_method()
# %% [md]
# # Private Methods
# Private methods are not accessible outside of the class
# %% codecell
class Base():
def public_method(self):
print('public')
def __private_method(self):
print('private')
class Derived(Base):
pass
# %% codecell
b = Base()
b.public_method()
b.__private_method()
# %% [md]
# # Protected Member Variables
# %% codecell
class ProtectedVariables():
def __init__(self, firstName, lastName):
self._firstName = firstName
self._lastName = lastName
# %% codecell
p = ProtectedVariables('First', 'Last')
print(p._firstName)
print(p._lastName)
# %% [md]
# # Private Member Variables
# %% codecell
class PrivateVariables():
def __init__(self, firstName, lastName):
self.__firstName = firstName
self.__lastName = lastName
# %% codecell
p = PrivateVariables('First', 'Last')
print(p.__firstName)
<file_sep># %% [md]
# # Scoping - Instance, Class & Static Methods
# %% [md]
# # Instance Methods
# * A method available to the instance
# * Has a reference to self
# * With a reference to self, it has access to the instance state
# %% codecell
class MyClass():
def instanceWork(self):
print('Instance Method - Work')
# %% codecell
my = MyClass()
my.instanceWork()
# %% [md]
# # Class Methods
# To attach a method to a class, use the @classmethod annotation and
# rather than self, use cls as the first parameter
# %% codecell
class MyClass():
def instanceWork(self):
print('Instance Method - Work')
print(self)
@classmethod
def classWork(cls):
print('Class Method - Work')
print(cls)
# %% [md]
# You can call class methods using your reference to the class instance
# %% codecell
my = MyClass()
my.instanceWork()
my.classWork()
# %% [md]
# You can also call class methods using the class name
# %% codecell
MyClass.classWork()
# %% [md]
# # Usage : Alternative Constructors
# Class methods are great for creating alternative Constructors
# %% codecell
from datetime import date
# %% codecell
class Customer():
def __init__(self, firstName:str, lastName:str, age:int):
self.firstName = firstName
self.lastName = lastName
self.age = age
def output(self):
print(self.firstName, self.lastName, self.age)
@classmethod
def fromFullName(cls, fullName:str, age:int):
firstName, lastName = fullName.split(' ')
return cls(firstName, lastName, age)
# %% codecell
c1 = Customer('Anne', 'Smith', 30)
c2 = Customer.fromFullName('<NAME>', 50)
c1.output()
c2.output()
# %% [md]
# # Static Methods
# Convenient for grouping methods that logically make sense in a class
# but do not require an object. Helper methods are good candidates for
# staticmethods in classes.
# %% codecell
class MyClass():
def instanceWork(self):
print('Instance Method - Work')
print(self)
@classmethod
def classWork(cls):
print('Class Method - Work')
print(cls)
@staticmethod
def staticWork():
print('Static Method - Work')
# %% codecell
c = MyClass()
c.staticWork()
# %% codecell
MyClass.staticWork()<file_sep># %% [md]
# # Property
# Properties are a clean way of hiding internal details in a convenient API friendly way
# %% [md]
# # Simple Approach
# * As a user of the class, can I change it?
# * What happens if I do?
# * Are there any rules about changing it?
# * The simple approach lacks expressiveness
# %% codecell
class Person():
name = '<NAME>'
# %% [md]
# # Functional Get / Set
# * I know more about this with functions fronting the variable
# * I know I can't direcltly access it (double underscore performs a rewrite)
# * The method gives me an opportunity to inject any business logic I need
# %% codecell
class Person():
def __init__(self):
self.__name = None
def getName(self):
return self.__name
def setName(self, name):
self.__name = name
# %% codecell
p = Person()
print(p.getName())
p.setName('Tom')
print(p.getName())
# %% [md]
# # Property
# * Properties sit atop a method
# * The getter method has the @property annotation & uses the method name
# * If the property can be written to, we add an annotation @[name].setter
# * Properties do not have to be aligned to one variable
# %% codecell
class Person():
def __init__(self):
self.__firstName = None
self.__lastName = None
@property
def firstName(self):
return self.__firstName
@firstName.setter
def firstName(self, value):
self.__firstName = value
@property
def lastName(self):
return self.__lastName
@lastName.setter
def lastName(self, value):
self.__lastName = value
@property
def fullName(self):
return self.__firstName + " " + self.__lastName
# %% codecell
p = Person()
print(p.firstName)
p.firstName = 'Tom'
print(p.firstName)
p.lastName = 'Thumb'
print(p.lastName)
# Property for full name
print(p.fullName)
# %% codecell
#Can't set - not defined
p.fullName = '<NAME>'
# %% codecell
# Can't get the state directly
print(p.__firstName)<file_sep># %% [md]
# # Dunders
# * Named for the double underscore surrounding the method
# * These methods affect how your classes function and respond
# %% [md]
# # Constructors
# There are two methods invoked when you create an object.
# * __new__
# * __init__
# * New creates an object in memory
# * Init gives you an opportunity to initiatize the object before handing it to a client.
# * It is relatively uncommon to override new
# * Frequently, you will implement __init__.
# %% codecell
class Example():
def __init__(self):
print('Running init')
self.some_variable = 1
# %% codecell
e = Example()
print(f'Value {e.some_variable}')
# # Strings and Representing
# In addition to constructors and initialization (__init__)
# Dunders control several aspects of objects.
# * str = familiar output from print
# * repr = debugging and formal representation
# * print looks for __str__, then __repr__
# %% codecell
class Point:
# Constructor
def __init__(self, x, y):
self.x = x
self.y = y
# Called by repr(). Object information
def __repr__(self):
return f'{self.__class__.__name__}, ({self.x}, {self.y})'
# Called by str(). Readable formatting
def __str__(self):
return f'({self.x}, {self.y})'
# %% codecell
# Examples
p = Point(10, 20)
# str / print
print(str(p)) # Same as "print t"
print(p)
# repr
print(repr(p))
# %% [md]
# # Arithmetic Dunders
# Special dunders implement arithmetic operations + - * /
# * Plus : __add__
# * Subtract : __sub__
# * Multiply : __mul__
# * Divide : __div__
# %% codecell
class Point:
# Constructor
def __init__(self, x, y):
self.x = x
self.y = y
# Called by repr(). Object information
def __repr__(self):
return f'{self.__class__.__name__}, ({self.x}, {self.y})'
# Called by str(). Readable formatting
def __str__(self):
return f'({self.x}, {self.y})'
# Adding Points
def __add__(self, obj):
return (self.x + obj.x, self.y + obj.y)
# %% codecell
p1 = Point(5, 5)
p2 = Point(10, 10)
p1 + p2
# %% [md]
# # Equality Dunder
# Special dunder for comparison of equals
# * Equals : __eq__
# * Less Than : __lt__
# * Greater Than : __gt__
# %% codecell
class Point:
# Constructor
def __init__(self, x, y):
self.x = x
self.y = y
# Called by repr(). Object information
def __repr__(self):
return f'{self.__class__.__name__}, ({self.x}, {self.y})'
# Called by str(). Readable formatting
def __str__(self):
return f'({self.x}, {self.y})'
# Adding Points
def __add__(self, obj):
return (self.x + obj.x, self.y + obj.y)
# Equals
def __eq__(self, obj):
if (self.x == obj.x and self.y == obj.y):
return True
return False
# %% codecell
p1 = Point(5, 5)
p2 = Point(5, 10)
p3 = Point(10, 5)
p4 = Point(5, 5)
# %% codecell
p1 == p2
p1 == p3
p1 == p4
# %% [md]
# # Hash
# Defines the hash key a dictionary uses
# If you derive from Object, you will inherit the __hash__ implementation
# If you don't derive from Object, you have to implement __hash__
# Rules for hash:
# * Hash must never change through the lifetime of an object
# * Classes are unhashable if you implement __eq__ but not __hash__
# * Hash does not mean equality. There can be collisions.
# * Consider using the hash function to hash an immuatable type (pass a tuple)
# %% codecell
d = {}
p1 = Point(5, 5)
d[p1] = 'Treasure'
# %% codecell
class PointFromObject(object):
pass
# %% codecell
d = {}
p = PointFromObject()
d[p] = 'Treasure'
d
# %% codecell
class Point:
# Constructor
def __init__(self, x, y):
self._x = x
self._y = y
# Called by repr(). Object information
def __repr__(self):
return f'{self.__class__.__name__}, ({self._x}, {self._y})'
# Called by str(). Readable formatting
def __str__(self):
return f'({self._x}, {self._y})'
# Adding Points
def __add__(self, obj):
return (self._x + obj._x, self._y + obj._y)
# Equals
def __eq__(self, obj):
if (self._x == obj._x and self._y == obj._y):
return True
return False
# hash - a trivial example
# We're using mutable values to define a hash, not a good plan
# So, we've flagged our x and y with an underscore to indicate protected
def __hash__(self):
return hash((self._x, self._y))
# %% codecell
d = {}
d[Point(5, 5)] = 'Treasure'
d[Point(3, 3)] = 'Trap'
d[Point(10, 10)] = 'Ship'
d
# %% [md]
# # With Block -- Context Managers
# * The with block interacts with two dunders
# * Entering a with block calls __enter__
# * Exiting a with block calls __exit__
# * You often see this around a file resource
# * with open(file) as f: ...
# * We use this dunder to handle resource clean up automatically
# %% codecell
class Point:
# Constructor
def __init__(self, x, y):
self._x = x
self._y = y
# Called by repr(). Object information
def __repr__(self):
return f'{self.__class__.__name__}, ({self.x}, {self.y})'
# Called by str(). Readable formatting
def __str__(self):
return f'({self.x}, {self.y})'
# Adding Points
def __add__(self, obj):
return (self._x + obj._x, self._y + obj._y)
# Equals
def __eq__(self, obj):
if (self._x == obj._x and self._y == obj._y):
return True
return False
# Hash
def __hash__(self):
return hash((self._x, self._y))
# With Support
def __enter__(self):
print('Entering')
# exc_type - Exception Type
# exc_val - Exception Value
# exc_tb - Exception Traceback
def __exit__(self, exc_type, exc_val, exc_tb):
print('Exiting')
# %% codecell
with (Point(3, 3)) as pt:
print('Using our Point')
# %% [md]
# # Call
# * Give our class instance a method
# %% codecell
class Point:
# Constructor
def __init__(self, x, y):
self._x = x
self._y = y
# Called by repr(). Object information
def __repr__(self):
return f'{self.__class__.__name__}, ({self.x}, {self.y})'
# Called by str(). Readable formatting
def __str__(self):
return f'({self.x}, {self.y})'
# Adding Points
def __add__(self, obj):
return (self._x + obj._x, self._y + obj._y)
# Equals
def __eq__(self, obj):
if (self._x == obj._x and self._y == obj._y):
return True
return False
# Hash
def __hash__(self):
return hash((self._x, self._y))
# With Support
def __enter__(self):
print('Entering')
def __exit__(self, exc_type, exc_val, exc_tb):
print('Exiting')
# Call
def __call__(self, val):
if val == 'X' or val == 'x':
return self._x
if val == 'Y' or val == 'y':
return self._y
# %% codecell
c = Point(5,6)
print(c('X'))
print(c('Y'))<file_sep># %% [md]
# # Factory Pattern
# * Factory is a creational pattern
# * We use it when we want to control the construction & initialization of objects
# * In this example:
# * We have a Reader that is "complicated"
# * It has to read from different types of sources
# * The sources may have different versions of the data
# * We want to hide the complexity of setting up reading
# %% codecell
from abc import ABC
from abc import abstractmethod
# %% [md]
# # Data Loading Classes
# %% codecell
class Loader(ABC):
@abstractmethod
def load(self):
pass
def read(self):
pass
def log(self, message):
print(message)
class Version(ABC):
@abstractmethod
def map(self, d:dict):
pass
class Reader():
def __init__(self, loader:Loader, version:Version):
self.loader = loader
self.version = version
def read(self):
results = []
self.loader.load()
row = self.loader.read()
while row is not None:
mapped = self.version.map(row)
results.append(mapped)
row = self.loader.read()
return results
# %% [md]
# There are three different ways to read in our data
# * CSV FlatFile
# * JSON
# * Database
# %% codecell
class CSVLoader(Loader):
def load(self):
self.log('Reading from CSV')
class JSONLoader(Loader):
def load(self):
self.log('Reading from JSON')
class DatabaseLoader(Loader):
def load(self):
self.log('Reading from Database')
# %% codecell
l = Loader()
# %% codecell
loaderCSV = CSVLoader()
loaderCSV.load()
loaderJSON = JSONLoader()
loaderJSON.load()
loaderDB = DatabaseLoader()
loaderDB.load()
# %% [md]
# There are two versions of data formats
# * V1
# * V2
# %% codecell
class DataVersion1():
def map(self, d:dict):
return (d['item'], d['customer'])
class DataVersion2():
def map(self, d:dict):
return (d['item'], d['customer'], d['quantity'])
# %% [md]
# # Creation Pattern
# What's the best way to pick the loader you need at runtime?
# %% [md]
# ## Main Method
# If we code a main method, we need to select the correct loader type
# and the correct version. Our unittests around the main method
# would need to test all 6 paths in this example along with other duties in the main.
# %% [md]
# ## Factory Pattern
# %% codecell
class ReaderFactory():
def getReader(self, config):
loader = None
if config['loader'] == 'CSV':
loader = CSVLoader()
if config['loader'] == 'JSON':
loader = JSONLoader()
if config['loader'] == 'DB':
loader = DatabaseLoader()
version = None
if config['version'] == 1:
version = DataVersion1()
if config['version'] == 2:
version = DataVersion2()
return Reader(loader=loader, version=version)
# %% codecell
config = {'loader':'DB', 'version':2}
factory = ReaderFactory()
reader = factory.getReader(config)
reader.read()
<file_sep># %% [md]
# # Introduction
# * Real world objects have state and behavior
# * Software objects have state and behavior
# * State = variables
# * Behavior = functions
# %% [md]
# # Class
# * A Class is our building block for modeling the real world
# * In python we define a class as a template for objects we want to use
# * When we create a class, we create an instance of the class
# * Think "is a" for a class
# %% codecell
class A():
pass
# %% codecell
a = A()
# %% [md]
# # State
# * State is represented by variables in a class
# %% codecell
class A():
state = 'My State'
# %% codecell
a = A()
print(a.state)
# %% [md]
# # Behavior
# * Methods represent behavior in classes
# %% codecell
class A():
def behavior(self, do):
print('Doing', do)
# %% codecell
a = A()
a.behavior('Move')
# %% [md]
# # Self
# * Reference to the object
# * In some languages it is implied (java - this)
# * In Python it's explicit declared in functions
# * A method defined with self in a class is available using the . followed by the function name.
# %% codecell
class A():
def __init__(self, action):
self.action = action
def behavior(self):
print('Doing', self.action)
# %% codecell
a1 = A('Run')
a1.behavior()
a2 = A('Walk')
a2.behavior()
# %% [md]
# # Why Classes
# * Modularity - Modular classes allow you to define in one place independent of other objects
# * Code Re-Use - Share the implementation within and between projects
# * Manage Complexity - Classes model real world objects and improve readability / understanding
# * Debugging - Hiding information in classes makes debugging easier <file_sep># %% [md]
# # Overview
#
# We cover how to model relationships and behaviors in this class.
# * Is A = Inheritance
# * Behavior = Functions
# * State = Variables
#
# We model inheritance with classes and base classes.
# %% [md]
# # Example
# Requirements:
# * Dog is an Animal
# * Cat is an Animal
# * Dogs bark
# * Cats meow
# * Cats have 9 lives
# %% [md]
# ## Step 1 - Model Relationships
# * We would consider creating an Animal base class with two derived classes, Dog and Cat.
# * Classes then form a heirarchical relationship.
# * Dog is an Animal
# * Cat is an Animal
# %% codecell
class Animal():
pass
class Dog(Animal):
"""
Dog is an Animal.
"""
pass
class Cat(Animal):
"""
Cat is an Animal
"""
pass
# %% [md]
# ## Step 2 - Model Behaviors
# We define functions to model the sound behavior. We place these functions
# in the class heirarchy based on our requirements.
# * Cats meow
# * Dogs bark
# * Note: We'll build on this simple model over the next few notebooks
# %% codecell
class Animal():
pass
class Dog(Animal):
def sound(self):
"""
Dogs bark
"""
return "Bark"
class Cat(Animal):
def sound(self):
"""
Cats meow
"""
return "Meow"
# %% codecell
animal = Animal()
dog = Dog()
print(dog.sound())
cat = Cat()
print(cat.sound())
# %% [md]
# ## Step 3 - Model State
# We use member variables to model state
# * Cats have 9 lives
# * Seems wrong for dogs not to have lives
# %% codecell
class Animal():
pass
class Dog(Animal):
def __init__(self):
self.lives = 1
def sound(self):
return "Bark"
class Cat(Animal):
def __init__(self):
self.lives = 9
def sound(self):
return "Meow"
# %% codecell
cat = Cat()
print(f'Cat has {cat.lives} lives')
dog = Dog()
print(f'Dog has {dog.lives} lives')
# %% [md]
# # Inheritance Trees
# * No rule on how deep you can go with classes
# * For example:
# * Working is a type of dog
# * Hunting is a type of dog
# * Lap is a type of dog
# %% codecell
class Animal():
def __init__(self, lives=1):
self.lives = lives
class Dog(Animal):
def __init__(self):
super().__init__()
def sound(self):
return "Bark"
class WorkingDog(Dog):
pass
class HuntingDog(Dog):
pass
class LapDog(Dog):
pass
# %% codecell
pebbles = LapDog()
print(pebbles.sound())
print(pebbles.lives)
<file_sep># %% [md]
# # Singletons
# * With a singleton, we want exactly one instance of a class created
# * This is typically done so we can manage state in a centralized location
# * An example would of a singleton, may be a logger that manages writing to one or more files.
# * We want to use the logger from many places and it's convenient to create an instance of a logger as needed
# %% codecell
class NotSingleton(object):
pass
# %% codecell
ns1 = NotSingleton()
ns2 = NotSingleton()
print(ns1)
print(ns2)
print(ns1 == ns2)
print(ns1 is ns2)
# %% [md]
# The == operator compares the values of both the operands and checks for value equality.
# Whereas is operator checks whether both the operands refer to the same object or not.
# %% [md]
# # Dunder __new__
# * The key to creating a singleton, is intercepting the dunder __new__ method.
# * This is called when we want to construct an instance.
# * If you look at the signature, it's a class method.
# * Within the method, we look to see if an instance of our class exists.
# * If it does, we return that instance.
# * If it does not, we create an instance of the class, save it in our Singleton class and return the instance.
# %% codecell
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
# %% codecell
s1 = Singleton()
s2 = Singleton()
print(s1)
print(s2)
print(s1 == s2)
# %% [md]
# # Tracking Handouts
# * A toy example of shared state using a Singleton.
# * Our need is to track the number of times we hand out a reference.
# * Note: we need to take special care of our singleton initialization.
# %% codecell
class TrackingSingleton(object):
_instance = None
_handouts = 0
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
def handout(self):
TrackingSingleton._handouts += 1
return TrackingSingleton._handouts
def handedOut(self):
return TrackingSingleton._handouts
# %% codecell
ts1 = TrackingSingleton()
print(ts1.handout())
ts2 = TrackingSingleton()
print(ts2.handout())
print(ts1.handedOut())
print(ts2.handedOut())
# %% [md]
# # Enforcing Maximum Handouts
# We have state in our instance class that we need to run exactly once
# %% codecell
class MaxHandoutSingleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls, *args, **kwargs)
# Setup our instance state on max handouts & current handouts
cls._instance._handouts = 0
cls._instance._max = 3
return cls._instance
def __init__(self):
# Runs on every construction
pass
def handout(self):
if self._handouts == self._max:
raise Exception('Max Handouts Reached')
self._handouts += 1
return self._handouts
def turnin(self):
self._handouts -= 1
def handedOut(self):
return self._handouts
# %% codecell
maxer = MaxHandoutSingleton()
maxer.handout(); print(maxer.handedOut())
maxer.handout(); print(maxer.handedOut())
maxer.handout(); print(maxer.handedOut())
maxer.handout()
# %% codecell
maxer.turnin()
maxer.turnin()
print(maxer.handedOut())
# %% [md]
# # Singleton Factory
# It's common to make our singleton the basis of a Factory pattern
# %% codecell
class LimitedResource():
def __init__(self, id):
self._id = id
def __enter__(self):
print(' Entering')
def __exit__(self, exc_type, exc_val, exc_tb):
print(' Exiting')
factory = LimitedResourceFactory()
factory.returnItem(self)
class LimitedResourceFactory(object):
_instance = None
def __new__(cls, *args, **kwargs):
print('New')
if not cls._instance:
cls._instance = object.__new__(cls, *args, **kwargs)
cls._instance._initialized = False
return cls._instance
def __init__(self):
"""
Create items in a pool of resources
"""
if self._initialized == False:
print('Init')
self.pool = []
self.out = []
for x in range(3):
self.pool.append(LimitedResource(x))
self._initialized = True
def checkoutItem(self):
"""
Take an item from the pool or exception if not available
"""
if len(self.pool) == 0:
raise('No Resources Available')
item = self.pool.pop()
self.out.append(item)
print(f'Handing out item {item._id}')
return item
def returnItem(self, item):
"""
Returns to the pool
(Note, not checking edge cases, like called twice etc)
"""
print(f'Item {item._id} returned to pool')
self.out.remove(item)
self.pool.append(item)
def status(self):
print('Pool Status')
for i in self.pool:
print(f' Item {i._id} in pool')
for i in self.out:
print(f' Item {i._id} handed out')
# %% codecell
with LimitedResourceFactory().checkoutItem() as item:
print(' Doing some work!!!')
print('\n')
LimitedResourceFactory().status()
print('\n')
print('After Complete')
LimitedResourceFactory().status()
# %% codecell
item = LimitedResourceFactory().checkoutItem()
print('Doing more work!!!')
LimitedResourceFactory().status()
print('Returning Item')
LimitedResourceFactory().returnItem(item)
LimitedResourceFactory().status()<file_sep># %% [md]
# # Observer Problem
# How can we watch for state changes and events in a manner that allows
# us to extend and test our code without making a codebase woven with
# orthogonal concerns.
# %% codecell
import numpy as np
class NeuralNetwork():
def forward(self, batch):
"""
Forward pass through the network
Returns our prediction (output)
"""
print('Forward Pass')
def backward(self, loss):
"""
Backward pass through the network
Returns our gradients given the loss
"""
print('Backward Pass')
def computeLoss(self, preds):
"""
Compute our loss between pred / actual
"""
print('Compute Loss')
def updateWeights(self, gradients, learning_rate=0.001):
"""
Given the gradients and our learning rate, update our weights
"""
print('Update Weight Parameters')
def train(self, epochs, batches):
"""
Training loop, for each epoch, for each batch
"""
for epoch in epochs:
for batch in batches():
preds = self.forward(batch)
loss = self.computeLoss(preds)
gradients = self.backward(loss)
self.updateWeights(gradients)
# %% [md]
# # Extend Functionality
# In this example, we want to do three things:
# * Adjust learning rate schedule (annealling)
# * Log loss after each batch
# * Log accuracy after each epoch
# We're also quite sure we'll want to make more adjustments
# %% [md]
# # Observer Pattern
# * Rather than add orthoginal code into our net, we separate concerns
# * Observed -> Code that creates events / state changes (our neural network)
# * Observer -> Watches for changes and dispatches events to those who are interested
# * Callback -> The interface an iterested party implements to get notified
# Note: Our code focuses on a specific implementation, and takes advantage of dunders
# for implementation details. We don't fully implement a neural net as well
# preferring to focus on the details of the three actors in this pattern.
# %% codecell
class Callback():
"""
Marker Interface
"""
pass
class Observer():
def __init__(self):
"""
Create a list of callbacks
"""
self.callbacks = []
def registerCallback(self, callback):
"""
Add the callback to our list
"""
self.callbacks.append(callback)
def __call__(self, *args, **kwargs):
"""
Got an event, invoke on our callbacks given the name
"""
invoke = args[0]
for c in self.callbacks:
try:
func = getattr(c, invoke)
func(args[1])
except:
pass
# %% [md]
# # Network 2.0
# %% codecell
class NeuralNetwork():
def __init__(self, callbacks=None):
"""
Setup an observer and add the callbacks provided
"""
self.observer = Observer()
if callbacks is not None:
for c in callbacks:
self.observer.registerCallback(c)
def observe(self, action, state={}):
"""
Observed a state or event, propagate to observer to forward
Set a reference to this neural network
"""
state['net'] = self
self.observer(action, state)
def forward(self, batch):
"""
Forward pass through the network
Returns our prediction (output)
"""
print('Forward Pass')
def backward(self, loss):
"""
Backward pass through the network
Returns our gradients given the loss
"""
print('Backward Pass')
def computeLoss(self, preds):
"""
Compute our loss between pred / actual
"""
print('Compute Loss')
return np.random.random()
def computeAccuracy(self):
"""
Compute our loss between pred / actual
"""
print('Compute Accuracy')
return np.random.random()
def updateWeights(self, gradients, learning_rate=0.001):
"""
Given the gradients and our learning rate, update our weights
"""
print('Update Weight Parameters')
def train(self, epochs, batches, learning_rate=0.001):
"""
Training loop, for each epoch, for each batch
"""
state = {}
state['epochs'] = epochs
state['batches'] = batches
state['learning_rate'] = learning_rate
for epoch in range(epochs):
state['epoch'] = epoch
self.observe('beforeEpoch', state)
for batch in range(batches):
state['batch'] = batch
self.observe('beforeBatch', state)
preds = self.forward(batch)
loss = self.computeLoss(preds)
gradients = self.backward(loss)
self.updateWeights(gradients)
state['loss'] = loss
self.observe('afterBatch', state)
accuracy = self.computeAccuracy()
state['accuracy'] = accuracy
self.observe('afterEpoch', state)
# %% [md]
# # Logging
# %% codecell
class CallbackLogging(Callback):
def beforeEpoch(self, state):
print(f'-> Before Epoch {state["epoch"] + 1} of {state["epochs"]}')
def afterEpoch(self, state):
print(f'-> After Epoch {state["epoch"] + 1} of {state["epochs"]}\n')
def beforeBatch(self, state):
print(f'--> Before Batch {state["batch"] + 1} of {state["batches"]}')
def afterBatch(self, state):
print(f'--> After Batch {state["batch"] + 1} of {state["batches"]}')
# %% codecell
logger = CallbackLogging()
ann = NeuralNetwork(callbacks=[logger])
ann.train(2,2)
# %% [md]
# # Callback Loss & Accuracy Tracking
# %% codecell
class CallbackMetricTracker(Callback):
def __init__(self):
self.losses = []
self.accuracy = []
def afterBatch(self, state):
self.losses.append(state['loss'])
def afterEpoch(self, state):
self.accuracy.append(state['accuracy'])
def __str__(self):
return(f'Losses {self.losses}\nAccuracy {self.accuracy}')
# %% codecell
logger = CallbackLogging()
tracker = CallbackMetricTracker()
ann = NeuralNetwork(callbacks=[logger, tracker])
ann.train(2,2)
print(tracker)
# %% [md]
# # Callback Learning Rate Annealing
# Most modern frameworks (PyTorch, Keras, TF), hold the learning rate with the optimizer.
# In this simple net, we're building our network and optimizer in one class.
# %% codecell
class CallbackLearningRate(Callback):
def afterBatch(self, state):
"""
Log a message for demo
"""
print(f'. Anneal learning rate {state["learning_rate"]}')
# %% codecell
logger = CallbackLogging()
tracker = CallbackMetricTracker()
learning = CallbackLearningRate()
ann = NeuralNetwork(callbacks=[logger, tracker, learning])
ann.train(2,2)
print(tracker)<file_sep># %% [md]
# # State Pattern
# * How can we enforce viable transitions without heavy use of if statements?
# %% codecell
class FlightState():
name = 'State'
allowed = []
def switch(self, switchTo):
""" Switch to new state """
if switchTo.name in self.allowed:
print(f'Current: {self.name} => switched to new state {switchTo.name}')
self.__class__ = switchTo
else:
print(f'Current: {self.name} => switching to {switchTo} not possible.')
def __str__(self):
return self.name
def __repr__(self):
return self.name
# %% codecell
class AtGate(FlightState):
name = 'AtGate'
allowed = ['Taxiing']
class Taxiing(FlightState):
name = 'Taxiing'
allowed = ['AtGate', 'Holding', 'Airborne']
class Airborne(FlightState):
name = 'Airborne'
allowed = ['Climbing']
class Climbing(FlightState):
name = 'Climbing'
allowed = ['Cruising', 'Descending']
class Cruising(FlightState):
name = 'Cruising'
allowed = ['Climbing', 'Descending']
class Descending(FlightState):
name = 'Descending'
allowed = ['Landing']
class Landing(FlightState):
name = 'Landing'
allowed = ['Taxiing']
class Holding(FlightState):
name = 'Holding'
allowed = ['Taxiing']
# %% codecell
class Flight():
def __init__(self, state=AtGate()):
self._state = state
self._history = [state]
def change(self, state):
""" Change state """
self._state.switch(state)
self._history.append(state)
def history(self):
for i in self._history:
print(i.name)
# %% codecell
flight75 = Flight()
flight75.change(Taxiing)
flight75.change(Holding)
flight75.change(Taxiing)
flight75.change(Airborne)
flight75.change(Climbing)
flight75.change(Cruising)
flight75.change(Descending)
flight75.change(Landing)
flight75.change(Taxiing)
flight75.change(AtGate)
# %% codecell
flight75.history() | 53f31799553d627f038ecc02c815bec8c27fa2f5 | [
"Python"
] | 15 | Python | swilsonmfc/oop4ds | a9f8e5fbfc58253850db623af370a9829a19357e | a47c5ac5db9f35cdda0c50ee0b31a65c4689650f |
refs/heads/master | <repo_name>d54365/pet<file_sep>/main.js
import Vue from 'vue'
import store from "./store"
import App from './App'
Vue.prototype.$store = store
Vue.config.productionTip = false
import divider from "@/components/common/divider.vue"
Vue.component('divider', divider)
import cuCustom from '@/components/cu-custom/cu-custom.vue';
Vue.component('cuCustom', cuCustom)
import loading from "@/components/common/loading.vue"
Vue.component('loading', loading)
import loadingPlus from "@/common/mixin/loading-plus.vue"
Vue.component('loading-plus', loadingPlus)
import request from '@/common/lib/request.js';
Vue.prototype.$http = request
Vue.prototype.navigateTo = (options)=>{
// 判断用户是否登录
if (!store.state.user.loginStatus) {
uni.showToast({
title: '请先登录',
icon: 'none'
});
return uni.navigateTo({
url: '/pages/login/login'
});
}
uni.navigateTo(options);
}
App.mpType = 'app'
const app = new Vue({
store,
...App
})
app.$mount()
| c3cba749e5dc5e50d7d5c08bea60dc21a1bc2ced | [
"JavaScript"
] | 1 | JavaScript | d54365/pet | 10b51babba8377154e4d87961418d7e8b63e402b | 8058f29791f4dc3712c8cb60af19cb3612f47e2b |
refs/heads/master | <file_sep>/* jshint node: true, asi: true, laxcomma: true, esversion: 6 */
'use strict'
const makeRes = require('./index').connectResponseFactory
// feed a connect style request object into this
let res = makeRes({
url: "/api/jfoise/things/390230r9",
query: {
name: 'farts'
}
}, {
data: {
messages: [
{ id: 0, text: 'wooo' },
{ id: 1, text: 'woooooo' }
]
}
}, req => {
// this 3rd arg is an optional callback used to mutate the req props
// that are ultimately set on the response body
return {
// query: omitSensitiveData(req.query),
query: req.query
}
})
console.info(res)
<file_sep>/* jshint node: true, asi: true, laxcomma: true, esversion: 6 */
'use strict'
/*
* @param req {object} Connect style Request object
* @param opts {object} Meta about response
* @param paramsGenerator {function} Optional factory for creating params object
*
* Pass a paramsGenerator as third argument to take control of creating params
* prop on response. Otherwise this function will just stick the req.params,
* req.query, and req.body object right on there all willy nilly.
*/
module.exports = function connectPayloadFactory (req, opts, paramsGenerator) {
opts = opts || {};
let reqId = req.requestId || opts.requestId || opts.reqId;
let id = opts.id || opts.documentId || opts.docId;
let lastUpdated = opts.lastUpdated;
let push = opts.push;
let start = opts.start;
let limit = opts.limit;
let data = opts.data;
let error = opts.error;
let statusCode = opts.statusCode;
let channel = opts.channel;
let resourcePath = req.url || req.path || opts.url || opts.path;
let params;
if (paramsGenerator && typeof paramsGenerator === 'function')
params = paramsGenerator(req);
else {
params = {
query: req.query,
body: req.body,
params: req.params
}
}
// pack response object such that we don't end up with a bunch of
// undefined props
let response = {};
response.timestamp = Date.now();
// touched timestamp for entity
if (lastUpdated !== undefined)
response.lastUpdated = lastUpdated;
// request lifecycle id - should
// match on request/response pair if applicable
if (reqId !== undefined)
response.requestId = reqId;
// entity id
if (id !== undefined)
response.id = id;
// full path to entity on server
if (resourcePath !== undefined)
response.resourcePath = resourcePath;
// flag indicates if this payload was sent from
// server without request (i.e. a push via websocket)
// sanitized to a bool here
if (push !== undefined)
response.push = push ? true : false;
// another prop for websockets, allowing for socket listeners on the client
// and server side to listen for messages on a given channel (string)
if (channel !== undefined)
response.channel = channel
if (start)
response.start = start;
if (limit !== undefined)
response.limit = limit;
// original request body
if (params !== undefined)
response.params = params;
// response payload
if (data !== undefined)
response.data = data;
// response meta
if (statusCode !== undefined)
response.statusCode = statusCode;
// optional error message or object
if (error !== undefined)
response.error = error;
return response;
}
<file_sep>/* jshint node: true, asi: true, laxcomma: true, esversion: 6 */
'use strict'
/**
* This file surfaces the various response factories available via this
* module (of which there is only one right now).
*/
const connectResponseFactory = require('./lib/connect-response-factory.js');
module.exports.connectResponseFactory = connectResponseFactory;
| f577b23a445719e5310baf33568fd35ef293c5d5 | [
"JavaScript"
] | 3 | JavaScript | enlore/eims-rest-contract | 5829464cd7b82307160c6fc2a590a34bae3d4974 | 9f0e4b7f63d281daafc55133f76d25428ba303d3 |
refs/heads/master | <repo_name>ruthbuena/CurbYourComment<file_sep>/brocial_db.sql
DROP DATABASE IF EXISTS brocial_networkDB;
CREATE database brocial_networkDB;
USE brocial_networkDB;
<file_sep>/README.md
# Project-2
Group Project incorporating a Node and Express web server; backed by MySQL using an ORM and deployed using Heroku
The enclosed repo includes a social networking application for Curb your Enthusiasm fans built by a team of (3) using a MVC paradigm and ORM with a Node and Express web server. The application was initially backed by a local MySQL database then deployed via Heroku allowing users to access the same relational database using JawsDB. Grunt.js was used as a task runner to ensure dynamic styling with Sass and included Travis CI for continuous integration.
My contribution to the project included incorporating the initial MySQL database, implementing the CRUD (Create/Read/Update/Delete) process for blog posts within the app, assisting with establishing the routes, incorporated the show’s theme song and a countdown using JavaScript, and integrated the use of Grunt.js, Sass and Travis CI into the project.
<file_sep>/routing/htmlRoutes.js
const
express = require('express'),
path = require('path'),
app = express();
module.exports = function(app) {
app.get('/', function(req, res) {
res.redirect('/home');
});
app.get('/home', function(req, res) {
res.sendFile(path.join(__dirname, '../public/home.html'))
});
app.get('/signup', function(req, res) {
res.sendFile(path.join(__dirname, '../public/signup.html'))
});
// blog route loads blog.html
app.get("/blog", function(req, res) {
res.sendFile(path.join(__dirname, "../public/blog.html"));
});
app.get('/post', function(req, res) {
res.sendFile(path.join(__dirname, '../public/post.html'))
});
};
<file_sep>/routing/apiRoutes.js
// Requiring our Todo model
var db = require('../models');
// Routes
// =============================================================
module.exports = function(app) {
console.log(db.User);
// GET route for getting all of the users
app.get("/api/users", function(req, res) {
var query = {};
if (req.query.username) {
query.username = req.query.username;
};
db.User.findAll({
where: query
}).then(function(dbUser) {
res.json(dbUser);
});
});
// POST route for saving a new user
app.post("/api/users", function(req, res) {
console.log(req.body);
db.User.create({
username: req.body.username,
password: <PASSWORD>,
name: req.body.name,
email: req.body.email
}).then(function(results) {
res.end();
});
});
app.post('/api/posts', function(req, res) {
console.log(req.body);
db.Post.create({
title: req.body.title,
body: req.body.body
}).then(function(results) {
res.end();
});
});
app.delete("/api/users/:id", function(req, res) {
db.User.destroy({
where: {
id: req.params.id
}
})
.then(function(dbUser) {
res.json(dbUser);
});
});
app.put("/api/posts", function(req, res) {
console.log('asdf');
db.Post.update(
req.body, {
where: {
id: req.body.id
}
}).then(function(dbPost) {
res.json(dbPost);
});
});
};
// // Get route for returning users of a specific category
// app.get("/api/users/category/:category", function(req, res) {
// db.User.findAll({
// where: {
// // category: req.params.category
// }
// })
// .then(function(dbUser) {
// res.json(dbUser);
// });
// });
// Get rotue for retrieving a single user
// app.get("/api/users/:id", function(req, res) {
// db.User.findOne({
// where: {
// id: req.params.id
// }
// })
// .then(function(dbUser) {
// res.json(dbUser);
// });
// });
// DELETE route for deleting users
//
// // PUT route for updating users
// app.put("/api/users", function(req, res) {
// var user = {
// username: req.body.username,
// password: <PASSWORD>,
// name: req.body.name,
// email: req.body.email
// }
// db.User.update(user,
// {
// where: {
// id: req.body.id
// }
// })
// .then(function(dbUser) {
// res.json(dbUser);
// });
// });
| 1503dd3dce08662b3901a9674c33b21ecdd3971c | [
"Markdown",
"SQL",
"JavaScript"
] | 4 | SQL | ruthbuena/CurbYourComment | 4758c0508878a4d0041a39f98ae22f0ec870bac3 | f99434b3c5893c264a5a657086ff4caf44bd1994 |
refs/heads/master | <repo_name>DanielNaizabekov/danielnaizabekov.github.io<file_sep>/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/3.6.8/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.6.8/firebase-messaging.js');
firebase.initializeApp({
apiKey: "<KEY>",
authDomain: "decoblog-4df8b.firebaseapp.com",
databaseURL: "https://decoblog-4df8b.firebaseio.com",
projectId: "decoblog-4df8b",
storageBucket: "decoblog-4df8b.appspot.com",
messagingSenderId: "180553791102",
appId: "1:180553791102:web:e233eddec7ca012bc54a2f",
measurementId: "G-VCD20PZ0HE",
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('Recieved background message', payload);
payload.data.data = JSON.parse(JSON.stringify(payload.data));
return self.registration.showNotification(payload.data.title, payload.data);
});<file_sep>/js/firebase_subscribe.js
let btn = document.querySelector('.btn');
btn.onclick = () => {
alert('Sending...');
sendNotify();
};
setTimeout(() => {
sendNotify();
}, 7000);
function sendNotify() {
messaging.getToken().then(token => {
console.log(token);
fetch('https://fcm.googleapis.com/fcm/send', {
method: 'POST',
headers: {
'Authorization': 'key=<KEY>',
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: {
title: 'Уведомление',
body: 'Начало в 21:00',
},
to: token,
}),
}).then(response => console.log(response));
});
};
firebase.initializeApp({
apiKey: "<KEY>",
authDomain: "decoblog-4df8b.firebaseapp.com",
databaseURL: "https://decoblog-4df8b.firebaseio.com",
projectId: "decoblog-4df8b",
storageBucket: "decoblog-4df8b.appspot.com",
messagingSenderId: "180553791102",
appId: "1:180553791102:web:e233eddec7ca012bc54a2f",
measurementId: "G-VCD20PZ0HE",
});
if ('Notification' in window) {
messaging = firebase.messaging();
subscribe();
messaging.onMessage(function(payload) {
console.log('Message received', payload);
alert('Message recieved');
});
}
function subscribe() {
messaging.requestPermission()
.then(function () {
messaging.getToken()
.then(function (currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
} else {
console.log('Не удалось получить токен.');
setTokenSentToServer(false);
}
})
.catch(function (err) {
console.log('При получении токена произошла ошибка.', err);
setTokenSentToServer(false);
});
})
.catch(function (err) {
console.log('Не удалось получить разрешение', err);
});
};
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer(currentToken)) {
// var url = ''; // адрес, где хранятся токены
// $.post(url, {
// token: currentToken
// });
setTokenSentToServer(currentToken);
} else {
console.log('Токен уже отправлен на сервер.');
}
}
function isTokenSentToServer(currentToken) {
return window.localStorage.getItem('sentFirebaseMessagingToken') == currentToken;
}
function setTokenSentToServer(currentToken) {
window.localStorage.setItem(
'sentFirebaseMessagingToken',
currentToken ? currentToken : ''
);
} | 11c06b4b7879b87d45b425baea0ea7ff82456434 | [
"JavaScript"
] | 2 | JavaScript | DanielNaizabekov/danielnaizabekov.github.io | f2074bd1020a766e43d79ebe61e8ae0aaa108f7c | ec532e59caaf6564e29587a3fef7cc37b48a49aa |
refs/heads/master | <repo_name>chukwumaokere/ionic4-javascript-framework<file_sep>/stencil.config.ts
exports.config = {
// ...
globalStyle: 'src/global.css'
// ...
}; | 6d1e4ce5a3966280042466ace4025f51f600b98e | [
"TypeScript"
] | 1 | TypeScript | chukwumaokere/ionic4-javascript-framework | cc941f5fda3a1fda1e4b4fc08182ff22b3311d01 | ef7b1a70fb81035bef3a5d31f7c4ebaf7779fe8e |
refs/heads/master | <repo_name>efitr/EcologicalAlgorithms<file_sep>/C/birth_death_simulation.c
/* Immigration-Emigration Models */
/* Alternatives immigration-emigration models
Queuing organisms, their population's net emigration rate is independent
of the queue size when the queue is greater than zero.
Non-queuing organisms, their population's net emigration rate depends
on the population number.
*/
/* The objective
What are the processes that cause population numbers to rise and fall.
Depends on one basic feature, whether it is an open or closed system.
*/
/* Characterictics of the model
-
*/
/* Characteristics of the program
- This is an open system.
- There is no track of specific individuals only the total number.
*/
/*Libraries I depend upon for some functions */
#include <stdlib.h> /* Call random number generator drand48() */
#include <studio.h> /* Use printf() */
/*Global variables, they can be changed through the whole program */
#define MAXTIME 100
#define PRNTTIME 10
/* */
/* First procedure to be called */
int main(void) /* The int represents that the program eventually expects
a particular type of number after the program finishes executing */
/* The void denotes that the program expects nothing to be passed to
it from the operating system when execution starts */
{
/* Every variable must have it's type predefined before be used */
int ttt, event, n;
int seed;
double alpha, beta; /* individual immigrates with alpha rate per unit time
individual emigrates from the system with rate beta per unit time*/
/* After the type assignment,you get to give the pertaining values to each one */
alpha = beta = 0.1;
n = 10;
/* */
seed = 1456739853;
srand48(seed);
printf(" time pop\n");
for(ttt=0;ttt<MAXTIME;ttt++)
{
event = 0;
if(drand48()<alpha) event = 1;
if(drand48()<beta) event = event - 1;
n += event;
if(n<0) n = 0;
if(ttt%PRNTTIME==0)
printf(" %3d %-4d\n", ttt, n);
}
return(0);
} | f316d76d800033cc5b56b69f02bc6d3f40d340f7 | [
"C"
] | 1 | C | efitr/EcologicalAlgorithms | 93966f453a0bb23b54c8e7dbe2485b1b45de6143 | 7755434991efbdbf7afbd45add36f17da938c6b6 |
refs/heads/master | <repo_name>saketkc/elearning_academy1<file_sep>/upload/templates/upload/upload.html
{% extends 'assignments/assignments_base.html' %}
{% load i18n %}
{% block content_title %}{% endblock %}
{% block main %}
<div class="well sidebar-nav">
<div class="row-fluid">
<div class="span10 offset1">
<script type="text/javascript">
$(function() {
$('form').submit(function(e) {
if($(this).attr('ajaxify')) {
/*
function my_js_callback(data) {
var $response=$(data);
var oneval = $response.find('#files');
$('#files').html(oneval);
}
formdata = $('#myform').serializeObject();
Dajaxice.upload.uploadFile(Dajax.process, {'form': formdata});
*/
data = new FormData();
data.append( 'docfile', $( '#id_docfile' )[0].files[0] );
data.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
url: $(this).attr('ajaxify'),
type: 'POST',
processData: false,
contentType:false,
data: data,
error: function(request, status, error){
alert(request.responseText);
},
success : function(data){
var $response=$(data);
var oneval = $response.find('#files');
$('#files').html(oneval);
}
});
return false;
}
else { return true; }
});
});
</script>
<li class="nav-header"><h4>Your assignment files</h4></li>
<li class="nav-header">{{assignId}}</li>
<div id="files">
{% if documents %}
<ul>
{% for document in documents %}
<!-- <li><a href="{{ document.filePath.url }}">{{ document.filePath.name }}</a> -->
<li><a href="{% url 'submission_downloadfile' document.id %}">{{ document.filePath.name }}</a>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
</div>
<div id="uplodForm">
<!-- Upload form. Note enctype attribute! -->
<form id="myform" action="{% url 'upload' %}" method="post" enctype="multipart/form-data" ajaxify="{% url 'upload' %}">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
<file_sep>/quiz_template/template_parser.py
"""Template Parser"""
import ConfigParser
import os
import unittests
class TemplateParser:
"""Class to parse quiz templates
"""
def __init__(self, template_file):
self.template = ConfigParser.ConfigParser()
self.template.read(template_file)
def get_all_sections(self):
return self.templates.sections()
def get_question_map(self, question_tag):
question_map = {}
details = self.template.options(question_tag)
for sub_tag in details:
try:
question_map[sub_tag] = self.template.get(question_tag,
sub_tag)
if question_map[sub_tag] == -1:
raise ValueError("Question sub tags not found")
except Exception as ex:
print "Exception %s on %s" % (ex, sub_tag)
question_map[sub_tag] = None
return question_map
def club_question_with_subparts(self, question_list):
pass
def template_reader(self):
all_sections = self.get_all_sections()
assert len(all_sections) is not 0
for question in all_sections:
pass
<file_sep>/document/models.py
from django.db import models
from uuid import uuid4
import json
# Create your models here.
SHORT_TEXT = 255
LARGE_TEXT = 1023
UUID_TEXT = 32
class Document(models.Model):
"""
Class for storing General HTML Markup doument which can have \
multiple sections.
Will be used in additional course info pages
"""
title = models.CharField(max_length=SHORT_TEXT) # Page/Link Title
uid = models.CharField(max_length=UUID_TEXT) # Unique ID for Document
is_heading = models.BooleanField(default=False)
#This document can be link to another page too
is_link = models.BooleanField(default=False)
link = models.URLField(max_length=SHORT_TEXT, blank=True)
description = models.TextField(
blank=True,
help_text="Short description/text for document \
Leave it blank for no display"
)
playlist = models.TextField(default="[]")
def save(self, *args, **kwargs): # pylint: disable=W0613
""" Overriding save method for assigning random uid on create """
if not self.pk:
self.uid = uuid4().hex
super(Document, self).save(*args, **kwargs)
def sections(self):
""" Returns array of sections of this documents """
sects = Section.objects.filter(document=self)
return [x.to_dict() for x in list(sects)]
def to_dict(self):
""" Returns dict object of this document """
obj = {
"title": self.title,
"description": self.description,
"id": self.pk
}
obj["sections"] = self.sections()
_playlist = json.loads(str(self.playlist))
N = len(_playlist)
ordered_data = [""]*N
for i in range(N):
ordered_data[i] = obj["sections"][_playlist[i][1]]
obj["sections"] = ordered_data
return obj
class Section(models.Model):
"""
This class will be subpart of Document Class. This stores part \
of information
"""
document = models.ForeignKey(
Document,
related_name="Document_Section",
db_index=True)
title = models.CharField(max_length=SHORT_TEXT)
description = models.TextField()
file = models.FileField(upload_to='uploads/section', null=True, blank=True)
def to_dict(self):
""" Returns dictionary format of this object """
data = {
"id": self.pk,
"title": self.title,
"description": self.description
}
if self.file:
data["file"] = self.file.url
return data
<file_sep>/upload/receivers.py
from django.db import models
# Pre_Delete receiver. Deletes all the files of the instance passed as input.
def delete_files(sender, instance, **kwargs):
for field in instance._meta.fields:
if isinstance(field, models.FileField):
filefield = getattr(instance, field.name)
if filefield:
filefield.delete(save=False)<file_sep>/assignments/ajax.py
from assignments.models import Assignment
from assignments.models import Program
from assignments.models import Testcase
from assignments.views import isCourseCreator
from evaluate.models import ProgramResults
from evaluate.models import TestcaseResult
from upload.models import Upload
from django.shortcuts import get_object_or_404
from django.core.exceptions import PermissionDenied
from dajax.core import Dajax
from dajaxice.decorators import dajaxice_register
from utils.archives import archive_filepaths, extract_or_copy_singlefile
import shutil, tempfile
@dajaxice_register
def getfilesUploaded(request, submissionID):
submission = get_object_or_404(Upload, pk=submissionID)
assignment = submission.assignment
if not (request.user == submission.owner or isCourseCreator(assignment.course,request.user)):
raise PermissionDenied
src = submission.filePath.file.name # gives absolute path
submission.filePath.close()
submittedFiles = archive_filepaths(name=src)
dajax = Dajax()
# htmldata = ""
popupdata = ''
for submittedFile in submittedFiles:
# htmldata += '<a href = "javascript:loadfile(' + str(submissionID) + ',\'' + submittedFile + '\');">' + submittedFile + '</a>,'
popupdata += '<li style="text-align:center;"><a href = "javascript:loadfile(' + str(submissionID) + ',\'' + submittedFile + '\');">' + submittedFile + '</a></li>'
popupdata += '<li class="divider"></li>'
# dajax.clear('#filelist', 'innerHTML')
# dajax.append('#filelist','innerHTML',htmldata)
dajax.clear('.popup-data-files', 'innerHTML')
dajax.append('.popup-data-files','innerHTML',popupdata)
return dajax.json()
@dajaxice_register
def loadFile(request, submissionID, filePath):
submission = get_object_or_404(Upload, pk=submissionID)
assignment = submission.assignment
if not (request.user == submission.owner or isCourseCreator(assignment.course,request.user)):
raise PermissionDenied
src = submission.filePath.file.name # gives absolute path
submission.filePath.close()
temp_dir = tempfile.mkdtemp(prefix="grader")
filedata = ''
try:
extract_or_copy_singlefile(src, temp_dir, filePath)
#reading file data and storing it as a string
temp_file_path = temp_dir + "/" + filePath
print temp_file_path
filePtr = open(temp_file_path, 'r')
for line in filePtr:
filedata += line
if filePtr:
filePtr.close()
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
dajax = Dajax()
dajax.assign('#filedata', 'value', filedata)
return dajax.json()
@dajaxice_register
def loadStats(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
programs = Program.objects.filter(assignment=assignment)
numSubmissions = Upload.objects.filter(assignment=assignment).count()
statsTable = "<div style='text-align:center;'><b>Total Number of submissions : " + str(numSubmissions) + "</b></div><br />"
statsTable += "<table class='table table-bordered'><thead><tr><th>Section Name</th><th>Compilation Errors</th><th>Testcase Name</th><th>Failed this testcase</th></tr></thead><tbody>"
for aprogram in programs:
numCompErrors = ProgramResults.objects.filter(program=aprogram, compiler_return_code=1).count()
testcases = Testcase.objects.filter(program=aprogram)
if testcases.__len__() == 0:
statsTable += "<tr>"
statsTable += "<td>" + aprogram.name + "</td>"
statsTable += "<td>" + str(numCompErrors) + "</td>"
statsTable += "<td></td>"
statsTable += "<td></td>"
statsTable += "</tr>"
else:
statsTable += "<tr>"
statsTable += "<td rowspan='" + str(testcases.__len__()) + "'>" + aprogram.name + "</td>"
statsTable += "<td rowspan='" + str(testcases.__len__()) + "'>" + str(numCompErrors) + "</td>"
i = 0
for atestcase in testcases:
failedTestcases = TestcaseResult.objects.filter(test_case=atestcase, test_passed=False).count()
if i == 0:
i += 1
statsTable += "<td>" + atestcase.name + "</td>"
statsTable += "<td>" + str(failedTestcases) + "</td>"
statsTable += "</tr>"
else:
i += 1
statsTable += "<tr>"
statsTable += "<td>" + atestcase.name + "</td>"
statsTable += "<td>" + str(failedTestcases) + "</td>"
statsTable += "</tr>"
statsTable += "</tbody></table>"
dajax = Dajax()
dajax.clear('#stats', 'innerHTML')
dajax.append('#stats','innerHTML',statsTable)
return dajax.json()
<file_sep>/courseware/typed_playlist.py
"""
This file stores the functions used by generic playlist
"""
import json
def compare_function(a, b):
if a[0] == b[0]:
return a[2]-b[2]
else:
return a[0]-b[0]
def is_valid(mylist, actuallist):
"""
To keep the sanctity of the playlist, we would want checks of the sort of
count same at both places and ids are correct
"""
a = json.loads(mylist)
sa = sorted(a)
b = json.loads(actuallist)
sb = sorted(b, cmp=compare_function)
N = len(a)
M = len(b)
if(N != M):
return False
c = []
for i in range(N):
if (sa[i][0] != sb[i][0]) or (sa[i][1] != sb[i][2]):
return False
for i in range(N):
for j in range(N):
if(a[i][0] == b[j][0]) and a[i][1] == b[j][2]:
c.append(b[j])
break
return c
def to_array(mylist):
a = json.loads(mylist)
return a
def append(obj, mylist, contenttype):
a = json.loads(mylist)
N = len(a)
count = 0
for i in range(N):
if(a[i][2] == contenttype):
count += 1
a.append([obj, count, contenttype])
mylist = json.dumps(a)
return mylist
def delete(mylist, pk, contenttype):
a = json.loads(mylist)
N = len(a)
for i in range(N):
if (int(a[i][0]) == int(pk)) and (int(a[i][2]) == int(contenttype)):
myindex = i
rank = a[myindex][1]
for j in range(N):
if (a[j][2] == int(contenttype)) and (a[j][1] > rank):
a[j][1] -= 1
del a[myindex]
mylist = json.dumps(a)
return mylist
return False
<file_sep>/user_profile/static/user_profile/js/settings_root.jsx
/** @jsx React.DOM */
var SettingsBody = React.createClass({
mixins: [LoadMixin],
getUrl: function() {
url = "/user/pending_approvals";
return url;
},
approveRequests: function() {
users = []
pending_approvals = this.state.data.users;
selected = $('input[name=user]').map(function(node, i) {
return this.checked
});
for (var i = 0; i < selected.length; i++) {
if (selected[i]) {
users.push(pending_approvals[i]["user"]);
}
}
data = {users: JSON.stringify(users)};
console.log(data);
url = "/user/approve/?format=json";
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
this.loadData();
this.forceUpdate();
this.props.updateApprovedStudents();
console.log("Student List should reload now")
}.bind(this));
request.fail(function(response) {
display_global_message("Not allowed. Only root user has permission","error")
}.bind(this));
},
discardRequests: function() {
users = []
pending_approvals = this.state.data.users;
selected = $('input[name=user]').map(function(node, i) {
return this.checked
});
for (var i = 0; i < selected.length; i++) {
if (selected[i]) {
users.push(pending_approvals[i]["user"]);
}
}
data = {users: JSON.stringify(users)};
console.log(data);
url = "/user/discard/?format=json";
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
this.loadData();
this.forceUpdate();
this.props.updateApprovedStudents();
console.log("Student List should reload now")
}.bind(this));
request.fail(function(response) {
display_global_message("Not allowed. Only root user has permission","error")
}.bind(this));
},
toggleAll: function() {
check = $('input[name=heading]')[0].checked;
nodes = $('input[name=user]');
for (var i = 0; i < nodes.length; i++) {
nodes[i].checked = check;
};
},
handleChange: function(event) {
if (! event.target.checked) {
$('input[name=heading]')[0].checked = false;
}
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
render: function() {
if (this.state.loaded) {
if (! this.state.data.response) {
return (
<div class="row" style={{'margin-top':'15px'}}>
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger">
TextBook Course does not have Students
</div>
</div>
</div>
);
}
pending_approvals = this.state.data.users;
pending_approvals = pending_approvals.map( function(user, i) {
return (
<div class="checkbox-row">
<div class="col-md-1 col-md-offset-0 checkbox-container">
<input onChange={this.handleChange} type="checkbox" name="user" key={"pending_student_" + i}> </input>
</div>
<div class="col-md-3 col-md-offset-0 username"> {user["username"]} </div>
<div class="col-md-4 col-md-offset-0 fullname"> {user["fullname"]} </div>
<div class="col-md-4 col-md-offset-0 email"> {user["email"]} </div>
</div>
);
}.bind(this));
if (pending_approvals.length > 0) {
return (
<div class="panel-collapse collapse in" id="pending-students">
<div class="row">
<div class="col-md-offset-7 col-md-2 no-padding">
<button ref="approve" onClick={this.approveRequests}
class="btn btn-primary approve-btn" type="button"> Approve </button>
</div>
<div class="col-md-2">
<button ref="approve" onClick={this.discardRequests}
class="btn btn-danger approve-btn" type="button"> Discard </button>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1 no-padding student-container">
<div class="student-heading">
<div class="col-md-1 col-md-offset-0 checkbox-container">
<input type="checkbox" name="heading" key="student_heading"
onChange={this.toggleAll}>
</input>
</div>
<div class="col-md-3 col-md-offset-0 username">
User Name </div>
<div class="col-md-4 col-md-offset-0 fullname">
Full Name </div>
<div class="col-md-4 col-md-offset-0 email">
Email </div>
</div>
{pending_approvals}
</div>
</div>
</div>
);
} else {
return (
<div class="panel-collapse collapse in" id="pending-students">
<div class="col-md-offset-7 col-md-2">
<button ref="approve" onClick={this.approveRequests}
class="btn btn-primary approve-btn" type="button"> Approve </button>
</div>
<div class="col-md-2">
<button ref="approve" onClick={this.discardRequests}
class="btn btn-danger approve-btn" type="button"> Discard </button>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
No pending Users to approve.
</div>
</div>
</div>
</div>
);
}
} else {
return <LoadingBar />
}
}
});
var CourseStudent = React.createClass({
updateApprovedStudents: function() {
console.log("Sending signal to Approved Users");
this.setState({loaded: false});
},
getInitialState: function(){
return {
loaded:false,
};
},
});<file_sep>/quiz/tests.py
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase, Client
from django.contrib.auth.models import User
from user_profile.models import CustomUser
from quiz.models import *
import json
from quiz.grader import Grader
class QuizModelTest(TestCase):
def setUp(self):
#instructor or content developer
user = User(username='user', is_active=True, email="<EMAIL>")
user.set_password('<PASSWORD>')
user.save()
self.instructor = CustomUser.objects.get(user=user)
self.instructor.is_instructor = True
self.instructor.is_content_developer = True
self.instructor.default_mode = 'C'
self.instructor.save()
#student user
user = User(username='student', is_active=True, email="<EMAIL>")
user.set_password('<PASSWORD>')
user.save()
self.student = CustomUser.objects.get(user=user)
self.student.is_instructor = False
self.student.is_content_developer = False
self.student.default_mode = 'S'
self.student.save()
quiz1 = Quiz(title='quiz 1')
quiz1.save()
module1 = QuestionModule(quiz=quiz1, title='module 1')
module1.save()
question1 = DescriptiveQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,answer='this is the answer',grader_type='M')
question1.save()
submission = Submission(question=question1,student=user, answer='this is the answer', grader_type='M')
submission.save()
question1 = SingleChoiceQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,options='["a1","a2","a3"]',answer=0)
question1.save()
submission = Submission(question=question1,student=user, answer='1')
submission.save()
submission = Submission(question=question1,student=user, answer='0')
submission.save()
question1 = MultipleChoiceQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,options='["a1","a2","a3"]', answer='[true, false, true]')
question1.save()
submission = Submission(question=question1,student=user, answer='[true, false, false]')
submission.save()
submission = Submission(question=question1,student=user, answer='[true, false, true]')
submission.save()
question1 = FixedAnswerQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,answer='["a1", "a2", "a3"]')
question1.save()
submission = Submission(question=question1,student=user, answer='a4')
submission.save()
submission = Submission(question=question1,student=user, answer='a2')
submission.save()
def test_quiz_model(self):
quiz = Quiz.objects.get(pk=1)
self.assertEqual(quiz.title, 'quiz 1')
self.assertEqual(quiz.question_modules, 1)
self.assertEqual(quiz.questions, 4)
self.assertEqual(quiz.marks, 12)
module = QuestionModule.objects.get(pk=1)
self.assertEqual(module.quiz, quiz)
self.assertEqual(module.title, 'module 1')
self.assertEqual(module.questions, 4)
question = DescriptiveQuestion.objects.get(pk=1)
self.assertEqual(question.question_module, module)
self.assertEqual(question.quiz, quiz)
self.assertEqual(question.description, 'q1')
self.assertEqual(question.marks, 3)
self.assertEqual(question.attempts, 2)
self.assertEqual(question.grader_type, 'M')
self.assertEqual(question.granularity, '3,2,0')
self.assertEqual(question.answer, 'this is the answer')
question.delete()
question = SingleChoiceQuestion.objects.get(pk=2)
self.assertEqual(question.options, '["a1","a2","a3"]')
self.assertEqual(question.answer, 0)
self.assertEqual(question.get_answer(), 0)
self.assertEqual(question.get_answer(True), 'a1')
question = MultipleChoiceQuestion.objects.get(pk=3)
self.assertEqual(question.options, '["a1","a2","a3"]')
self.assertEqual(question.answer, '[true, false, true]')
self.assertEqual(question.get_answer(), '[true, false, true]')
self.assertEqual(question.get_answer(True), '["a1", "a3"]')
question = FixedAnswerQuestion.objects.get(pk=4)
self.assertEqual(question.answer, '["a1", "a2", "a3"]')
self.assertEqual(question.get_answer(), json.loads('["a1", "a2", "a3"]'))
module = QuestionModule.objects.get(pk=1)
quiz = Quiz.objects.get(pk=1)
self.assertEqual(module.questions, 3)
self.assertEqual(quiz.questions, 3)
self.assertEqual(quiz.marks, 9)
module.delete()
quiz = Quiz.objects.get(pk=1)
self.assertEqual(quiz.question_modules, 0)
self.assertEqual(quiz.questions, 0)
def test_quiz_history_model(self):
submission = Submission.objects.get(pk=1)
self.assertEqual(submission.question, Question.objects.get(pk=1))
self.assertEqual(submission.student, self.student.user)
self.assertEqual(submission.answer, 'this is the answer')
self.assertEqual(submission.status, 'A')
grader = Grader(submission,None,None)
self.assertFalse(grader.grade())
self.assertEqual(submission.status, 'A')
with self.assertRaises(QuestionHistory.DoesNotExist):
QuestionHistory.objects.get(student=submission.student, question=submission.question)
submission = Submission.objects.get(pk=2)
grader = Grader(submission,None,None)
self.assertTrue(grader.grade())
self.assertEqual(submission.status, 'D')
self.assertEqual(submission.is_correct, False)
self.assertEqual(submission.result, 0.0)
question_hist = QuestionHistory.objects.get(student=submission.student, question=submission.question)
#Note : attempts not increased in grader or submission model
# self.assertEqual(question_hist.attempts, 1)
self.assertEqual(question_hist.status, 'O')
quiz_hist = QuizHistory(user=submission.student, quiz=Quiz.objects.get(pk=1))
self.assertEqual(quiz_hist.marks, 0.0)
submission = Submission.objects.get(pk=3)
grader = Grader(submission,None,None)
self.assertTrue(grader.grade())
self.assertEqual(submission.status, 'D')
self.assertEqual(submission.is_correct, True)
# marks not updated as depend on attempts
# self.assertEqual(submission.result, 2.0)
question_hist = QuestionHistory.objects.get(student=submission.student, question=submission.question)
self.assertEqual(question_hist.status, 'S')
# self.assertEqual(quiz_hist.marks, 2.0)
quiz_hist = QuizHistory(user=submission.student, quiz=Quiz.objects.get(pk=1))
# self.assertEqual(quiz_hist.marks, 2.0)
submission = Submission.objects.get(pk=4)
grader = Grader(submission,None,None)
self.assertTrue(grader.grade())
self.assertEqual(submission.is_correct, False)
question_hist = QuestionHistory.objects.get(student=submission.student, question=submission.question)
self.assertEqual(question_hist.status, 'O')
submission = Submission.objects.get(pk=5)
grader = Grader(submission,None,None)
self.assertTrue(grader.grade())
self.assertEqual(submission.is_correct, True)
question_hist = QuestionHistory.objects.get(student=submission.student, question=submission.question)
self.assertEqual(question_hist.status, 'S')
submission = Submission.objects.get(pk=6)
grader = Grader(submission,None,None)
self.assertTrue(grader.grade())
self.assertEqual(submission.is_correct, False)
question_hist = QuestionHistory.objects.get(student=submission.student, question=submission.question)
self.assertEqual(question_hist.status, 'O')
submission = Submission.objects.get(pk=7)
grader = Grader(submission,None,None)
self.assertTrue(grader.grade())
self.assertEqual(submission.is_correct, True)
question_hist = QuestionHistory.objects.get(student=submission.student, question=submission.question)
self.assertEqual(question_hist.status, 'S')
class QuizViewAdminTest(TestCase):
def setUp(self):
#instructor or content developer
user = User(username='user', is_active=True, email="<EMAIL>")
user.set_password('<PASSWORD>')
user.save()
self.instructor = CustomUser.objects.get(user=user)
self.instructor.is_instructor = True
self.instructor.is_content_developer = True
self.instructor.default_mode = 'C'
self.instructor.save()
quiz1 = Quiz(title='quiz 1')
quiz1.save()
module1 = QuestionModule(quiz=quiz1, title='module 1')
module1.save()
# question1 = DescriptiveQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,answer='this is the answer',grader_type='M')
# question1.save()
# submission = Submission(question=question1,student=user, answer='this is the answer', grader_type='M')
# submission.save()
question1 = SingleChoiceQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,options='["a1","a2","a3"]',answer=0)
question1.save()
submission = Submission(question=question1,student=user, answer='1')
submission.save()
submission = Submission(question=question1,student=user, answer='0')
submission.save()
question1 = MultipleChoiceQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,options='["a1","a2","a3"]', answer='[true, false, true]')
question1.save()
submission = Submission(question=question1,student=user, answer='[true, false, false]')
submission.save()
submission = Submission(question=question1,student=user, answer='[true, false, true]')
submission.save()
question1 = FixedAnswerQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,answer='["a1", "a2", "a3"]')
question1.save()
submission = Submission(question=question1,student=user, answer='a4')
submission.save()
submission = Submission(question=question1,student=user, answer='a2')
submission.save()
self.c = Client()
self.c.post('/accounts/login/', {'username':'user','password':'<PASSWORD>'}, follow=True)
def test_quiz_view_get(self):
response = self.c.get('/quiz/api/quiz/', follow=True)
self.assertEqual(response.status_code, 200)
quiz_list = json.loads(response.content)
self.assertEqual(len(quiz_list), 1)
response = self.c.get('/quiz/api/quiz/1/', follow=True)
self.assertEqual(response.status_code, 200)
quiz = json.loads(response.content)
self.assertEqual(quiz['id'], 1)
self.assertEqual(quiz['title'], 'quiz 1')
self.assertEqual(quiz['question_modules'], 1)
self.assertEqual(quiz['questions'], 3)
self.assertEqual(quiz['marks'], 9)
response = self.c.get('/quiz/api/quiz/1000/', follow=True)
self.assertEqual(response.status_code, 404)
response = self.c.get('/quiz/api/quiz/1/get_question_modules/',follow=True)
self.assertEqual(response.status_code, 200)
module_list = json.loads(response.content)
self.assertEqual(len(module_list), 1)
response = self.c.get('/quiz/api/quiz/1/get_questions_manual_grade/',follow=True)
self.assertEqual(response.status_code, 200)
question_list = json.loads(response.content)
self.assertEqual(len(question_list), 0)
def test_quiz_view_post(self):
response = self.c.post('/quiz/api/quiz/', {'title':'Quiz 2'})
self.assertEqual(response.status_code, 201)
response = self.c.post('/quiz/api/quiz/1/', {'title':'Quiz 1 mod', '_method':'PUT'})
self.assertEqual(response.status_code, 200)
quiz = json.loads(response.content)
self.assertEqual(quiz['id'], 1)
self.assertEqual(quiz['title'], 'Quiz 1 mod')
self.assertEqual(quiz['question_modules'], 1)
self.assertEqual(quiz['questions'], 3)
self.assertEqual(quiz['marks'], 9)
response = self.c.post('/quiz/api/quiz/2/', {'_method':'DELETE'})
self.assertEqual(response.status_code, 204)
with self.assertRaises(Quiz.DoesNotExist):
Quiz.objects.get(pk=2)
response = self.c.post('/quiz/api/quiz/1/add_question_module/', {'quiz':1,'title': 'module'})
self.assertEqual(response.status_code, 200)
response = self.c.post('/quiz/api/quiz/1/add_question_module/', {'title': 'module'})
self.assertEqual(response.status_code, 400)
def test_quiz_module_view_get(self):
response = self.c.get('/quiz/api/question_module/1/', follow=True)
self.assertEqual(response.status_code, 200)
module = json.loads(response.content)
self.assertEqual(module['quiz'], 1)
self.assertEqual(module['title'], 'module 1')
self.assertEqual(module['questions'], 3)
response = self.c.get('/quiz/api/question_module/1000/', follow=True)
self.assertEqual(response.status_code, 404)
response = self.c.get('/quiz/api/question_module/1/get_questions_admin/')
self.assertEqual(response.status_code, 200)
questions = json.loads(response.content)
self.assertEqual(len(questions), 3)
response = self.c.get('/quiz/api/question_module/1/get_questions/')
self.assertEqual(response.status_code, 200)
questions = json.loads(response.content)
self.assertEqual(len(questions), 3)
# /quiz/api/question_module/1/get_question_and_history_data/
def test_quiz_module_view_post(self):
response = self.c.post('/quiz/api/quiz/1/add_question_module/', {'quiz':1,'title': 'module'})
self.assertEqual(response.status_code, 200)
response = self.c.post('/quiz/api/question_module/2/', {'quiz':'1', 'title':'module mod', '_method':'PUT'})
self.assertEqual(response.status_code, 200)
module = json.loads(response.content)
self.assertEqual(module['quiz'], 1)
self.assertEqual(module['title'], 'module mod')
self.assertEqual(module['questions'], 0)
response = self.c.post('/quiz/api/question_module/2/', {'_method':'DELETE'})
self.assertEqual(response.status_code, 204)
with self.assertRaises(QuestionModule.DoesNotExist):
QuestionModule.objects.get(pk=2)
question = {'quiz':1, 'question_module':1, 'description':'q1', 'marks':3, 'attempts':2, 'answer':'["a1", "a2", "a3"]', 'type':'D', 'granularity':' '}
response = self.c.post('/quiz/api/question_module/1/add_fixed_answer_question/', question)
self.assertEqual(response.status_code, 200)
response = self.c.post('/quiz/api/question_module/1/add_fixed_answer_question/', {})
self.assertEqual(response.status_code, 400)
question = {'quiz':1, 'question_module':1, 'description':'q1', 'marks':3, 'attempts':2, 'options':'["a1","a2","a3"]', 'answer':0, 'type':'D', 'granularity':' '}
response = self.c.post('/quiz/api/question_module/1/add_single_choice_question/', question)
self.assertEqual(response.status_code, 200)
response = self.c.post('/quiz/api/question_module/1/add_single_choice_question/', {})
self.assertEqual(response.status_code, 400)
#TODO should give error if form of answer is wrong it accepts 0 as answer
question = {'quiz':1, 'question_module':1, 'description':'q1', 'marks':3, 'attempts':2, 'options':'["a1","a2","a3"]', 'answer':'[true, false, true]', 'type':'D', 'granularity':' '}
response = self.c.post('/quiz/api/question_module/1/add_multiple_choice_question/', question)
self.assertEqual(response.status_code, 200)
response = self.c.post('/quiz/api/question_module/1/add_multiple_choice_question/', {})
self.assertEqual(response.status_code, 400)
class QuizViewStudentTest(TestCase):
def setUp(self):
#student user
user = User(username='student', is_active=True, email="<EMAIL>")
user.set_password('<PASSWORD>')
user.save()
self.student = CustomUser.objects.get(user=user)
self.student.is_instructor = False
self.student.is_content_developer = False
self.student.default_mode = 'S'
self.student.save()
quiz1 = Quiz(title='quiz 1')
quiz1.save()
module1 = QuestionModule(quiz=quiz1, title='module 1')
module1.save()
# question1 = DescriptiveQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,answer='this is the answer',grader_type='M')
# question1.save()
# submission = Submission(question=question1,student=user, answer='this is the answer', grader_type='M')
# submission.save()
question1 = SingleChoiceQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,options='["a1","a2","a3"]',answer=0)
question1.save()
submission = Submission(question=question1,student=user, answer='1')
submission.save()
submission = Submission(question=question1,student=user, answer='0')
submission.save()
question1 = MultipleChoiceQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,options='["a1","a2","a3"]', answer='[true, false, true]')
question1.save()
submission = Submission(question=question1,student=user, answer='[true, false, false]')
submission.save()
submission = Submission(question=question1,student=user, answer='[true, false, true]')
submission.save()
question1 = FixedAnswerQuestion(quiz=quiz1, question_module=module1, description='q1',marks=3,attempts=2,answer='["a1", "a2", "a3"]')
question1.save()
submission = Submission(question=question1,student=user, answer='a4')
submission.save()
submission = Submission(question=question1,student=user, answer='a2')
submission.save()
self.c = Client()
self.c.post('/accounts/login/', {'username':'student','password':'<PASSWORD>'}, follow=True)
def test_quiz_view_get(self):
response = self.c.get('/quiz/api/quiz/', follow=True)
self.assertEqual(response.status_code, 200)
quiz_list = json.loads(response.content)
self.assertEqual(len(quiz_list), 1)
response = self.c.get('/quiz/api/quiz/1/', follow=True)
self.assertEqual(response.status_code, 200)
quiz = json.loads(response.content)
self.assertEqual(quiz['id'], 1)
self.assertEqual(quiz['title'], 'quiz 1')
self.assertEqual(quiz['question_modules'], 1)
self.assertEqual(quiz['questions'], 3)
self.assertEqual(quiz['marks'], 9)
response = self.c.get('/quiz/api/quiz/1000/', follow=True)
self.assertEqual(response.status_code, 404)
response = self.c.get('/quiz/api/quiz/1/get_question_modules/',follow=True)
self.assertEqual(response.status_code, 200)
module_list = json.loads(response.content)
self.assertEqual(len(module_list), 1)
response = self.c.get('/quiz/api/quiz/1/get_questions_manual_grade/',follow=True)
self.assertEqual(response.status_code, 200)
question_list = json.loads(response.content)
self.assertEqual(len(question_list), 0)
def test_quiz_view_post(self):
response = self.c.post('/quiz/api/quiz/', {'title':'Quiz 2'})
self.assertEqual(response.status_code, 403)
response = self.c.post('/quiz/api/quiz/1/', {'title':'Quiz 1 mod', '_method':'PUT'})
self.assertEqual(response.status_code, 403)
response = self.c.post('/quiz/api/quiz/2/', {'_method':'DELETE'})
self.assertEqual(response.status_code, 403)
with self.assertRaises(Quiz.DoesNotExist):
Quiz.objects.get(pk=2)
response = self.c.post('/quiz/api/quiz/1/add_question_module/', {'quiz':1,'title': 'module'})
self.assertEqual(response.status_code, 403)
response = self.c.post('/quiz/api/quiz/1/add_question_module/', {'title': 'module'})
self.assertEqual(response.status_code, 403)
def test_quiz_module_view_get(self):
response = self.c.get('/quiz/api/question_module/1/', follow=True)
self.assertEqual(response.status_code, 200)
module = json.loads(response.content)
self.assertEqual(module['quiz'], 1)
self.assertEqual(module['title'], 'module 1')
self.assertEqual(module['questions'], 3)
response = self.c.get('/quiz/api/question_module/1000/', follow=True)
self.assertEqual(response.status_code, 404)
response = self.c.get('/quiz/api/question_module/1/get_questions_admin/')
self.assertEqual(response.status_code, 200)
questions = json.loads(response.content)
self.assertEqual(len(questions), 3)
response = self.c.get('/quiz/api/question_module/1/get_questions/')
self.assertEqual(response.status_code, 200)
questions = json.loads(response.content)
self.assertEqual(len(questions), 3)
# /quiz/api/question_module/1/get_question_and_history_data/
def test_quiz_module_view_post(self):
response = self.c.post('/quiz/api/quiz/1/add_question_module/', {'quiz':1,'title': 'module'})
self.assertEqual(response.status_code, 403)
response = self.c.post('/quiz/api/question_module/1/', {'quiz':'1', 'title':'module mod', '_method':'PUT'})
self.assertEqual(response.status_code, 403)
response = self.c.post('/quiz/api/question_module/1/', {'_method':'DELETE'})
self.assertEqual(response.status_code, 403)
with self.assertRaises(QuestionModule.DoesNotExist):
QuestionModule.objects.get(pk=2)
question = {'quiz':1, 'question_module':1, 'description':'q1', 'marks':3, 'attempts':2, 'answer':'["a1", "a2", "a3"]', 'type':'D', 'granularity':' '}
response = self.c.post('/quiz/api/question_module/1/add_fixed_answer_question/', question)
self.assertEqual(response.status_code, 403)
response = self.c.post('/quiz/api/question_module/1/add_fixed_answer_question/', {})
self.assertEqual(response.status_code, 403)
question = {'quiz':1, 'question_module':1, 'description':'q1', 'marks':3, 'attempts':2, 'options':'["a1","a2","a3"]', 'answer':0, 'type':'D', 'granularity':' '}
response = self.c.post('/quiz/api/question_module/1/add_single_choice_question/', question)
self.assertEqual(response.status_code, 403)
response = self.c.post('/quiz/api/question_module/1/add_single_choice_question/', {})
self.assertEqual(response.status_code, 403)
question = {'quiz':1, 'question_module':1, 'description':'q1', 'marks':3, 'attempts':2, 'options':'["a1","a2","a3"]', 'answer':'[true, false, true]', 'type':'D', 'granularity':' '}
response = self.c.post('/quiz/api/question_module/1/add_multiple_choice_question/', question)
self.assertEqual(response.status_code, 403)
response = self.c.post('/quiz/api/question_module/1/add_multiple_choice_question/', {})
self.assertEqual(response.status_code, 403)
<file_sep>/registration/__init__.py
"""
init file. Not being used currently
"""
from django.contrib.auth.models import User
User._meta.get_field_by_name('email')[0]._unique = True
<file_sep>/quiz/static/quiz/js/quiz_admin.jsx
/** @jsx React.DOM */
// TODO: Disable buttons when ajax request is sent
// Enable back when request completes
/*
* |--------------------------------------|
* | QuestionModuleEditAdmin: |
* | |-----------------------------| |
* | | QuestionCreate | |
* | | QuestionEditRow | |
* | |-----------------------------| |
* | |
* | QuizEditAdmin: |
* | |-----------------------------| |
* | | QuestionModuleCreate | |
* | | QuestionModuleEditRow | |
* | |-----------------------------| |
* | |
* | QuizAdmin: |
* | |-----------------------------| |
* | | QuizCreate | |
* | | QuizEditRow | |
* | |-----------------------------| |
* |--------------------------------------|
*/
var QuizAdminId = 'quiz-admin';
var QuizEditAdminId = 'quiz-edit-admin';
var QuestionModuleEditId = 'question-module-edit-admin';
var QUESTION_TYPES = {
SINGLE_CHOICE_QUESTION: 'S',
MULTIPLE_CHOICE_QUESTION: 'M',
FIXED_ANSWER_QUESTION: 'F',
DESCRIPTIVE_ANSWER_QUESTION: 'D',
PROGRAMMING_QUESTION: 'P'
};
function add_error_to_element(element, errors) {
element.attr('title', 'This field is required.');
element.tooltip('show');
element.focus(function() {
element.tooltip('destroy');
});
element.parent().addClass("has-warning");
}
function remove_error_from_element(element) {
element.parent().removeClass("has-warning");
}
function close_question_list() {
$("#" + QuestionModuleEditId).hide().fadeOut(function() {
$(this).html("");
});
}
function close_question_module_list(QuizEditAdminId) {
$("#" + QuizEditAdminId).hide().fadeOut(function() {
$(this).html("");
});
}
/* Option Plugin Code Starts here - DO NOT MODIFY */
var ChoiceBox = React.createClass({
getDefaultProps: function() {
return {
checked: false,
text: '',
changeCallback: function(){},
closeCallback: function(){
$(this.getDOMNode()).hide();
}.bind(this)
}
},
getInitialState: function() {
return {
checked: this.props.checked,
text: this.props.text
};
},
onCheckChange: function(event) {
this.setState({checked: event.target.checked});
},
onTextChange: function(event) {
this.setState({text: event.target.value});
},
componentDidUpdate: function() {
this.props.changeCallback(this.state);
},
render: function() {
return(
<li>
<div>
<div class="input-group">
<span class="input-group-addon">
<input type={this.props.type}
name={this.props.name}
ref="select"
checked={this.state.checked}
onChange={this.onCheckChange}/>
</span>
<WmdTextarea class="form-control option-list-text"
placeholder="Type Something Here.."
value={this.state.text}
ref="text"
onChange={this.onTextChange}>
</WmdTextarea>
<span class="input-group-btn">
<button class="btn btn-default"
type="button"
onClick={this.props.closeCallback}>
<span class="glyphicon glyphicon-remove"></span>
</button>
</span>
</div>
</div>
</li>
);
}
});
var OptionsBox = React.createClass({
getData: function() {
optionNodes = $(this.refs.optionList.getDOMNode()).children("li").filter(":visible");
type = this.props.type;
data = []
//data['multiple'] = type == "checkbox";
data['options'] = JSON.stringify($(optionNodes).map(function(i,node) {
return $($(node).find("textarea")[0]).val();
}).get());
optionList = $(optionNodes).map(function(i,node) {
query = "input[type=" + type + "]";
elmt = $(node).find(query)[0];
return elmt.checked;
}).get();
if (type == 'checkbox'){
data['selected'] = JSON.stringify(optionList);
data['answer'] = JSON.stringify(optionList);
}
else {
for (i = 0; i < optionList.length; i++){
if (optionList[i]) data['answer'] = i;
}
}
return data;
},
addChoice: function(checked, text) {
state = this.state;
state.choiceBoxes.push(<ChoiceBox type={this.props.type} name={this.props.name}
id={state.lastId.toString()} checked={checked} text={text} changeCallback={this.onDataChange} />);
state.lastId++;
this.setState(state, this.onDataChange);
},
getInitialState: function() {
return {
choiceBoxes: [],
lastId: 0
};
},
getDefaultProps: function() {
return {
changeCallback: $.noop
};
},
onDataChange: function() {
this.props.changeCallback(this.getData());
},
componentDidMount: function() {
if (this.props.data && this.props.data['options']){
data = this.props.data;
options = jQuery.parseJSON(data['options']);
if (data.type=='S') {
for (var i = 0; i < options.length; i++){
this.addChoice(i==data.answer, options[i]);
}
} else {
selected = jQuery.parseJSON(data['selected']);
for (var i = 0; i < options.length; i++){
this.addChoice(selected[i], options[i]);
}
}
}
else this.addChoice(true,'');
$(this.refs.optionList.getDOMNode()).sortable({
axis: "y",
update: this.onDataChange
});
},
render: function() {
return (
<div class="form-group">
<label class="control-label col-md-2">Options</label>
<div class="col-md-9">
<ul ref="optionList" class="list-unstyled option-module-list">
{this.state.choiceBoxes}
</ul>
<button type="button" class="btn btn-default" onClick={this.addChoice.bind(this,false,'')}>
Add Option
</button>
</div>
</div>
);
},
componentWillReceiveProps: function(props) {
for (var i = 0; i < this.state.choiceBoxes.length; i++){
this.state.choiceBoxes[i].props.type = props.type;
}
}
});
var OptionsBoxWithType = React.createClass({
getInitialState: function() {
return {
type: "radio"
};
},
getData: function() {
return this.refs.box.getData();
},
changeType: function() {
state = this.state;
if (this.refs.type.getDOMNode().checked) state.type = "checkbox";
else state.type = "radio";
this.setState(state);
},
render: function() {
return (
<div>
<div class="checkbox">
<label>
<input type="checkbox" ref="type" onChange={this.changeType} />
Allow selection of multiple options
</label>
</div>
<OptionsBox type={this.state.type} name={this.props.name} ref="box" data={this.props.data}/>
</div>
);
}
});
/* Options Plugin Code Ends Hre */
var confirmDeleteMixin = {
getInitialState: function() {
return {
delete_stage: false
};
},
resetDelete: function() {
state = this.state;
state.delete_stage = false;
this.setState(state);
},
getDeleteBar: function() {
delete_bar =
<button type="submit" class="btn btn-danger btn-sm" onClick={this.deleteObject}>
Delete
</button>;
if (this.state.delete_stage) {
delete_bar =
<div>
<button type="submit" class="btn btn-warning btn-sm quiz-right-margin" onClick={this.resetDelete}>No</button>
<button type="submit" class="btn btn-danger btn-sm" onClick={this.deleteObject}>Yes</button>
</div>;
}
return delete_bar;
},
checkDeleteStage: function() {
if (!this.state.delete_stage) {
state = this.state;
state.delete_stage = true;
this.setState(state);
return true;
}
return false;
}
};
var ListCreator = React.createClass({
componentWillReceiveProps: function(nextProps) {
this.setState({list: nextProps.defaultValue});
},
getInitialState: function() {
list = [];
if (this.props.defaultValue != undefined) {
list = this.props.defaultValue;
}
max = this.maxInRow;
if (this.props.maxInRow != undefined) {
max = this.props.maxInRow;
}
return {
list: list,
maxInRow: max
};
},
onChange: function() {
if (this.props.onChange != undefined) {
this.props.onChange(this.state.list);
}
},
addItem: function() {
list = this.state.list;
item_node = this.refs.item.getDOMNode();
item = item_node.value.trim();
this.refs.item.getDOMNode().value = '';
item_node.focus();
check = this.props.check;
if (check == undefined) {
check = function(item) {return !isNaN(item);};
}
if (item != '' && check(item)) {
list.push(item);
}
state = this.state;
state.list = list;
this.setState(state);
this.onChange();
},
removeItem: function() {
this.refs.item.getDOMNode().focus();
list = this.state.list;
if (list.length != 0) {
list.pop();
}
state = this.state;
state.list = list;
this.setState(state);
this.onChange();
},
maxInRow: 6,
render: function() {
all_values = this.state.list.map(function(l) {
return <span class="input-group-addon">{l}</span>;
});
values = new Array();
rows = Math.floor(all_values.length / this.state.maxInRow);
extra = all_values.length % this.state.maxInRow;
counter = 0;
for (var i = 0; i < rows; i++) {
this_row = new Array();
for (var j = 0; j < this.state.maxInRow; j++) {
this_row.push(all_values[counter]);
counter++;
}
values.push(this_row);
}
more_values = new Array();
for (var i = 0; i < extra; i++) {
more_values.push(all_values[counter]);
counter++;
}
div_values = values.map(function(v) {
return(
<div class="input-group">
{v}
</div>);
});
id = '';
if (this.props.id != undefined) {
id = this.props.id;
}
remove_button = <div></div>;
if (this.state.list.length != 0) {
remove_button =
<span class="input-group-btn">
<button class="btn btn-default" type="button" onClick={this.removeItem}>
<span class="glyphicon glyphicon-remove"></span>
</button>
</span>;
}
return (
<div>
{div_values}
<div class="input-group">
{remove_button}
{more_values}
<input type="text" class="form-control" ref="item" id={id} />
<span class="input-group-btn">
<button class="btn btn-default" type="button" onClick={this.addItem}>
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
);
}
});
var ChoiceQuestionCreate = OptionsBox;
var FixedAnswerQuestionCreate = React.createClass({
setAnswer: function(answer) {
this.props.onChange({'answer': JSON.stringify(answer)});
},
getInitialState: function() {
answer = [];
if (this.props.defaults != undefined) {
if (this.props.defaults.answer != undefined) {
answer = [].concat(this.props.defaults.answer);
}
}
return {answer: answer};
},
check: function(text) {
return true;
},
render: function() {
// Important to call setAnswer here once, so that parent gets correct
// default value of answer
this.setAnswer(this.state.answer);
id = this.props.answerId;
return (
<div class="form-group">
<label class="control-label col-md-2">Correct Answer</label>
<div class="col-md-9">
<ListCreator
id={id}
check={this.check}
onChange={this.setAnswer}
defaultValue={this.state.answer} />
</div>
</div>
);
}
});
var QuestionCreate = React.createClass({
// CAUTION: This class modifies this.state directly at some places
// TODO: FETCH answers
// mixins: [ScrollToElementMixin],
base_url: '/quiz/api/',
answer_box_id: 'answer_box',
// The name createQuestion is slightly misleading. It is used for both create and edit
createQuestion: function() {
if (this.state['answer'] == undefined || this.state['answer'].length == 0) {
add_error_to_element($("#" + this.answer_box_id), 'This field is required.');
return;
}
if (this.state['answer'] == '[]') {
if (! confirm("Continue without any answer ?")) {
return;
}
}
var url_map ={
'F': "fixed_answer_question",
'S': "single_choice_question",
'M': "multiple_choice_question",
'D': "descriptive_question"
};
var url = '';
var method = '';
var type = this.refs.type.getDOMNode().value;
if (this.props.edit) {
url = this.base_url + "question_module/" + this.props.question_module.id + '/edit_' +
url_map[type] +'/?question=' + this.props.defaults.id + '&format=json';
}
else{
url = this.base_url + "question_module/" + this.props.question_module.id + '/add_' +
url_map[type] +'/?format=json';
}
method = 'POST';
data = {};
for (var i = 0; i < this.validationFields.length; i++) {
if (this.refs[this.validationFields[i]] != undefined) {
data[this.validationFields[i]] = this.refs[this.validationFields[i]].getDOMNode().value.trim();
}
}
data["granularity"] = this.state.defaults.granularity.toString();
data["granularity_hint"] = this.state.defaults.granularity_hint.toString();
if (data["granularity"] == "") {
data["granularity"] = "undefined";
}
if (data["granularity_hint"] == "") {
data["granularity_hint"] = "undefined";
}
if (this.state.answer_props != undefined) {
for (var attrname in this.state.answer_props) {
data[attrname] = this.state[attrname];
}
}
request = ajax_json_request(url, method, data);
request.done(function(response) {
response = jQuery.parseJSON(response);
data = response;
data['answer_fields'] = {};
for (var attrname in this.state.answer_props) {
data.answer_fields[attrname] = this.state[attrname];
}
data['prev_id'] = -1;
if (this.props.defaults) {
data['prev_id'] = this.props.defaults.id;
}
this.props.callback(data);
}.bind(this));
request.complete(function(response) {
if (response.status == 400) {
// BAD REQUEST - Data Validation failed
response = jQuery.parseJSON(response.responseText);
this.validation(response);
}
else {
this.removeValidation();
}
}.bind(this));
return false;
},
changeType: function() {
type = this.refs.type.getDOMNode().value;
state = this.state;
state.type = type;
this.setState(state);
},
setAnswer: function(obj) {
state = this.state;
state["answer_props"] = obj;
for (var attrname in obj) {
state[attrname] = obj[attrname];
}
// WARNING: modifying this.state directly here
this.state = state;
},
getInitialState: function() {
state = {
description: '',
answer_description: '',
granularity: '',
granularity_hint: '',
type: QUESTION_TYPES.FIXED_ANSWER_QUESTION,
marks: 0,
grader_type: 'D',
hint: '',
attempts: 1,
answer_fields: {}
}
main_state = {'answer_props': {}};
main_state['type'] = state.type;
if (this.props.defaults != undefined) {
// There may be a better way to do this
for (var i = 0; i < this.validationFields.length; i++) {
if (this.props.defaults[this.validationFields[i]] != undefined) {
state[this.validationFields[i]] = this.props.defaults[this.validationFields[i]];
}
}
if (this.props.defaults.answer_fields != undefined) {
state['answer_fields'] = this.props.defaults.answer_fields;
for (var attr in this.props.defaults.answer_fields) {
main_state[attr] = this.props.defaults.answer_fields[attr];
main_state.answer_props[attr] = this.props.defaults.answer_fields[attr];
}
}
}
if (this.props.defaults && this.props.defaults.type){
main_state['type'] = state['type'] = this.props.defaults.type;
}
if (state.granularity == '' || state.granularity == "0,0") {
state.granularity = [];
}
else {
state.granularity = state.granularity.split(",");
}
if (state.granularity_hint == '' || state.granularity_hint == "0,0") {
state.granularity_hint = [];
}
else {
state.granularity_hint = state.granularity_hint.split(",");
}
main_state['defaults'] = state;
return main_state;
},
onGranularityChange: function(list) {
// WARNING: modifying this.state directly here
this.state.defaults.granularity = list;
},
onHintGranularityChange: function(list) {
// WARNING: modifying this.state directly here
this.state.defaults.granularity_hint = list;
},
onMarksChange: function() {
this.onGranularityChange([]);
this.onHintGranularityChange([]);
this.setState(this.state);
},
validationFields: new Array('description', 'answer_description', 'hint', 'granularity',
'granularity_hint', 'marks', 'grader_type', 'type', 'attempts'),
removeValidation: function() {
// this may not be needed because after creation, the parent of QuestionCreate should
// be re-rendered and hence this module
if (this.refs == undefined) {
return;
}
for (var i = 0; i < this.validationFields.length; i++) {
if (this.refs[this.validationFields[i]] != undefined) {
input = $(this.refs[this.validationFields[i]].getDOMNode());
remove_error_from_element(input);
}
}
},
validation: function(response) {
for (var i = 0; i < this.validationFields.length; i++) {
if (response[this.validationFields[i]] != undefined) {
input = $(this.refs[this.validationFields[i]].getDOMNode());
add_error_to_element(input, response[this.validationFields[i]]);
}
}
},
checkGranularity: function(text) {
return !isNaN(text);
},
componentDidMount: function() {
selected = $(this.refs.type.getDOMNode()).children("option[value="+this.state.type+"]")[0]
$(selected).attr("selected","selected");
this.changeType();
/*$('html,body').animate({
scrollTop: $(this.getDOMNode()).offset().top - 100
}, 1000).bind(this);*/
},
render: function() {
answer_box = <div></div>;
if (this.state.type == QUESTION_TYPES.FIXED_ANSWER_QUESTION) {
answer_box = <FixedAnswerQuestionCreate defaults={this.state.defaults.answer_fields}
onChange={this.setAnswer} answerId={this.answer_box_id} />
}
else if (this.state.type == QUESTION_TYPES.SINGLE_CHOICE_QUESTION ||
this.state.type == QUESTION_TYPES.MULTIPLE_CHOICE_QUESTION) {
answer_box = <ChoiceQuestionCreate data={this.state.defaults.answer_fields}
name={this.answer_box_id}
type={this.state.type== QUESTION_TYPES.SINGLE_CHOICE_QUESTION ? "radio" : "checkbox"}
changeCallback={this.setAnswer} />
}
if (this.state.defaults.type == QUESTION_TYPES.FIXED_ANSWER_QUESTION) {
select_type = <select class="form-control" ref="type" onChange={this.changeType} >
<option value={QUESTION_TYPES.FIXED_ANSWER_QUESTION} selected="selected">
Fixed Answer Question</option>
<option value={QUESTION_TYPES.SINGLE_CHOICE_QUESTION}>Single Choice Question</option>
<option value={QUESTION_TYPES.MULTIPLE_CHOICE_QUESTION}>Multiple Choice Question</option>
</select>
} else if (this.state.defaults.type == QUESTION_TYPES.SINGLE_CHOICE_QUESTION) {
select_type = <select class="form-control" ref="type" onChange={this.changeType} >
<option value={QUESTION_TYPES.FIXED_ANSWER_QUESTION}> Fixed Answer Question</option>
<option value={QUESTION_TYPES.SINGLE_CHOICE_QUESTION} selected="selected">
Single Choice Question</option>
<option value={QUESTION_TYPES.MULTIPLE_CHOICE_QUESTION}>Multiple Choice Question</option>
</select>
} else {
select_type = <select class="form-control" ref="type" onChange={this.changeType} >
<option value={QUESTION_TYPES.FIXED_ANSWER_QUESTION}> Fixed Answer Question</option>
<option value={QUESTION_TYPES.SINGLE_CHOICE_QUESTION}> Single Choice Question</option>
<option value={QUESTION_TYPES.MULTIPLE_CHOICE_QUESTION} selected="selected">
Multiple Choice Question</option>
</select>
}
return (
<form role="form" class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2">Description</label>
<div class="col-md-9">
<WmdTextarea ref="description" placeholder="Description"
defaultValue={this.state.defaults.description} rows="2" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Marks</label>
<div class="col-md-4">
<input type="number" class="form-control" ref="marks"
placeholder="Maximum marks"
defaultValue={""+this.state.defaults.marks}
onChange={this.onMarksChange}/>
</div>
<label class="control-label col-md-1">Attempts</label>
<div class="col-md-4">
<input type="number" class="form-control" ref="attempts"
placeholder="Maximum attempts"
defaultValue={this.state.defaults.attempts} />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Type</label>
<div class="col-md-4">
{select_type}
</div>
</div>
{answer_box}
<div class="form-group">
<label class="control-label col-md-2">Hint</label>
<div class="col-md-9">
<WmdTextarea ref="hint" placeholder="Hint"
defaultValue={this.state.defaults.hint} rows="2"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Answer Description</label>
<div class="col-md-9">
<WmdTextarea ref="answer_description"
placeholder="Answer Description" rows="2"
defaultValue={this.state.defaults.answer_description} />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Granularity</label>
<div class="col-md-4">
<ListCreator check={this.checkGranularity}
onChange={this.onGranularityChange}
defaultValue={this.state.defaults.granularity} />
<span class="help-block">Leave blank for default value</span>
</div>
<label class="control-label col-md-1">With hint</label>
<div class="col-md-4">
<ListCreator check={this.checkGranularity}
onChange={this.onHintGranularityChange}
defaultValue={this.state.defaults.granularity_hint} />
<span class="help-block">Leave blank for default value</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Grading Type</label>
<div class="col-md-4">
<select class="form-control" ref="grader_type"
defaultValue={this.state.defaults.grader_type}>
<option value='D'>Direct</option>
<option value='M'>Manual</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-2">
<button type="button" class="btn btn-primary"
onClick={this.createQuestion}>Save</button>
</div>
<div class="col-md-2 col-md-offset-3">
<button type="button" class="btn btn-danger"
onClick={this.props.closeCallback}>Close</button>
</div>
</div>
</form>
);
}
});
var QuestionEditRow = React.createClass({
mixins: [confirmDeleteMixin, MathJaxMixin, ],
base_url: '/quiz/api/',
editQuestion: function() {
this.props.editCallback(this.props.data);
return false;
},
deleteObject: function() {
if (this.checkDeleteStage()) return;
url = this.base_url + "question/" + this.props.data.id + "/?format=json";
request = ajax_json_request(url, "DELETE", {});
request.done(function(response) {
this.props.deleteCallback(this.props.data);
}.bind(this));
request.complete(function(response) {
this.resetDelete();
}.bind(this));
},
render: function() {
delete_bar = this.getDeleteBar();
var _description = converter.makeHtml(this.props.data.description);
return (
<tr id={"question_" + this.props.data.id} class={"questions"+this.props.question_module_id}>
<td>
<button type="button" class="btn btn-default btn-sm" onClick={this.editQuestion}>
Edit
</button>
</td>
<td>
<span dangerouslySetInnerHTML={{__html: _description}} />
</td>
<td>{this.props.data.marks}</td>
<td>{this.props.data.attempts}</td>
<td>
{delete_bar}
</td>
</tr>
);
}
});
var QuestionModuleEditAdmin = React.createClass({
mixins: [SortableMixin],
closePanel: function() {
close_question_list();
},
base_url: "/quiz/api/",
openQuestion: null,
componentDidMount: function() {
this.getQuestions();
$(this.getDOMNode()).hide().fadeIn();
$('html,body').animate({
scrollTop: $(this.getDOMNode()).offset().top - 100
}, 1000).bind(this);
$("#questionOrderSave"+this.props.quiz.id).hide();
},
componentDidUpdate: function() {
if(this.state.order)
{
$("#questionReorder"+this.props.question_module.id).hide();
$("#questionOrderSave"+this.props.question_module.id).show();
$(".questions"+this.props.question_module.id).addClass("sortable-items");
}
else {
$("#questionReorder"+this.props.question_module.id).show();
$("#questionOrderSave"+this.props.question_module.id).hide();
$(".questions"+this.props.question_module.id).removeClass("sortable-items");
}
if(!this.state.loaded){
this.getQuestions();
}
},
saveOrder: function(data) {
url = this.base_url + "question_module/" + this.props.question_module.id + "/reorder_questions/?format=json";
request = ajax_json_request(url, "PATCH", data);
request.done(function(response) {
display_global_message("Successfully reordered the questions", "success");
this.saveOrderSuccess("#questions"+this.props.question_module.id);
}.bind(this));
},
getInitialState: function() {
return {
loaded: false,
create: false,
edit: false,
title_edit: false,
question_module: this.props.question_module
};
},
editQuestion: function(data) {
this.openQuestion = data.id;
state = this.state;
state.create = false;
state.edit = true;
state.defaults = data;
this.setState(state);
window.scrollTo(0, document.getElementById(QuestionModuleEditId).offsetTop-75);
},
createQuestion: function(data) {
oldState = this.state;
if (this.state.edit) {
for (var i = 0; i < oldState.questions.length; i++) {
if (oldState.questions[i]['id'] == data['prev_id']) {
oldState.questions[i] = data;
break;
}
}
}
else if (this.state.create) { // Either one must be true
oldState.questions.push(data);
}
oldState.create = false;
oldState.edit = false;
oldState.loaded = false;
this.setState(oldState);
window.scrollTo(0, document.getElementById(QuestionModuleEditId).offsetTop-75);
},
deleteQuestion: function(data) {
questions = this.state.questions;
index = questions.indexOf(data);
if (index > -1) {
questions.splice(index, 1);
}
oldState = this.state;
oldState.loaded = false;
oldState.questions = questions;
if (this.openQuestion == data.id) {
oldState.create = false;
oldState.edit = false;
window.scrollTo(0, document.getElementById(QuestionModuleEditId).offsetTop-75);
}
this.setState(oldState);
},
getQuestions: function() {
url = this.base_url + "question_module/" + this.props.question_module.id + "/get_questions_admin/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.questions = response;
oldState.loaded = true;
this.setState(oldState);
//alert("return from getQuestions ajax");
}.bind(this));
request.fail(function(response) {
//alert("Get Questions failed");
});
//alert("return from getQuestions");
},
showQuestionCreate: function() {
oldState = this.state;
oldState.create = true;
this.setState(oldState);
},
closeCreate: function() {
oldState = this.state;
oldState.create = false;
oldState.edit = false;
// Change this to suit the application of this component
window.scrollTo(0, document.getElementById(QuestionModuleEditId).offsetTop-75);
this.setState(oldState);
},
editQuestionModule: function(data) {
state = this.state;
if ( state.question_module.title != data.title) {
display_global_message("Successfully saved", "success");
state.question_module = data;
state.title_edit = false;
this.setState(state);
this.props.refreshCallback();
} else {
state.title_edit = false;
this.setState(state);
}
},
showTitleEdit: function() {
state = this.state;
state.title_edit = true;
this.setState(state);
},
render: function() {
if (!this.state.loaded) {
return (
<div class="panel panel-default">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>
);
}
//alert("procesing question module");
question_create = <button type="button" class="btn btn-primary" onClick={this.showQuestionCreate}> Add new Question </button>;
if (this.state.create) {
question_create =
<QuestionCreate
callback={this.createQuestion}
question_module={this.state.question_module}
closeCallback={this.closeCreate} />;
}
else if (this.state.edit) {
question_create =
<QuestionCreate
key={this.state.question_module.id + "/" + this.state.defaults.id}
edit={true}
callback={this.createQuestion}
defaults={this.state.defaults}
question_module={this.props.question_module}
closeCallback={this.closeCreate} />;
}
//alert("Listing all questions");
question_edit = this.state.questions.map(function(q) {
return <QuestionEditRow editCallback={this.editQuestion} deleteCallback={this.deleteQuestion} data={q} question_module_id={this.props.question_module.id} />;
}.bind(this));
title_edit = '';
if (this.state.title_edit) {
title_edit =
<ul class="list-group">
<li class="list-group-item question-module-edit">
<QuestionModuleCreate data={this.state.question_module} callback={this.editQuestionModule} />
</li>
</ul>;
}
else {
title_edit =
<ul class="list-group">
<li class="list-group-item question-module-edit elements-control">
<button type="button" class="btn btn-default" onClick={this.showTitleEdit} >Edit Description</button>
<button id={"questionReorder"+this.props.question_module.id} onClick={this.handleSortClick.bind(this, "#questions"+this.props.question_module.id,"tr.questions"+this.props.question_module.id)} class="btn btn-default sort-btn">
<span class="glyphicon glyphicon-sort"></span>
Reorder Questions
</button>
<button id={"questionOrderSave"+this.props.question_module.id} onClick={this.handleSaveOrder.bind(this, "#questions"+this.props.question_module.id, 9)} class="btn btn-primary sort-btn">
<span class="glyphicon glyphicon-save"></span>
Save Current Order
</button>
</li>
</ul>;
}
//alert("rendering Question Module Edit");
return (
<div class="panel panel-default">
<div class="panel-heading">
<span class="quiz-text-mute quiz-right-margin">Editing</span>
<strong class="quiz-right-margin">
{this.props.quiz.title}
</strong>
<span class="glyphicon glyphicon-arrow-right quiz-right-margin"></span>
<strong>
Module ID {this.state.question_module.id}
</strong>
<span class="pull-right">
<button type="button" class="close" onClick={this.closePanel}>×</button>
</span>
</div>
<div class="panel-body" ref="create">
{question_create}
</div>
{title_edit}
<table class="table table-hover quiz-table" id={"questions"+this.props.question_module.id}>
<tbody>
<tr>
<th width="11%"></th>
<th>Description</th>
<th>Points</th>
<th>Attempts</th>
<th class="confirm-delete"></th>
</tr>
{question_edit}
</tbody>
</table>
</div>
);
}
});
var QuestionModuleCreate = React.createClass({
base_url: "/quiz/api/",
// always return false
createQuestionModule: function() {
url = this.base_url + "quiz/" + this.props.quiz_id + "/add_question_module/?format=json";
method = "POST";
data = {
quiz: this.props.quiz_id,
title: this.refs.title.getDOMNode().value.trim()
};
if (this.props.data != undefined) {
url = this.base_url + "question_module/" + this.props.data.id + "/?format=json";
method = "PATCH";
}
request = ajax_json_request(url, method, data);
request.done(function(response) {
response = jQuery.parseJSON(response);
data = response;
this.props.callback(data);
}.bind(this));
title_input = this.refs.title.getDOMNode();
request.complete(function(response) {
if (response.status == 400) {
// BAD REQUEST - Data Validation failed
response = jQuery.parseJSON(response.responseText);
if (response.title != undefined) {
// TODO: replace with foreach (this.refs)
//title_input = $(this.refs.title.getDOMNode());
add_error_to_element($(title_input), response.title);
}
}
else {
//title_input = $(this.refs.title.getDOMNode());
remove_error_from_element($(title_input));
}
if (this.props.data == undefined) {
//this.refs.title.getDOMNode().value = '';
title_input.value = ''
}
}.bind(this));
this.cancelCreate();
return false;
},
returnWithoutCreate: function() {
this.props.callback(this.props.data);
return false;
},
showCreate: function() {
$("#add-button-container").hide();
$("#title-container").show();
return false;
},
cancelCreate: function() {
$("#add-button-container").show();
$("#title-container").hide();
return false;
},
getInitialState: function() {
return {
errors: {
title: "",
description: ""
}
};
},
render: function() {
if (this.props.data != undefined) {
return (
<div id="title-container" class="panel panel-default">
<div class="panel-heading" data-toggle="collapse" data-parent="#title-container"
data-target="#module-title">
<span class="heading"> Question Module Description </span>
</div>
<div class="panel-body" id="module-title">
<div>
<div class="col-md-12 form-group">
<WmdTextarea ref="title" placeholder="Question Module Description"
defaultValue={this.props.data.title} />
</div>
</div>
<div>
<div class="col-md-3 col-md-offset-2">
<button onClick={this.createQuestionModule}
type="submit" class="btn btn-primary">Save</button>
</div>
<div class="col-md-3 col-md-offset-2">
<button onClick={this.returnWithoutCreate} class="btn btn-danger">
Cancel</button>
</div>
</div>
</div>
</div>
);
}
if (! this.props.published) {
publish_button = <button onClick={this.props.publishQuiz} class="btn btn-primary">
Publish
</button>
} else {
publish_button = <button onClick={this.props.publishQuiz} class="btn btn-danger">
Un-Publish
</button>
}
return (
<div>
<div class="row" id="add-button-container">
<div class=" elements-control col-md-offset-1">
{publish_button}
<button onClick={this.showCreate} class="btn btn-primary">
Add Question Module
</button>
<button id={"questionModuleReorder"+this.props.quiz_id} onClick={this.props.handleSortClick.bind(this, "#questionModules"+this.props.quiz_id,"tr.questionModules"+this.props.quiz_id)} class="btn btn-default sort-btn">
<span class="glyphicon glyphicon-sort"></span>
Reorder Question Modules
</button>
<button id={"questionModuleOrderSave"+this.props.quiz_id} onClick={this.props.handleSaveOrder.bind(this, "#questionModules"+this.props.quiz_id, 15)} class="btn btn-primary sort-btn">
<span class="glyphicon glyphicon-save"></span>
Save Current Order
</button>
</div>
</div>
<div id="title-container" class="panel panel-default" style={{'display': 'none'}}>
<div class="panel-heading" >
<span class="heading"> Question Module Description </span>
</div>
<div class="panel-body" id="module-title">
<div class="col-md-12 form-group">
<WmdTextarea ref="title" placeholder="Question Module Description" />
</div>
<div class="col-md-2 col-md-offset-3">
<button onClick={this.createQuestionModule}
type="submit" class="btn btn-primary">Save</button>
</div>
<div class="col-md-2 col-md-offset-2">
<button onClick={this.cancelCreate} class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</div>
);
}
});
var QuestionModuleEditRow = React.createClass({
mixins: [confirmDeleteMixin, MathJaxMixin],
base_url: "/quiz/api/",
editQuestionModule: function() {
this.props.editCallback(this.props.data);
return false;
},
deleteObject: function() {
if (this.checkDeleteStage()) return;
url = this.base_url + "question_module/" + this.props.data.id + "/?format=json";
request = ajax_json_request(url, "DELETE", {});
request.done(function(response) {
this.props.deleteCallback(this.props.data);
}.bind(this));
request.complete(function(response) {
this.resetDelete();
}.bind(this));
},
render: function() {
delete_bar = this.getDeleteBar();
var _title = converter.makeHtml(this.props.data.title);
return (
<tr id={"questionModule_" + this.props.data.id} class={"questionModules"+this.props.quiz_id}>
<td>
<button type="button" class="btn btn-default btn-sm" onClick={this.editQuestionModule}>
Edit
</button>
</td>
<td>{this.props.data.id}</td>
<td><span dangerouslySetInnerHTML={{__html: _title}} /></td>
<td>
{delete_bar}
</td>
</tr>
);
}
});
var QuizEditAdmin = React.createClass({
mixins: [SortableMixin],
// TODO: Use a mixin to implement functionality of QuizEditAdmin and QuizAdmin
// when the course module is completed and quizzes are fetched from the
// course instead of list(quiz)
closePanel: function() {
close_question_list();
close_question_module_list(QuizEditAdminId);
},
base_url: "/quiz/api/",
openQuestionModule: null,
getInitialState: function() {
this.getQuestionModules();
return {
loaded: false,
published: this.props.quiz.is_published
};
},
editQuestionModule: function(data) {
this.openQuestionModule = data.id;
$("#" + QuestionModuleEditId).html("");
React.renderComponent(
<QuestionModuleEditAdmin question_module={data} quiz={this.props.quiz}
refreshCallback={this.refresh}/>,
document.getElementById(QuestionModuleEditId)
);
$("#" + QuestionModuleEditId).hide().fadeIn();
},
createQuestionModule: function(data) {
oldState = this.state;
oldState.question_modules.push(data);
this.setState(oldState);
this.editQuestionModule(data);
},
deleteQuestionModule: function(data) {
if (this.openQuestionModule == data.id) {
close_question_list();
window.scrollTo(0, document.getElementById(QuizEditAdminId).offsetTop-75);
}
question_modules = this.state.question_modules;
index = question_modules.indexOf(data);
if (index > -1) {
question_modules.splice(index, 1);
}
oldState = this.state;
oldState.question_modules = question_modules;
this.setState(oldState);
},
getQuestionModules: function() {
url = this.base_url + "quiz/" + this.props.quiz.id + "/get_question_modules/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.question_modules = response;
oldState.loaded = true;
this.setState(oldState);
}.bind(this));
},
refresh: function() {
this.getQuestionModules();
},
componentDidMount: function() {
$('html,body').animate({
scrollTop: $(this.getDOMNode()).offset().top - 100
}, 1000).bind(this);
$("#questionModuleOrderSave"+this.props.quiz.id).hide();
},
componentDidUpdate: function() {
if(this.state.order)
{
$("#questionModuleReorder"+this.props.quiz.id).hide();
$("#questionModuleOrderSave"+this.props.quiz.id).show();
$(".questionModules"+this.props.quiz.id).addClass("sortable-items");
}
else {
$("#questionModuleReorder"+this.props.quiz.id).show();
$("#questionModuleOrderSave"+this.props.quiz.id).hide();
$(".questionModules"+this.props.quiz.id).removeClass("sortable-items");
}
},
saveOrder: function(data) {
url = this.base_url + "quiz/" + this.props.quiz.id + "/reorder_question_modules/?format=json";
request = ajax_json_request(url, "PATCH", data);
request.done(function(response) {
display_global_message("Successfully reordered the question modules", "success");
this.saveOrderSuccess("#questionModules"+this.props.quiz.id);
}.bind(this));
},
publishQuiz: function() {
url = this.base_url + "quiz/" + this.props.quiz.id + "/publish/?format=json";
request = ajax_json_request(url, "POST",{});
request.done(function(response) {
response = JSON.parse(response);
display_global_message(response.msg, "success");
this.setState({published: ! this.state.published});
}.bind(this));
return false;
},
render: function() {
if (!this.state.loaded) {
return (
<div class="panel panel-default">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>
);
}
qm_edit = this.state.question_modules.map(function(q) {
return <QuestionModuleEditRow editCallback={this.editQuestionModule} deleteCallback={this.deleteQuestionModule} data={q} quiz_id={this.props.quiz.id}/>;
}.bind(this));
return (
<div class="panel panel-default">
<div class="panel-heading">
<span class="quiz-text-mute quiz-right-margin">Editing</span>
<strong>{this.props.quiz.title}</strong>
<span class="pull-right">
<button type="button" class="close" onClick={this.closePanel}>×</button>
</span>
</div>
<div class="panel-body">
<QuestionModuleCreate quiz_id={this.props.quiz.id} published={this.state.published} publishQuiz={this.publishQuiz} callback={this.createQuestionModule} handleSortClick={this.handleSortClick} handleSaveOrder={this.handleSaveOrder}/>
</div>
<table class="table table-hover quiz-table" id={"questionModules"+this.props.quiz.id}>
<tbody>
<tr>
<th width="11%"></th>
<th>ID</th>
<th>Title</th>
<th class="confirm-delete">
<span class="pull-right">
<button class="btn btn-default" title="Refresh">
<span class="glyphicon glyphicon-refresh" onClick={this.refresh}></span>
</button>
</span>
</th>
</tr>
{qm_edit}
</tbody>
</table>
</div>
);
}
});
var QuizCreate = React.createClass({
base_url: "/quiz/api/",
// always return false
createQuiz: function() {
url = this.base_url + "quiz/?format=json";
data = {
title: this.refs.title.getDOMNode().value.trim()
};
this.refs.title.getDOMNode().value = '';
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
data = response;
this.props.callback(data);
}.bind(this));
request.complete(function(response) {
if (response.status == 400) {
// BAD REQUEST - Data Validation failed
response = jQuery.parseJSON(response.responseText);
if (response.title != undefined) {
// TODO: replace with foreach (this.refs)
title_input = $(this.refs.title.getDOMNode());
add_error_to_element(title_input, response.title);
}
}
else {
title_input = $(this.refs.title.getDOMNode());
remove_error_from_element(title_input);
}
}.bind(this));
return false;
},
getInitialState: function() {
return {
errors: {
title: ""
}
};
},
render: function() {
return (
<form role="form" class="form-inline" onSubmit={this.createQuiz}>
<div class="col-md-2 form-group">
<button type="submit" class="btn btn-primary">Add Quiz</button>
</div>
<div class="col-md-4 form-group">
<input type="text" class="form-control" ref="title" placeholder="Quiz Title" />
</div>
</form>
);
}
});
var QuizEditRow = React.createClass({
mixins: [confirmDeleteMixin],
base_url: "/quiz/api/",
editQuiz: function() {
this.props.editCallback(this.props.data);
return false;
},
deleteObject: function() {
if (this.checkDeleteStage()) return;
url = this.base_url + "quiz/" + this.props.data.id + "/?format=json";
request = ajax_json_request(url, "DELETE", {});
request.done(function(response) {
this.props.deleteCallback(this.props.data);
}.bind(this));
request.complete(function(response) {
this.resetDelete();
}.bind(this));
},
render: function() {
delete_bar = this.getDeleteBar();
return (
<tr>
<td>
<button type="submit" class="btn btn-default btn-sm" onClick={this.editQuiz}>
Edit
</button>
</td>
<td>{this.props.data.title}</td>
<td>{this.props.data.marks}</td>
<td>{this.props.data.question_modules}</td>
<td>{this.props.data.questions}</td>
<td>
{delete_bar}
</td>
</tr>
);
}
});
var QuizAdmin = React.createClass({
/*
* We do not update the question stats in this component using callbacks
* since we want to be able to include any component anywhere on the platform
* and doing so will make it more complex for reusablity. Hence we provide
* a REFRESH button
*/
base_url: "/quiz/api/",
openQuiz: null,
getInitialState: function() {
this.getQuizzes();
return {
loaded: false
};
},
editQuiz: function(data) {
this.openQuiz = data.id;
$("#" + QuizEditAdminId).html("");
React.renderComponent(
<QuizEditAdmin quiz={data} />,
document.getElementById(QuizEditAdminId)
);
$("#" + QuizEditAdminId).hide().fadeIn();
},
createQuiz: function(data) {
oldState = this.state;
oldState.quizzes.push(data);
this.setState(oldState);
this.editQuiz(data);
},
deleteQuiz: function(data) {
if (this.openQuiz == data.id) {
close_question_list();
close_question_module_list();
window.scrollTo(0, document.getElementById(QuizAdminId).offsetTop-75);
}
quizzes = this.state.quizzes;
index = quizzes.indexOf(data);
if (index > -1) {
quizzes.splice(index, 1);
}
oldState = this.state;
oldState.quizzes = quizzes;
this.setState(oldState);
},
getQuizzes: function() {
url = this.base_url + "quiz/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.quizzes = response;
oldState.loaded = true;
this.setState(oldState);
}.bind(this));
},
refresh: function() {
this.getQuizzes();
},
render: function() {
if (!this.state.loaded) {
return (
<div class="panel panel-default">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>
);
}
else {
quiz_edit = this.state.quizzes.map(function(q) {
return <QuizEditRow editCallback={this.editQuiz} deleteCallback={this.deleteQuiz} data={q} />;
}.bind(this));
return (
<div class="panel panel-default">
<div class="panel-heading">
Course Quizzes
<span class="pull-right quiz-text-mute">Admin Panel</span>
</div>
<div class="panel-body">
<QuizCreate callback={this.createQuiz} />
<span class="pull-right">
<button class="btn btn-default" title="Refresh">
<span class="glyphicon glyphicon-refresh" onClick={this.refresh}></span>
</button>
</span>
</div>
<table class="table table-hover quiz-table">
<tbody>
<tr>
<th></th>
<th>Title</th>
<th>Maximum points</th>
<th>Question modules</th>
<th>Questions</th>
<th class="confirm-delete"></th>
</tr>
{quiz_edit}
</tbody>
</table>
</div>
);
}
}
});
<file_sep>/registration/views.py
"""
Contains views for the Registration app
"""
import sys
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django import forms
from django.core.urlresolvers import reverse
from django.shortcuts import render, redirect
from django.http.response import Http404
from django.shortcuts import get_object_or_404
from elearning_academy import settings
from user_profile.models import CustomUser
from registration.models import ForgotPassword
from user_profile.models import Company
from user_profile.models import Work
from user_profile.models import UserProfile
from registration.models import Registration
from registration.serializers import UserSerializer
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
class UserViewSet(viewsets.ModelViewSet):
permission_classes = (AllowAny,)
model = User
serializer_class = UserSerializer
def retrieve(self, request, pk=None):
queryset = User.objects.all()
user = get_object_or_404(queryset, pk=pk)
serializer = UserSerializer(user)
return Response(serializer.data)
##NOTE: This is one big hack, meant to get it running for
## the teacher training workshop
## A more cleaner way would be to serialize every model
## and hence a lot TODO
def create(self, request):
data = request.DATA
username = data.get('username', None)
password = data.get('password', None)
email = data.get('email', None)
first_name = data.get('first_name', None)
last_name = data.get('last_name', None)
try:
user = User(username=username,
first_name=first_name,
last_name=last_name,
email=email,
is_active=True
)
user.set_password(password)
user.save()
except Exception as e:
message = {'error': str(e), 'error_message': "Error saving model"}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
try:
mobile = data.get('mobile', None)
city = data.get('city', None)
user_profile = UserProfile(user=user)
user_profile.mobile = mobile
user_profile.city = city
user_profile.save()
except Exception as e:
user.delete()
message = {'error': str(e), 'error_message': "Error saving model"}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
request.user = user
user_lst = User.objects.filter(username=username, email=email)
if len(user_lst) == 0:
error = True
error_message = "Please enter valid user details"
errors = {'error': error, 'error_message': error_message}
return Response(errors, status=status.HTTP_400_BAD_REQUEST)
else:
user = user_lst[0]
fp_object_lst = ForgotPassword.objects.filter(user=user)
if len(fp_object_lst) == 0:
fp_object = ForgotPassword(user=user)
fp_object.generate_key(request)
else:
fp_object = fp_object_lst[0]
fp_object.generate_key(request)
fp_object.save()
user_company = data.get('remoteid', None)
user_company_desc = data.get('remotecentrename', None)
if user_company is None:
user.delete()
error_message = "Remote ID Missing"
errors = {'error': True, 'error_message': error_message}
return Response(errors, status=status.HTTP_400_BAD_REQUEST)
company = Company.objects.filter(company=user_company)
if (len(company) == 0):
company = Company()
company.company = user_company
company.save()
user_company = company
else:
user_company = company[0]
user_work = Work(user=user)
user_work.company = user_company
user_work.company_description = user_company_desc
user_work.save()
return Response({"alldone": "All"}, status=status.HTTP_201_CREATED)
class RegistrationForm(forms.ModelForm):
""" Registration form """
# TODO: Find a better way to pass the class value, not from view
attrs = {'placeholder': 'Select a Username', 'class': 'form-control'}
username = forms.CharField(widget=forms.TextInput(attrs=attrs))
attrs['placeholder'] = 'First name'
first_name = forms.CharField(widget=forms.TextInput(attrs=attrs))
attrs['placeholder'] = 'Last name'
last_name = forms.CharField(widget=forms.TextInput(attrs=attrs))
attrs['placeholder'] = 'Email address'
email = forms.EmailField(widget=forms.TextInput(attrs=attrs))
attrs['placeholder'] = 'Choose a Password'
password = forms.CharField(widget=forms.PasswordInput(attrs=attrs))
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password')
class LoginForm(forms.Form):
""" Login form """
attrs = {'placeholder': 'Username', 'class': 'form-control'}
username = forms.CharField(widget=forms.TextInput(attrs=attrs))
attrs['placeholder'] = 'Password'
password = forms.CharField(widget=forms.PasswordInput(attrs=attrs))
class ForgotPasswordForm(forms.Form):
""" Forgot password form """
attrs = {'placeholder': 'Username', 'class': 'form-control'}
username = forms.CharField(widget=forms.TextInput(attrs=attrs))
attrs['placeholder'] = 'Email address'
email = forms.CharField(widget=forms.TextInput(attrs=attrs))
class ChangePasswordForm(forms.Form):
""" Change password form """
attrs = {'placeholder': 'Password', 'class': 'form-control'}
password = forms.CharField(widget=forms.PasswordInput(attrs=attrs))
attrs['placeholder'] = 'Re-enter password'
re_password = forms.CharField(widget=forms.PasswordInput(attrs=attrs))
def render_login_page(request, register_form=None, login_form=None,
parameters={}, next=None):
"""
Helper function to pass the login and registration forms and render
the main page
"""
if register_form is None:
register_form = RegistrationForm()
if login_form is None:
login_form = LoginForm()
form = {'reg_form': register_form, 'login_form': login_form}
parameters.update(form)
parameters['next'] = next
if 'login' not in parameters and 'signup' not in parameters:
parameters['login'] = 'active'
return render(request, 'registration/login.html', parameters)
def login_(request):
"""
If .../login/ is accessed by GET, show the login and registration form
If it is accessed by POST, try to login the user and redirect as necessary
"""
if request.user.is_authenticated():
return redirect(settings.LOGIN_REDIRECT_URL)
if request.method == 'GET':
if 'next' in request.GET.keys():
next = request.GET['next']
else:
next = None
return render_login_page(request, parameters={'login': 'active'},
next=next)
elif request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
error = False
username = form.cleaned_data["username"]
password = form.cleaned_data["<PASSWORD>"]
user = authenticate(username=username, password=<PASSWORD>)
if user is not None:
if user.is_active:
login(request, user)
customuser = CustomUser.objects.get(user=user)
request.session['mode'] = customuser.default_mode
print request.session['mode']
if 'next' in request.GET.keys():
next_url = request.GET["next"]
else:
next_url = None
if next_url:
return redirect(next_url)
else:
return redirect(settings.LOGIN_REDIRECT_URL)
else:
error = True
error_message = "Please activate your account first"
else:
error = True
error_message = "Invalid username / password"
parameters = {
'error': error,
'error_message': error_message,
'login': 'active'
}
else:
error = True
error_list = True
error_message = []
if request.POST["username"] == "":
error_message.append("Username is required")
if request.POST["password"] is None:
error_message.append("Password is required")
parameters = {
'error': error,
'error_list': error_list,
'error_message': error_message
}
return render_login_page(request, parameters=parameters)
else:
raise Http404
def signup(request):
"""
Register the user and log him in
"""
if request.user.is_authenticated():
return redirect(settings.LOGIN_REDIRECT_URL)
if request.method == 'GET':
return render_login_page(request, parameters={'signup': 'active'})
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = <PASSWORD>_data["<PASSWORD>"]
email = form.cleaned_data["email"]
user = User(username=username,
first_name=form.cleaned_data["first_name"],
last_name=form.cleaned_data["last_name"],
email=email,
is_active=False
)
user.set_password(<PASSWORD>)
user.save()
registration = Registration(user=user)
try:
registration.register(request)
registration.save()
except:
print sys.exc_info()[0]
user.delete()
error = True
error_message = ["Unable to Register user"]
errors = {
'error': error,
'error_list': True,
'error_message': error_message, 'signup': 'active'
}
return render_login_page(request, register_form=form,
parameters=errors)
info = {
'info': True,
'info_message': 'Successfully registered. \
Check %s and activate your account.' % (email)}
return render_login_page(request, parameters=info)
else:
error = True
error_message = []
for key, value in form.errors.iteritems():
error_message.append((', '.join(value)))
errors = {
'error': error,
'error_list': True,
'error_message': error_message, 'signup': 'active'}
return render_login_page(request, register_form=form,
parameters=errors)
else:
raise Http404
def logout_(request):
"""
Logout the current user
"""
logout(request)
return redirect(reverse('login'))
def activate(request, key):
"""
Fetch Registration record corresponding to activation key and activate \
user accordingly
"""
try:
user_record = Registration.objects.get(activation_key=key)
user_record.activate()
parameters = {
'info': True,
'info_message': "Successfully activated the account. \
Go ahead and log in now!"}
return render_login_page(request, parameters=parameters)
except:
parameters = {
'error': True,
'error_message': "Could not activate. Please re-check!"}
return render_login_page(request, parameters=parameters)
def render_forgotpassword_page(request, textdisplay=False,
formdisplay=False, parameters={}):
"""
Display the form to enter username and dob for the user to change or \
set new password
"""
if textdisplay:
parameters['textdisplay'] = True
parameters['formdisplay'] = False
elif formdisplay:
forgotpassword_form = ForgotPasswordForm()
form = {'forgotpassword_form': forgotpassword_form}
parameters.update(form)
parameters['formdisplay'] = True
parameters['textdisplay'] = False
return render(request, 'registration/forgotpassword.html', parameters)
def forgot_password(request):
"""
If request of type GET then render/ display the form for entering details \
to change password \
Else if the request of type POST then add an entry to forgot password \
table, send email to user's email id and display a message that email \
has been sent
"""
if request.method == 'GET':
return render_forgotpassword_page(request, formdisplay=True)
if request.method == 'POST':
form = ForgotPasswordForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
email = form.cleaned_data["email"]
user_lst = User.objects.filter(username=username, email=email)
if len(user_lst) == 0:
error = True
error_message = "Please enter valid user details"
errors = {'error': error, 'error_message': error_message}
return render_forgotpassword_page(
request, formdisplay=True, parameters=errors)
else:
user = user_lst[0]
fp_object_lst = ForgotPassword.objects.filter(user=user)
if len(fp_object_lst) == 0:
fp_object = ForgotPassword(user=user)
fp_object.generate_key(request)
else:
fp_object = fp_object_lst[0]
fp_object.generate_key(request)
fp_object.save()
display_msg = "An email has been sent to your email address"
parameters = {'message': display_msg}
return render_forgotpassword_page(
request, textdisplay=True, parameters=parameters)
else:
error = True
error_message = "Please fill all the details"
errors = {'error': error, 'error_message': error_message}
return render_forgotpassword_page(
request, formdisplay=True, parameters=errors)
else:
raise Http404
def render_updatepassword_page(request,
textdisplay=False,
formdisplay=False, parameters={}):
"""
Display the form to set a new password
"""
if textdisplay:
parameters['textdisplay'] = True
parameters['formdisplay'] = False
elif formdisplay:
changepassword_form = ChangePasswordForm()
form = {'changepassword_form': changepassword_form}
parameters.update(form)
parameters['formdisplay'] = True
parameters['textdisplay'] = False
return render(request, 'registration/changepassword.html', parameters)
def update_password(request, key):
"""
Take the url from mail sent to user and display a form if GET request and \
update the password if POST request
"""
if request.method == 'GET':
get_object_or_404(ForgotPassword, activation_key=key)
parameters = {'key': key}
return render_updatepassword_page(request, formdisplay=True,
parameters=parameters)
if request.method == 'POST':
form = ChangePasswordForm(request.POST)
if form.is_valid():
npassword = form.cleaned_data["password"]
cnpassword = form.cleaned_data["re_password"]
if npassword == cnpassword:
# change password in the database
fp_object = get_object_or_404(ForgotPassword,
activation_key=key)
fp_object.update_password(npassword)
display_message = """Password successfully updated.
Please login again."""
parameters = {
'info': True,
'info_message': display_message}
return render_login_page(request, parameters=parameters)
else:
error = True
error_message = "Please enter same the password in both fields"
errors = {'error': error,
'error_message': error_message,
'key': key}
return render_updatepassword_page(request, formdisplay=True,
parameters=errors)
else:
error = True
error_message = "Please fill all the details"
errors = {'error': error,
'error_message': error_message,
'key': key}
return render_updatepassword_page(request,
formdisplay=True,
parameters=errors)
else:
raise Http404
def register(request):
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
serialized.save()
return Response(serialized.data,
status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors,
status=status.HTTP_400_BAD_REQUEST)
<file_sep>/quiz_template/tests/test001.ini
[q1]
Q=This the common for all sub-parts. There should be aline break after this <lb>
TI=Title of the Question
[q1:p1]
Q=This is a question?
T=mcq
DE=Default Explanation of error
DC=Default Explanation when correct
C1=Choice1
E1=Explaination if Choice 1 is selected
C2=Choice2
E2=Explaination if Choice 2 is selected
C3=Choice3
E3=Explaination if Choice 3 is selected
C4=Choice4
E4=Explaination if Choice 4 is selected
A=C1,C2
M=10,3,4,2,0
H=Hint for the question
[q1:p2]
q=SubPart of Question1
T=mcq
C1
C2
A=C1
## This is a comment and wont be parsed
[q2]
Q=Question 2
T=des
M=Marks
A=Answer
[q3]
Q=Question
T=fix
A1=fixed-answer1
A2=fixed-answer2
M=Marks
H=Hint
[q4]
Q=Question
T=fix
A1=4-5
A2=10-15
M=Marks
H=Hint
<file_sep>/upload/models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import pre_delete
from assignments.models import Assignment
from upload import receivers
import os
# Function to retrieve the upload path for an upload instance given the filename.
# Takes as input the instance of upload and the filename of the file uploading to the server.
# If the instance has assignment then the path is "user/assignment-id/filename", else it is "user/filename".
def get_upload_path(instance, filename):
if instance.assignment:
return os.path.join(
instance.owner.username,
str(instance.assignment.id),
filename
)
else:
return os.path.join(
instance.owner.username,
filename
)
# Model to represent submissions by students.
# It stores the owner of the submission, the assignment to which the subsmission belongs, filepath to the solution uploaded, date of uploading,
# and a flag that denotes if the submission is stale w.r.t the assignment description.
class Upload(models.Model):
owner = models.ForeignKey(User)
assignment = models.ForeignKey(Assignment, blank=True, null=True)
filePath = models.FileField(upload_to=get_upload_path)
uploaded_on = models.DateTimeField(auto_now_add=True)
is_stale = models.BooleanField(default=False) # stale means it requires re-submission.
comments = models.TextField(null=True,blank=True)
pre_delete.connect(receivers.delete_files, sender=Upload, dispatch_uid="delete_submission")<file_sep>/courseware/permissions.py
"""
Handles permissions of the courseware API
Permission Classes:
IsInstructorOrReadOnly
- safe methods allowed for all users. other only for instructor
IsContentDeveloper
- Checks whether he is a ContentDeveloper
IsRegistered
- Checks whether the student is enrolled in the course
"""
from rest_framework import permissions
from courseware.models import CourseHistory
from user_profile.models import CustomUser
from courseware.models import Group, Concept
class IsAdminUserOrReadOnly(permissions.BasePermission):
"""
safe methods allowed for all the users. other only for admin
"""
def has_permission(self, request, view):
"""
Returns whether user has permission for this table or not
"""
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_superuser
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
return request.user.is_superuser
class IsContentDeveloperOrReadOnly(permissions.BasePermission):
"""
Check if the current mode of operation is valid
and in content developer mode
"""
def has_permission(self, request, view):
if request.method in permissions.SAFE_METHODS:
return True
else:
if request.user.is_authenticated():
customuser = CustomUser.objects.get(user=request.user)
if customuser.is_content_developer:
return True
return False
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
if request.user.is_authenticated():
# return true if he is the content developer for this textbook
try:
CourseHistory.objects.get(
course=obj,
user=request.user,
is_owner=True
)
except:
if request.method in permissions.SAFE_METHODS:
# return true if he is an instructor
customuser = CustomUser.objects.get(user=request.user)
if customuser.is_instructor:
return True
return False
return True
return False
class IsInstructorOrReadOnly(permissions.BasePermission):
"""
Allows complete permission to instructor and list access to others
"""
def has_permission(self, request, view):
if request.method in permissions.SAFE_METHODS:
return True
else:
if request.user.is_authenticated():
customuser = CustomUser.objects.get(user=request.user)
if customuser.is_instructor:
return True
return False
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
if request.user.is_authenticated():
if request.method in permissions.SAFE_METHODS:
# return true if registered
try:
CourseHistory.objects.get(
course=obj,
user=request.user,
active='A'
)
except:
return False
return True
# return true if he is the instructor for this offering
try:
CourseHistory.objects.get(
course=obj,
user=request.user,
is_owner=True
)
except:
return False
return True
return False
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Allows complete permission to the owner and list access to others
"""
def has_permission(self, request, view):
if request.method in permissions.SAFE_METHODS:
return True
else:
if request.user.is_authenticated():
customuser = CustomUser.objects.get(user=request.user)
if customuser.is_instructor or customuser.is_content_developer:
return True
return False
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
if request.user.is_authenticated():
if type(obj) == Group:
obj = obj.course
if type(obj) == Concept:
obj = obj.group.course
if request.method in permissions.SAFE_METHODS:
# return true if registered if it is an offering
if obj.type == 'O':
try:
CourseHistory.objects.get(
course=obj,
user=request.user,
active='A'
)
except:
return False
return True
elif obj.type == 'T':
customuser = CustomUser.objects.get(user=request.user)
if customuser.is_instructor:
return True
return False
# return true if he is the owner of the course
try:
CourseHistory.objects.get(
course=obj,
user=request.user,
is_owner=True
)
except:
return False
return True
return False
class IsOwner(permissions.BasePermission):
"""
Allows complete permission to the owner and none to others
"""
def has_permission(self, request, view):
if request.user.is_authenticated():
customuser = CustomUser.objects.get(user=request.user)
if customuser.is_instructor or customuser.is_content_developer:
return True
return False
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
if request.user.is_authenticated():
# return true if he is the owner of the course
try:
CourseHistory.objects.get(
course=obj,
user=request.user,
is_owner=True
)
except:
return False
return True
return False
class IsRegistered(permissions.BasePermission):
"""Checks whether a user is registered in the course"""
def has_permission(self, request, view):
"""
Checks whether person is the course instructor or is a superuser
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
try:
if request.user.is_authenticated():
CourseHistory.objects.get(
course=obj,
user=request.user,
active='A')
else:
return False
except:
return False
return True
<file_sep>/user_profile/views.py
"""
Contains views for the user profile app
"""
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.http.response import Http404
from django import forms
from django.forms.extras.widgets import SelectDateWidget
from django.shortcuts import render, get_object_or_404
from model_utils import Choices
from rest_framework import status
from user_profile.models import CustomUser
from user_profile.models import GetInstructorPrivileges
from user_profile.countries import COUNTRIES
from user_profile.models import UserProfile
from user_profile.models import DEGREE, Education
from user_profile.models import College, Major
from user_profile.models import Company, Work
from elearning_academy.settings import MEDIA_ROOT
from elearning_academy.permissions import is_valid_mode
from rest_framework.decorators import action
from rest_framework.response import Response
from datetime import date
import ast
import json
import os
from datetime import datetime
# Constants
GENDER_CHOICES = Choices(('M', 'Male'), ('F', 'Female'))
BIRTH_YEAR_CHOICES = tuple(str(n) for n in range(1960,
datetime.now().year - 15))
COLLEGE_YEAR_CHOICES = tuple(str(n) for n in range(1960, datetime.now().year))
COLLEGE_YEAR_CHOICES = tuple(reversed(COLLEGE_YEAR_CHOICES))
class ImageForm(forms.Form):
"""
Profile Image form
"""
form_method = forms.CharField(widget=forms.HiddenInput(), initial='image')
image = forms.ImageField(label="Image")
class AboutForm(forms.Form):
"""
User About form
"""
form_method = forms.CharField(widget=forms.HiddenInput(), initial='about')
attrs = {'placeholder': '<NAME>', 'class': 'form-control'}
first_name = forms.CharField(widget=forms.TextInput(attrs=attrs))
attrs = {'placeholder': '<NAME>', 'class': 'form-control'}
last_name = forms.CharField(widget=forms.TextInput(attrs=attrs))
attrs = {'placeholder': 'About you . . .', 'class': 'form-control', 'rows': 2}
about = forms.CharField(widget=forms.Textarea(attrs=attrs), required=False)
attrs = {'placeholder': 'What interests you ?', 'class': 'form-control', 'rows': 2}
interests = forms.CharField(widget=forms.Textarea(attrs=attrs), required=False)
class PersonalInfoForm(forms.Form):
"""
Personal Information form
"""
attrs = {'class': 'btn btn-default dropdown-toggle'}
dob = forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES, attrs=attrs),
label="Date of Birth", required=False, initial=date(1991, 1, 1))
attrs = {'class': 'btn btn-default dropdown-toggle'}
gender = forms.ChoiceField(widget=forms.Select(attrs=attrs), required=False,
choices=GENDER_CHOICES, initial=GENDER_CHOICES.M)
attrs = {'class': 'btn btn-default dropdown-toggle'}
country = forms.ChoiceField(widget=forms.Select(attrs=attrs), required=False,
choices=COUNTRIES, initial=COUNTRIES.IN)
attrs = {'placeholder': 'State', 'class': 'form-control'}
state = forms.CharField(widget=forms.TextInput(attrs=attrs), initial='Maharashtra',
required=False)
attrs = {'placeholder': 'City', 'class': 'form-control'}
city = forms.CharField(widget=forms.TextInput(attrs=attrs), initial='Mumbai',
required=False)
form_method = forms.CharField(widget=forms.HiddenInput(), initial='personal_info')
class AddEducationForm(forms.Form):
"""
User Education Details - Add
"""
form_method = forms.CharField(widget=forms.HiddenInput(), initial='add_education')
attrs = {'placeholder': 'Where did you go to study?',
'class': 'typeahead tt-query form-control'}
college = forms.CharField(widget=forms.TextInput(attrs=attrs), required=True)
attrs = {'placeholder': 'Whats yours major?', 'class': 'typeahead tt-query form-control'}
major = forms.CharField(widget=forms.TextInput(attrs=attrs), required=True)
attrs = {'class': 'btn btn-default dropdown-toggle',
'style': 'font-size: small; width: 100%'}
degree = forms.ChoiceField(widget=forms.Select(attrs=attrs), required=True,
choices=DEGREE, initial=DEGREE.BTECH)
attrs = {'class': 'btn btn-default dropdown-toggle dropdown-date'}
start_date = forms.DateField(widget=SelectDateWidget(years=COLLEGE_YEAR_CHOICES, attrs=attrs),
label="From", required=True, initial=date.today())
attrs = {'class': 'btn btn-default dropdown-toggle dropdown-date'}
end_date = forms.DateField(widget=SelectDateWidget(years=COLLEGE_YEAR_CHOICES, attrs=attrs),
label="To", required=False, initial=date.today())
class AddWorkForm(forms.Form):
"""
User Work Details - Add
"""
form_method = forms.CharField(widget=forms.HiddenInput(), initial='add_work')
attrs = {'placeholder': 'Where did you work ?', 'class': 'typeahead tt-query form-control'}
company = forms.CharField(widget=forms.TextInput(attrs=attrs), required=True)
attrs = {'placeholder': 'What was your position ?', 'class': 'form-control'}
position = forms.CharField(widget=forms.TextInput(attrs=attrs), required=True)
attrs = {'placeholder': 'Describe your role', 'class': 'form-control', 'rows': 3}
description = forms.CharField(widget=forms.Textarea(attrs=attrs), required=False)
attrs = {'class': 'btn btn-default dropdown-toggle dropdown-date'}
start_date = forms.DateField(widget=SelectDateWidget(years=COLLEGE_YEAR_CHOICES, attrs=attrs),
label="From", required=True, initial=date.today())
attrs = {'class': 'btn btn-default dropdown-toggle dropdown-date'}
end_date = forms.DateField(widget=SelectDateWidget(years=COLLEGE_YEAR_CHOICES, attrs=attrs),
label="To", required=False, initial=date.today())
class RemoveWorkform(forms.Form):
"""
User Work Details - Remove
"""
form_method = forms.CharField(widget=forms.HiddenInput())
work_id = forms.CharField(widget=forms.HiddenInput())
class RemoveEducationForm(forms.Form):
"""
User Education Details - Remove
"""
form_method = forms.CharField(widget=forms.HiddenInput())
education_id = forms.CharField(widget=forms.HiddenInput())
class SocialForm(forms.Form):
"""
User social data
"""
form_method = forms.CharField(widget=forms.HiddenInput(), initial='social')
attrs = {'placeholder': 'twitter-handle', 'class': 'form-control'}
twitter = forms.CharField(widget=forms.TextInput(attrs=attrs), required=False,
label='Twitter Handle')
attrs = {'placeholder': 'facebook-username', 'class': 'form-control'}
facebook = forms.CharField(widget=forms.TextInput(attrs=attrs),
required=False, label='Facebook Timeline')
@login_required
def home(request):
"""
Home page for the user
"""
return render(request, 'elearning_academy/logged_in.html')
def create_profile(request):
"""
Display the view-profile for the user whose profile is not yet created
"""
user = request.user
error = True
error_message = "Your profile is empty. Create Now !"
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters = {
'error': error,
'error_message': error_message
}
parameters.update({
'default_image': default_image,
'photo': '/media/',
'user_name': user.get_full_name(),
'profile_exists': False,
'about': 'About : Describe yourself !',
'interests': 'Interests : What excites you ?'
})
form = get_update_form(user)
parameters.update(form)
print parameters
return render(request, 'user_profile/profile.html', parameters)
def get_update_form(user):
"""
Returns dictionary of all forms used in profile page
"""
user_profile = UserProfile.objects.filter(user=user)
image_form = ImageForm()
if len(user_profile) == 0:
about_form = AboutForm({
'first_name': user.first_name,
'last_name': user.last_name,
'form_method': 'about'
})
personal_info_form = PersonalInfoForm()
add_education_form = AddEducationForm()
add_work_form = AddWorkForm()
social_form = SocialForm()
else:
user_profile = user_profile[0]
about_form = AboutForm({
'first_name': user.first_name,
'last_name': user.last_name,
'about': user_profile.about,
'interests': user_profile.interests,
'form_method': 'about'
})
if user_profile.gender:
gender = user_profile.gender
else:
gender = 'M'
if user_profile.dob:
dob = user_profile.dob
else:
## date(1991, 1, 1)
dob = None
if user_profile.place_country:
country = user_profile.place_country
else:
country = 'IN'
personal_info_form = PersonalInfoForm({
'gender': gender,
'dob': dob,
'city': user_profile.place_city,
'state': user_profile.place_state,
'country': country,
'form_method': 'personal_info'
})
add_education_form = AddEducationForm({
'form_method': 'add_education'
})
add_work_form = AddWorkForm({
'form_method': 'add_work'
})
social_form = SocialForm({
'form_method': 'social',
'twitter': user_profile.website_twitter,
'facebook': user_profile.website_facebook
})
form = {
'image_form': image_form,
'about_form': about_form,
'personal_info_form': personal_info_form,
'add_education_form': add_education_form,
'add_work_form': add_work_form,
'social_form': social_form
}
return form
@login_required
def view_profile(request, pk=None):
"""
View the profile for a user
"""
if pk:
#user = User.objects.get(pk=pk)
user = get_object_or_404(User, pk=pk)
allow_edit = False
else:
user = request.user
allow_edit = True
username = user.username
fullname = user.get_full_name()
if request.method == 'GET':
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) == 0:
return create_profile(request)
else:
default_image = "/static/elearning_academy/img/default/user.jpg"
user_profile_dictionary = json.loads(user_profile[0].toJson())
parameters = {'user_name': fullname,
'default_image': default_image,
'profile_exists': True,
'allow_edit': allow_edit}
parameters.update(user_profile_dictionary)
print parameters
#return HttpResponse(json.dumps(parameters, content_type='application/json')
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
elif request.method == 'POST':
if request.POST['form_method'] == 'image':
return edit_image(request)
elif request.POST['form_method'] == 'about':
return edit_user_intro(request)
elif request.POST['form_method'] == 'personal_info':
return edit_user_personal_info(request)
elif request.POST['form_method'] == 'social':
return edit_user_social(request)
elif request.POST['form_method'] == 'add_education':
return add_user_education(request)
elif request.POST['form_method'] == 'remove_education':
return remove_user_education(request)
elif request.POST['form_method'] == 'add_work':
return add_user_work(request)
elif request.POST['form_method'] == 'remove_work':
return remove_user_work(request)
else:
return HttpResponse("No form_method defined. This is error in user_profile/views.py")
else:
raise Http404
@login_required
def edit_user_social(request):
"""
Edit User social details
"""
user = request.user
fullname = user.get_full_name()
form = SocialForm(request.POST)
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) != 0:
current_user_profile = user_profile[0]
elif form.is_valid():
current_user_profile = UserProfile(user=user)
current_user_profile.generate_user_id()
current_user_profile.save()
if form.is_valid():
current_user_profile.website_twitter = form.cleaned_data["twitter"]
current_user_profile.website_facebook = form.cleaned_data["facebook"]
current_user_profile.save()
info = True
info_message = "Social Networks Updated !"
parameters = {'info': info, 'info_message': info_message}
else:
error = True
error_message = "Invalid Form Details"
parameters = {'error': error, 'error_message': error_message}
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters.update({'user_name': fullname,
'default_image': default_image,
'profile_exists': True})
user_profile_dictionary = json.loads(current_user_profile.toJson())
parameters.update(user_profile_dictionary)
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
@login_required
def remove_user_work(request):
"""
Remove a record for User Work Experience
"""
user = request.user
fullname = user.get_full_name()
form = RemoveWorkform(request.POST)
work_id = request.POST['work_id']
work = Work.objects.filter(id=work_id)
if (len(work) == 0) or (work[0].user != user):
error = True
error_message = "Work Experience not found in your records"
parameters = {'error': error, 'error_message': error_message}
else:
work[0].delete()
info = True
info_message = "Work Experience removed"
parameters = {'info': info, 'info_message': info_message}
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) != 0:
profile_exists = True
current_user_profile = user_profile[0]
user_profile_dictionary = json.loads(current_user_profile.toJson())
parameters.update(user_profile_dictionary)
else:
profile_exists = False
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters.update({'user_name': fullname,
'default_image': default_image,
'profile_exists': profile_exists})
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
@login_required
def add_user_work(request):
"""
Add a record for User Work Experience
"""
user = request.user
fullname = user.get_full_name()
form = AddWorkForm(request.POST)
if (form.is_valid() and
(form.cleaned_data["end_date"] is None or
form.cleaned_data["end_date"] > form.cleaned_data["start_date"])):
user_company = form.cleaned_data["company"]
company = Company.objects.filter(company=user_company)
if (len(company) == 0):
company = Company()
company.company = user_company
company.save()
user_company = company
else:
user_company = company[0]
user_position = form.cleaned_data["position"]
user_description = form.cleaned_data["description"]
user_work = Work(user=user)
user_work.company = user_company
user_work.position = user_position
user_work.description = user_description
user_work.start_date = form.cleaned_data["start_date"]
user_work.end_date = form.cleaned_data["end_date"]
user_work.save()
info = True
info_message = "Added Work Experience !"
parameters = {'info': info, 'info_message': info_message}
else:
error = True
error_list = True
error_message = []
if form.cleaned_data["start_date"] is None:
error_message.append("Start Date is required")
if form.cleaned_data["company"] is None:
error_message.append("Company is required")
if form.cleaned_data["position"] is None:
error_message.append("Position is required")
if (form.cleaned_data["end_date"] is not None and
(form.cleaned_data["end_date"] < form.cleaned_data["start_date"])):
error_message.append("End Date has to be later than Start Date")
parameters = {'error': error, 'error_list': error_list, 'error_message': error_message}
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) != 0:
profile_exists = True
current_user_profile = user_profile[0]
user_profile_dictionary = json.loads(current_user_profile.toJson())
parameters.update(user_profile_dictionary)
else:
profile_exists = False
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters.update({'user_name': fullname,
'default_image': default_image,
'profile_exists': profile_exists})
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
@login_required
def remove_user_education(request):
"""
Remove a record for User Education Experience
"""
user = request.user
fullname = user.get_full_name()
form = RemoveEducationForm(request.POST)
education_id = request.POST['education_id']
education = Education.objects.filter(id=education_id)
if (len(education) == 0) or (education[0].user != user):
error = True
error_message = "Education instance not found in your records !"
parameters = {'error': error, 'error_message': error_message}
else:
education[0].delete()
info = True
info_message = "Education record removed !"
parameters = {'info': info, 'info_message': info_message}
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) != 0:
profile_exists = True
current_user_profile = user_profile[0]
user_profile_dictionary = json.loads(current_user_profile.toJson())
parameters.update(user_profile_dictionary)
else:
profile_exists = False
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters.update({'user_name': fullname,
'default_image': default_image,
'profile_exists': profile_exists})
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
@login_required
def add_user_education(request):
"""
Add a record for User Education Experience
"""
user = request.user
fullname = user.get_full_name()
form = AddEducationForm(request.POST)
if (form.is_valid() and
(form.cleaned_data["end_date"] is None or
form.cleaned_data["end_date"] > form.cleaned_data["start_date"])):
user_college = form.cleaned_data["college"]
college = College.objects.filter(college=user_college)
if len(college) != 0:
user_college = college[0]
else:
college = College()
college.college = user_college
college.save()
user_college = college
user_major = form.cleaned_data["major"]
major = Major.objects.filter(major=user_major)
if len(major) != 0:
user_major = major[0]
else:
major = Major()
major.major = user_major
major.save()
user_major = major
user_education = Education(user=user)
user_education.college = user_college
user_education.major = user_major
user_education.degree = form.cleaned_data["degree"]
user_education.start_date = form.cleaned_data["start_date"]
user_education.end_date = form.cleaned_data["end_date"]
user_education.save()
info = True
info_message = "Added Education Details !"
parameters = {'info': info, 'info_message': info_message}
else:
error = True
error_list = True
error_message = []
if form.cleaned_data["start_date"] is None:
error_message.append("Start Date is required")
if (form.cleaned_data["end_date"] is not None and
(form.cleaned_data["end_date"] < form.cleaned_data["start_date"])):
error_message.append("End Date has to be later than Start Date")
parameters = {'error': error, 'error_list': error_list, 'error_message': error_message}
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) != 0:
profile_exists = True
current_user_profile = user_profile[0]
user_profile_dictionary = json.loads(current_user_profile.toJson())
parameters.update(user_profile_dictionary)
else:
profile_exists = False
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters.update({'user_name': fullname,
'default_image': default_image,
'profile_exists': profile_exists})
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
@login_required
def edit_user_personal_info(request):
"""
Edit the User Personal Info in User Profile
"""
user = request.user
fullname = user.get_full_name()
form = PersonalInfoForm(request.POST)
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) != 0:
current_user_profile = user_profile[0]
elif form.is_valid():
current_user_profile = UserProfile(user=user)
current_user_profile.generate_user_id()
current_user_profile.save()
if form.is_valid():
current_user_profile.gender = form.cleaned_data["gender"]
current_user_profile.dob = form.cleaned_data["dob"]
current_user_profile.place_city = form.cleaned_data["city"]
current_user_profile.place_state = form.cleaned_data["state"]
current_user_profile.place_country = form.cleaned_data["country"]
current_user_profile.save()
info = True
info_message = "Personal Information Updated !"
parameters = {'info': info, 'info_message': info_message}
else:
error = True
error_message = "Invalid Personal-Info Form Details"
parameters = {'error': error, 'error_message': error_message}
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters.update({'user_name': fullname,
'default_image': default_image,
'profile_exists': True})
user_profile_dictionary = json.loads(current_user_profile.toJson())
parameters.update(user_profile_dictionary)
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
@login_required
def edit_user_intro(request):
"""
Edit the User Intro in User Profile
"""
user = request.user
fullname = user.get_full_name()
form = AboutForm(request.POST)
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) != 0:
current_user_profile = user_profile[0]
elif form.is_valid():
current_user_profile = UserProfile(user=user)
current_user_profile.generate_user_id()
current_user_profile.save()
if form.is_valid():
user.first_name = form.cleaned_data["first_name"]
user.last_name = form.cleaned_data["last_name"]
user.save()
current_user_profile.about = form.cleaned_data["about"]
current_user_profile.interests = form.cleaned_data["interests"]
current_user_profile.save()
info = True
info_message = "Introduction Updated !"
parameters = {'info': info, 'info_message': info_message}
print "success"
else:
error = True
error_message = "Invalid Form Entry"
parameters = {'error': error, 'error_message': error_message}
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters.update({'user_name': fullname,
'default_image': default_image,
'profile_exists': True})
user_profile_dictionary = json.loads(current_user_profile.toJson())
parameters.update(user_profile_dictionary)
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
def delete_image(url):
"""
Delete the previous profile image of the user from media folder
"""
try:
os.remove(url)
except WindowsError:
print "%s does not exists" % url
return True
@login_required
def edit_image(request):
"""
Edit the profile image for a user profile
"""
username = request.user.username
user = User.objects.get(username=username)
fullname = user.get_full_name()
form = ImageForm(request.POST, request.FILES)
user_profile = UserProfile.objects.filter(user=user)
if len(user_profile) != 0:
current_user_profile = user_profile[0]
elif form.is_valid():
current_user_profile = UserProfile(user=user)
current_user_profile.generate_user_id()
current_user_profile.save()
if form.is_valid():
photo = request.FILES["image"]
if str(current_user_profile.photo) != "":
delete_image(MEDIA_ROOT + str(user_profile[0].photo))
current_user_profile.photo = photo
current_user_profile.save()
info = True
info_message = "Image Succesfully Updated !"
parameters = {'info': info, 'info_message': info_message}
else:
error = True
error_message = "Please select a valid Image"
parameters = {'error': error, 'error_message': error_message}
default_image = "/static/elearning_academy/img/default/user.jpg"
parameters.update({
'user_name': fullname,
'default_image': default_image,
'profile_exists': True
})
user_profile_dictionary = json.loads(current_user_profile.toJson())
parameters.update(user_profile_dictionary)
form = get_update_form(user)
parameters.update(form)
return render(request, 'user_profile/profile.html', parameters)
@login_required
def all_data(request, key):
"""
return a json of all colleges or major in the database
"""
if key == "college":
response_data = [c.college for c in College.objects.all()]
elif key == "company":
response_data = [c.company for c in Company.objects.all()]
else:
response_data = [m.major for m in Major.objects.all()]
return HttpResponse(json.dumps(response_data), content_type="application/json")
@login_required
def view_settings(request):
"""
Edit User contrib details for user
Edit general preference on mails/ updates/ forums/ default mode
"""
# _course = get_object_or_404(Course, pk=pk)
# context = {"request": request, "course": _course}
user = request.user
customUser = CustomUser.objects.get(user=user)
if user.id == 1:
return render(request,'user_profile/settings_root.html',{})
elif customUser.is_instructor:
return render(request,'user_profile/settings_instructor.html',{})
else :
return render(request,'user_profile/settings.html',{})
# return render(request, 'user_profile/settings.html', {})
@login_required
def get_privileges(request):
"""
a
"""
print("lololo")
u = GetInstructorPrivileges.objects.filter(user = request.user)
print(len(u))
if len(u) > 0:
return HttpResponse(json.dumps({"message": "Your approval is pending. Please contact root user for your approval"}), content_type="application/json",
status=status.HTTP_200_OK)
else:
u1 = GetInstructorPrivileges(user = request.user)
u1.save()
return HttpResponse(json.dumps({"message": "Successfully requested"}), content_type="application/json",
status=status.HTTP_200_OK)
@login_required
def pending_approvals(request):
"""
List the students which are pending approval in the course
"""
users = GetInstructorPrivileges.objects.all()
returned_data = []
for person in users:
user = User.objects.get(pk=person.user.id)
returned_data.append({
"user": user.id,
"username": user.username,
"fullname": user.get_full_name(),
"email": user.email,
})
return HttpResponse(json.dumps({'response': True, 'users': returned_data}), content_type="application/json",
status=status.HTTP_200_OK)
@action(methods=['POST'])
def approve(request):
"""
This function takes a list of student ids and
approve their request to register
"""
if request.user.id == 1:
if 'users' in request.POST:
# converting a string representation of array to
users = ast.literal_eval(request.POST['users'])
for user in users:
customUser = CustomUser.objects.get(user = user)
customUser.is_instructor = True
customUser.default_mode = CustomUser.INSTRUCTOR_MODE
customUser.save()
GetInstructorPrivileges.objects.get(user = user).delete()
return HttpResponse(json.dumps({"msg": 'Success'}), content_type="application/json",
status=status.HTTP_200_OK)
else:
return HttpResponse(json.dumps({"error": "Bad request format"}), content_type="application/json",
status=status.HTTP_400_BAD_REQUEST)
else:
return HttpResponse(json.dumps({"error":"forbidden"}), content_type="application/json",
status=status.HTTP_400_BAD_REQUEST)
@action(methods=['POST'])
def discard(request):
"""
This function takes a list of student ids and
discard their request to register
"""
if request.user.id == 1:
if 'users' in request.POST:
# converting a string representation of array to
users = ast.literal_eval(request.POST['users'])
for user in users:
GetInstructorPrivileges.objects.get(user = user).delete()
return HttpResponse(json.dumps({"msg": 'Success'}), content_type="application/json",
status=status.HTTP_200_OK)
else:
print request.DATA
return HttpResponse(json.dumps({"error": "Bad request format"}), content_type="application/json",
status=status.HTTP_400_BAD_REQUEST)
else:
return HttpResponse(json.dumps({"error":"forbidden"}), content_type="application/json",
status=status.HTTP_400_BAD_REQUEST)
def switch_mode(request):
"""
Switch the mode if its possible at this authorization
"""
print "Switching Mode"
if (request.method == 'POST'):
new_mode = request.POST['new_mode']
print new_mode
if ('mode' in request.session.keys()):
cur_mode = request.session['mode']
else:
request.session['mode'] = 'S'
cur_mode = 'S'
request.session['mode'] = new_mode
print is_valid_mode(request)
if (is_valid_mode(request)):
return HttpResponse(json.dumps({}), content_type="application/json",
status=status.HTTP_200_OK)
else:
request.session['mode'] = cur_mode
return HttpResponse(json.dumps({}), content_type="application/json",
status=status.HTTP_400_BAD_REQUEST)
else:
return HttpResponse(json.dumps({}), content_type="application/json",
status=status.HTTP_400_BAD_REQUEST)
<file_sep>/chat/urls.py
__author__ = 'dheerendra'
from django.conf.urls import include, patterns, url
from rest_framework.routers import DefaultRouter
from viewsets.chatroom import ChatRoomViewSet
from viewsets.chatObj import ChatViewSet
import views
router = DefaultRouter()
router.register(r'chatroom', ChatRoomViewSet)
router.register(r'chat', ChatViewSet)
urlpatterns = patterns(
'',
url(r'^api/', include(router.urls)),
url(r'^(\d+)/', views.index),
url(r'^reply/(\d+)', views.reply)
)<file_sep>/courseware/static/courseware/js/content_developer/course_student.jsx
/** @jsx React.DOM */
var PendingStudents = React.createClass({
mixins: [LoadMixin],
base_url: '/courseware/api/course/',
getUrl: function() {
url = this.base_url + this.props.courseid + "/pending_students/?format=json";
return url;
},
approveStudents: function() {
students = []
pending_students = this.state.data.students;
selected = $('input[name=student]').map(function(node, i) {
return this.checked
});
for (var i = 0; i < selected.length; i++) {
if (selected[i]) {
students.push(pending_students[i]["user"]);
}
}
data = {students: JSON.stringify(students)};
url = this.base_url + this.props.courseid + "/approve/?format=json";
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
this.loadData();
this.forceUpdate();
this.props.updateApprovedStudents();
console.log("Student List should reload now")
}.bind(this));
request.fail(function(response) {
display_global_message("Error completing request. Try again later")
}.bind(this));
},
toggleAll: function() {
check = $('input[name=heading]')[0].checked;
nodes = $('input[name=student]');
for (var i = 0; i < nodes.length; i++) {
nodes[i].checked = check;
};
},
handleChange: function(event) {
if (! event.target.checked) {
$('input[name=heading]')[0].checked = false;
}
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
render: function() {
if (this.state.loaded) {
if (! this.state.data.response) {
return (
<div class="row" style={{'margin-top':'15px'}}>
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger">
TextBook Course does not have Students
</div>
</div>
</div>
);
}
pending_students = this.state.data.students;
pending_students = pending_students.map( function(student, i) {
return (
<div class="checkbox-row">
<div class="col-md-1 col-md-offset-0 checkbox-container">
<input onChange={this.handleChange} type="checkbox" name="student" key={"pending_student_" + i}> </input>
</div>
<div class="col-md-3 col-md-offset-0 username"> {student["username"]} </div>
<div class="col-md-4 col-md-offset-0 fullname"> {student["fullname"]} </div>
<div class="col-md-4 col-md-offset-0 email"> {student["email"]} </div>
</div>
);
}.bind(this));
if (pending_students.length > 0) {
return (
<div class="panel-collapse collapse in" id="pending-students">
<div class="row">
<div class="col-md-offset-9 col-md-2 no-padding">
<button ref="approve" onClick={this.approveStudents}
class="btn btn-primary approve-btn" type="button"> Approve </button>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1 no-padding student-container">
<div class="student-heading">
<div class="col-md-1 col-md-offset-0 checkbox-container">
<input type="checkbox" name="heading" key="student_heading"
onChange={this.toggleAll}>
</input>
</div>
<div class="col-md-3 col-md-offset-0 username">
User Name </div>
<div class="col-md-4 col-md-offset-0 fullname">
Full Name </div>
<div class="col-md-4 col-md-offset-0 email">
Email </div>
</div>
{pending_students}
</div>
</div>
</div>
);
} else {
return (
<div class="panel-collapse collapse in" id="pending-students">
<div class="col-md-offset-9 col-md-2">
<button ref="approve" onClick={this.approveStudents}
class="btn btn-primary approve-btn" type="button"> Approve </button>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
No pending Student to approve.
</div>
</div>
</div>
</div>
);
}
} else {
return <LoadingBar />
}
}
});
var ApprovedStudents = React.createClass({
mixins: [LoadMixin],
base_url: '/courseware/api/course/',
getUrl: function() {
url = this.base_url + this.props.courseid + "/approved_students/?format=json";
return url;
},
componentWillReceiveProps: function(nextProps) {
if (this.state.loaded){
this.loadData();
console.log("Updated Approved Students");
}
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
render: function() {
if (this.state.loaded) {
if (!this.state.data.response){
return (
<div class="row" style={{'margin-top':'15px'}}>
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger">
TextBook Course does not have Students
</div>
</div>
</div>
);
}
approved_students = this.state.data.students;
approved_students = approved_students.map( function(student, i) {
return (
<div class="student-row">
<span class="col-md-3 username"> {student["username"]} </span>
<span class="col-md-5 fullname"> {student["fullname"]} </span>
<span class="col-md-4 email"> {student["email"]} </span>
</div>
);
});
if (approved_students.length > 0) {
return (
<div class="row">
<div class="col-md-10 col-md-offset-1 student-container no-padding">
<div class="student-heading">
<span class="col-md-3 username"> User Name </span>
<span class="col-md-5 fullname"> Full Name </span>
<span class="col-md-4 email"> Email </span>
</div>
{approved_students}
</div>
</div>
);
} else {
return (
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close"
data-dismiss="alert" aria-hidden="true">×</button>
No Student registered yet.
</div>
</div>
</div>
);
}
} else {
return <LoadingBar />
}
}
});
var CourseStudent = React.createClass({
updateApprovedStudents: function() {
console.log("Sending signal to Approved Students");
this.setState({loaded: false});
},
getInitialState: function(){
return {
loaded:false,
};
},
render: function() {
approved_students = <div>Some other content</div>;
return (
<div id="student" class="col-md-12">
<div class="panel panel-default pending-students" id="pending-student-container">
<div class="panel-heading" data-toggle="collapse" data-parent="#student"
data-target="#pending-students" id="pending-student-heading">
<span class="heading"> Pending Students </span>
</div>
<PendingStudents courseid={this.props.courseid} updateApprovedStudents={this.updateApprovedStudents}/>
</div>
<div class="panel panel-default approved-students" id="approved-student-container">
<div class="panel-heading" data-toggle="collapse" data-parent="#student"
data-target="#approved-students" id="approved-student-heading">
<span class="heading"> Approved Students </span>
</div>
<div class="panel-collapse collapse" id="approved-students">
<ApprovedStudents courseid={this.props.courseid} loaded={this.state.loaded}/>
</div>
</div>
</div>);
}
});<file_sep>/cribs/urls.py
'''
Created on Jun 17, 2013
@author: aryaveer
'''
from django.conf.urls import patterns, url
urlpatterns = patterns('cribs.views',
url(r'^create/(?P<assignmentID>\d+)$', 'createCrib', name='cribs_createcrib'),
url(r'^crib/(?P<assignmentID>\d+)$', 'myCribs', name='cribs_mycribs'),
url(r'^cribdetails/(?P<cribID>\d+)$', 'cribDetail', name='cribs_cribDetail'),
url(r'^allcribs/(?P<assignmentID>\d+)$', 'allCribs', name='cribs_allcribs'),
url(r'^edit/(?P<cribID>\d+)$', 'editCrib', name='cribs_editcrib'),
url(r'^close/(?P<cribID>\d+)$', 'closeCrib', name='cribs_closecrib'),
url(r'^open/(?P<cribID>\d+)$', 'reopenCrib', name='cribs_reopencrib'),
url(r'^comments/add/(?P<cribID>\d+)$', 'postComment', name='cribs_postcomment'),
url(r'^comments/edit/(?P<commentID>\d+)$', 'editComment', name='cribs_editcomment'),
)<file_sep>/chat/websocket/wsChat.py
__author__ = 'dheerendra'
import json
from collections import defaultdict
import cgi
import random
import datetime
import django.utils.importlib
import tornado.ioloop
import tornado.websocket
from django.conf import settings
from django.contrib.sessions.backends.cache import SessionStore
from rest_framework.renderers import JSONRenderer
from django.db import transaction
from chat.models import Chat, ChatRoom
from chat.serializers import ChatSerializers, RealTimeChatSerializers
from courseware.permissions import IsRegistered, IsOwner
def get_session(request):
'''
:param request: Non-wsgi request (Tornado Request object)
:return: sessionid cookie from request (Created by Django)
'''
if not hasattr(request, '_session'):
session_key = request.get_cookie(settings.SESSION_COOKIE_NAME)
request._session = SessionStore(session_key)
request._session.load()
return request._session
def get_current_user(request):
'''
Gets the current signed In Django User
:param request: (Non-Wsgi) Request. Tornado Request.
:return: Djagno User object. (None or Authenticated User)
'''
class Dummy(object):
pass
django_request = Dummy()
django_request.session = get_session(request)
user = django.contrib.auth.get_user(django_request)
'''
get_user needs a django request object, but only looks at the session
:func <django.contrib.auth.get_user>
'''
if user.is_authenticated():
return user
else:
# try basic auth
if not request.request.headers.has_key('Authorization'):
return None
kind, data = request.request.headers['Authorization'].split(' ')
if kind != 'Basic':
return None
(username, _, password) = data.decode('base64').partition(':')
user = django.contrib.auth.authenticate(username=username,
password=<PASSWORD>)
if user is not None and user.is_authenticated():
return user
return None
chatMessage = {
'userId': 0,
'username': 'Anonymous',
'isTeacher': False,
'type': 'join',
'chat': 'Dummy',
'parent': -1
}
'''
dictionary which will be sent over websocket as chat message in JSON format
'''
class ChatSocketHandler(tornado.websocket.WebSocketHandler):
client = defaultdict(set)
""" stores the set of connection in a dictionary. Key is the chatroom id """
online_users = defaultdict(lambda: defaultdict(int))
"""
dictionary of dictionary of integers. Store counts of user instances in a chatroom.
User can be logged-in into same chatroom through multiple devices or multiple windows from same device.
'join' should not be sent if user is already logged-in from other device/instance
'leave' message should be send only if user has left from all instances
example instance of dictionary:
{
'10': {
('1', 'dheerendra'): 2
}
}
this means user with userId '1' and username 'dheerendra' tuple (userId, username) is logged in from 2
instances for chatroom Id '10'
"""
def __init__(self, application, request, **kwargs):
super(ChatSocketHandler, self).__init__(application, request, **kwargs)
self.io_loop = tornado.ioloop.IOLoop.instance()
''' tornado.ioloop behaves much like javascript's setTimeout '''
def check_origin(self, origin):
'''
:param origin: Get the origin header of request
:return: whether request.HOST == request
Remove this function in production. This will prevent CSRF attacks
'''
return True
def openHelper(self, id, course):
'''
An abstract function which checks if user is allowed to connect
and do other necessary initialization
'''
user = get_current_user(self)
if user is None or user.is_anonymous():
self.close(400, 'User not Authenticated')
return
class Dummy(object):
pass
req = Dummy()
req.user = user
isRegistered = IsRegistered()
permit = isRegistered.has_object_permission(req, None, course)
# checks if user is registered to course i.e. user is owner of the course or a registered student
if not permit:
self.close(400, 'User not authorized')
return
isOwner = IsOwner()
isOwner = isOwner.has_object_permission(req, None, course)
# checks if user is owner of course object
chat = dict(chatMessage)
chat['userId'] = user.id
chat['username'] = user.username
if isOwner:
chat['isTeacher'] = True
self.id = id
self.chat = chat
self.user = user
self.set_nodelay(True)
self.__class__.client[self.id].add(self)
# adds self to list of clients who will receive messages at a chatroom
if self.__class__.online_users[self.id][(self.user.id, self.user.username)] == 0:
# If users is logged in from first instance, then send the join message
self.send_message()
self.__class__.online_users[self.id][(self.user.id, self.user.username)] += 1
# online users
ou = []
ouUser = {
'id': -1,
'username': 'Dummy'
}
for key_tuple in self.__class__.online_users[self.id]:
ouUser['id'] = key_tuple[0]
ouUser['username'] = key_tuple[1]
ou.append(ouUser.copy())
ouData = chatMessage.copy()
ouData['type'] = 'ou'
ouData['list'] = ou
self.write_message(json.dumps(ouData))
#sends list of online users for each time user join as a instance
#Start Ping Pong so that connection never dies due to timeout
self.ping_timeout = self.io_loop.add_timeout(datetime.timedelta(seconds=random.randint(5, 30)), self.send_ping)
def open(self, chatroom, parent):
'''
Setup websocket connection to open
:param chatroom: chatroom id
:param parent: parent id in case of reply. If parent is "-1" then it is not a reply
and chat is for main chatroom itself
'''
# TODO: Remove these transaction line in case of django.VERSION > 1.6.2
# http://stackoverflow.com/a/7794220/3341358
transaction.enter_transaction_management()
transaction.commit()
if parent == '-1':
try:
chatroomObj = ChatRoom.objects.get(pk=chatroom)
course = chatroomObj.course
except:
self.close(404, 'Incorrect Chatroom')
return
else:
try:
chat = Chat.objects.get(pk=parent)
course = chat.chatroom.course
if int(chatroom) != chat.chatroom.id:
raise Exception
except:
self.close(404, 'Incorrect Chat for reply')
return
self.parent = parent
self.openHelper(chatroom, course)
def on_message(self, message):
message = cgi.escape(message.strip())
# escape message to escape html tags. prevent XSS
if not message:
# do nothing for empty message
return
if self.parent != '-1':
parent = Chat.objects.get(pk=self.parent)
else:
parent = None
chatroom = ChatRoom.objects.filter(pk=int(self.id))[0]
chat = Chat(
chatroom=chatroom,
user=self.user,
message=message,
parent=parent,
)
chat.save()
chatJSON = RealTimeChatSerializers(chat)
chatJSON = JSONRenderer().render(chatJSON.data)
jsonData = json.loads(chatJSON)
self.chat['chat'] = jsonData
self.chat['type'] = 'text'
self.send_message()
def send_message(self):
'''
sends self.chat to all clients listed in client dictionary
'''
dump = json.dumps(self.chat)
for waiter in self.__class__.client[self.id]:
try:
waiter.write_message(dump)
except Exception as e:
pass
def on_close(self):
if hasattr(self, "ping_timeout"):
# remove timeout so that no more ping pong have to be send. Prevent ping-pong message
# error in case of closed connection
self.io_loop.remove_timeout(self.ping_timeout)
try:
self.__class__.client[self.id].remove(self)
# Remove the self from list of clients/waiters.
except:
pass
try:
self.__class__.online_users[self.id][(self.user.id, self.user.username)] -= 1
if self.__class__.online_users[self.id][(self.user.id, self.user.username)] <= 0:
# if user has left from all instances, then send the leave message
self.__class__.online_users[self.id].pop((self.user.id, self.user.username), None)
self.chat['type'] = 'leave'
self.send_message()
except:
pass
def on_pong(self, data):
if hasattr(self, "ping_timeout"):
# remove the timeout for connection_time
self.io_loop.remove_timeout(self.ping_timeout)
self.ping_timeout = self.io_loop.add_timeout(datetime.timedelta(seconds=15), self.send_ping)
# send new ping message
def connection_timeout(self):
# if no pong message is received within the timeout then close the connection
self.close(None, 'Connection Timeout')
def send_ping(self):
self.ping("a")
self.ping_timeout = self.io_loop.add_timeout(datetime.timedelta(minutes=1), self.connection_timeout)
# pong timeout of 1 minute. If no pong is received within 1 minute then call self.connection_timeout<file_sep>/concept/serializers.py
"""Serializers for Concept Models"""
from rest_framework import serializers
from concept import models
class ConceptQuizHistorySerializer(serializers.ModelSerializer):
"""Serializer for ConceptQuizHistory"""
class Meta:
model = models.ConceptQuizHistory
class ConceptDocumentHistorySerializer(serializers.ModelSerializer):
"""Serializer for ConceptDocumentHistory"""
class Meta:
model = models.ConceptDocumentHistory
<file_sep>/discussion_forum/permissions.py
""""
Handles permission for Discussion Forum API management
To access any record of a forum User must be part of that forum
Permission Classes:
IsForumAdminOrReadOnly
- safe methods allowed for all forum users. other actions for admin only
IsOwnerOrModeratorReadOnly
- owner has full access while moderator has just read access. False for \
others
IsOwnerOrModerator
- owner and moderator has full access rest have none access
IsOwnerOrModeratorOrReadOnly
- owner and moderator has full access rest have read only access
IsForumAdmin
- Checks for forum admin
IsForumModerator
- Checks for forum moderator+admin
IsForumUser
- Checks whether loggedIn user is subscribed to forum or not
DiscussionForum:
+ retrieve: IsForumAdminOrReadOnly
+ patching: partial update: IsForumAdminOrReadOnly
- add_tag: IsForumAdmin
- activity: IsForumUser
- threads: IsForumUser
- add_thread: IsForumUser
- review_content: IsForumModerator
Tag: forum:
+ retrieve: IsForumAdminOrReadOnly
+ patching: partial update: IsForumAdminOrReadOnly
+ delete: IsForumAdminOrReadOnly
- threads: IsForumUser
UserSetting: forum
+ retrieve: IsOwnerOrModeratorReadOnly
+ patching: partial update: IsOwnerOrModeratorReadOnly
- update_badge: IsForumModerator
- update_moderation_permission: IsForumAdmin
Content: forum
+ delete: IsOwnerOrModerator
- upvote, downvote, mark_spam: IsForumUser
- pin_content: IsForumModerator
- disable: IsForumModerator
- enable: IsForumModerator
- reset_spam_flags: IsForumModerator
Thread: forum
+ retrieve: IsOwnerOrModeratorOrReadOnly
+ update: IsOwnerOrModeratorOrReadOnly
+ delete: IsOwnerOrModeratorOrReadOnly
- comments: ForumUser
- add_comment: ForumUser
- add_tag: ForumUser
- remove_tag: ForumUser
- subscribe: ForumUser
- unsubscribe: ForumUser
Comment: forum
+ retrieve: IsOwnerOrModeratorOrReadOnly
+ update: IsOwnerOrModeratorOrReadOnly
+ delete: IsOwnerOrModeratorOrReadOnly
- replies: IsForumUser
- add_reply: IsForumUser
Reply: forum
+ retrieve: IsOwnerOrModeratorOrReadOnly
+ update: IsOwnerOrModeratorOrReadOnly
+ delete: IsOwnerOrModeratorOrReadOnly
"""
from rest_framework import permissions
from discussion_forum import models
class IsForumAdminOrReadOnly(permissions.BasePermission):
"""
Allows complete permission to Forum Admin and read only access to other \
forum users
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Returns whehter user has permission on this object or not
"""
try:
if type(obj) == models.DiscussionForum:
forum = obj
else:
forum = obj.forum
setting = models.UserSetting.objects.get(
forum=forum,
user=request.user
)
except:
return False
if request.method in permissions.SAFE_METHODS:
return True
else:
if type(obj) == models.Tag and obj.auto_generated:
# Auto generated tags can't be operated on
return False
return setting.super_user
class IsOwnerOrModeratorReadOnly(permissions.BasePermission):
"""
Complete access to owner and read only access to moderator. Other's have \
no access at all
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Returns whehter user has permission on this object or not
"""
try:
if type(obj) == models.DiscussionForum:
forum = obj
else:
forum = obj.forum
if type(obj) == models.UserSetting:
owner = obj.user
else:
owner = obj.author
setting = models.UserSetting.objects.get(
forum=forum,
user=request.user
)
except:
return False
if request.method in permissions.SAFE_METHODS:
if setting.super_user or setting.moderator:
return True
else:
return owner == request.user
else:
return (owner == request.user)
class IsOwnerOrModerator(permissions.BasePermission):
"""
Owner and Moderator have full access other's have no access at all
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Returns whehter user has permission on this object or not
"""
try:
if type(obj) == models.DiscussionForum:
forum = obj
else:
forum = obj.forum
if type(obj) == models.UserSetting:
owner = obj.user
else:
owner = obj.author
setting = models.UserSetting.objects.get(
forum=forum,
user=request.user
)
except:
return False
if (setting.super_user or setting.moderator):
return True
else:
return (owner == request.user)
class IsOwnerOrModeratorOrReadOnly(permissions.BasePermission):
"""
Full access to owner and moderator. Other forum users have Readonly access
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Returns whehter user has permission on this object or not
"""
try:
if type(obj) == models.DiscussionForum:
forum = obj
else:
forum = obj.forum
if type(obj) == models.UserSetting:
owner = obj.user
else:
owner = obj.author
setting = models.UserSetting.objects.get(
forum=forum,
user=request.user
)
except:
return False
if request.method in permissions.SAFE_METHODS:
return True
elif (setting.super_user or setting.moderator):
return True
else:
return (owner == request.user)
class IsForumAdmin(permissions.BasePermission):
"""
Provide access for moderation purpose to Forum Super User's only
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Check for forum admin
"""
try:
if type(obj) == models.DiscussionForum:
forum = obj
else:
forum = obj.forum
setting = models.UserSetting.objects.get(
forum=forum,
user=request.user
)
except:
return False
return setting.super_user
class IsForumModerator(permissions.BasePermission):
"""
Provide access for moderation purpose to Forum Moderators
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Check for forum moderator
"""
try:
if type(obj) == models.DiscussionForum:
forum = obj
else:
forum = obj.forum
setting = models.UserSetting.objects.get(
forum=forum,
user=request.user
)
except:
return False
return (setting.super_user or setting.moderator)
class IsForumUser(permissions.BasePermission):
"""
General permission class for ForumUser
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Check whether current user is subscribed to forum or not
"""
try:
if type(obj) == models.DiscussionForum:
forum = obj
else:
forum = obj.forum
setting = models.UserSetting.objects.get(
forum=forum,
user=request.user
)
except:
return False
return True
<file_sep>/courseware/static/courseware/js/student/course_playlist.jsx
/** @jsx React.DOM */
var ConceptPlaylist = React.createClass({
render: function() {
itemNodes = this.props.list.map(function(item, i) {
return (
<li key={i}>
<ConceptPlaylistItem
index={i}
type={item.type}
title={item.title} id={item.id}
content = {item}/>
</li>
);
}.bind(this));
return (
<div class="pull-right">
<ul class="list-inline concept-playlist">
{itemNodes}
</ul>
</div>
);
}
});
var ConceptPlaylistItem = React.createClass({
getLink: function() {
link = '';
if (this.props.content.type=="document"){
content = this.props.content.content;
documents = content.sections.map(function(item, i) {
if (!item.file){
return(
<li key={i}></li>
);
} else {
return(
<li key={i}>
<a href={item.file} data-container="body" data-toggle="popover"
data-trigger="hover" data-placement="bottom" title="" data-original-title=""
ref="linkBlock" target="_blank">
<span class={"glyphicon glyphicon-file"}></span></a>
</li>
);
}
});
return (
<div>
<ul class="list-unstyled concept-document-sections">
{documents}
</ul>
</div>
);
}
else if (this.props.content.type=="video"){
content = this.props.content;
if(content.content.other_file!='/media/'){
return (
<div>
<ul class="list-unstyled concept-document-sections"><li>
<a href={content.content.other_file} data-container="body" data-toggle="popover"
data-trigger="hover" data-placement="bottom" title="" data-original-title=""
ref="linkBlock" target="_blank">
<span class={"glyphicon glyphicon-credit-card"}></span></a></li>
</ul>
</div>
);
}
else{
return (<div>
<ul class="list-unstyled concept-document-sections"><li>
</li>
</ul>
</div>);
}
}
else{
return (<div>
<ul class="list-unstyled concept-document-sections"><li>
</li>
</ul>
</div>);
}
},
render: function() {
isVideo = this.props.type == "video";
isQuiz = this.props.type == "quiz";
return (
<div class="concept-playlist-item">
{this.getLink()}
</div>
);
}
});
var Concept = React.createClass({
base_url: "/concept/api/",
getInitialState: function() {
return {
loaded: false,
data: undefined,
highlight: undefined,
};
},
loadData: function() {
url = this.base_url + "concept/" + this.props.concept.id + "/playlist";
$.ajax({
url: url,
dataType: 'json',
mimeType: 'application/json',
data: {format: 'json'},
success: function(data) {
state = this.state;
state.loaded = true;
state.data = data
this.setState(state);
}.bind(this)
});
},
componentDidMount: function() {
if (!this.state.loaded) this.loadData();
},
render: function() {
if (!this.state.loaded){
return (
<div>
<LoadingBar />
</div>
);
}
else
{
links = '';
/*data = this.state.data.playlist.map(function(content){
type = content.type;
isVideo = type == "video";
isDocument = type == "document";
isQuiz = type == "quiz";
return (<a href={"" + (isVideo ? content.content.video_file: content.content.sections[0].file)} data-container="body" data-toggle="popover"
data-trigger="hover" data-placement="bottom"
title="" data-original-title=""
ref="linkBlock">
<span class={"glyphicon glyphicon-" +
(isVideo ? "film" : ( isQuiz ? "question-sign" : "file"))}></span>
</a>);
});*/
return (
<li class='concept'>
<a href={'/concept/' + this.props.concept.id + '/'} class="concept-title">
{this.props.concept.title}
</a>
<div class="pull-right">
<div>
<ConceptPlaylist
conceptId={this.props.concept.id}
list={this.state.data}
/>
</div>
</div>
</li>
);
} }
});
var Group = React.createClass({
mixins: [MathJaxMixin,],
getInitialState: function() {
return {
loaded: false,
concepts: undefined,
title: this.props.group.title,
description: this.props.group.description,
};
},
loadConcepts: function() {
url = "/courseware/api/group/" + this.props.group.id + "/published_concepts/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState['concepts'] = response;
oldState['loaded'] = true;
this.setState(oldState);
}.bind(this));
},
render: function() {
if(!this.state.loaded) {
concepts = <LoadingBar />;
if(this.props.groupid == "" || this.props.groupid != undefined){
this.loadConcepts();
}
}
else {
concepts = this.state.concepts.map(function (concept) {
return <Concept concept={concept} />;
}.bind(this));
}
var groupid = 'group_' + this.props.group.id;
var isCollapse = "collapse";
if(this.props.groupid == "" || this.props.groupid != undefined)
{
isCollapse = "in";
}
content = (
<div onClick={this.loadConcepts} class="panel panel-default group">
<div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target={"#"+groupid}>
<div class="panel-title group-heading">
{this.state.title}
</div>
<div class="muted">
<span dangerouslySetInnerHTML={{__html: converter.makeHtml(this.state.description)}} />
</div>
</div>
<div id={groupid} class={"panel-collapse "+ isCollapse}>
<div class="panel-body group-inner">
<ul class="concepts">
{concepts}
</ul>
</div>
</div>
</div>
);
return content;
}
});
var CoursePlaylist = React.createClass({
loadGroups: function() {
url = "/courseware/api/course/" + this.props.courseid + "/groups/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState['groups'] = response;
oldState['loaded'] = true;
this.setState(oldState);
}.bind(this));
},
getInitialState: function() {
return {
loaded: false,
groups: undefined,
};
},
componentDidMount: function() {
if(!this.state.loaded) {
this.loadGroups();
}
},
componentDidUpdate: function() {
if(this.state.loaded) {
$("#groups").accordion({
animate: 100,
collapsible: true,
heightStyle: "content"
});
//$("#groups li").disableSelection();
}
else {
this.loadGroups();
}
},
render: function() {
if(!this.state.loaded) {
groups = <LoadingBar />;
}
else {
if (this.state.groups == "")
groups = (<div class="alert alert-danger alert-dismissable">No content displayed yet in this course</div>);
else {
if(this.props.groupid == "" || this.props.groupid == undefined)
{
groups = this.state.groups.map(
function (group) {
return <Group group={group}/>;
}.bind(this));
}
else
{
groups = this.state.groups.map(
function (group) {
if(this.props.groupid == group.id)
{
return <Group group={group} groupid={this.props.groupid}/>;
}
}.bind(this));
groups = groups.filter(function(n) { return n != undefined; });
groups = groups[0];
}
}
}
return (
<div>
<h3 class='contentheading'>
Course Content
</h3>
<div class="panel-group" id="accordion">
{groups}
</div>
</div>
);
}
});
<file_sep>/upload/urls.py
#from django.conf.urls.defaults import patterns, url
from django.conf.urls import patterns, url
urlpatterns = patterns('upload.views',
url(r'^$', 'upload', name='upload'),
#url(r'^(?P<assignmentID>\d+)$', 'uploadAssignment', name='upload_uploadassignment'),
url(r'^showall/(?P<assignmentID>\d+)$', 'showAllSubmissions', name='upload_showAllSubmissions'),
url(r'^mysubmissions/(?P<courseID>\d+)$', 'my_submissions', name='upload_mysubmissions'),
url(r'^submission/download/(?P<submissionID>\d+)$', 'submissionDownload', name='submission_downloadfile'),
)
<file_sep>/TestBed/C++/Teacher/common_strings.cpp
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int memo[5005][5005];
string s1,s2;
int n;
int max_sub_seq(int pos1, int pos2){
if(pos1 >= n || pos2 >= n){
return 0;
}
else if(memo[pos1][pos2] == -1){
if(s1[pos1] == s2[pos2]){
memo[pos1][pos2] = 1 + max_sub_seq(pos1+1,pos2+1);
}
else{
int i1 = max_sub_seq(pos1,pos2+1);
int i2 = max_sub_seq(pos1+1,pos2);
memo[pos1][pos2] = i1>i2?i1:i2;
}
}
return memo[pos1][pos2];
}
int main() {
cin >> s1 >> s2;
n = s1.length();
int i,j;
for(i=0;i<n;++i){
for(j=0;j<n;++j){
memo[i][j] = -1;
}
}
cout << max_sub_seq(0,0) << endl;
return 0;
}<file_sep>/quiz_template/serializers.py
from rest_framework import serializers
from quiz_template import models
class QuizSerializer(serializers.ModelSerializer):
"""
Serialization of Quiz model
"""
class Meta:
""" Meta """
model = models.Quiz
fields = ('id', 'title', 'questions', 'marks')
read_only_fields = ('marks', 'questions')
class QuestionMasterSerializer(serializers.ModelSerializer):
"""
Serialization of Question_Master model
"""
class Meta:
""" Meta """
model = models.Question_Master
class QuestionScqSerializer(serializers.ModelSerializer):
"""
Serialization of Question_Scq model
"""
class Meta:
""" Meta """
model = models.Question_Scq
class QuestionMcqSerializer(serializers.ModelSerializer):
"""
Serialization of Question_Mcq model
"""
class Meta:
""" Meta """
model = models.Question_Mcq
class QuestionFixSerializer(serializers.ModelSerializer):
"""
Serialization of Question_Fix model
"""
class Meta:
""" Meta """
model = models.Question_Fix
class QuestionDesSerializer(serializers.ModelSerializer):
"""
Serialization of Question_Des model
"""
class Meta:
""" Meta """
model = models.Question_Des
class QuestionModuleSerializer(serializers.ModelSerializer):
"""
Serialization of Question_Module model
"""
class Meta:
""" Meta """
model = models.Question_Module
fields = ('id', 'static_text', 'title', 'quiz')
class UserSubmissionsSerializer(serializers.ModelSerializer):
"""
Serialization of UserSubmssions model
"""
class Meta:
""" Meta """
model = models.User_Submissions
read_only_fields = ('attempts', 'marks', 'status')
class FrontEndQuestionSerializer(serializers.Serializer):
"""
Serializer to show all Question_Master data and user submission together
"""
id = serializers.IntegerField()
marks = serializers.CharField()
attempts = serializers.IntegerField()
text = serializers.CharField()
is_hint_available = serializers.BooleanField(default=False)
type = serializers.CharField(max_length=3)
user_attempts = serializers.IntegerField(default=0)
user_marks = serializers.FloatField(default=0.0)
user_status = serializers.CharField(max_length=1)
hint_taken = serializers.BooleanField(default=False)
hint = serializers.CharField(default=None)
answer_shown = serializers.BooleanField(default=False)
answer = serializers.CharField(default=None)
options = serializers.CharField(default=None)
explaination = serializers.CharField(default=None)
class FrontEndSubmissionSerializer(serializers.Serializer):
"""
Serialization utility to send back a submission to the front end
"""
status = serializers.CharField()
marks = serializers.FloatField()
attempts_remaining = serializers.IntegerField()
answer = serializers.CharField(default=None)
explaination = serializers.CharField(default=None)
class AnswerSubmitSerializer(serializers.Serializer):
"""
Serialization utility for submission of an answer
"""
answer = serializers.CharField()<file_sep>/elearning_academy/context_processor.py
"""
Make the variables in settings.py as globally available in templates
"""
from django.conf import settings
from user_profile.models import CustomUser
def my_global_name(request):
"""
Function is context processor for templates which makes the
user defined variables as globally available.
"""
if (request.user.is_authenticated()):
customuser = CustomUser.objects.filter(user=request.user)
else:
customuser = []
if len(customuser) == 0:
is_instructor = False
is_content_developer = False
else:
is_instructor = customuser[0].is_instructor
is_content_developer = customuser[0].is_content_developer
return {
"MY_SERVER": settings.MY_SERVER,
"COPYRIGHT_YEAR": settings.COPYRIGHT_YEAR,
"MY_SITE_NAME": settings.MY_SITE_NAME,
"IS_INSTRUCTOR": is_instructor,
"IS_CONTENT_DEVELOPER": is_content_developer,
"favicon": settings.TITLE_ICON
}
<file_sep>/courseware/viewsets/category.py
"""
This file contains viewsets for ParentCategory and Category models.
Functionality Provided:
ParentCategory:
+ Add, Update, PartialUpdate, Delete - (IsAdminUser)
+ List, Retrieve - (everyone allowed)
Category:
+ Add, Update, PartialUpdate, Delete - (IsAdminUser)
+ List, Retrieve - (everyone allowed)
"""
from courseware.models import ParentCategory, Category
from courseware.vsserializers.category import ParentCategorySerializer, CategorySerializer
from courseware import permissions
from rest_framework import viewsets
class ParentCategoryViewSet(viewsets.ModelViewSet):
"""
ViewSet for ParentCategory. All operations permitted.
"""
model = ParentCategory
serializer_class = ParentCategorySerializer
permission_classes = [permissions.IsAdminUserOrReadOnly]
class CategoryViewSet(viewsets.ModelViewSet):
"""
ViewSet for Category Model. All operations permitted.
"""
model = Category
serializer_class = CategorySerializer
permission_classes = [permissions.IsAdminUserOrReadOnly]
def get_queryset(self):
"""
Optionally restricts the returned categories to a given parentcategory.
"""
queryset = Category.objects.all()
parent = self.request.QUERY_PARAMS.get('parent', None)
if parent is not None:
queryset = queryset.filter(parent__id=parent)
return queryset
<file_sep>/assignments/assignments_utils/create_output.py
from evaluate.utils.executor import CommandExecutor
from utils.archives import get_file_name_list, extract_or_copy
from elearning_academy.settings import PROJECT_DIR
from utils.filetypes import is_intermediate_files, compile_required, get_execution_command, get_compilation_command
import assignments
import os, shutil, tempfile, tarfile
# This class manages the creation of model output for the given testcase when the instructor does not upload the model output.
# The class attributes are the section to which the testcase belongs to, the testcase itself, the input file, a command executor, and a flag
# to denote if the creation of output succeeded.
class CreateOutput(object):
def __init__(self, instance):
self.program = instance.program
self.testcase = instance
self.input_files = instance.input_files
self.commandExecutor = CommandExecutor()
self.failed = False
self.eval_dir = os.path.join(PROJECT_DIR, './evaluate/safeexec')
# Function to get resource limit for the testcase. During the creation of the testcase a Resource limit object with limits for various features
# is also created (with default values if the instructor does not change this).
# This function returns the dictionary mapping the attributes to their respective limits for this testcase.
def get_resource_limit(self):
'''return {'cpu_time':10, 'clock_time':10,
'memory': 32768, 'stack_size': 8192, 'child_processes': 0,
'open_files': 512, 'file_size': 1024,
}
'''
# Solve this by actually retrieving the exact SafeExec object.
try:
resource = {}
safeexec_obj = assignments.models.SafeExec.objects.get(testcase=self.testcase)
attrs = ['cpu_time', 'clock_time', 'memory', 'stack_size', 'child_processes', 'open_files', 'file_size']
for attr in attrs:
val = getattr(safeexec_obj, attr)
if val is not None:
resource[attr] = val
return resource
except assignments.models.SafeExec.DoesNotExist:
return {'cpu_time':10, 'clock_time':10,
'memory': 32768, 'stack_size': 8192, 'child_processes': 0,
'open_files': 512, 'file_size': 1024,
}
# Function to setup the environment before creating the output. This function copies the model solution, the program files and the input files
# related to the testcase.
def setup(self):
# Create a temporary directory and change to it.
self.temp_dir = tempfile.mkdtemp(prefix="solution", dir=self.eval_dir)
os.chdir(self.temp_dir)
currentDir = os.getcwd()
# Copy the program files and assignment model solution to the directory.
if self.program.program_files :
extract_or_copy(src=self.program.program_files.file.name, dest=currentDir)
self.program.program_files.close()
if self.program.assignment.model_solution:
extract_or_copy(src=self.program.assignment.model_solution.file.name, dest=currentDir)
self.program.assignment.model_solution.close()
# Create a temp file to store the input and write the input file to this temp file. Once the writing is done, copy the input file to
# the current directory.
self.temp_input_d = tempfile.mkdtemp(prefix="input")
if self.input_files:
self.input = os.path.join(
self.temp_input_d,
os.path.basename(self.testcase.input_files.file.name)
)
self.testcase.input_files.close()
f = open(self.input, 'w')
for a_line in self.input_files.file:
f.write(a_line)
f.close()
extract_or_copy(src=self.input, dest=currentDir)
else:
self.input = ''
# Function to run the model solution against the input file. If successful then the model output is created and stored in the database.
def run(self):
# If compilation is required then compile the solution. If there are errors then write it to the error file and return. Fail!!
if compile_required(self.program.language):
compiler_command = get_compilation_command(self.program)
print "Compiling model solution. Compilation Command - " + compiler_command
self.command_output = self.commandExecutor.safe_execute(
command=compiler_command,
limits=self.get_resource_limit(),
safe=False
)
# If the return code is non-zero, there was some error. Write it in database.
if self.command_output.getReturnCode():
print "Compilation of model solution failed."
self.failed = True
_, self.error_file = tempfile.mkstemp(prefix="error", dir=self.temp_input_d)
f = open(self.error_file, 'w')
for a_line in self.command_output.get_stderr():
f.write(a_line)
f.close()
return
# No errors and thus can continue. Run the execution command on the model solution. Add the input files and command line args as needed.
execution_command = get_execution_command(self.program)
if self.testcase.command_line_args:
execution_command = execution_command + self.testcase.command_line_args
if self.testcase.std_in_file_name:
execution_command = execution_command + " < " + self.testcase.std_in_file_name
print "Creating Output. Running following execution command - " + execution_command
self.command_output = self.commandExecutor.safe_execute(
command=execution_command,
limits=self.get_resource_limit()
)
self.success = bool(self.command_output.getReturnCode())
self.command_output.printResult()
# Clean up the current directory. Delete input files from current directory. And the program files
dir_content = os.listdir('./')
for a_file in dir_content:
if self.is_program_file(a_file):
os.remove(a_file)
if self.input:
for a_file in get_file_name_list(name=self.input):
if os.path.isfile(a_file):
os.remove(a_file)
# Write standard output to a file and save it in database.
directory_content = os.listdir('./')
_, self.std_out_file = tempfile.mkstemp(prefix='output', dir="./")
out_file = open(self.std_out_file, 'w')
for a_line in ["\n".join(self.command_output.get_stdout())]:
out_file.write(a_line)
out_file.close()
# There was some error. Write it in database.
if self.command_output.getReturnCode():
self.failed = True
_, self.error_file = tempfile.mkstemp(prefix="error", dir=self.temp_input_d)
f = open(self.error_file, 'w')
for a_line in self.command_output.get_stderr():
f.write(a_line)
f.close()
# If directory has any content left then make a tar, else set the outfile to the output file.
if directory_content:
self.out_file = self.make_tar(directory_content + [self.std_out_file], self.std_out_file)
else:
self.out_file = self.std_out_file
# Function to get the filenmae of the file to which the std output was written.
def get_stdout_file_name(self):
return os.path.basename(self.std_out_file)
# Function to get the filenmae of the file to which the std error was written.
def get_stderr_file_name(self):
return os.path.basename(self.error_file)
# Function to get the filepathof the file to which the std error was written.
def get_stderr_file_path(self):
return self.error_file
# Function to make a tar of the contents of the directory.
def make_tar(self, files, tarname):
tarname = tarname + ".tar.bz2"
output_files_tar = tarfile.open(name=tarname, mode="w:bz2")
# Make tar file from all output files.
for afile in files:
if os.path.isfile(afile):
output_files_tar.add(os.path.basename(afile))
output_files_tar.close()
return tarname
# Function to get the model output. This is function called and this function first sets the environment and then calls run().
def get_output(self):
prev_dir = os.getcwd()
try:
self.setup()
self.run()
finally:
os.chdir(prev_dir)
return self
# Function to check if a file is a program file (not output file). This does so by checking the filename against the list of
# program files and model solution files. It also checks if the file was created during the execution of the model solution (compilation or
# execution)
def is_program_file(self, fname):
filename = fname.split("/")[-1]
if self.program.program_files and filename in get_file_name_list(self.program.program_files.file.name):
self.program.program_files.close()
return True
elif self.program.assignment.model_solution and filename in get_file_name_list(self.program.assignment.model_solution.file.name):
self.program.assignment.model_solution.close()
return True
elif is_intermediate_files(filename,self.program,self.program.language):
return True
else:
return False
# Function to clean up the directory in which the execution happened.
def clean_up(self):
shutil.rmtree(self.temp_dir, ignore_errors=True)
shutil.rmtree(self.temp_input_d, ignore_errors=True)
<file_sep>/document/serializers.py
"""
Serializers for document app.
"""
from rest_framework import serializers
from document.models import Document, Section
from courseware.models import SHORT_TEXT
class DocumentSerializer(serializers.ModelSerializer):
"""ModelSerializer for Document class"""
class Meta:
model = Document
exclude = ('uid',)
class SectionSerializer(serializers.ModelSerializer):
"""ModelSerializer for Section"""
class Meta:
"""Meta"""
model = Section
class AddSectionSerializer(serializers.Serializer):
title = serializers.CharField(max_length=SHORT_TEXT)
description = serializers.CharField()
<file_sep>/cribs/views.py
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from cribs.models import Crib
from cribs.models import Comment
from cribs.forms import CribForm, CommentForm
from assignments.models import Assignment
@login_required
def createCrib(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
if request.method == 'POST':
form = CribForm(request.POST)
if form.is_valid():
Crib.objects.get_or_create(
assignment=assignment,
created_by=request.user,
defaults=form.cleaned_data
)
return HttpResponseRedirect(reverse('cribs.views.myCribs', kwargs={'assignmentID': assignment.id}))
else:
try:
Crib.objects.get(assignment=assignment, created_by=request.user) # checking if there is already a crib.
return HttpResponseRedirect(reverse('cribs.views.myCribs', kwargs={'assignmentID': assignment.id}))
except Crib.DoesNotExist:
form = CribForm() # render empty form if crib was not registered.
return render_to_response(
'cribs/create_crib.html',
{'form': form, 'assignment': assignment},
context_instance=RequestContext(request)
)
@login_required
def myCribs(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
try:
crib = Crib.objects.get(assignment=assignment, created_by=request.user)
except Crib.DoesNotExist:
crib = None
comments = Comment.objects.filter(crib=crib)
form = CommentForm()
return render_to_response(
'cribs/my_crib.html',
{'crib': crib, 'form': form, 'comments': comments,
'assignment': assignment,},
context_instance=RequestContext(request)
)
@login_required
def allCribs(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
allCribs = Crib.objects.filter(assignment=assignment)
return render_to_response(
'cribs/all_cribs.html',
{'assignment': assignment, 'allcribs': allCribs},
context_instance=RequestContext(request)
)
@login_required
def cribDetail(request, cribID):
crib = get_object_or_404(Crib, pk=cribID)
comments = Comment.objects.filter(crib=crib)
form = CommentForm()
return render_to_response(
'cribs/my_crib.html',
{'crib': crib, 'form': form, 'comments': comments},
context_instance=RequestContext(request)
)
@login_required
def editCrib(request, cribID):
pass
@login_required
def closeCrib(request, cribID):
pass
@login_required
def reopenCrib(request, cribID):
pass
@login_required
def postComment(request, cribID):
# TODO: Implement in Ajax.
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment(**form.cleaned_data)
comment.posted_by = request.user
comment.crib = get_object_or_404(Crib, pk=cribID)
comment.save()
return HttpResponse("Saved! (Later this will be implemented with Ajax. Hit back button and refresh page to see your comment.)")
@login_required
def editComment(request, commentID):
pass<file_sep>/video/serializers.py
"""
Serializers for the video API
"""
from rest_framework import serializers
from video import models
class MarkerSerializer(serializers.ModelSerializer):
class Meta:
model = models.Marker
class SectionMarkerSerializer(serializers.ModelSerializer):
class Meta:
model = models.SectionMarker
class QuizMarkerSerializer(serializers.ModelSerializer):
quiz_title = serializers.Field(source='get_quiz_title')
class Meta:
model = models.QuizMarker
fields = ('id', 'time', 'video', 'type', 'quiz', 'quiz_title')
class MarkerListingField(serializers.RelatedField):
def to_native(self, value):
value = models.Marker.objects.filter(pk=value.id).select_subclasses()[0]
if isinstance(value, models.SectionMarker):
return SectionMarkerSerializer(value).data
elif isinstance(value, models.QuizMarker):
return QuizMarkerSerializer(value).data
#elif isinstance(value, models.Marker):
# return 'Marker came instead'
else:
print "Unknown Marker found in video. %s" % (value)
return {}
class VideoSerializer(serializers.ModelSerializer):
markers = serializers.Field(source='get_markers')
video_file = serializers.Field(source='get_video_file')
other_file = serializers.Field(source='get_other_file')
class Meta:
model = models.Video
fields = ('id', 'title', 'content', 'upvotes', 'downvotes', 'video_file', 'markers', 'other_file', 'duration')
class AddVideoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Video
exclude = ('video_file', 'other_file')
class VideoHistorySerializer(serializers.ModelSerializer):
"""Serializer for VideoHistory"""
class Meta:
model = models.VideoHistory
class QuizMarkerHistorySerializer(serializers.ModelSerializer):
"""Serializer for QuizMarkerHistory"""
class Meta:
model = models.QuizMarkerHistory
<file_sep>/cribs/forms.py
'''
Created on Jun 17, 2013
@author: aryaveer
'''
from django import forms
class CribForm(forms.Form):
title = forms.CharField(max_length=512)
crib_detail = forms.CharField(widget=forms.Textarea)
class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea, label="Add your comment")<file_sep>/document/urls.py
"""
URL Mapping for Document API
"""
from django.conf.urls import include, patterns, url
from rest_framework.routers import DefaultRouter
from document.views import DocumentViewSet, SectionViewSet
# Configuring ROUTERs
router = DefaultRouter()
router.register(r'page', DocumentViewSet)
router.register(r'section', SectionViewSet)
urlpatterns = patterns(
'',
url(r'^api/', include(router.urls)),
url(r'^api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
)
<file_sep>/notification/views.py
"""
Contains views for the Email Notification app
"""
from django.template.loader import get_template
from django.template import RequestContext
from notification.models import NotificationEmail
def activation_email(user, activation_key, request):
"""
Function to send email to user stored email address for activation of account
"""
html_activation_template = get_template("notification/html_activation_email.html")
text_activation_template = get_template("notification/text_activation_email.html")
parameters = {
"username": user.username,
"activation_key": activation_key
}
html_activation_body = html_activation_template.render(RequestContext(request, parameters))
text_activation_body = text_activation_template.render(RequestContext(request, parameters))
email = NotificationEmail(user=user, service="register_user",
email_subject="Verify Account for Elearning",
text_email_body=text_activation_body,
html_email_body=html_activation_body)
email.send_email()
def forgot_password_email(user, activation_key, request):
"""
Function to send email to user to update password which was lost
"""
html_fp_template = get_template("notification/html_forgot_password_email.html")
text_fp_template = get_template("notification/text_forgot_password_email.html")
parameters = {
"username": user.username,
"activation_key": activation_key
}
html_fp_body = html_fp_template.render(RequestContext(request, parameters))
text_fp_body = text_fp_template.render(RequestContext(request, parameters))
email = NotificationEmail(user=user, service="update_password",
email_subject="Change Password for BodhiTree",
text_email_body=text_fp_body,
html_email_body=html_fp_body)
email.send_email()
<file_sep>/grader/middleware.py
from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile
def get_login_url():
return settings.LOGIN_URL
def get_exempts():
exempts = [compile(get_login_url().lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
exempts += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
return exempts
class LoginRequiredMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'user'), "The Login Required middleware\
requires authentication middleware to be installed. Edit your\
MIDDLEWARE_CLASSES setting to insert\
'django.contrib.auth.middlware.AuthenticationMiddleware'. If that\
doesn't work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
'django.core.context_processors.auth'."
if not request.user.is_authenticated():
path = request.path.lstrip('/')
if not any(m.match(path) for m in get_exempts()):
return HttpResponseRedirect(
get_login_url() + "?next=" + request.path)
'''from django.http import HttpResponseRedirect
from grader.settings import LOGIN_URL
class GraderUrlMiddleware(object):
def process_request(self, request):
if not request.META['REMOTE_ADDR'] == "10.105.1.3":
return
print request.path_info
request.path_info = request.path_info.replace("//static", "/autograder/static")
request.path_info = request.path_info.replace("//", "/")
print "Redirecting to {0}".format(request.path_info)
print request.META['REMOTE_ADDR']
#return HttpResponsePermanentRedirect(request.path)
if not request.user.is_authenticated():
return HttpResponseRedirect(LOGIN_URL)'''
<file_sep>/quiz_old/urls.py
"""
Quiz URL resolver file
"""
from django.conf.urls import include, patterns, url
from quiz.views import QuizViewSet, QuestionModuleViewSet, \
FixedAnswerQuestionViewSet, SubmissionViewSet, QuestionViewSet, view, admin
from rest_framework import routers
# Configuring routers
router = routers.DefaultRouter()
router.register(r'quiz', QuizViewSet)
router.register(r'question_module', QuestionModuleViewSet)
router.register(r'question', QuestionViewSet)
router.register(r'fixed_answer_question', FixedAnswerQuestionViewSet)
router.register(r'submission', SubmissionViewSet)
urlpatterns = patterns('',
url(r'^api/', include(router.urls)),
url(r'^view/', view, name="view"),
url(r'^admin/', admin, name="admin")
)
<file_sep>/TestBed/Python/Student/Syntax/beads.py
T=input()
for a in range(T):
N=input()
b=[in(next) for next in raw_input().split(' ')]
ans=1
for x in b:
ans*=x**(x-1)
ans*=sum(b)**(N-2)
print int(ans)%1000000007<file_sep>/courses/forms.py
'''
Created on May 16, 2013
@author: aryaveer
'''
from django.forms.util import ErrorList
from django import forms
from courses.models import Role
class DivErrorList(ErrorList):
def __unicode__(self):
return self.as_divs()
def as_divs(self):
if not self: return u''
return u'<div class="alert alert-warning">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])
class RoleForm(forms.Form):
roles = (
('S','Student'),
('T', 'Teacher')
)
role = forms.ChoiceField(choices=roles)
def __init__(self, *args, **kwargs):
kwargs['error_class']=DivErrorList
super(RoleForm, self).__init__(*args, **kwargs)
class JoinCourseForm(forms.Form):
choices = [('S', 'Student'),]
name_or_id = forms.CharField(label="Course Name or course code")
role = forms.ChoiceField(
choices=choices,
label="Join as",
)
def __init__(self, *args, **kwargs):
kwargs['error_class']=DivErrorList
super(JoinCourseForm, self).__init__(*args, **kwargs)
def clean_name_or_id(self):
# form field has been cleaned and value is stored in self.cleaned_data
data = self.cleaned_data['name_or_id']
try:
self.course = self.course_class.objects.get(name=data)
except self.course_class.DoesNotExist:
raise forms.ValidationError(["This course does not exist."])
return data
def clean(self):
cleaned_data = super(JoinCourseForm, self).clean()
if self.errors: return cleaned_data
has_joined = Role.objects.filter(user=self.current_user, course=self.course, role=cleaned_data.get('role')).count()
if bool(has_joined):
self._errors['name_or_id'] = self.error_class(["You have already joined this course"])
elif self.current_user == self.course.creater:
self._errors['name_or_id'] = self.error_class(["You are instructor of this course. You cannot join"])
return cleaned_data<file_sep>/courseware/static/courseware/js/grid_template.jsx
/** @jsx React.DOM */
var converter = new Showdown.converter();
var Paginator = React.createClass({
setPage: function(event) {
element_a = $(event.target);
element_li = element_a.parent();
pos = element_li.parent().index();
if (this.props.totalPages <= this.props.maxPages) {
this.props.callback(this.state.start + pos);
}
else {
if (pos == 0) {
start_ = (this.state.start == 1) ? 1 : (this.state.start - 1);
end_ = start_ + this.props.maxPages - 1;
this.setState({start: start_, end: end_});
}
else if (pos == (this.props.maxPages + 1)) {
end_ = (this.state.end == this.props.totalPages) ? this.state.end : (this.state.end + 1);
start_ = end_ - this.props.maxPages + 1;
this.setState({start: start_, end: end_});
}
else {
this.props.callback(this.state.start + pos - 1);
}
}
},
getInitialState: function() {
return {
start: 0,
end: 0
};
},
componentWillMount: function() {
start_ = 1;
end_ = this.props.totalPages > this.props.maxPages ?
this.props.maxPages :
this.props.totalPages;
this.setState({start: start_, end: end_});
},
render: function() {
// parameters:
// maxPages
// totalPages
// callback function
var prev = <div class="col-md-1 no-padding"><a href="javascript:void(0);" class="thumbnail" ref="prev" onClick={this.setPage}><img class="navigators" src="/static/elearning_academy/img/blackleft.jpg" alt="..." /></a></div>;
var next = <div class="col-md-1 no-padding"><a href="javascript:void(0);" class="thumbnail" ref="next" onClick={this.setPage}><img class="navigators" src="/static/elearning_academy/img/blackright.jpg" alt="..." /></a></div>;
pages = [];
for (var i = this.state.start; i <= this.state.end; i++) {
element = <div>{this.props.category[i-1]}</div>;
pages[i-1] = element;
}
/*TODO: Hard Coded, needs to be dynamics
*/
if(this.state.end<=10){
prev = "";
next = "";
}
return (
<div>
<h2 style={{'margin-top': '0px'}}> {this.props.heading} </h2>
<p class='text-info'> {this.props.description} </p>
{prev}
{pages}
{next}
</div>
);
}
});
var MinorList = React.createClass({
mixins: [LoadMixin],
getUrl: function() {
var url = '';
if(this.props.coursepage=='2') {
url = '/courseware/api/' + this.props.suburl + '?' + this.props.subsuburl + this.props.id + '&format=json';
}
else {
url = '/courseware/api/' + this.props.suburl + this.props.id + this.props.subsuburl + '?format=json';
}
return url;
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
render: function() {
if (this.state.loaded) {
var results = this.state.data;
if (this.props.coursepage=='2') {
results = results.results;
}
var categories = results.map(function (category) {
path = "/media/" + category.image;
if (this.props.subhpath == "#" ) {
hrefpath = "#";
}
else {
hrefpath = "/courseware" + this.props.subhpath + "/" + category.id;
}
return <div class="col-md-3">
<div class="thumbnail sliders">
<img class="mimage" src={path} alt="Not Available" />
<a class="caption smallheading" href={hrefpath}><h5>{category.title}</h5>
</a>
</div>
</div>
}.bind(this));
return (
<Paginator
key={this.props.id}
category={categories}
totalPages={categories.length}
maxPages={30}
callback={this.setPage}
/>
);
}
else {
return (
<LoadingBar />
);
}
}
});
var CourseList = React.createClass({
mixins: [LoadMixin],
getUrl: function() {
var url = '';
url = '/courseware/api/all_courses' + '?' + 'format=json';
return url;
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
render: function() {
if (this.state.loaded) {
var results = this.state.data;
if(results.count==0){
return (<div class="col-md-3">
No courses</div>);
}
if (this.props.coursepage=='2') {
results = results.results;
}
var courses = results.map(function (course) {
path = "/media/" + course.image;
if (this.props.subhpath == "#" ) {
hrefpath = "#";
}
else {
hrefpath = "/courseware" + this.props.subhpath + "/" + course.id;
}
return <div class="col-md-3">
<div class="thumbnail sliders-course">
<img class="mimage-course" src={path} alt="Not Available" />
<a class="caption smallheading" href={hrefpath}><h5>{course.title}</h5>
</a>
</div>
</div>
}.bind(this));
return (
<Paginator
key={this.props.id}
category={courses}
totalPages={courses.length}
maxPages={30}
callback={this.setPage}
heading={this.props.heading}
description={this.props.description}
>
</Paginator>
);
}
else {
return (
<LoadingBar />
);
}
}
});
/*var MajorList = React.createClass({
mixins: [LoadMixin],
getUrl: function() {
url = '/courseware/api/' + this.props.myurl + "&format=json";
return url;
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
render: function() {
var categories = '';
if (this.state.loaded) {
categories = this.state.data.results.map(function (category) {
var hrefpath = "/courseware" + this.props.hrefpath + "/" + category.id;
var minorlist = '';
if (this.props.coursepage=='2') {
minorlist = (
<div class="col-md-9">
<MinorList
key={category.id}
suburl={this.props.suburl}
subsuburl={this.props.subsuburl}
subhpath={this.props.subhpath}
coursepage = {this.props.coursepage}
id={category.id} />
</div>
);
}
return <div class="row listrow">
<a class="col-md-3 largeheading" href={hrefpath}>
<h3>{category.title}</h3>
</a>
{minorlist}
</div>;
}.bind(this));
}
else {
categories = <LoadingBar />;
}
return (
<div>
<h2 style={{'margin-top': '0px'}}> {this.props.heading} </h2>
<p class='text-info'> {this.props.description} </p>
<br/>
{categories}
</div>
);
}
});*/
<file_sep>/chat/static/chat/js/chat.jsx
/** @jsx React.DOM */
/**
* @name Chat
* @description React Class for Chat page
* @example
* http://{project_url}/chat/{digit}
*/
var Chat = React.createClass({
/**
* @description Intializes the websocket for chat and initializes the state dictionary
* messages: List of messages exchanged
* onlineUsers: List of online Users on current page
* loaded: boolean. Whether previous chats are loaded on current page
* sendOnEnter: Whether send on enter checkbox is checked
* ws: websocket instance
* limit: how many chats to load at scroll. default is 50
* offset: Lowest chat Id loaded. default is -1. -1 will load all the chats
* allLoaded: Whether all chats of this chatroom is loaded.
* @constructor
* @return {dict}
*/
getInitialState: function(){
var ws = new WebSocket(this.props.wsurl);
ws.onmessage = function(event){
this.showMessage(JSON.parse(event.data));
}.bind(this);
ws.onclose = function(event){
display_global_message("Closing connection to Chat server. Error: " +
event.code + " Reason: "+ event.reason, "error");
}
return {
messages: [],
onlineUsers: [],
replyCount: {},
newReplyCount: {},
loaded: false,
sendOnEnter: false,
ws: ws,
limit: 30,
offset: -1,
allLoaded: false,
}
},
componentDidMount: function() {
if(!this.state.loaded) {
this.loadChats();
}
},
/**
* Loads chats from server and stores them in state key 'messages'
*/
loadChats: function(){
url = this.props.apiurl + "&offset="+this.state.offset + "&limit="+this.state.limit;
request = ajax_json_request(url, "GET", {});
request.done(function(response){
response = jQuery.parseJSON(response);
oldState = this.state;
for (index in response){
var message = response[index];
oldState['messages'].push(message);
oldState['replyCount'][message.id] = message.replyCount;
oldState['newReplyCount'][message.id] = 0;
}
//oldState['messages'] = oldState['messages'].concat(response);
oldState['loaded'] = true;
if (response.length < this.state.limit){
oldState['allLoaded'] = true;
}
if(response.length > 0){
oldState['offset'] = response[response.length -1].id;
}
this.setState(oldState);
}.bind(this));
},
markAsOffensive: function (id) {
url = "/chat/api/chat/" + id + "/report/?format=json";
request = ajax_json_request(url, "POST", {});
request.done(function(response){
response = jQuery.parseJSON(response);
oldState = this.state;
for (var i=0; i< oldState['messages'].length; i++){
if (oldState['messages'][i].id == response.id){
oldState['messages'][i] = response;
}
}
this.setState(oldState);
}.bind(this));
},
/**
* Show chats in case of new chats are arrived via websocket
* @param {json} JSON data arrived in new chat
* @return {void}
*/
showMessage: function(data){
/*
If new user has joined then appened the new User on the top of the list this.state.onlineUsers
*/
if (data.type == 'join'){
oldState = this.state;
oldState['onlineUsers'].unshift({'id': data.userId, 'username': data.username});
this.setState(oldState);
return;
}
/*
If the list of online users is arrived then change the list of online users
*/
if (data.type == 'ou'){
oldState = this.state;
oldState['onlineUsers'] = data.list;
this.setState(oldState);
return;
}
/*
Update onlineUsers in case of an user has left the chat
*/
if (data.type == 'leave'){
oldState = this.state;
var onlineUsers = oldState['onlineUsers'];
for (var i=0; i< oldState['onlineUsers'].length; i++){
if (onlineUsers[i].id == data.userId){
onlineUsers.splice(i, 1);
break;
}
}
oldState['onlineUsers'] = onlineUsers;
this.setState(oldState);
return;
}
/*
Update the list of messages if new chat is arrived
*/
if (data.type == 'text'){
if (this.props.parentId != data.chat.parent){
oldState = this.state;
oldState['replyCount'][data.chat.parent]++;
oldState['newReplyCount'][data.chat.parent]++;
this.setState(oldState);
return;
}
oldState = this.state;
oldState['messages'].unshift(data.chat);
oldState['replyCount'][data.chat.id] = 0;
oldState['newReplyCount'][data.chat.id] = 0;
this.setState(oldState);
return;
}
},
/**
* Send message via websocket
* @param {event} Form submit event
*/
sendMessage: function(event){
event.preventDefault();
message = this.refs.message.getDOMNode().value.trim();
if (message == "" || message == undefined){
return false;
}
this.state.ws.send(message);
$("#message").val("");
},
/**
* Called if submit on enter is checked/unchecked
* @param {event} onClick event
*/
sendMethodChange: function(event){
oldState = this.state;
oldState['sendOnEnter'] = !this.state.sendOnEnter;
this.setState(oldState);
},
/**
* KeyPress event. trigged if keys are pressed when "send on Enter" is checked
* If keypress is "ENTER" without shift then form submit is triggered
* Else normal keypress happens
* @param {event} keyPress event
*/
textareaKeypress: function(event){
if (event.which == 13 && !event.shiftKey){
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
var input = document.getElementById("submitMessageBox");
input.dispatchEvent(event);
}
},
messageOnScroll: function(event){
if (this.state.allLoaded){
return true;
}
var receivedChat = $("#receivedChat");
if(receivedChat.scrollTop() + receivedChat.innerHeight() >= receivedChat[0].scrollHeight) {
this.loadChats();
}
},
render: function () {
if (!this.state.loaded)
{
return <LoadingBar/>
}
/*
List of chat messages
*/
var messages = this.state.messages.map(function(chat, index){
var date = new Date(chat.timestamp);
date = date.toLocaleString();
var classes = "message ";
if (chat.isTeacher){
classes += "message-teacher ";
}
var textclasses = "";
if (chat.offensive){
textclasses = "offensive";
}
var removeIcon = "";
if (this.props.teacher){
removeIcon = (<span class="glyphicon glyphicon-remove" onClick={this.markAsOffensive.bind(this,chat.id)}></span>);
}
return (
<div id={"message-"+chat.id} message-id={chat.id} class={classes}>
<div class="username"><b>{chat.user.username} :</b>
<div class="reply_count">
<b>Replies:</b> all: {this.state.replyCount[chat.id]}, new: {this.state.newReplyCount[chat.id]}
</div>
<div class="timestamp">
<a href={"/chat/reply/" + chat.id} target="_blank"><span class="glyphicon glyphicon-edit"></span>reply</a>
</div>
</div>
<div>
{removeIcon}
<div class="text"><span class={textclasses}>{chat.message}</span><div class="timestamp">{date}</div></div>
</div>
</div>
);
}.bind(this));
/*
List of online users
*/
var onlineUsers = this.state.onlineUsers.map(function(user, index){
return (
<div id={"user-"+user.id}>{user.username}</div>
);
});
/*
Defining textarea keypress event. void(0) if no event needs to be triggered
if sendOnEnter is checked then this.textareaKeypress
Else void(0)
*/
var textareaEvent = void(0);
if (this.state.sendOnEnter) {
textareaEvent = this.textareaKeypress;
}
var allLoadedDiv = <LoadingBar/>;
if (this.state.allLoaded){
allLoadedDiv = (
<div class="allLoaded"> All Chats Loaded</div>
);
}
return (
<div class="row chatbox">
<div class="col-md-12 courseTitle">
<a href={this.props.homeURL}>{this.props.homeTitle}</a>
::
<a href={this.props.parentURL}>{this.props.parentTitle}</a>
</div>
<div class="col-md-10 border-divider">
<form id="messagebox" role="form" onSubmit={this.sendMessage}>
<textarea class="form-control" id="message" ref="message" rows={3} placeholder="Enter your message" onKeyPress={textareaEvent}/>
<input class="btn btn-primary" id="submitMessageBox" style={{marginTop: "5px"}} type="submit" value="Send"/>
<div class="checkbox pull-right">
<input id="enter-checkbox" type="checkbox" checked={this.state.sendOnEnter} onChange={this.sendMethodChange} /> Send message on Enter
</div>
</form>
<div class="received-chat" id="receivedChat" onScroll={this.messageOnScroll}>
{messages}
{allLoadedDiv}
</div>
</div>
<div class="col-md-2 onlinebox">
{onlineUsers}
</div>
</div>
);
},
});<file_sep>/quiz_template/urls.py
"""
Quiz_Template URL resolver file
"""
from django.conf.urls import include, patterns, url
from quiz_template.views import QuizViewSet, QuestionModuleViewSet, \
QuestionMasterViewSet, QuestionScqViewSet, QuestionMcqViewSet, QuestionFixViewSet, \
QuestionDesViewSet, UserSubmissionsViewSet, view
from rest_framework import routers
# Configuring routers
router = routers.DefaultRouter()
router.register(r'quiz', QuizViewSet)
router.register(r'question_module', QuestionModuleViewSet)
router.register(r'question_master', QuestionMasterViewSet)
router.register(r'question_scq', QuestionScqViewSet)
router.register(r'question_mcq', QuestionMcqViewSet)
router.register(r'question_fix', QuestionFixViewSet)
router.register(r'question_des', QuestionDesViewSet)
router.register(r'submission', UserSubmissionsViewSet)
urlpatterns = patterns(
'',
url(r'^api/', include(router.urls)),
url(r'^view/', view, name="view"),
)
<file_sep>/assignments/views.py
from assignments.models import Assignment, AssignmentErrors, AssignmentScript
from assignments.models import Program, ProgramErrors
from assignments.models import Testcase, TestcaseErrors, SafeExec, Checker, CheckerErrors
from evaluate.models import AssignmentResults
from upload.models import Upload
from assignments.forms import AssignmentForm,AssignmentMetaForm
from assignments.forms import ProgramFormCNotE,ProgramFormE,ProgramFormCandE, SafeExecForm, CheckerCodeForm
from upload.forms import UploadForm
from elearning_academy.settings import MEDIA_ROOT, PROJECT_DIR
from utils.archives import get_file_name_list, extract_or_copy
from utils.filetypes import language_category, get_compiler_name, get_interpreter_name, get_compilation_command, get_execution_command, README_LINKS
from django.core.exceptions import PermissionDenied
from django.db.models import Max
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.core.files.storage import default_storage
from django.core.files import File
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.contenttypes.models import ContentType
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.forms import model_to_dict
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.utils import timezone
from courseware.models import Course, CourseHistory, CourseInfo
from datetime import datetime
import os, pickle, json, tempfile
import datetime as DateTime
from django.utils.encoding import smart_str
import mimetypes
from django.core.mail import send_mail
def isCourseCreator(course, user):
try:
course_history = CourseHistory.objects.get(course_id=course, user_id=user.id)
return course_history.is_owner
except:
return False
def isCourseModerator(course, user):
try:
course_history = CourseHistory.objects.get(course_id=course, user_id=user.id)
return course_history.is_owner or course_history.is_moderator
except:
return False
def isEnrolledInCourse(course, user):
try:
course_history = CourseHistory.objects.filter(course_id=course, user_id=user.id)
return len(course_history)>0
except:
return False
@login_required
def index(request, courseID):
''' List all assignments for courseID. courseID is automatically generated
in Course table.'''
course = get_object_or_404(Course, pk=courseID)
all_assignments = Assignment.objects.filter(course=course).order_by('-serial_number')
if CourseHistory.objects.filter(course_id=course, user_id=request.user.id).count() == 0:
return HttpResponseForbidden("Forbidden 403")
course_history = CourseHistory.objects.get(course_id=course, user_id=request.user.id)
course_info = CourseInfo.objects.get(pk=course.course_info_id)
is_creator = isCourseCreator(course, request.user)
is_moderator = isCourseModerator(course, request.user)
if is_moderator:
assignments = all_assignments
leave_course = False
#number_of_students = Role.objects.filter(course=course).count()
number_of_students = 0
else:
assignments = [a for a in all_assignments if a.publish_on <= timezone.now()]
#leave_course = Role.objects.filter(user=request.user, course=course, role='S').count()
leave_course = True
number_of_students = 0
return render_to_response(
'assignments/index.html',
{'assignments': assignments, 'is_moderator': is_moderator, 'course_info':course_info,
'date_time': timezone.now(),
'course': course, 'leave_course': bool(leave_course),
'number_of_students': number_of_students}, context_instance=RequestContext(request),
)
@login_required
def deleteSubmission(request, uploadID):
upload = get_object_or_404(Upload, pk=uploadID)
if not request.user == upload.owner:
return HttpResponseForbidden("Forbidden 403")
assignmentID = upload.assignment.id
upload.delete()
return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID':assignmentID}))
@login_required
def detailsAssignment(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
course_history = CourseHistory.objects.get(course_id=course, user_id=request.user.id)
course_info = CourseInfo.objects.get(pk=course.course_info_id)
is_creator = isCourseCreator(course, request.user)
is_moderator = isCourseModerator(course, request.user)
if timezone.now() < assignment.publish_on and not is_creator and not is_moderator:
raise PermissionDenied
has_joined = CourseHistory.objects.filter(course_id=course, user_id=request.user.id)
if assignment.late_submission_allowed:
submission_allowed = (timezone.now() <= assignment.hard_deadline) and bool(has_joined)
else:
submission_allowed = (timezone.now() <= assignment.deadline) and bool(has_joined)
is_due = (timezone.now() >= assignment.deadline)# and bool(has_joined)
if request.method == "POST" and submission_allowed:
form = UploadForm(request.POST, request.FILES, assignment_model_obj=assignment)
if form.is_valid():
older_upload = Upload.objects.filter(
owner=request.user,
assignment=assignment
)
if older_upload:
older_upload[0].delete()
newUpload = Upload(
owner=request.user,
assignment=assignment,
filePath=request.FILES['docfile']
)
newUpload.save()
return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID':assignmentID}))
else:
form = UploadForm()
perror_ctype = ContentType.objects.get_for_model(ProgramErrors)
terror_ctype = ContentType.objects.get_for_model(TestcaseErrors)
program_errors = []
test_errors = []
for error in AssignmentErrors.objects.filter(assignment=assignment, content_type=terror_ctype):
test_errors.extend(TestcaseErrors.objects.filter(pk=error.object_id))
for error in AssignmentErrors.objects.filter(assignment=assignment, content_type=perror_ctype):
program_errors.extend(ProgramErrors.objects.filter(pk=error.object_id))
course = assignment.course
programs = Program.objects.filter(assignment=assignment)
#test_cases = Testcase.objects.filter(program__in=programs)
practice_program = [a_program for a_program in programs if a_program.program_type == "Practice"]
programs_with_errors = []
for aprogram in programs:
if not aprogram.is_sane:
try:
p_error = ProgramErrors.objects.get(program=aprogram)
programs_with_errors.append(p_error)
except ProgramErrors.DoesNotExist:
p_error = None
submittedFiles = Upload.objects.filter(owner=request.user, assignment=assignment)
program_not_ready = False
disable_grading = False
if programs_with_errors or submission_allowed == False:
program_not_ready = True
if (submittedFiles and submittedFiles[0].is_stale) :
disable_grading = True
all_assignments = Assignment.objects.filter(course=course).order_by('-serial_number')
courseHistory = CourseHistory.objects.get(user=request.user,course=course)
if courseHistory.is_owner:
assignments = all_assignments
else:
assignments = [a for a in all_assignments if a.publish_on <= timezone.now()]
total_sumissions = Upload.objects.filter(assignment=assignment).count()
isSubmitted = Upload.objects.filter(assignment=assignment).count() > 0
get_params = {'source': 'assignment', 'id': assignmentID}
return render_to_response(
'assignments/details.html',
{'assignment': assignment, 'course': course, 'has_joined': has_joined, 'is_moderator':is_moderator,
'programs': programs, 'form': form, 'submission_allowed': submission_allowed,
'submittedFiles': submittedFiles, 'programs_with_errors': programs_with_errors,
'disable_grading': disable_grading, 'program_not_ready':program_not_ready, 'practice_program': practice_program,
'assignments' : assignments, 'program_errors':program_errors, 'test_errors':test_errors,
'published': assignment.publish_on <= timezone.now(), 'is_due': is_due,
'isSubmitted':isSubmitted, 'date_time': timezone.now(), 'get_params': get_params,
'total_sumissions': total_sumissions},
context_instance=RequestContext(request),
)
@login_required
def editAssignment(request, assignmentID):
# Only creator of the course can edit this assignment.
assignment = get_object_or_404(Assignment, pk=assignmentID)
is_moderator = isCourseModerator(assignment.course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if request.method == 'POST':
form = AssignmentForm(request.POST, request.FILES, initial=model_to_dict(assignment))
form.assignment_model = assignment
if form.is_valid():
# check if new file is uploaded
if 'document' in form.changed_data:
if assignment.document:
assignment.document.delete(save=False)
if not form.cleaned_data['document']:
form.cleaned_data.pop('document')
if 'helper_code' in form.changed_data:
if assignment.helper_code:
assignment.helper_code.delete(save=False)
if not form.cleaned_data['helper_code']:
form.cleaned_data.pop('helper_code')
if 'model_solution' in form.changed_data:
if assignment.model_solution:
assignment.model_solution.delete(save=False)
if not form.cleaned_data['model_solution']:
form.cleaned_data.pop('model_solution')
for key in form.cleaned_data.keys():
setattr(assignment, key, form.cleaned_data[key])
for afield in ['model_solution', 'student_program_files', 'program_language']:
if afield in form.changed_data:
assignment.verify_programs = True
assignment.program_model = Program
assignment.changed_list = form.changed_data
break
assignment.save()
if any(f in ['student_program_files', 'helper_code'] for f in form.changed_data):
all_submissions = Upload.objects.select_related('owner').select_for_update().filter(assignment=assignment)
all_submissions.update(is_stale=True)
subject_line = "Evalpro: Please re-submit assignment '{0}' of the course '{1}'".format(assignment.name, assignment.course.title)
message = "Course {0} assignment {1} specification has been changed since you submit your assignment last time. \
You are required to submit your assignment again. Your current submission will not be considered.".format(assignment.course.title, assignment.name)
message_from = 'noreply@evalpro'
message_to = [a.owner.email for a in all_submissions]
try:
send_mail(subject_line, message, message_from,message_to, fail_silently=False)
messages.add_message(request,messages.SUCCESS,"Students have been successfully informed about the changes.")
except Exception as e:
print e.message,type(e)
messages.add_message(request,messages.ERROR,"Students have not been informed about the changes.")
return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID':assignmentID}))
else:
form = AssignmentForm(initial=model_to_dict(assignment))
course = assignment.course
return render_to_response(
'assignments/edit.html',
{'assignment': assignment, 'form': form, 'course': course, 'is_moderator':is_moderator},
context_instance=RequestContext(request),
)
@login_required
def createAssignment(request, courseID):
course = get_object_or_404(Course, pk=courseID)
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if request.method == 'POST':
form = AssignmentForm(request.POST, request.FILES)
form.this_course = course
if form.is_valid():
newAssignment = Assignment(**form.cleaned_data)
newAssignment.course = course
newAssignment.creater = request.user
newAssignment.serial_number = (Assignment.objects.filter(course=course).aggregate(Max('serial_number'))['serial_number__max'] or 0) + 1
newAssignment.save()
link = reverse('assignments_createprogram', kwargs={'assignmentID': newAssignment.id})
messages.success(request, 'Assignment Created! Now <a href="{0}">ADD</a> programs to assignment.'.format(link),
extra_tags='safe'
)
#return HttpResponseRedirect(reverse('assignments_index', kwargs={'courseID':courseID}))
return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID': newAssignment.id}))
else:
form = AssignmentForm()
return render_to_response(
'assignments/createAssignment.html',
{'form':form, 'course': course, 'is_moderator':is_moderator},
context_instance=RequestContext(request)
)
@login_required
def removeAssignment(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
assignment.delete()
return HttpResponseRedirect(reverse('assignments_index', kwargs={'courseID': course.id}))
@login_required
def createProgram(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
# Only creator of course can create new program in assignment.
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if request.method == 'POST':
lang_category = language_category(assignment.program_language)
if(lang_category == 0): #Compilation needed. Execution not needed. C and C++
form = ProgramFormCNotE(request.POST, request.FILES)
elif(lang_category == 1): #Compilation and execution needed.
form = ProgramFormCandE(request.POST, request.FILES)
elif(lang_category == 2): #Execution needed. Python and bash
form = ProgramFormE(request.POST, request.FILES)
form.assignment = assignment # files submitted by student
if form.is_valid():
newProgram = Program(**form.cleaned_data)
newProgram.assignment = assignment
newProgram.is_sane = True
newProgram.compile_now = True
newProgram.execute_now = True
newProgram.language = assignment.program_language
newProgram.save()
link = reverse('assignments_createtestcase', kwargs={'programID': newProgram.id})
messages.success(request, 'Section Created! Now <a href="{0}">ADD</a> testcase for this program.'.format(link),
extra_tags='safe'
)
all_submissions = Upload.objects.filter(assignment=assignment)
AssignmentResults.objects.filter(submission__in=all_submissions).update(is_stale=True)
return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID':assignmentID}))
else:
objs = Program.objects.filter(assignment=assignment)
initial = {}
lang_category = language_category(assignment.program_language)
if objs:
if lang_category == 0:
comp_command = pickle.loads(objs[0].compiler_command)
initial['compiler_command'] = pickle.dumps([comp_command[0], '', ''])
elif lang_category == 1:
comp_command = pickle.loads(objs[0].compiler_command)
initial['compiler_command'] = pickle.dumps([comp_command[0], '', ''])
exe_command = pickle.loads(objs[0].execution_command)
initial['execution_command'] = pickle.dumps([exe_command[0], '', ''])
elif lang_category == 2:
exe_command = pickle.loads(objs[0].execution_command)
initial['execution_command'] = pickle.dumps([exe_command[0], '', ''])
else:
if lang_category == 0:
comp_command = get_compiler_name(assignment.program_language)
initial['compiler_command'] = pickle.dumps([comp_command, '', ''])
elif lang_category == 1:
comp_command = get_compiler_name(assignment.program_language)
initial['compiler_command'] = pickle.dumps([comp_command, '', ''])
exe_command = get_interpreter_name(assignment.program_language)
initial['execution_command'] = pickle.dumps([exe_command, '', ''])
elif lang_category == 2:
exe_command = get_interpreter_name(assignment.program_language)
initial['execution_command'] = pickle.dumps([exe_command, '', ''])
if lang_category == 0 : #Compilation needed. Execution not needed. C and C++
form = ProgramFormCNotE(initial=initial)
elif lang_category == 1 : #Compilation and execution needed.
form = ProgramFormCandE(initial=initial)
elif lang_category == 2 : #Execution needed. Python and bash
form = ProgramFormE(initial=initial)
course = assignment.course
return render_to_response(
'assignments/createProgram.html',
{'form':form, 'assignment': assignment, 'course': course, 'is_moderator':is_moderator},
context_instance=RequestContext(request)
)
@login_required
def editProgram(request, programID):
program = get_object_or_404(Program, pk=programID)
is_moderator = isCourseModerator(program.assignment.course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if request.method == 'POST':
# form is initialized by model then overwritten by request data and files.
lang_category = language_category(program.assignment.program_language)
if(lang_category == 0): #Compilation needed. Execution not needed. C and C++
form = ProgramFormCNotE(request.POST, request.FILES, initial=model_to_dict(program))
elif(lang_category == 1): #Compilation and execution needed.
form = ProgramFormCandE(request.POST, request.FILES, initial=model_to_dict(program))
elif(lang_category == 2): #Execution needed. Python and bash
form = ProgramFormE(request.POST, request.FILES, initial=model_to_dict(program))
form.assignment = program.assignment
form.program_model = program
if form.is_valid():
# check if new file is uploaded
if 'program_files' in form.changed_data: # program_files are changed."
if program.program_files: # delete older file if any.
program.program_files.delete(save=False)
if not form.cleaned_data['program_files']: # if file is being cleared.
form.cleaned_data.pop('program_files')
if 'makefile' in form.changed_data:
if program.makefile:
program.makefile.delete(save=False)
if not form.cleaned_data['makefile']:
form.cleaned_data.pop('makefile')
for key in form.cleaned_data.keys():
setattr(program, key, form.cleaned_data[key])
program.delete_error_message()
program.is_sane = True
for afield in ['program_files', 'compiler_command', 'makefile', 'execution_command']:
if afield in form.changed_data:
program.compile_now = True
program.execute_now = True
break
program.save()
# Mark all assignment results to stale if either program_files or compiler_command or execution_command have changed
changed_fields = ['program_files']
if program.compiler_command:
changed_fields.append('compiler_command')
if program.execution_command:
changed_fields.append('execution_command')
if set(changed_fields) - set(form.changed_data):
all_submissions = Upload.objects.filter(assignment=program.assignment)
AssignmentResults.objects.filter(submission__in=all_submissions).update(is_stale=True)
return HttpResponseRedirect(reverse('assignments_detailsprogram', kwargs={'programID':programID}))
else:
lang_category = language_category(program.assignment.program_language)
if(lang_category == 0): #Compilation needed. Execution not needed. C and C++
form = ProgramFormCNotE(initial=model_to_dict(program))
elif(lang_category == 1): #Compilation and execution needed.
form = ProgramFormCandE(initial=model_to_dict(program))
elif(lang_category == 2): #Execution needed. Python and bash
form = ProgramFormE(initial=model_to_dict(program))
return render_to_response(
'assignments/editProgram.html',
{'form':form, 'program': program},
context_instance=RequestContext(request)
)
@login_required
def detailProgram(request, programID):
program = get_object_or_404(Program, pk=programID)
testcases = Testcase.objects.filter(program=program)
assignment = program.assignment
is_due = (timezone.now() >= assignment.deadline)
course = assignment.course
has_submitted = Upload.objects.filter(owner=request.user, assignment=assignment)
all_assignments = Assignment.objects.filter(course=course).order_by('-serial_number')
is_moderator = isCourseModerator(course, request.user)
if is_moderator:
assignments = all_assignments
else:
assignments = [a for a in all_assignments if a.publish_on <= timezone.now()]
compiler_command = get_compilation_command(program)
execution_command = get_execution_command(program)
program_errors = None
if not program.is_sane:
try:
program_errors = ProgramErrors.objects.get(program=program)
except ProgramErrors.DoesNotExist:
program_errors = None
testcase_errors = []
terror_ctype = ContentType.objects.get_for_model(TestcaseErrors)
for error in AssignmentErrors.objects.filter(assignment=program.assignment, content_type=terror_ctype):
testcase_errors.extend(TestcaseErrors.objects.filter(pk=error.object_id))
get_params = {'source': 'section', 'id': programID}
try:
checker = Checker.objects.filter(program=program)
except Checker.DoesNotExist:
checker = None
if checker:
checker = checker[0]
return render_to_response(
'assignments/detailsProgram.html',
{'program':program, 'testcases':testcases, 'assignment':assignment, 'checker':checker,
'assignments':assignments, 'date_time': timezone.now(),
'program_errors':program_errors, 'compiler_command':compiler_command, 'execution_command':execution_command, 'course':course, 'is_moderator':is_moderator,
'is_due': is_due, 'has_submitted':has_submitted, 'get_params': get_params,
'testcase_errors': testcase_errors},
context_instance=RequestContext(request)
)
@login_required
def removeProgram(request, programID):
program = get_object_or_404(Program, pk=programID)
is_moderator = isCourseModerator(program.assignment.course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
assignment = program.assignment
program.delete()
return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID':assignment.id}))
class CreateTestcaseWizard(SessionWizardView):
file_storage = default_storage
template_name = 'assignments/createTestcasewizard.html'
def dispatch(self, request, *args, **kwargs):
program_id = kwargs['programID']
program = get_object_or_404(Program, pk=program_id)
# self.solution_ready is used in from clean method.
if Testcase.objects.filter(program=program):
self.solution_ready = program.solution_ready
else:
self.solution_ready = bool(program.program_files or program.assignment.model_solution)
is_moderator = isCourseModerator(program.assignment.course, request.user)
if is_moderator:
return super(CreateTestcaseWizard, self).dispatch(request, *args, **kwargs)
else:
return HttpResponseForbidden("Forbidden 403")
def get_form_kwargs(self, step=None):
if step == '0':
return {'solution_ready' : self.solution_ready}
if step == '1':
choice_dict = {}
if self.storage.get_step_files('0'):
if self.storage.get_step_files('0').get('0-input_files', ""):
f_in_obj = self.storage.get_step_files('0').get('0-input_files')
f_in_obj.open()
choice_dict['in_file_choices'] = [(a, a) for a in get_file_name_list(fileobj=f_in_obj)]
if self.storage.get_step_files('0').get('0-output_files', ""):
f_out_obj = self.storage.get_step_files('0').get('0-output_files')
f_out_obj.open()
choice_dict['out_file_choices'] = [(b, b) for b in get_file_name_list(fileobj=f_out_obj)]
return choice_dict
else:
return super(CreateTestcaseWizard, self).get_form_kwargs(step)
def get_context_data(self, form, **kwargs):
context = super(CreateTestcaseWizard, self).get_context_data(form=form, **kwargs)
program = Program.objects.get(pk=self.kwargs['programID'])
compiler_command = get_compilation_command(program)
execution_command = get_execution_command(program)
context.update({'program': program, 'compiler_command': compiler_command, 'execution_command':execution_command})
return context
def done(self, form_list, **kwargs):
frmdict = form_list[0].cleaned_data
frmdict.update(form_list[1].cleaned_data)
program = Program.objects.get(pk=self.kwargs['programID'])
frmdict.update({'program': program})
Testcase.objects.create(**frmdict)
# Remove temporary files
if self.storage.get_step_files('0'):
for a in self.storage.get_step_files('0').values():
try:
os.remove(os.path.join(MEDIA_ROOT, a.name))
except Exception:
pass
all_submissions = Upload.objects.filter(assignment=program.assignment)
AssignmentResults.objects.filter(submission__in=all_submissions).update(is_stale=True)
return HttpResponseRedirect(reverse('assignments_detailsprogram', kwargs={'programID': self.kwargs['programID']}))
class EditTestcaseWizard(SessionWizardView):
file_storage = default_storage
template_name = 'assignments/editTestcasewizard.html'
def dispatch(self, request, *args, **kwargs):
testcase_id = kwargs['testcaseID']
testcase = get_object_or_404(Testcase, pk=testcase_id)
program = testcase.program
# self.solution_ready is used in from clean method.
self.solution_ready = bool(program.program_files or program.assignment.model_solution)
is_moderator = isCourseModerator(program.assignment.course, request.user)
if is_moderator:
return super(EditTestcaseWizard, self).dispatch(request, *args, **kwargs)
else:
return HttpResponseForbidden("Forbidden 403")
def get_form_initial(self, step):
testcase = Testcase.objects.get(pk=self.kwargs['testcaseID'])
return model_to_dict(testcase)
def get_form_kwargs(self, step=None):
if step == '0':
return {'solution_ready' : self.solution_ready}
if step == '1':
choice_dict = {}
testcase = Testcase.objects.get(pk=self.kwargs['testcaseID'])
if self.storage.get_step_files('0'): # if there is at least one file.
if self.storage.get_step_files('0').get('0-input_files', ""): # if input_file is uploaded.
f_in_obj = self.storage.get_step_files('0').get('0-input_files')
f_in_obj.open()
choice_dict['in_file_choices'] = [(a, a) for a in get_file_name_list(fileobj=f_in_obj)]
elif testcase.input_files: # provide options from older file.
choice_dict['in_file_choices'] = [(b, b) for b in get_file_name_list(fileobj=testcase.input_files.file)]
if self.storage.get_step_files('0').get('0-output_files', ""): # if output_file is uploaded.
f_out_obj = self.storage.get_step_files('0').get('0-output_files')
f_out_obj.open()
choice_dict['out_file_choices'] = [(b, b) for b in get_file_name_list(fileobj=f_out_obj)]
elif testcase.output_files: # provide options from older file.
choice_dict['out_file_choices'] = [(b, b) for b in get_file_name_list(fileobj=testcase.output_files.file)]
else: # No file uploaded in step 0
if '0-input_files-clear' not in self.storage.get_step_data('0') and testcase.input_files:
choice_dict['in_file_choices'] = [(b, b) for b in get_file_name_list(fileobj=testcase.input_files.file)]
else:
pass
if '0-output_files-clear' not in self.storage.get_step_data('0') and testcase.output_files:
choice_dict['out_file_choices'] = [(b, b) for b in get_file_name_list(fileobj=testcase.output_files.file)]
return choice_dict
else:
return super(EditTestcaseWizard, self).get_form_kwargs(step)
def get_context_data(self, form, **kwargs):
context = super(EditTestcaseWizard, self).get_context_data(form=form, **kwargs)
testcase = Testcase.objects.get(pk=self.kwargs['testcaseID'])
program = testcase.program
compiler_command = get_compilation_command(program)
execution_command = get_execution_command(program)
context.update({'testcase': testcase, 'compiler_command': compiler_command, 'execution_command':execution_command})
return context
def done(self, form_list, **kwargs):
frmdict = form_list[0].cleaned_data
frmdict.update(form_list[1].cleaned_data) # consolidated list from both steps.
testcase = Testcase.objects.get(pk=self.kwargs['testcaseID'])
if 'input_files' in form_list[0].changed_data: # either new file is being uploaded or older is cleared
if testcase.input_files: # there was an older file in test-case
testcase.input_files.delete(save=False) # delete older file.
if not form_list[0].cleaned_data['input_files']: # no new file so do nothing
form_list[0].cleaned_data.pop('input_files')
if 'output_files' in form_list[0].changed_data:
if testcase.output_files:
testcase.output_files.delete(save=False)
if not form_list[0].cleaned_data['output_files']:
form_list[0].cleaned_data.pop('output_files')
for key in frmdict.keys(): # update database table row.
setattr(testcase, key, frmdict[key])
testcase.save()
files_change = set(['input_files', 'output_files']) - set(form_list[0].changed_data)
stdIO_change = set(['std_in_file_name', 'std_out_file_name']) - set(form_list[1].changed_data)
if files_change or stdIO_change:
testcase = Testcase.objects.get(pk=self.kwargs['testcaseID'])
all_submissions = Upload.objects.filter(assignment=testcase.program.assignment)
AssignmentResults.objects.filter(submission__in=all_submissions).update(is_stale=True)
# Remove temporary files
if self.storage.get_step_files('0'):
for a in self.storage.get_step_files('0').values():
try:
os.remove(os.path.join(MEDIA_ROOT, a.name))
except Exception:
pass
return HttpResponseRedirect(reverse('assignments_detailstestcase', kwargs={'testcaseID': self.kwargs['testcaseID']}))
@login_required
def detailTestcase(request, testcaseID):
testcase = get_object_or_404(Testcase, pk=testcaseID)
course = testcase.program.assignment.course
all_assignments = Assignment.objects.filter(course=course).order_by('-serial_number')
is_moderator = isCourseModerator(course, request.user)
if is_moderator:
assignments = all_assignments
else:
assignments = [a for a in all_assignments if a.publish_on <= timezone.now()]
is_due = (timezone.now() >= testcase.program.assignment.deadline)
get_params = {'source': 'testcase', 'id': testcaseID}
testcase_errors = TestcaseErrors.objects.filter(testcase=testcase)
return render_to_response(
'assignments/detailsTestcase.html',
{'testcase': testcase, 'assignments': assignments, 'date_time': timezone.now(),
'course': course, 'is_due': is_due, 'is_moderator':is_moderator,
'testcase_errors': testcase_errors, 'get_params': get_params},
context_instance=RequestContext(request)
)
@login_required
def removeTestcase(request, testcaseID):
testcase = get_object_or_404(Testcase, pk=testcaseID)
course = testcase.program.assignment.course
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
program = testcase.program
testcase.delete()
return HttpResponseRedirect(reverse('assignments_detailsprogram', kwargs={'programID': program.id}))
@login_required
def config_safeexec_params(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if request.method == 'POST':
form = SafeExecForm(request.POST)
source = request.POST.get('page_source', '')
test_ids = request.POST.getlist('testcases_cbx')
if form.is_valid():
for test_id in test_ids:
testcase_obj = get_object_or_404(Testcase, pk=test_id)
obj = SafeExec.objects.filter(testcase=testcase_obj)
if len(obj) != 0:
form.cleaned_data['testcase'] = testcase_obj
obj.update(**form.cleaned_data)
else:
form.cleaned_data['testcase'] = testcase_obj
SafeExec.objects.create(**form.cleaned_data)
return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID':assignmentID}))
else:
default_limits = {'cpu_time':10, 'clock_time':60,
'memory':32768, 'stack_size':8192,
'child_processes':0, 'open_files':512,
'file_size':1024,}
form = SafeExecForm(initial=default_limits)
source = request.GET.get('source', '')
if source == "section":
section_id = request.GET.get('id', '')
program = get_object_or_404(Program, pk=section_id)
test_cases = Testcase.objects.filter(program=program)
title = program.name
elif source == "testcase":
testcase_id = request.GET.get('id', '')
test_cases = get_object_or_404(Testcase, pk=testcase_id)
title = test_cases.name
else:
programs = Program.objects.filter(assignment=assignment).order_by('name')
test_cases = []
for a_program in programs:
test_cases.append(Testcase.objects.filter(program=a_program).order_by('name'))
#Testcase.objects.filter(program__in=programs)
title = assignment.name
return render_to_response(
'assignments/safeexec_params.html',
{'form': form, 'testcases': test_cases, 'source': source, 'title': title, 'assignment': assignment},
context_instance=RequestContext(request)
)
@login_required
def programList(request):
data = ''
if request.is_ajax():
if request.method == 'GET':
assignmentID = request.GET['asgnid']
assignment = get_object_or_404(Assignment, pk=assignmentID)
programs = Program.objects.filter(assignment=assignment).order_by('-program_type', 'id')
if programs:
for program in programs:
link = reverse('assignments_detailsprogram', kwargs={'programID': program.id})
data = data + '<a class="list-group-item" href="%s" >'
data = data + '<span data-toggle="collapse" data-parent="#a%s" href="#p' + str(program.id) +'" class="sign programs"><span class="glyphicon glyphicon-plus"></span></span> '
data = data + program.name + ' (' + program.program_type + ')'
data = data + '<input type="hidden" class="progid" value="' + str(program.id) + '" />'
data = data + '<input type="hidden" class="loaded-testcases" value="1" /></a>'
data = data + '<div class="collapse list-group-submenu programs" id="p' + str(program.id) +'">'
data = data%(link,str(assignmentID))
program = get_object_or_404(Program, pk=program.id)
testcases = Testcase.objects.filter(program=program).order_by('id')
if testcases:
for testcase in testcases:
link = reverse('assignments_detailstestcase', kwargs={'testcaseID': testcase.id})
data = data + '<a class="list-group-item" href="{0}">' + testcase.name + '</a></li>'
data = data.format(link)
else:
data += '<a class="list-group-item">No testcases for this program</a>'
data = data + '</div>'
else:
data = '<a class="list-group-item">No programs for this assignment</a>'
else:
data = 'Error occurred'
else:
data = 'Error occurred'
return HttpResponse(data)
@login_required
def testcaseList(request):
data = ''
if request.is_ajax():
if request.method == 'GET':
programID = request.GET['progid']
program = get_object_or_404(Program, pk=programID)
testcases = Testcase.objects.filter(program=program).order_by('id')
if testcases:
for testcase in testcases:
link = reverse('assignments_detailstestcase', kwargs={'testcaseID': testcase.id})
data = data + '<a class="list-group-item" href="{0}">' + testcase.name + '</a></li>'
data = data.format(link)
else:
data = '<a class="list-group-item">No testcases for this program</a>'
else:
data = 'Error occurred'
else:
data = 'Error occurred'
return HttpResponse(data)
@login_required
def createChecker(request, programID):
program = get_object_or_404(Program, pk=programID)
course = program.assignment.course
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
try:
checker = Checker.objects.filter(program=program)
except Checker.DoesNotExist:
checker = None
if checker:
messages.success(request, 'Checker Code already exists for this section!!',
extra_tags='safe'
)
return HttpResponseRedirect(reverse('assignments_detailschecker', kwargs={'checkerID': checker[0].id}))
if request.method == 'POST':
form = CheckerCodeForm(request.POST, request.FILES)
if form.is_valid():
newChecker = Checker(**form.cleaned_data)
newChecker.program = program
newChecker.save()
return HttpResponseRedirect(reverse('assignments_detailschecker', kwargs={'checkerID':newChecker.id}))
else:
initial = {}
initial['execution_command'] = pickle.dumps(['python', '', ''])
form = CheckerCodeForm(initial=initial)
return render_to_response(
'assignments/createChecker.html',
{'form':form, 'program': program, 'course': course, 'is_moderator':is_moderator},
context_instance=RequestContext(request)
)
@login_required
def editChecker(request, checkerID):
checker = get_object_or_404(Checker, pk=checkerID)
is_moderator = isCourseModerator(checker.program.assignment.course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if request.method == 'POST':
# form is initialized by model then overwritten by request data and files.
form = CheckerCodeForm(request.POST, request.FILES, initial=model_to_dict(checker))
form.checker_model = checker
if form.is_valid():
# check if new file is uploaded
if 'checker_files' in form.changed_data: # program_files are changed."
if checker.checker_files: # delete older file if any.
checker.checker_files.delete(save=False)
if not form.cleaned_data['checker_files']: # if file is being cleared.
form.cleaned_data.pop('checker_files')
for key in form.cleaned_data.keys():
setattr(checker, key, form.cleaned_data[key])
checker.delete_error_message()
checker.save()
# Mark all assignment results to stale if either program_files or compiler_command or execution_command have changed
changed_fields = ['checker_files']
if checker.execution_command:
changed_fields.append('execution_command')
if set(changed_fields) - set(form.changed_data):
all_submissions = Upload.objects.filter(assignment=checker.program.assignment)
AssignmentResults.objects.filter(submission__in=all_submissions).update(is_stale=True)
return HttpResponseRedirect(reverse('assignments_detailschecker', kwargs={'checkerID':checkerID}))
else:
form = CheckerCodeForm(initial=model_to_dict(checker))
program = checker.program
return render_to_response(
'assignments/editChecker.html',
{'form':form, 'checker': checker, 'program': program},
context_instance=RequestContext(request)
)
@login_required
def detailChecker(request, checkerID):
checker = get_object_or_404(Checker, pk=checkerID)
course = checker.program.assignment.course
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
program = checker.program
all_assignments = Assignment.objects.filter(course=course).order_by('-serial_number')
execution_command = get_execution_command(program)
checker_errors = None
try:
checker_errors = CheckerErrors.objects.get(checker=checker)
except CheckerErrors.DoesNotExist:
checker_errors = None
all_testcases = Testcase.objects.filter(program=checker.program)
return render_to_response(
'assignments/detailsChecker.html',
{'program':program, 'checker':checker, 'assignments': all_assignments, 'assignment':program.assignment, 'testcases':all_testcases,
'checker_errors':checker_errors, 'execution_command':execution_command, 'course':course, 'is_moderator':is_moderator},
context_instance=RequestContext(request)
)
@login_required
def removeChecker(request, checkerID):
checker = get_object_or_404(Checker, pk=checkerID)
is_moderator = isCourseModerator(checker.program.assignment.course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
checker.delete()
program = checker.program
return HttpResponseRedirect(reverse('assignments_detailsprogram', kwargs={'programID':program.id}))
@login_required
def readme(request, courseID, topic):
course = get_object_or_404(Course, pk=courseID)
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if topic in README_LINKS.keys():
return render_to_response(
README_LINKS[topic],
{'course':course},
context_instance=RequestContext(request)
)
else:
return HttpResponseRedirect(reverse('assignments_index', kwargs={'courseID':courseID}))
@login_required
def createAssignmentScript(request, courseID):
course = get_object_or_404(Course, pk=courseID)
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if request.method == 'POST':
form = AssignmentMetaForm(request.POST, request.FILES)
form.this_course = course
if form.is_valid():
newAssignmentScript = AssignmentScript(**form.cleaned_data)
newAssignmentScript.creater = request.user
newAssignmentScript.course = course
newAssignmentScript.save()
metajson = json.load(newAssignmentScript.meta_file.file)
parent_dir = os.path.join(PROJECT_DIR, 'evaluate/safeexec')
temp_dir = tempfile.mkdtemp(prefix="solution")
os.chdir(temp_dir)
extract_or_copy(src=newAssignmentScript.assignment_archive.file.name, dest=os.getcwd())
newAssignmentScript.assignment_archive.close()
next_dir = os.listdir(os.getcwd())
os.chdir(next_dir[0])
newAssignment = createAssignmentFromJson(request, metajson, course)
newAssignment.save()
createProgramTestcasesFromJson(request, newAssignment,metajson)
return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID': newAssignment.id}))
else:
form = AssignmentMetaForm()
return render_to_response(
'assignments/createAssignmentScript.html',
{'form':form, 'course': course, 'is_moderator':is_moderator},
context_instance=RequestContext(request)
)
@login_required
def createAssignmentFromJson(request, jsonobject, course):
asgn_name = jsonobject["assignment_name"]
deadline_str = jsonobject["soft_deadline"]
year = int(deadline_str.split()[0])
month = int(deadline_str.split()[1])
day = int(deadline_str.split()[2])
hour = int(deadline_str.split()[3].split(":")[0])
minute = int(deadline_str.split()[3].split(":")[1])
soft_deadline = DateTime.datetime(year,month,day,hour,minute)
deadline_str = jsonobject["hard_deadline"]
year = int(deadline_str.split()[0])
month = int(deadline_str.split()[1])
day = int(deadline_str.split()[2])
hour = int(deadline_str.split()[3].split(":")[0])
minute = int(deadline_str.split()[3].split(":")[1])
hard_deadline = DateTime.datetime(year,month,day,hour,minute)
if jsonobject["late_submission"] == "Yes":
late_submission = True
else:
late_submission = False
language = jsonobject["language"]
student_files = jsonobject["student_files"]
if "documents" in jsonobject:
documents = jsonobject["documents"]
else:
documents = None
if "helper_code" in jsonobject:
helper_code = jsonobject["helper_code"]
else:
helper_code = None
if "solution_code" in jsonobject:
solution_code = jsonobject["solution_code"]
else:
solution_code = None
deadline_str = jsonobject["publish_date"]
year = int(deadline_str.split()[0])
month = int(deadline_str.split()[1])
day = int(deadline_str.split()[2])
hour = int(deadline_str.split()[3].split(":")[0])
minute = int(deadline_str.split()[3].split(":")[1])
publish_date = DateTime.datetime(year,month,day,hour,minute)
description = jsonobject["asgn_description"]
newAssignment = Assignment(name=asgn_name,program_language=language,deadline=soft_deadline,hard_deadline=hard_deadline,
publish_on=publish_date,late_submission_allowed=late_submission,student_program_files=student_files,
description=description)
newAssignment.course = course
newAssignment.creater = request.user
newAssignment.serial_number = (Assignment.objects.filter(course=course).aggregate(Max('serial_number'))['serial_number__max'] or 0) + 1
if documents:
with open(documents) as f:
newAssignment.document.save(documents, File(f))
if helper_code:
with open(helper_code) as f:
newAssignment.helper_code.save(helper_code, File(f))
if solution_code:
with open(solution_code) as f:
newAssignment.model_solution.save(solution_code, File(f))
newAssignment.save()
return newAssignment
@login_required
def createProgramTestcasesFromJson(request, assignment,jsonobject):
if "sections" in jsonobject:
for progjson in jsonobject["sections"]:
section_name = progjson["section_name"]
section_type = progjson["section_type"]
if "compilation_command" in progjson:
compilation_command = pickle.dumps(progjson["compilation_command"])
else:
compilation_command = None
if "execution_command" in progjson:
execution_command = pickle.dumps(progjson["execution_command"])
else:
execution_command = None
if "section_files" in progjson:
program_files = progjson["section_files"]
else:
program_files = None
if "sec_description" in progjson:
description = progjson["sec_description"]
else:
description = None
newProgram = Program(name=section_name,program_type=section_type)
if program_files:
with open(program_files) as f:
newProgram.program_files.save(program_files, File(f))
if compilation_command:
newProgram.compiler_command = compilation_command
if execution_command:
newProgram.execution_command = execution_command
if description:
newProgram.description = description
newProgram.assignment = assignment
newProgram.is_sane = True
newProgram.compile_now = True
newProgram.execute_now = True
newProgram.language = assignment.program_language
newProgram.save()
if "testcases" in progjson:
for testjson in progjson["testcases"]:
test_name = testjson["testcase_name"]
if "input_files" in testjson:
input_files = testjson["input_files"]
std_input = testjson["std_in_file_name"]
else:
input_files = None
std_input = None
if "output_files" in testjson:
output_files = testjson["output_files"]
std_output = testjson["std_out_file_name"]
else:
output_files = None
std_output = None
if "command_line_args" in testjson:
command_line_args = testjson["command_line_args"]
else:
command_line_args = None
if "marks" in testjson:
marks = testjson["marks"]
else:
marks = None
if "test_description" in testjson:
tdescription = testjson["test_description"]
else:
tdescription = None
newTestcase = Testcase(name=test_name, program=newProgram)
if std_input:
newTestcase.std_in_file_name = std_input
else:
newTestcase.std_in_file_name = "None"
if std_output:
newTestcase.std_out_file_name = std_output
else:
newTestcase.std_out_file_name = "None"
if command_line_args:
newTestcase.command_line_args = command_line_args
if marks:
newTestcase.marks = marks
if tdescription:
newTestcase.tdescription = tdescription
if input_files:
with open(input_files) as f:
newTestcase.input_files.save(input_files,File(f))
if output_files:
with open(output_files) as f:
newTestcase.output_files.save(output_files,File(f))
newTestcase.save()
def file_download(file):
try:
mime = mimetypes.guess_type(file.path)
except:
mime = 'application/octet-stream'
# print mime
response = HttpResponse(mimetype=mime)
# print "size ", os.stat(file.path).st_size
response['Content-Length'] = os.stat(file.path).st_size
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(os.path.basename(file.name))
response['X-Accel-Redirect'] = smart_str(os.path.join('/media', file.name))
return response
@login_required
def solutionDownload(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
# Only creator of course can download solution file in assignment.
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
if not assignment.model_solution:
return HttpResponseNotFound("File not found")
return file_download(assignment.model_solution)
@login_required
def documentDownload(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
# Only creator of course can download solution file in assignment.
if not isEnrolledInCourse(course, request.user):
return HttpResponseForbidden("Forbidden 403")
is_moderator = isCourseModerator(course, request.user)
if timezone.now() < assignment.publish_on and not is_moderator:
return HttpResponseNotFound("Assignment not published")
if not assignment.document:
return HttpResponseNotFound("File not found")
return file_download(assignment.document)
@login_required
def helperCodeDownload(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
# Only creator of course can download solution file in assignment.
if not isEnrolledInCourse(course, request.user):
return HttpResponseForbidden("Forbidden 403")
is_moderator = isCourseModerator(course, request.user)
if timezone.now() < assignment.publish_on and not is_moderator:
return HttpResponseNotFound("Assignment not published")
if not assignment.helper_code:
return HttpResponseNotFound("File not found")
return file_download(assignment.helper_code)
@login_required
def programFileDownload(request, programID):
program = get_object_or_404(Program, pk=programID)
assignment = program.assignment
is_due = (timezone.now() >= assignment.deadline)
course = assignment.course
if not isEnrolledInCourse(course, request.user):
return HttpResponseForbidden("Forbidden 403")
if not program.program_files:
return HttpResponseNotFound("File not found")
is_moderator = isCourseModerator(course, request.user)
if(is_moderator or program.program_type == "Practice" or is_due):
return file_download(program.program_files)
return HttpResponseForbidden("Forbidden 403")
@login_required
def makefileDownload(request, programID):
program = get_object_or_404(Program, pk=programID)
assignment = program.assignment
is_due = (timezone.now() >= assignment.deadline)
course = assignment.course
if not isEnrolledInCourse(course, request.user):
return HttpResponseForbidden("Forbidden 403")
if not program.makefile:
return HttpResponseNotFound("File not found")
is_moderator = isCourseModerator(course, request.user)
if(is_moderator or program.program_type == "Practice" or is_due):
return file_download(program.makefile)
return HttpResponseForbidden("Forbidden 403")
@login_required
def testcaseInputDownload(request, testcaseID):
testcase = get_object_or_404(Testcase, pk=testcaseID)
program = testcase.program
assignment = program.assignment
is_due = (timezone.now() >= assignment.deadline)
course = assignment.course
if not isEnrolledInCourse(course, request.user):
return HttpResponseForbidden("Forbidden 403")
if not testcase.input_files:
return HttpResponseNotFound("File not found")
is_moderator = isCourseModerator(course, request.user)
if(is_moderator or program.program_type == "Practice" or is_due):
return file_download(testcase.input_files)
return HttpResponseForbidden("Forbidden 403")
@login_required
def testcaseOutputDownload(request, testcaseID):
testcase = get_object_or_404(Testcase, pk=testcaseID)
program = testcase.program
assignment = program.assignment
is_due = (timezone.now() >= assignment.deadline)
course = assignment.course
if not isEnrolledInCourse(course, request.user):
return HttpResponseForbidden("Forbidden 403")
if not testcase.output_files:
return HttpResponseNotFound("File not found")
is_moderator = isCourseModerator(course, request.user)
if(is_moderator or program.program_type == "Practice" or is_due):
return file_download(testcase.output_files)
return HttpResponseForbidden("Forbidden 403")
@login_required
def chekerDownload(request, checkerID):
checker = get_object_or_404(Checker, pk=checkerID)
program = checker.program
assignment = program.assignment
is_due = (timezone.now() >= assignment.deadline)
course = assignment.course
if not isEnrolledInCourse(course, request.user):
return HttpResponseForbidden("Forbidden 403")
if not checker.checker_files:
return HttpResponseNotFound("File not found")
is_moderator = isCourseModerator(course, request.user)
if(is_moderator or program.program_type == "Practice" or is_due):
return file_download(checker.checker_files)
return HttpResponseForbidden("Forbidden 403")
<file_sep>/quiz_old/serializers.py
"""
Serializer classes for Django Rest Framework
"""
from rest_framework import serializers
from quiz import models
class QuizSerializer(serializers.ModelSerializer):
"""
Serialization of Quiz model
"""
class Meta:
""" Meta """
model = models.Quiz
read_only_fields = ('marks', 'questions', 'question_modules')
class QuestionModuleSerializer(serializers.ModelSerializer):
"""
Serialization of QuestionModule model
"""
class Meta:
""" Meta """
model = models.QuestionModule
class QuestionSerializer(serializers.ModelSerializer):
"""
Serialization of Question model
"""
is_hint_available = serializers.Field(source='is_hint_available')
class Meta:
""" Meta """
model = models.Question
exclude = ('gradable', 'hint', 'answer_description', 'granularity',
'granularity_hint')
class FixedAnswerQuestionSerializer(serializers.ModelSerializer):
"""
Serialization of FixedAnswerQuestion model
"""
class Meta:
""" Meta """
model = models.FixedAnswerQuestion
exclude = ('question_module', 'quiz')
class SubmissionSerializer(serializers.ModelSerializer):
"""
Serialization of FixedAnswerQuestion model
"""
class Meta:
""" Meta """
model = models.Submission
read_only_fields = ('status', 'is_plagiarised', 'has_been_checked')
class FrontEndQuestionSerializer(serializers.Serializer):
"""
Serializer to show all Question data and user history together
"""
id = serializers.IntegerField()
marks = serializers.FloatField(default=0.0)
attempts = serializers.IntegerField()
description = serializers.CharField()
is_hint_available = serializers.BooleanField(default=False)
type = serializers.CharField(max_length=1)
user_attempts = serializers.IntegerField(default=0)
user_marks = serializers.FloatField(default=0.0)
user_status = serializers.CharField(max_length=1)
hint_taken = serializers.BooleanField(default=False)
hint = serializers.CharField(default=None)
answer_shown = serializers.BooleanField(default=False)
answer = serializers.CharField(default=None)
answer_description = serializers.CharField(default=None)
class FrontEndSubmissionSerializer(serializers.Serializer):
"""
Serialization utility to send back a submission to the front end
"""
status = serializers.CharField()
result = serializers.FloatField()
is_correct = serializers.BooleanField()
attempts_remaining = serializers.IntegerField()
answer = serializers.CharField(default=None)
answer_description = serializers.CharField(default=None)
class PlagiarismSerializer(serializers.Serializer):
"""
Serialization utility for setting a submission to be plagiarised
"""
is_plagiarised = serializers.BooleanField()
class AnswerSubmitSerializer(serializers.Serializer):
"""
Serialization utility for submission of an answer
"""
answer = serializers.CharField()
class AdminQuestionSerializer(serializers.ModelSerializer):
""" All fields of Question model """
class Meta:
""" Meta """
model = models.Question
<file_sep>/evaluate/models.py
from django.db import models
from django.db.models import signals
import os
from assignments.models import Testcase
from upload.models import Upload
from assignments.models import Program
def delete_files(sender, instance, **kwargs):
for field in instance._meta.fields:
if isinstance(field, models.FileField):
filefield = getattr(instance, field.name)
if filefield:
filefield.delete(save=False)
# Model to store the results of an assignment submission for all sections of the assignment.
# Stores only the submission and submitted files fields.
class AssignmentResults(models.Model):
submission = models.ForeignKey(Upload)
submitted_files = models.TextField(null='True')
is_stale = models.BooleanField(default=True)
def get_marks(self, section_type='Evaluate'):
marks = 0
for prgrm_result in ProgramResults.objects.filter(assignment_result=self):
if prgrm_result.program.program_type == section_type:
marks += prgrm_result.get_marks()
return marks
# Model to store the results of a section. Used to manage section results.
# Stores the section, corresponding assignment result (consequently submission), compiler errors, output and return code.
class ProgramResults(models.Model):
program = models.ForeignKey(Program)
assignment_result = models.ForeignKey(AssignmentResults)
missing_file_names = models.TextField(null='true')
compiler_errors = models.TextField(null='true')
compiler_output = models.TextField(null='true')
compiler_return_code = models.IntegerField(null=True, blank=True)
#checker_result = models.TextField(null='true')
def get_marks(self):
marks = 0
for test_result in TestcaseResult.objects.filter(program_result=self):
if test_result.marks:
marks += test_result.marks
return marks
def testcase_upload_path(instance, filename):
assignment = instance.program.assignment
return os.path.join(
assignment.creater.username,
assignment.course.title,
assignment.name,
'testcase-results',
filename
)
# Model to store results of testcases.
# Stores the testcase, program result (consequently submission and assignment), error message, return code, output and status for the testcase,
class TestcaseResult(models.Model):
test_case = models.ForeignKey(Testcase)
program_result = models.ForeignKey(ProgramResults) # test_case and program_result will be unique in table.
error_messages = models.TextField(null='true')
return_code = models.IntegerField(null=True, blank=True)
test_passed = models.BooleanField()
output_files = models.FileField(upload_to='results/%Y/%m/%d', null='true')
marks = models.IntegerField(null=True,blank=True)
signals.pre_delete.connect(delete_files, sender=TestcaseResult, dispatch_uid="delete_testcaseresults")<file_sep>/registration/urls.py
"""
URL mappings for Registration
"""
from django.conf.urls import include, patterns, url
from registration import views
from registration.views import UserViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'register', UserViewSet)
urlpatterns = patterns(
'',
url(r'^api/', include(router.urls)),
url(r'^api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
url(r'^signup/', views.signup, name="signup"),
url(r'^login/', views.login_, name="login"),
url(r'^logout/', views.logout_, name="logout"),
url(r'^activate/(?P<key>\w{32})', views.activate, name="activate"),
url(r'^forgotpassword/', views.forgot_password, name="forgotpassword"),
url(r'^changepassword/(?P<key>\w{32})',
views.update_password,
name="changepassword"),
)
<file_sep>/elearning_academy/views.py
from django.shortcuts import render, redirect
from elearning_academy import settings
def index(request):
"""
this is the home page for elearning website
"""
if request.user.is_authenticated():
return redirect(settings.LOGIN_REDIRECT_URL)
return render(request, 'elearning_academy/welcome.html')
def contact(request):
return render(request, 'elearning_academy/contactus.html')
def team(request):
return render(request, 'elearning_academy/team.html')
def mission(request):
return render(request, 'elearning_academy/mission.html')
def old_site(request):
return render(request, 'elearning_academy/old.html')
<file_sep>/registration/serializers.py
"""
Serializers for the registration API
"""
from rest_framework import serializers
from registration import models
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ('username', 'first_name', 'last_name', 'email')
##TODO More Validation
def validate(self, attrs):
print "VALIDATION CALLED"
try:
email = attrs['email']
except KeyError:
raise serializers.ValidationError("Email field is required")
return attrs
##TODO: This is a hack to throw in validation errors
## else the user is returned a empty string
def get_validation_exclusions(self):
pass
class PasswordSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ('password')
<file_sep>/user_profile/viewsets.py
from rest_framework import mixins, status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import link, action
from rest_framework.permissions import AllowAny
from user_profile.serializers import UserProfileUserProfileSerializer
from user_profile import models
class UserProfileViewSet(viewsets.ModelViewSet):
model = models.UserProfile
serializer_class = UserProfileUserProfileSerializer
permission_classes = [AllowAny]
def get_queryset(self):
queryset = models.UserProfile.objects.all()
def list(self,pk):
queryset = models.UserProfile.objects.all()
serializer = UserProfileUserProfileSerializer(queryset)
return Response({"count": len(serializer.data),
"data": serializer.data})
<file_sep>/courseware/static/courseware/js/category_loader.jsx
/** @jsx React.DOM */
var CategoryLoader = React.createClass({
getInitialState: function() {
return {
loaded: false,
parent_categories: undefined,
categories: undefined,
category_loaded: false,
defaultCategory: undefined,
defaultParentCategory: undefined,
};
},
componentDidMount: function() {
if(!this.state.loaded) {
console.log("getting defaultParentCategory")
this.setState({
defaultCategory: this.props.defaultCategory,
});
if (this.state.defaultCategory) {
url = "/courseware/api/category/" + this.state.defaultCategory + "/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
this.setState({defaultParentCategory: response.parent});
}.bind(this));
}
this.loadParentCategories();
}
},
loadParentCategories: function() {
url = "/courseware/api/parent_category/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
this.setState({parent_categories: response.results, loaded: true});
this.loadCategories(undefined, this.state.defaultParentCategory);
}.bind(this));
},
loadCategories: function(selectObj, parentCategory) {
oldState = this.state;
oldState.category_loaded=false;
this.setState(oldState);
console.log(parentCategory);
if (parentCategory) {
pcid = parentCategory;
} else {
console.log(this.refs.parent_category.getDOMNode());
pcid = this.refs.parent_category.getDOMNode().value.trim();
}
console.log(pcid);
url = "/courseware/api/category/?parent="+ pcid + "&format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.categories = response.results;
oldState.category_loaded=true;
this.setState(oldState);
this.handleCategoryChange();
}.bind(this));
},
handleCategoryChange: function() {
category = this.refs.category.getDOMNode().value.trim();
this.props.callback(category);
},
render: function() {
if (!this.state.loaded){
return (
<LoadingBar />
);
}
else {
console.log(this.state);
var parent_category = this.state.parent_categories.map(
function (category) {
if (category.id != this.state.defaultParentCategory){
return <option value={category.id}>{category.title} </option>;
} else {
return <option value={category.id} selected="selected">{category.title} </option>;
}
}.bind(this));
if (this.state.category_loaded) {
var category = this.state.categories.map(function (cat) {
if (cat.id == this.defaultCategory) {
return <option value={cat.id} selected="selected">{cat.title}</option>;
} else {
return <option value={cat.id}>{cat.title}</option>;
}
});
var category_select =
<select class="form-control" onChange={this.handleCategoryChange} ref="category">
{category}
</select>;
}
else {
category_select =
<select class="form-control" ref="category" disabled>
</select>;
}
return (
<div>
<div class="form-group">
<label class="control-label col-md-3 col-md-offset-0">Parent Category</label>
<div class="col-md-7 col-md-offset-1">
<select onChange={this.loadCategories} ref="parent_category" class="form-control">
{parent_category}
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-md-offset-1">Category</label>
<div class="col-md-7 col-md-offset-1">
{category_select}
</div>
</div>
</div>
)
}
}
});<file_sep>/discussion_forum/views.py
"""
Views for Discussion Forum
Keeping activity for add operations only. Can be extended easily if required
TODO
- introduce user specific variable "follow" for thread
Whether user is following thread or not ?
- introduce 'liked', variable for Thread/Comment/Reply
- handle anonymity while serializing thread/comment/reply: instructor \
can see the User
- send notification to thread subscriber about new content
"""
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.shortcuts import get_object_or_404, render
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action, link
from rest_framework.response import Response
from discussion_forum import models
from discussion_forum import permissions
from discussion_forum import serializers
from courseware.models import Concept
ORDER_CHOICES = ['recent', 'earlier', 'popularity']
PAGINATED_BY = 5
@login_required
def forum(request):
"""
Serves forum.html template
"""
context = {"request": request}
return render(request, "discussion_forum/forum.html", context)
@login_required
def forum_admin(request):
"""
Serves forum.html template
"""
context = {"request": request}
return render(request, "discussion_forum/admin.html", context)
def apply_content_filters(order='recent', queryset=None):
""" Apply sorting_order, disable and pinned filter """
queryset = queryset.filter(disabled=False)
if order == 'earlier':
queryset = queryset.order_by('-pinned', 'created')
elif order == 'popularity':
queryset = queryset.order_by('-pinned', '-popularity', '-created')
else:
#default order recent
queryset = queryset.order_by('-pinned', '-created')
return queryset
def paginated_serializer(request=None, queryset=None, serializer=None):
"""
Returns the serializer containing objects corresponding to paginated page
"""
paginator = Paginator(queryset, PAGINATED_BY)
page = request.QUERY_PARAMS.get('page')
try:
items = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
items = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999),
# deliver last page of results.
items = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
return serializer(items, context=serializer_context)
def get_threads(forum=None, tag=None, request=None, search_term=None):
"""
Return threads according to the specifications.
Returns HTTP_400_BAD_REQUEST if any error occurs.
"""
if tag:
queryset = models.Thread.objects.filter(tags__pk=tag.pk)
else:
queryset = models.Thread.objects.filter(forum=forum)
if search_term:
queryset = queryset.filter(Q(content__icontains=search_term) | Q(title__icontains=search_term))
order = request.QUERY_PARAMS.get('order')
queryset = apply_content_filters(order=order, queryset=queryset)
serializer = paginated_serializer(
request=request,
queryset=queryset,
serializer=serializers.PaginatedThreadSerializer
)
response = serializer.data
for result in response["results"]:
thread = models.Thread.objects.get(pk=result["id"])
result["subscribed"] = thread.subscription.is_subscribed(request.user)
return Response(response)
class DiscussionForumViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
Methods for this ViewSet. Only retrieve and update are allowed
"""
model = models.DiscussionForum
serializer_class = serializers.DiscussionForumSettingSerializer
permission_classes = [permissions.IsForumAdminOrReadOnly]
paginate_by = 2
def retrieve(self, request, pk=None):
""" Returns discussion_forum object along with tags """
forum = get_object_or_404(models.DiscussionForum, pk=pk)
self.check_object_permissions(request, forum)
serializer = serializers.DiscussionForumSerializer(forum)
return Response(serializer.data)
@action(methods=['POST'], permission_classes=(permissions.IsForumAdmin, ))
def add_tag(self, request, pk=None):
"""
Add tag to this DiscussionForum
"""
forum = get_object_or_404(models.DiscussionForum, pk=pk)
self.check_object_permissions(request, forum)
serializer = serializers.ForumTagSerializer(data=request.DATA)
if serializer.is_valid():
tag = models.Tag(
forum=forum,
title=serializer.data['title'],
tag_name=serializer.data['tag_name'],
auto_generated=False
)
tag.save()
return Response(serializers.TagSerializer(tag).data)
else:
content = {"detail": "tag-name should be unique across forum-tags"}
return Response(content, status.HTTP_400_BAD_REQUEST)
@link(permission_classes=([permissions.IsForumUser]))
def activity(self, request, pk):
"""
Returns activities of particular discussion_forum
"""
forum = get_object_or_404(models.DiscussionForum, pk=pk)
self.check_object_permissions(request, forum)
activities = models.Activity.objects.filter(forum=forum)
activities = activities.order_by('-happened_at')
serializer = serializers.ActivitySerializer(activities, many=True)
return Response(serializer.data)
@link(permission_classes=([permissions.IsForumUser]))
def user_setting(self, request, pk):
"""
Returns the user_setting for currently loggedIn user
"""
forum = get_object_or_404(models.DiscussionForum, pk=pk)
self.check_object_permissions(request, forum)
setting = get_object_or_404(
models.UserSetting,
forum=forum,
user=request.user
)
serializer = serializers.UserSettingSerializer(setting)
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumUser, )))
def threads(self, request, pk):
"""
Return list of threads in a particular order
"""
forum = get_object_or_404(models.DiscussionForum, pk=pk)
self.check_object_permissions(request, forum)
return get_threads(forum=forum, tag=None, request=request)
@link(permission_classes=((permissions.IsForumUser, )))
def search_threads(self, request, pk):
"""
Return list of threads in a particular order
"""
search_term = request.GET.get('search', None)
tag = request.GET.get('tag', None)
if tag:
tag = get_object_or_404(models.Tag, pk=tag)
forum = models.DiscussionForum.objects.get(pk=pk)
self.check_object_permissions(request, forum)
return get_threads(forum=forum,
tag=tag,
request=request,
search_term=search_term)
@action(methods=['POST'], permission_classes=((permissions.IsForumUser,)))
def add_thread(self, request, pk=None):
"""
Add a new post to the forum
"""
forum = get_object_or_404(models.DiscussionForum, pk=pk)
self.check_object_permissions(request, forum)
serializer = serializers.ForumThreadSerializer(data=request.DATA)
try:
user_setting = models.UserSetting.objects.get(
forum=forum,
user=request.user
)
except:
content = {'detail': 'Not enough permissions'}
return Response(content, status=status.HTTP_401_UNAUTHORIZED)
if serializer.is_valid():
thread = models.Thread(
forum=forum,
author=request.user,
author_badge=user_setting.badge,
title=serializer.data['title'],
content=serializer.data['content'],
anonymous=serializer.data['anonymous'],
)
thread.save()
forum.thread_count += 1
forum.save()
subscribe = serializer.data['subscribe']
if subscribe:
thread.subscription.subscribe(request.user)
models.Activity.activity(
forum=forum,
user=request.user,
operation=models.ActivityOperation.add,
object_type=models.ActivityObject.thread,
object_id=thread.pk
)
serializer = serializers.ThreadSerializer(thread)
return Response(serializer.data)
else:
content = {"detail": "malformed data"}
return Response(content, status.HTTP_400_BAD_REQUEST)
@link(permission_classes=((permissions.IsForumModerator, )))
def review_content(self, request, pk=None):
"""
Returns list of disabled content to user
"""
forum = get_object_or_404(models.DiscussionForum, pk=pk)
self.check_object_permissions(request, forum)
content_set = models.Content.objects.filter(forum=forum)
content_set = content_set.filter(
Q(spam_count__gt=forum.review_threshold) | Q(disabled=True))
serializer = paginated_serializer(
request=request,
queryset=content_set,
serializer=serializers.PaginatedContentSerializer
)
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumAdmin, )))
def users(self, request, pk=None):
"""
Retuns list of all moderator's UserSetting object
"""
forum = get_object_or_404(models.DiscussionForum, pk=pk)
self.check_object_permissions(request, forum)
queryset = models.UserSetting.objects.filter(forum=forum)
utype = request.QUERY_PARAMS.get('type')
if utype == "moderators":
queryset = queryset.filter(
Q(super_user=True) | Q(moderator=True)
)
elif utype == "search":
search_str = request.QUERY_PARAMS.get('query')
queryset = queryset.filter(user__username__icontains=search_str)
serializer = paginated_serializer(
request=request,
queryset=queryset,
serializer=serializers.PaginatedUserSettingSerializer
)
return Response(serializer.data)
class TagViewSet(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
"""
Methods For this ViewSet
"""
model = models.Tag
serializer_class = serializers.TagSerializer
permission_classes = [permissions.IsForumAdminOrReadOnly]
# Modified IsForumAdminOrReadOnly permission to restrict admin from \
# deleting auto_generated tags
@link(permission_classes=((permissions.IsForumUser, )))
def threads(self, request, pk=None):
""" Return list of threads in a particular order """
tag = get_object_or_404(models.Tag, pk=pk)
self.check_object_permissions(request, tag)
return get_threads(forum=tag.forum, tag=tag, request=request)
class UserSettingViewSet(
mixins.UpdateModelMixin,
#mixins.DestroyModelMixin,: Automatically deleted on dropping course
viewsets.GenericViewSet):
"""
Methods For this ViewSet
"""
model = models.UserSetting
serializer_class = serializers.UserSettingSerializer
permission_classes = [permissions.IsOwnerOrModeratorReadOnly]
@action(methods=['POST'],
permission_classes=((permissions.IsForumModerator, )))
def update_badge(self, request, pk=None):
"""
Updates badge for a Current User. Only course moderator can update \
badge
"""
user_setting = get_object_or_404(models.UserSetting, pk=pk)
self.check_object_permissions(request, user_setting)
# Checking for current user's permission
try:
current_user_setting = models.UserSetting.objects.get(
forum=user_setting.forum,
user=request.user)
except:
content = {"detail": "not enough permission"}
return Response(content, status.HTTP_403_FORBIDDEN)
if not current_user_setting.moderator:
content = {"detail": "not enough permission"}
return Response(content, status.HTTP_403_FORBIDDEN)
serializer = serializers.BadgeSerializer(data=request.DATA)
if serializer.is_valid():
user_setting.badge = serializer.data['badge']
user_setting.save()
serializer = serializers.UserSettingSerializer(user_setting)
return Response(serializer.data)
else:
content = {"detail": "malformed data"}
return Response(content, status.HTTP_400_BAD_REQUEST)
@action(methods=['POST'],
permission_classes=((permissions.IsForumAdmin, )))
def update_moderation_permission(self, request, pk=None):
"""
Update moderator value of UserSetting for this object. Only \
allowed for Super Usersself.
"""
user_setting = get_object_or_404(models.UserSetting, pk=pk)
self.check_object_permissions(request, user_setting)
# Checking for current user's permission
try:
current_user_setting = models.UserSetting.objects.get(
forum=user_setting.forum,
user=request.user)
except:
content = {"detail": "not enough permission"}
return Response(content, status.HTTP_403_FORBIDDEN)
if not current_user_setting.super_user:
content = {"detail": "not enough permission"}
return Response(content, status.HTTP_403_FORBIDDEN)
serializer = serializers.BooleanSerializer(data=request.DATA)
if serializer.is_valid():
user_setting.moderator = serializer.data['mark']
user_setting.save()
serializer = serializers.UserSettingSerializer(user_setting)
return Response(serializer.data)
else:
content = {"detail": "malformed data"}
return Response(content, status.HTTP_400_BAD_REQUEST)
class ContentViewSet(mixins.DestroyModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
Methods For this ViewSet
"""
model = models.Content
serializer_class = serializers.ContentSerializer
permission_classes = [permissions.IsOwnerOrModerator]
def destroy(self, request, pk=None):
"""
Downcast to appropriate class member and delete that content
"""
try:
content = models.Content.objects.get_subclass(id=pk)
self.check_object_permissions(request, content)
content.delete()
response = {"detail": "Content deleted."}
return Response(response, status=status.HTTP_204_NO_CONTENT)
except:
response = {"detail": "invalid delete request"}
return Response(response, status=status.HTTP_400_BAD_REQUEST)
@link(permission_classes=((permissions.IsForumUser, )))
def upvote(self, request, pk=None):
"""
Do upvote for content object
"""
content = get_object_or_404(models.Content, pk=pk)
self.check_object_permissions(request, content)
content.vote_up(request.user)
serializer = serializers.ContentSerializer(content)
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumUser, )))
def downvote(self, request, pk=None):
"""
Do downvote for content object
"""
content = get_object_or_404(models.Content, pk=pk)
self.check_object_permissions(request, content)
content.vote_down(request.user)
serializer = serializers.ContentSerializer(content)
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumUser, )))
def mark_spam(self, request, pk=None):
"""
Mark content as spam. If spam count exceeds threshold then content \
gets disabled
"""
content = get_object_or_404(models.Content, pk=pk)
self.check_object_permissions(request, content)
content.mark_spam(request.user)
if content.disabled:
return Response({"detail": "Content is disabled."})
serializer = serializers.ContentSerializer(content)
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumModerator, )))
def pin_content(self, request, pk=None):
"""
Pin the content
"""
content = get_object_or_404(models.Content, pk=pk)
self.check_object_permissions(request, content)
content.pinned = not content.pinned
content.save()
serializer = serializers.ContentSerializer(content)
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumModerator, )))
def disable(self, request, pk=None):
"""
Disable the content object
"""
content = get_object_or_404(models.Content, pk=pk)
self.check_object_permissions(request, content)
content.disabled = True
content.save()
serializer = serializers.ContentSerializer(content)
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumModerator, )))
def enable(self, request, pk=None):
"""
Disable the content object
"""
content = get_object_or_404(models.Content, pk=pk)
self.check_object_permissions(request, content)
content.disabled = False
content.save()
serializer = serializers.ContentSerializer(content)
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumModerator, )))
def reset_spam_flags(self, request, pk=None):
"""
Reset spam_count and spammers and enable the content
"""
content = get_object_or_404(models.Content, pk=pk)
self.check_object_permissions(request, content)
content.reset_spam_flags()
content.disabled = False
content.save()
serializer = serializers.ContentSerializer(content)
return Response(serializer.data)
class ThreadViewSet(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
"""
Methods For this ViewSet
"""
model = models.Thread
serializer_class = serializers.ThreadSerializer
permission_classes = [permissions.IsOwnerOrModeratorOrReadOnly]
def retrieve(self, request, pk=None):
"""
Send a single thread instance. Perform make_hit operation.
If thread is disabled then it sends HTTP_404_NOT_FOUND
"""
thread = get_object_or_404(models.Thread, pk=pk)
self.check_object_permissions(request, thread)
thread.make_hit()
if thread.disabled:
content = {'detail': 'Content is disabled'}
return Response(content, status=status.HTTP_404_NOT_FOUND)
else:
return Response(serializers.ThreadSerializer(thread).data)
@link(permission_classes=((permissions.IsForumUser, )))
def comments(self, request, pk=None):
"""
Returns list of comments
"""
web_request = request._request
if 'order' in web_request.GET.keys():
order = web_request.GET['order']
else:
order = 'earlier'
thread = get_object_or_404(models.Thread, pk=pk)
self.check_object_permissions(request, thread)
comments = models.Comment.objects.filter(thread=thread)
comments = apply_content_filters(queryset=comments, order=order)
serializer = paginated_serializer(
request=request,
queryset=comments,
serializer=serializers.PaginatedCommentSerializer
)
if serializer.data["previous"] is None:
thread.make_hit()
return Response(serializer.data)
@link(permission_classes=((permissions.IsForumUser, )))
def get_tag_list(self, request, pk=None):
## Get all concept Names for this course
queryset = Concept.objects.filter(is_published=True).filter(group__course_id=pk)
data = {}
data['results'] = queryset.values("id", "title")
return Response(data)
@action(methods=['POST'],
permission_classes=((permissions.IsForumUser, )))
def add_comment(self, request, pk=None):
"""
Add a new comment for to the Thread
"""
thread = get_object_or_404(models.Thread, pk=pk)
self.check_object_permissions(request, thread)
serializer = serializers.ForumContentSerializer(data=request.DATA)
try:
user_setting = models.UserSetting.objects.get(
forum=thread.forum,
user=request.user
)
except:
content = {'detail': 'Not enough permissions'}
return Response(content, status=status.HTTP_401_UNAUTHORIZED)
if serializer.is_valid():
comment = models.Comment(
thread=thread,
forum=thread.forum,
author=request.user,
author_badge=user_setting.badge,
content=serializer.data['content'],
anonymous=serializer.data['anonymous']
)
comment.save()
thread.children_count += 1
thread.save()
models.Activity.activity(
forum=thread.forum,
user=request.user,
operation=models.ActivityOperation.add,
object_type=models.ActivityObject.comment,
object_id=comment.pk
)
return Response(serializers.CommentSerializer(comment).data)
else:
content = {"detail": "inconsistent data"}
return Response(content, status.HTTP_400_BAD_REQUEST)
@action(methods=['POST'],
permission_classes=((permissions.IsForumUser, )))
def add_tag(self, request, pk=None):
"""
Adds a new tag to this thread
"""
thread = get_object_or_404(models.Thread, pk=pk)
self.check_object_permissions(request, thread)
serializer = serializers.IntegerSerializer(data=request.DATA)
if serializer.is_valid():
tag_id = serializer.data['value']
tag = get_object_or_404(models.Tag, pk=tag_id)
if tag.forum == thread.forum:
thread.tags.add(tag)
serializer = serializers.TagSerializer(
thread.tags.all(),
many=True
)
return Response(serializer.data)
content = {"detail": "un-identified tag"}
return Response(content, status.HTTP_400_BAD_REQUEST)
else:
content = {"detail": "malformed data"}
return Response(content, status.HTTP_400_BAD_REQUEST)
@action(methods=['POST'],
permission_classes=((permissions.IsForumUser, )))
def remove_tag(self, request, pk=None):
"""
Removes tag from this thread
"""
thread = get_object_or_404(models.Thread, pk=pk)
self.check_object_permissions(request, thread)
serializer = serializers.IntegerSerializer(data=request.DATA)
if serializer.is_valid():
tag_id = serializer.data['value']
tag = get_object_or_404(models.Tag, pk=tag_id)
if tag.forum == thread.forum:
thread.tags.remove(tag)
serializer = serializers.TagSerializer(
thread.tags.all(),
many=True
)
return Response(serializer.data)
content = {"detail": "un-identified tag"}
return Response(content, status.HTTP_400_BAD_REQUEST)
else:
content = {"detail": "malformed data"}
return Response(content, status.HTTP_400_BAD_REQUEST)
@link(permission_classes=((permissions.IsForumUser, )))
def subscribe(self, request, pk=None):
"""
Subscribe to this thread notifications
"""
thread = get_object_or_404(models.Thread, pk=pk)
self.check_object_permissions(request, thread)
thread.subscription.subscribe(request.user)
response = {"success": "your subscribed to thread notifications"}
response["subscribed"] = True
return Response(response)
@link(permission_classes=((permissions.IsForumUser, )))
def unsubscribe(self, request, pk=None):
"""
Subscribe to this thread notifications
"""
thread = get_object_or_404(models.Thread, pk=pk)
self.check_object_permissions(request, thread)
thread.subscription.unsubscribe(request.user)
response = {"success": "you will no longer recieve notifications"}
response["subscribed"] = False
return Response(response)
class CommentViewSet(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
"""
Methods For this ViewSet
"""
model = models.Comment
serializer_class = serializers.CommentSerializer
permission_classes = [permissions.IsOwnerOrModeratorOrReadOnly]
@link(permission_classes=((permissions.IsForumUser, )))
def replies(self, request, pk=None):
"""
Returns list of replies in discussion_forum
"""
web_request = request._request
if 'order' in web_request.GET.keys():
order = web_request.GET['order']
else:
order = 'earlier'
comment = get_object_or_404(models.Comment, pk=pk)
self.check_object_permissions(request, comment)
replies = models.Reply.objects.filter(comment=comment)
replies = apply_content_filters(queryset=replies, order=order)
serializer = paginated_serializer(
request=request,
queryset=replies,
serializer=serializers.PaginatedReplySerializer
)
return Response(serializer.data)
@action(methods=['POST'],
permission_classes=((permissions.IsForumUser, )))
def add_reply(self, request, pk=None):
"""
Add a new reply for to the comment
"""
comment = get_object_or_404(models.Comment, pk=pk)
self.check_object_permissions(request, comment)
serializer = serializers.ForumContentSerializer(data=request.DATA)
try:
user_setting = models.UserSetting.objects.get(
forum=comment.forum,
user=request.user
)
except:
content = {'detail': 'Not enough permissions'}
return Response(content, status=status.HTTP_401_UNAUTHORIZED)
if serializer.is_valid():
reply = models.Reply(
thread=comment.thread,
comment=comment,
forum=comment.forum,
author=request.user,
author_badge=user_setting.badge,
content=serializer.data['content'],
anonymous=serializer.data['anonymous']
)
reply.save()
comment.children_count += 1
comment.save()
models.Activity.activity(
forum=comment.forum,
user=request.user,
operation=models.ActivityOperation.add,
object_type=models.ActivityObject.reply,
object_id=reply.pk
)
return Response(serializers.ReplySerializer(reply).data)
else:
content = {"detail": "inconsistent data"}
return Response(content, status.HTTP_400_BAD_REQUEST)
class ReplyViewSet(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
"""
Reply ViewSet.
Allowed methods are retrieve, content update and delete
"""
model = models.Reply
serializer_class = serializers.ReplySerializer
permission_classes = [permissions.IsOwnerOrModeratorOrReadOnly]
<file_sep>/registration/models.py
"""
Contains database schema for user registration
"""
from uuid import uuid4
from django.db import models
from django.contrib.auth.models import User
from notification.views import activation_email, forgot_password_email
# Constants
SHORT_TEXT = 63
LONG_TEXT = 255
class Registration(models.Model):
"""
Model for Storing Activation Records of users.
They gets deleted once User get activation
"""
user = models.ForeignKey(User, related_name='User_Registration')
activation_key = models.CharField(max_length=32)
def register(self, request):
""" Generate a new random key """
self.activation_key = uuid4().hex
activation_email(user=self.user, activation_key=self.activation_key, request=request)
def activate(self):
""" Activate user object and delete the table """
self.user.is_active = True
self.user.save()
self.delete()
class EmailUpdate(models.Model):
"""
Model for storing activation record for Email Validation
"""
user = models.ForeignKey(User, related_name='User_EmailUpdate')
new_email = models.CharField(max_length=SHORT_TEXT)
activation_key = models.CharField(max_length=32)
def generate_key(self):
""" Generate a new random key """
self.activation_key = uuid4().hex
def update_email(self):
""" Update email to new one and delete EmailUpdate instance """
self.user.email = self.new_email
self.delete()
class ForgotPassword(models.Model):
"""
Model for storing the users and a unique key related to it
who requested for change of ForgotPassword
"""
user = models.ForeignKey(User, related_name='User_ForgotPassword')
activation_key = models.CharField(max_length=32)
def generate_key(self, request):
""" Generate a new random key """
self.activation_key = uuid4().hex
forgot_password_email(user=self.user, activation_key=self.activation_key, request=request)
def update_password(self, passwd):
"""Update the password for the user"""
self.user.set_password(<PASSWORD>)
self.user.save()
self.delete()
def __unicode__(self):
return self.user.username + " " + self.activation_key
<file_sep>/courses/templates/courses/trash_create_course.html
{% extends "courses/base_courses.html" %}
{% block title %}Courses{% endblock %}
{% block sidebar %}
<h4>Create Course</h4>
{% endblock %}
{% block main %}
{% if messages %}
<div class="alert alert-success">
{% for message in messages %}
<div{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|safe }}</div>
{% endfor %}
</div>
{% endif %}
<form id="courseCreate" action="" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<fieldset>
<legend>Create Course</legend>
<table class="table">
{{ form.as_table }}
<tr><th></th><td>
<input class="btn btn-large btn-info" type="submit" value="Create"/>
</td></tr>
</table>
</fieldset>
</form>
{% endblock %}<file_sep>/assignments/urls.py
from django.conf.urls import patterns, url
from assignments.views import CreateTestcaseWizard, EditTestcaseWizard
from assignments.forms import TestcaseForm, TestcaseForm2
urlpatterns = patterns('assignments.views',
url(r'^(?P<courseID>\d+)$', 'index', name='assignments_index'),
url(r'^create/(?P<courseID>\d+)$', 'createAssignment', name='assignments_create'),
url(r'^createscript/(?P<courseID>\d+)$', 'createAssignmentScript', name='assignments_create_script'),
url(r'^details/(?P<assignmentID>\d+)$', 'detailsAssignment', name='assignments_details'),
url(r'^edit/(?P<assignmentID>\d+)$', 'editAssignment', name='assignments_edit'),
url(r'^delete/(?P<assignmentID>\d+)$', 'removeAssignment', name='assignments_removeassignment'),
url(r'^delete/submission/(?P<uploadID>\d+)$', 'deleteSubmission', name='assignments_deleteassignment'),
url(r'^program/create/(?P<assignmentID>\d+)$', 'createProgram', name='assignments_createprogram'),
url(r'^program/details/(?P<programID>\d+)$', 'detailProgram', name='assignments_detailsprogram'),
url(r'^program/edit/(?P<programID>\d+)$', 'editProgram', name='assignments_editprogram'),
url(r'^program/delete/(?P<programID>\d+)$', 'removeProgram', name='assignments_removeprogram'),
url(r'^checker/create/(?P<programID>\d+)$', 'createChecker', name='assignments_createchecker'),
url(r'^checker/details/(?P<checkerID>\d+)$', 'detailChecker', name='assignments_detailschecker'),
url(r'^checker/edit/(?P<checkerID>\d+)$', 'editChecker', name='assignments_editchecker'),
url(r'^checker/delete/(?P<checkerID>\d+)$', 'removeChecker', name='assignments_removechecker'),
url(r'^program/list/$', 'programList', name='assignment_programlist'),
url(r'^testcase/create/(?P<programID>\d+)$', CreateTestcaseWizard.as_view([TestcaseForm, TestcaseForm2]), name='assignments_createtestcase'),
url(r'^testcase/edit/(?P<testcaseID>\d+)$', EditTestcaseWizard.as_view([TestcaseForm, TestcaseForm2]), name='assignments_edittestcase'),
url(r'^testcase/details/(?P<testcaseID>\d+)$', 'detailTestcase', name='assignments_detailstestcase'),
url(r'^testcase/delete/(?P<testcaseID>\d+)$', 'removeTestcase', name='assignments_removetestcase'),
url(r'^testcase/list/$', 'testcaseList', name='assignment_testcaselist'),
url(r'^config/(?P<assignmentID>\d+)$', 'config_safeexec_params', name='assignments_configsafeexecparams'),
url(r'^(?P<courseID>\d+)/readme/(?P<topic>[A-Z]+)$', 'readme', name='assignments_readme'),
url(r'^solution/download/(?P<assignmentID>\d+)$', 'solutionDownload', name='assignments_downloadsolution'),
url(r'^document/download/(?P<assignmentID>\d+)$', 'documentDownload', name='assignments_downloaddocument'),
url(r'^helpercode/download/(?P<assignmentID>\d+)$', 'helperCodeDownload', name='assignments_downloadhelpercode'),
url(r'^program/programfile/download/(?P<programID>\d+)$', 'programFileDownload', name='program_downloadprogramfile'),
url(r'^program/makefile/download/(?P<programID>\d+)$', 'makefileDownload', name='program_downloadmakefile'),
url(r'^testcase/input/download/(?P<testcaseID>\d+)$', 'testcaseInputDownload', name='testcase_downloadinput'),
url(r'^testcase/output/download/(?P<testcaseID>\d+)$', 'testcaseOutputDownload', name='testcase_downloadoutput'),
url(r'^checker/download/(?P<checkerID>\d+)$', 'chekerDownload', name='checker_downloadchecker'),
)<file_sep>/quiz/models.py
"""
This file contains models for the Quiz module of the e-learning platform
It has models defined for the Quiz, QuestionModule, Question and Submissions
Also defines the model for saving the history for the above
"""
import json
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import pre_save, post_save, pre_delete
from django.dispatch.dispatcher import receiver
from util.models import HitCounter, TimeKeeper
from util.methods import receiver_subclasses
from model_utils.managers import InheritanceManager
import courseware
from courseware import playlist
class Quiz(models.Model):
"""
This class encapsulates the model of a quiz.
"""
title = models.TextField() # title of the quiz
# Number of question modules in Quiz, Auto
question_modules = models.IntegerField(default=0)
# Number of questions in Quiz, Auto
questions = models.IntegerField(default=0)
marks = models.FloatField(default=0.0) # max marks for this quiz
# JSON Object used to maintain the order of question
# modules in the Quiz
playlist = models.TextField(default='[]')
# to check if the quiz is published
is_published = models.BooleanField(default=False)
def update_score(self, difference):
self.marks += difference
self.save()
try:
concept = courseware.models.Concept.objects.get(quizzes__pk=self.id)
concept.update_score(difference)
except:
return
class QuestionModule(models.Model):
"""
Each quiz is composed of several QuestionModules where each QuestionModule
can have 1 or more questions. When the Question Module contains
only one question (thereby serving no purpose other than encapsulating
the question), and you do not want to display/use the content of the
module object itself, set the dummy flag to True
"""
#course = models.ForeignKey(
# Course,
# related_name="QuestionModule_Course",
# db_index=True
#)
quiz = models.ForeignKey(Quiz, related_name='QuestionModule_Quiz')
# title/description of the question module
title = models.TextField()
# Ordering of questions in the module
playlist = models.TextField(default='[]')
# Number of questions in Model, Auto
questions = models.IntegerField(default=0)
# flag whether the module is a dummy (for a single question)
dummy = models.BooleanField(default=False)
class QuizHistory(models.Model):
"""
This class captures the quiz history of a user
"""
quiz = models.ForeignKey(Quiz, related_name='QuizHistory_Quiz')
user = models.ForeignKey(User, related_name='QuizHistory_User')
current_question_module = models.ForeignKey(
QuestionModule, related_name='QuizHistory_QuestionModule', null=True)
marks = models.FloatField(default=0.0)
solved = models.IntegerField(default=0) # Number of questions solved
is_graded = models.BooleanField(default=False)
def progress(self):
data = {}
data['title'] = self.quiz.title
data['score'] = self.marks
data['max_score'] = self.quiz.marks
data['questions'] = self.quiz.questions
data['solved'] = self.solved
return data
def update_score(self, difference):
self.marks += difference
self.save()
try:
concept = courseware.models.Concept.objects.get(quizzes__pk=self.quiz.id)
ch, created = courseware.models.ConceptHistory.objects.get_or_create(
concept=concept, user=self.user)
ch.update_score(difference)
except:
return
class Meta:
"""
question and student combined should be unique
"""
unique_together = ("quiz", "user")
class Question(HitCounter):
"""
This is the basic gradable unit - a question. It can be of multiple types
"""
MANUAL_GRADING = 'M'
DIRECT_GRADING = 'D'
GRADER_TYPES = (
(MANUAL_GRADING, 'Manual Grading'),
(DIRECT_GRADING, 'Direct Grading')
)
SINGLE_CHOICE_QUESTION = 'S'
MULTIPLE_CHOICE_QUESTION = 'M'
FIXED_ANSWER_QUESTION = 'F'
DESCRIPTIVE_ANSWER_QUESTION = 'D'
PROGRAMMING_QUESTION = 'P'
QUESTION_TYPES = (
(SINGLE_CHOICE_QUESTION, 'Single Choice Correct'),
(MULTIPLE_CHOICE_QUESTION, 'Multiple Choice Correct'),
(FIXED_ANSWER_QUESTION, 'Fixed Answer'),
(DESCRIPTIVE_ANSWER_QUESTION, 'Descriptive Answer'),
(PROGRAMMING_QUESTION, 'Programming Question')
)
#course = models.ForeignKey(
# Course,
# related_name="Question_Course",
# db_index=True
#)
quiz = models.ForeignKey(Quiz, related_name="Question_Quiz")
question_module = models.ForeignKey(
QuestionModule,
related_name='Question_QuestionModule',
db_index=True) # index this field
description = models.TextField()
# hint_available = models.BooleanField(default=False)
hint = models.TextField(
help_text="Hint you want to give if any",
blank=True,
null=True)
grader_type = models.CharField(
max_length=1,
help_text="Which grader to use for grading this question",
choices=GRADER_TYPES,
default='D')
#order = models.IntegerField()
answer_description = models.TextField(
help_text="Description of the answer",
blank=True)
marks = models.FloatField(default=0)
gradable = models.BooleanField(default=True)
granularity = models.TextField(
help_text="Enter a string with marks separated by commas. \
Last entry will be repeated until infinity attempts")
# granularity after the hint is given
granularity_hint = models.TextField(
help_text="Enter a string with marks separated by commas. \
Last entry will be repeated until infinity attempts",
blank=True,
null=True)
# type : this fields exists so that the question type can be accessed
# directly. This need not be set explicitly. It is set automatically
# in the child classes
type = models.CharField(
max_length=1,
choices=QUESTION_TYPES,
help_text="Type of question",
)
attempts = models.IntegerField(default=1)
def is_hint_available(self):
""" Whether a hint is available """
if self.hint is not None:
return True
else:
return False
def get_data(self):
""" Get the data of the model as a dict """
return {
'id': self.pk,
'quiz': self.quiz,
'question_module': self.question_module,
'description': self.description,
'hint': self.hint,
'grader_type': self.grader_type,
'type': self.type,
'gradable': self.gradable,
'granularity': self.granularity,
'granularity_hint': self.granularity_hint,
'marks': self.marks,
'attempts': self.attempts,
'answer_description': self.answer_description
}
def get_default_granularity(self, hint=False):
"""
When courseware module is completed, uncomment the below code to
define the default granularity for a course
course_info = self.course.course_info
if hint:
if (course_info.granularity_hint is not None and
course_info.granularity_hint.strip() != ''):
return course_info.granularity_hint
else:
if (course_info.granularity is not None and
course_info.granularity.strip() != ''):
return course_info.granularity
"""
# NOTE on implementation of default granularity:
# It is very naive implementation since I couldn't get the serializer
# to accept Blank value for granularity. So UI send "undefined" to backend
# and backend takes this as a keyword and assignes default value
# In future we may need granularity in a different format since the current
# one seems to be inefficient for larger number of attempts
# Need to comment out lines from courseware models to add granularity
# to course info.
granularity = ""
marks = self.marks
factor = int(marks/self.attempts)
for i in range(self.attempts):
granularity = granularity + str(marks) + ","
marks = marks - factor
granularity = granularity + "0"
#granularity = ((str(self.marks) + ',') * self.attempts) + "0"
return granularity
def save(self, *args, **kwargs):
""" Process some fields before save """
if self.hint is not None and self.hint.strip() == '':
self.hint = None
if (self.granularity is None or
self.granularity.strip() == '' or
self.granularity == 'undefined'):
self.granularity = self.get_default_granularity()
if (self.granularity_hint is None or
self.granularity_hint.strip() == '' or
self.granularity_hint == 'undefined'):
self.granularity_hint = self.get_default_granularity(hint=True)
if self.answer_description is None:
self.answer_description = ''
super(Question, self).save(*args, **kwargs)
objects = InheritanceManager()
class Meta:
"""
This is not an abstract class
"""
abstract = False
class DescriptiveQuestion(Question):
"""
A question with a descriptive answer.
Ideally, this will be graded manually and the answer field will
contain a model answer/guidelines.
"""
answer = models.TextField()
# set the type field of the question
def save(self, *args, **kwargs):
self.type = self.DESCRIPTIVE_ANSWER_QUESTION
super(DescriptiveQuestion, self).save(*args, **kwargs)
class SingleChoiceQuestion(Question):
"""
A question which has only 1 of the possible choices as the correct answer
"""
# JSON Array containing the options
# E.g.: "['Django', 'Ruby', 'Scala']"
options = models.TextField(
help_text='Enter choices one by one')
answer = models.IntegerField(
help_text="Answer will be the (0-based) index of the choice above")
# set the type field of the question
def save(self, *args, **kwargs):
self.type = self.SINGLE_CHOICE_QUESTION
super(SingleChoiceQuestion, self).save(*args, **kwargs)
def get_answer(self, showToUser=False):
"""
Return the answer to this question.
"""
if showToUser:
options = json.loads(self.options)
return options[self.answer]
else:
return self.answer
def get_answer_data(self):
"""
Return answer data packaged up
"""
selected = [False] * len(json.loads(self.options))
selected[self.answer] = True
data = {
'options': self.options,
'selected': json.dumps(selected)
}
return data
class MultipleChoiceQuestion(Question):
"""
A question which may have 1 or more correct answers from
the possible choices
"""
# JSON Array containing the options
# E.g.: "['Django', 'Ruby', 'Scala']"
options = models.TextField(
help_text='Enter choices seperated by comma (no comma at end): \
e.g.: choice_1, choice 2, choice 2')
# JSON Array of Booleans
# E.g.: "[true, false, true]"
answer = models.TextField(
help_text='Answer will be in the form or "[true, false, true]" etc')
# set the type field of the question
def save(self, *args, **kwargs):
self.type = self.MULTIPLE_CHOICE_QUESTION
super(MultipleChoiceQuestion, self).save(*args, **kwargs)
def get_answer(self, showToUser=False):
"""
Return answer for grading if showToUSer not supplied
"""
if showToUser:
i = 0
selected = []
options = json.loads(self.options)
answer = json.loads(self.answer)
for opt in answer:
if opt:
selected.append(options[i])
i = i + 1
return json.dumps(selected)
else:
return self.answer
def get_answer_data(self):
"""
Return answer data packaged up
"""
data = {
'options': self.options,
'selected': self.get_answer()
}
return data
class FixedAnswerQuestion(Question):
"""
A question which has a fixed answer to be input in a text field
"""
# JSON array of acdeptable answers
answer = models.CharField(max_length=128)
def get_answer(self, showToUser=False):
"""
Return the answer to this question.
Ideally we want that we should set the answer_shown in question_history
whenever this is called, but that is expensive. So, wherever we
call get_answer, set answer_shown = True and save.
"""
return json.loads(self.answer)
# TODO : replace the function below to work with a json string
#if showToUser:
# answer = self.answer
# if len(self.answer.split(',')) > 1:
# answer = string.replace(answer, ',', ', ')
# return answer
#else:
# return self.answer.split(',')
def get_answer_data(self):
"""
Return answer data packaged up
"""
data = {
'answer': self.get_answer()
}
return data
# set the type field of the question
def save(self, *args, **kwargs):
self.type = self.FIXED_ANSWER_QUESTION
super(FixedAnswerQuestion, self).save(*args, **kwargs)
class ProgrammingQuestion(Question):
"""
A question which requires the submission of a file to be graded
according to the command given with it
"""
num_testcases = models.IntegerField()
command = models.TextField() # command to compile and run the submission
# string of file extensions separated by comma
acceptable_languages = models.TextField()
# set the type field of the question
def save(self, *args, **kwargs):
self.type = self.PROGRAMMING_QUESTION
super(ProgrammingQuestion, self).save(*args, **kwargs)
class Testcase(models.Model):
"""
A testcase is one of the many inputs against which a ProgrammingQuestion is
to be evaluated
"""
question = models.ForeignKey(
ProgrammingQuestion,
related_name='Testcase_ProgrammingQuestion')
input_text = models.TextField()
correct_output = models.TextField()
class QuestionHistory(models.Model):
"""
This class captures the history of a question associated with each student
"""
question = models.ForeignKey(
Question,
related_name='QuestionHistory_Question')
student = models.ForeignKey(User, related_name='QuestionHistory_User')
attempts = models.IntegerField(default=0)
marks = models.FloatField(default=0.0)
NOT_ATTEMPTED = 'N'
ATTEMPTED_ONCE = 'O'
AWAITING_RESULTS = 'A'
SOLVED = 'S'
status_codes = (
(NOT_ATTEMPTED, 'Not Attempted'),
(ATTEMPTED_ONCE, 'Attempted atleast once'),
(AWAITING_RESULTS, 'Awaiting Results'),
(SOLVED, 'Solved')
)
status = models.CharField(max_length=1, choices=status_codes, default='N')
hint_taken = models.BooleanField(default=False)
answer_shown = models.BooleanField(default=False)
class Meta:
"""
question and student combined should be unique
"""
unique_together = ("question", "student")
class Queue(TimeKeeper):
"""
This is a utility class to store objects that we need to perform actions
on asynchronously - email, notification, grading of programming question
"""
object_id = models.TextField() # id of notification or email or submission
is_processed = models.BooleanField(default=False)
EMAIL = 'E'
NOTIFICATION = 'N'
SUBMISSION = 'S'
object_types = (
(EMAIL, 'Email'),
(NOTIFICATION, 'Notification'),
(SUBMISSION, 'Submission')
)
object_type = models.CharField(
max_length=1,
choices=object_types,
default='E')
info = models.TextField() # extra information
class Submission(TimeKeeper):
"""
A submission is added when a student answers the question. Depending on the
type of grader being used, the evaluation may be instant or waiting
"""
#course = models.ForeignKey(
# Course,
# related_name="Submission_Course",
# db_index=True
#)
question = models.ForeignKey(Question, related_name='Submission_Question')
student = models.ForeignKey(User, related_name='Submission_User')
grader_type = models.CharField(
max_length=1,
choices=Question.GRADER_TYPES,
default='D') # so its easy to know rather than going to question
answer = models.TextField()
# No queue for the time being
#queue_id = models.ForeignKey(Queue, related_name='Submission_Queue')
AWAITING_RESULTS = 'A'
DONE = 'D'
status_codes = (
(AWAITING_RESULTS, 'Awaiting Results'),
(DONE, 'Done')
)
status = models.CharField(
max_length=1,
choices=status_codes,
default=AWAITING_RESULTS)
feedback = models.TextField(default='') # feedback from the grader
result = models.FloatField(default=0.0) # marks given to this submission
is_correct = models.BooleanField(default=False)
is_plagiarised = models.BooleanField(default=False) # plagiarism checking
# has been checked for plagiarism or not
has_been_checked = models.BooleanField(default=False)
@receiver_subclasses(pre_save, Question, "question_pre_save")
def update_question_stats_pre_save(sender, **kwargs):
""" Increase question count by 1 and max_marks"""
instance = kwargs['instance']
if instance.pk is not None: # update
instance.quiz.update_score(-1*(instance.marks))
@receiver_subclasses(post_save, Question, "question_post_save")
def update_question_stats_post_save(sender, **kwargs):
""" Increase question count by 1 and max_marks"""
instance = kwargs['instance']
if kwargs['created']: # create
instance.quiz.questions += 1
instance.question_module.questions += 1
instance.question_module.playlist = playlist.append(instance.id, instance.question_module.playlist)
instance.quiz.save()
instance.quiz.update_score(instance.marks)
instance.question_module.save()
@receiver_subclasses(pre_delete, Question, "question_pre_delete")
def update_question_stats_on_delete(sender, **kwargs):
""" Decrease question count by 1 and max_marks"""
instance = kwargs['instance']
if type(instance) != Question:
# This is necessary otherwise it is called twice: once for parent class
# and other for subclass
instance.quiz.questions -= 1
instance.quiz.save()
instance.quiz.update_score(-1*(instance.marks))
instance.question_module.questions -= 1
instance.question_module.playlist = playlist.delete(instance.question_module.playlist, pk=instance.id)
instance.question_module.save()
@receiver(post_save, sender=QuestionModule)
def update_question_module_stats_post_save(sender, **kwargs):
""" Increase question module count by 1"""
instance = kwargs['instance']
if kwargs['created']: # create
instance.quiz.question_modules += 1
instance.quiz.playlist = playlist.append(instance.id, instance.quiz.playlist)
instance.quiz.save()
@receiver(pre_delete, sender=QuestionModule)
def update_question_module_stats_on_delete(sender, **kwargs):
""" Decrease question module count by 1"""
instance = kwargs['instance']
instance.quiz.question_modules -= 1
instance.quiz.playlist = playlist.delete(instance.quiz.playlist, pk=instance.id)
instance.quiz.save()
#TODO add the above classes for question modules
@receiver(pre_delete, sender=QuestionHistory)
def update_concept_history_on_delete(sender, **kwargs):
"""Update quizhistory marks"""
instance = kwargs['instance']
quiz_history, created = QuizHistory.objects.get_or_create(
quiz=instance.question.quiz, user=instance.student)
quiz_history.update_score(-1*(instance.marks))
<file_sep>/evaluate/views.py
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.http import Http404, HttpResponse
import os, tempfile,json,zipfile
from django.core.servers.basehttp import FileWrapper
import mimetypes
from assignments.models import Program as ProgramModel
from assignments.views import isCourseModerator
from assignments.models import Assignment
from evaluate.models import AssignmentResults,TestcaseResult
from upload.models import Upload
from utils.evaluator import Evaluate, Results
from utils.checkOutput import CustomTestcase
from utils.errorcodes import error_codes, error_msg
# Function to evaluate a submission (passed as submissionID).
# Takes as input the request, submission ID, the section type (evaluate or practice), and the template page to which the response is to be rendered.
def evaluate(request, submissionID, program_type, template):
submission = get_object_or_404(Upload, pk=submissionID)
assignment = submission.assignment
# Checking if the user sending the request is either the owner of the submission or the assignment creator (the only people authorized to evaluate).
is_moderator = isCourseModerator(assignment.course, request.user)
if not (request.user == submission.owner or is_moderator):
raise PermissionDenied
# Checking if the user is a student. Checking if the assignment is past its due date.
is_student = True if (request.user == submission.owner) else False
is_due = (assignment.deadline <= timezone.now())
# Evaluating the submission.
current_dir = os.getcwd()
try:
results = Evaluate(submission).getResults(program_type=program_type)
finally:
os.chdir(current_dir)
return render_to_response(
template,
{'submission': submission, 'assignment': assignment,
'results': results, 'error_code': error_codes, 'is_student': is_student,
'is_due': is_due, 'error_msg': error_msg},
context_instance=RequestContext(request)
)
# Function to evaluate an assignment submission. Called by either the student who submitted the solution or the instructor.
# Takes as input the submission ID and calls evaluate() function above appropriately.
@login_required
def evaluateAssignment(request, submissionID):
'''Compile student's submission run all test cases and display results on html page.'''
return evaluate(request, submissionID, "Evaluate", template='evaluate/results.html')
# Redundant function, but not removed so as to not break the code.
@login_required
def evaluateSubmission(request, submissionID):
return evaluate(request, submissionID, "Evaluate", template='evaluate/results.html')
# Function that evaluates the result for custom input.
# Takes as input the section ID for which the testing is done with custom input.
@login_required
def checkOutput(request, programID):
# Checking if the request method is POST
if request.method == 'POST':
temp_fname = ''
# This stores the input text. If this is not present then a custom testcase file was uploaded (else).
if request.POST.get('inputText'):
# Create a temporary file, and open it as inputFile variable. Read the custom testcase and store it in the file object.
_, temp_fname = tempfile.mkstemp(prefix='user_input')
inputFile = open(temp_fname, 'wb+')
for a_char in request.POST.get('inputText'):
inputFile.write(a_char)
inputFile.close()
inputFile = open(temp_fname)
else:
# If the custom testcase was not given in the text box, then a file was uploaded. It is read from the inputFile attribute of the request.
inputFile = request.FILES.get('inputFile')
# Get the section, assignment and the submission using the programID and user of the requestgiven as input.
program = get_object_or_404(ProgramModel, pk=programID)
assignment = program.assignment
submission = Upload.objects.get(owner=request.user, assignment=assignment)
# TODO: Handle error if there was no submission.
# Create a testcase object using the input file, the section and the submission. Get the results for this custom testcase.
testcaseObject = CustomTestcase(inputFile, program, submission)
if inputFile:
inputFile.close()
old_pwd = os.getcwd()
try:
results = testcaseObject.getResult()
finally:
# Clear all temp files.
if os.path.isfile(temp_fname):
os.remove(temp_fname)
os.chdir(old_pwd)
return render_to_response(
'evaluate/customTestResults.html',
{'assignment': assignment, 'error_msg': error_msg,
'results': results, 'error_code': error_codes, 'program': program},
context_instance=RequestContext(request)
)
else:
raise Http404
# Function to show results for a submission. This is different from the above functions in the sense that the other functions are called to evaluate
# a subsmission while this function is called to retrieve the results for a submission (already evaluated).
@login_required
def showResult(request, submissionID):
# Retrieve the submission object and then retrieve the results of that submission using the Results class.
submission = get_object_or_404(Upload, pk=submissionID)
results = Results(submission, program_type="Evaluate")
course = submission.assignment.course
is_moderator = isCourseModerator(course, request.user)
# if is_moderator:
# return HttpResponseRedirect(reverse('evaluate_evaluationdetails', kwargs={'submissionID': submissionID}))
# else:
# If any results were found then render them.
if results:
assignment = submission.assignment
is_student = True if (request.user == submission.owner) else False
is_moderator = isCourseModerator(assignment.course, request.user)
is_due = (assignment.deadline <= timezone.now())
return render_to_response(
'evaluate/result_table.html',
{'submission': submission, 'assignment': assignment, 'error_msg': error_msg,
'results': results, 'error_code': error_codes, 'is_student': is_student, 'is_due': is_due, 'is_moderator': is_moderator},
context_instance=RequestContext(request)
)
# Function to evaluate all submissions of an assignment.
# Takes as input the assignment ID for which all submissions needs to be evaluated.
@login_required
def eval_all_submissions(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
all_submissions = Upload.objects.filter(assignment=assignment)
# Retrieve all the submissions for this assignment and evaluate them if the submission is stale.
# Then redirect to upload_showAllSubmissions to take care of rendering the results.
current_dir = os.getcwd()
try:
for submission in all_submissions:
if not submission.is_stale:
Evaluate(submission).eval(program_type="Evaluate")
finally:
os.chdir(current_dir)
return HttpResponseRedirect(reverse('upload_showAllSubmissions', kwargs={'assignmentID': assignmentID}))
# Function to run practice testcases on the submission.
# Takes as input the submission ID and calls evaluate() function.
@login_required
def run_practice_test(request, submissionID):
return evaluate(request, submissionID, "Practice", template='evaluate/practice_results.html')
# Function to evaluate submission and render a detailed table of results.
# Takes as input the submission ID and calls evaluate() function. The details of the results are rendered to evaluate/result_table.html.
@login_required
def evaluation_details(request, submissionID):
return evaluate(request, submissionID, "Evaluate", template='evaluate/result_table.html')
"""
JSON FORMAT:
[
{
'id':userid,
'name':username,
'submissionId':submissionId,
'programs':
[
{
'name': prgram_name,
'marks':marks,
'testcases':
[
{
'id' : testcase_result_id,
'name':name,
'marks':marks,
}
]
}
]
'remarks':'remarks'
}
]
"""
def get_all_results_json(assignmentID):
assignment=get_object_or_404(Assignment, pk=assignmentID)
allSubmission = Upload.objects.filter(assignment=assignment)
assignment_results = []
for submission in allSubmission:
if not submission.is_stale:
try:
# Gather the results for the submission.
results = Results(submission, program_type="Evaluate")
# Retrieve the marks and submission ID for each section. This is all we need.
assignment_result_row = {}
assignment_result_row['id'] = submission.owner.id
assignment_result_row['name'] = submission.owner.username
assignment_result_row['submissionId'] = submission.id
assignment_result_row['programs'] = []
for prgm_rslt in results.program_results :
# program_result[prgm_rslt.program_result.program.name] = {'marks': prgm_rslt.marks, 'submissionId' : submission.id}
program_dict = {}
program_dict['name'] = prgm_rslt.program_result.program.name
program_dict['marks'] = prgm_rslt.marks
program_dict['testcases'] = []
for tst_case in prgm_rslt.testResults:
testcase_dict = {}
testcase_dict['id'] = tst_case.id
testcase_dict['name'] = tst_case.test_case.name
testcase_dict['marks'] = tst_case.marks
program_dict['testcases'].append(testcase_dict)
if len(program_dict['testcases']) > 0:
assignment_result_row['programs'].append(program_dict)
assignment_result_row['remarks'] = submission.comments
if len(assignment_result_row["programs"]) > 0:
assignment_results.append(assignment_result_row)
except AssignmentResults.DoesNotExist:
return {}
return assignment_results
##get_evaluation_details_in_csv
def get_evaluation_details_in_csv(request, assignmentID):
#save a file in safeexec/results
assignment=get_object_or_404(Assignment, pk=assignmentID)
allSubmission = Upload.objects.filter(assignment=assignment)
line = ""
header = ""
count = 0
for submission in allSubmission:
if not submission.is_stale:
try:
results = Results(submission, program_type="Evaluate")
line += str(submission.owner.username)+","
if count==0:
header += "username,"
for prgm_rslt in results.program_results :
for tst_case in prgm_rslt.testResults:
line+=str(tst_case.marks)+","
if count == 0:
header+=str(tst_case.test_case.name)+","
if count==0:
header+=str(prgm_rslt.program_result.program.name)+","
line+=str(prgm_rslt.marks)+","
line+="\n"
except AssignmentResults.DoesNotExist:
return {}
count+=1
line = header+"\n"+line
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s.csv'%(assignment.name)
response.write(line)
return response
# Function to retrieve the results of all submissions and render in a good format.
# Takes as input the assignment ID and gathers the results of all submissions.
@login_required
def complete_evaluation_details(request, assignmentID):
template = "evaluate/students_result_table.html"
# Gather the assigment object and then all submissions and section of this assignment.
assignment=get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
all_assignments = Assignment.objects.filter(course=course).order_by('-serial_number')
is_moderator = isCourseModerator(course, request.user)
if is_moderator:
assignments = all_assignments
leave_course = False
number_of_students = 0
else:
assignments = [a for a in all_assignments if a.publish_on <= timezone.now()]
leave_course = True
number_of_students = 0
assignment_results = get_all_results_json(assignmentID);
if len(assignment_results) >0:
table_main_headers = [{"name":"Name","colspan":1,"rowspan":2}]
table_secondary_headers = []
for ar in assignment_results[0]["programs"]:
table_main_headers.append({"name":ar["name"],"colspan":len(ar["testcases"])})
for tc in ar["testcases"]:
table_secondary_headers.append({"name":tc["name"]})
content = []
for ar in assignment_results:
row = {"name":ar["name"]}
row["testcases"] = []
for pr in ar["programs"]:
for tc in pr["testcases"]:
row["testcases"].append({"marks":tc["marks"],"id":tc["id"]})
row["submissionId"] = ar["submissionId"]
row["remarks"] = ar["remarks"]
content.append(row)
table_main_headers.append({"name":"remarks","colspan":1,"rowspan":2})
return render_to_response(
template,
{'assignment': assignment, "table_main_headers":table_main_headers,
"table_secondary_headers":table_secondary_headers,"content":content,
'course':course,'assignments':assignments,'date_time': timezone.now(),
'is_moderator':is_moderator,'data':True},
context_instance=RequestContext(request)
)
else:
return render_to_response(
template,
{'assignment': assignment,'course':course,'assignments':assignments,'date_time': timezone.now(),
'is_moderator':is_moderator},
context_instance=RequestContext(request)
)
@login_required
def get_evaluation_details_in_json(request,assignmentID):
assignment=get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
allSubmission = Upload.objects.filter(assignment=assignment)
programs = ProgramModel.objects.filter(assignment=assignment, program_type="Evaluate")
assignment_results = get_all_results_json(assignmentID)
return HttpResponse(json.dumps(assignment_results), content_type="application/json")
@login_required
def edit_evaluation_details(request,assignmentID):
template = "evaluate/excel.html"
assignment = get_object_or_404(Assignment, pk=assignmentID)
return render_to_response(template,
{"assignment":assignment},
context_instance=RequestContext(request))
@login_required
def format_json_for_excel(request,assignmentID):
assignment_results = get_all_results_json(assignmentID)
response_data = {}
colheaders = ["name"]
for ar in assignment_results[0]["programs"]:
for tc in ar["testcases"]:
colheaders.append(ar["name"]+ " | "+ tc["name"])
response_data["data"] = colheaders
return HttpResponse(json.dumps(response_data),content_type="application/json")
@login_required
def edit_testcase_marks(request):
if request.method == "POST":
pk = request.POST["pk"]
value = request.POST["value"]
t = TestcaseResult.objects.get(id=pk)
course = t.test_case.program.assignment.course
is_moderator = isCourseModerator(course, request.user)
if is_moderator:
t.marks = value
t.save()
return HttpResponse("true")
else:
raise Http404
else:
raise Http404
@login_required
def edit_testcase_comments(request):
if request.method == "POST":
pk = request.POST["pk"]
value = request.POST["value"]
t = Upload.objects.get(id=pk)
course = t.assignment.course
is_moderator = isCourseModerator(course, request.user)
if is_moderator:
t.comments = value
t.save()
return HttpResponse("true")
else:
raise Http404
else:
raise Http404
<file_sep>/quiz_template/models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from model_utils.managers import InheritanceManager
from django.db.models.signals import pre_save, post_save, pre_delete
import json
from util.methods import receiver_subclasses
class Quiz(models.Model):
"""Quiz
title: String
--title of Quiz
questions: int
-- number of questions in Quiz
marks: int
-- total max marks
"""
title = models.TextField()
questions = models.IntegerField(default=0)
marks = models.FloatField(default=0)
class Question_Module(models.Model):
"""Question Module for common question Title
static_text: String | Null
--shared text of multiple questions
title: String
--shared title of multiple questions
quiz: Quiz
-- each question/question set belongs to a quiz
"""
static_text = models.TextField(default="")
title = models.TextField()
quiz = models.ForeignKey(Quiz, related_name="question_modules")
class Question_Master(models.Model):
"""Master Question Table
Stores:
-------
type: String [ mcq | des | fix ]
--Type of Question
title: String | Null
--Title of the question
text: String
--Question Text
module: Question_Module
-- For storing title, common text in set of questions
marks: Stringified JSON Array of Numbers
-- For storing different granularity and marks
hint: String | Null
-- Hint for the question
answer: String
-- IF SCQ - String(int) which denotes correct
-- IF MCQ - Array of integers to denote choices
-- IF FIX - Different sets of possible answers
-- IF DES - Answer of the question
"""
SINGLE_CHOICE_QUESTION = 'scq'
MULTIPLE_CHOICE_QUESTION = 'mcq'
FIXED_ANSWER_QUESTION = 'fix'
DESCRIPTIVE_ANSWER_QUESTION = 'des'
QUESTION_TYPES = (
(SINGLE_CHOICE_QUESTION, 'Single Choice Question'),
(MULTIPLE_CHOICE_QUESTION, 'Multiple Choice Question'),
(FIXED_ANSWER_QUESTION, 'Fixed Answer Question'),
(DESCRIPTIVE_ANSWER_QUESTION, 'Descriptive Answer Question'),
)
type = models.CharField(max_length=3, choices=QUESTION_TYPES)
text = models.TextField()
module = models.ForeignKey(
Question_Module, related_name='module_questions')
marks = models.TextField()
hint = models.TextField(default="")
answer = models.TextField()
attempts = models.IntegerField(default=0)
objects = InheritanceManager()
def cleanup(self):
if self.type not in ["scq", "mcq", "des", "fix"]:
raise ValidationError("Question type " +
self.type +
" is not supported")
def save(self, *args, **kwargs):
"""Processing some fields before save"""
marks = json.loads(self.marks)
self.attempts = len(marks)
super(Question_Master, self).save(*args, **kwargs)
def is_hint_available(self):
if self.hint is None:
return False
if self.hint is not None and self.hint.strip() == '':
return False
else:
return True
def get_max_marks(self):
marks = json.loads(self.marks)
return marks[0]
class Question_Scq(Question_Master):
"""Question_Scq for question with choices - SCQ
options: Stringified JSON Array
--choices for question
explainations: Stringified JSON Array
--explainations for wrong answers
default: String
--default explainations to be used
"""
options = models.TextField()
explainations = models.TextField(default="[]")
default_explanation_correct = models.TextField(default="Answer Correct")
default_explanation_wrong = models.TextField(default="Answer Wrong")
def save(self, *args, **kwargs):
self.type = self.SINGLE_CHOICE_QUESTION
super(Question_Scq, self).save(*args, **kwargs)
def get_answer(self):
options = json.loads(self.options)
return options[int(self.answer)]
class Question_Mcq(Question_Master):
"""Question_Choice for question with choices - SCQ
options: Stringified JSON Array
--choices for question
explainations: Stringified JSON Array
--explainations for wrong answers
default: String
--default explainations to be used
"""
options = models.TextField()
explainations = models.TextField(default="[]")
default_explanation_correct = models.TextField(default="Answer Correct")
default_explanation_wrong = models.TextField(default="Answer Wrong")
def save(self, *args, **kwargs):
self.type = self.MULTIPLE_CHOICE_QUESTION
super(Question_Mcq, self).save(*args, **kwargs)
def get_answer(self):
options = json.loads(self.options)
answers = json.loads(self.answer)
answer = ""
for ans, opt in zip(answers, options):
if ans:
answer += opt + "\n"
print answer
return answer
class Question_Fix(Question_Master):
"""Question_Fix
explainations: Stringified JSON Array
--explainations for wrong answers
default: String
--default explainations to be used
"""
explainations = models.TextField(default="[]")
default_explanation_correct = models.TextField(default="Answer Correct")
default_explanation_wrong = models.TextField(default="Answer Wrong")
def save(self, *args, **kwargs):
self.type = self.FIXED_ANSWER_QUESTION
super(Question_Fix, self).save(*args, **kwargs)
def get_answer(self):
return self.answer
class Question_Des(Question_Master):
"""Question_Des
default: String
--default explainations to be used
"""
default_explanation_correct = models.TextField(default="Answer Correct")
default_explanation_wrong = models.TextField(default="Answer Wrong")
def save(self, *args, **kwargs):
self.type = self.DESCRIPTIVE_ANSWER_QUESTION
super(Question_Des, self).save(*args, **kwargs)
def get_answer(self):
return self.answer
class User_Submissions(models.Model):
"""UserSubmissions for answer submission by student
question: Question_Master
-- question for which submission is made
user: User
-- who made the submission
answer: String
-- answer in format as required by different type of questions
attempts: Integer
-- number of attempts
marks: Float
-- marks scored in the question by user
status: Char
-- IF N - Not attempted even once
-- IF A - Attempted and attempts remain, but wrong
-- IF C - Correct answer, no changes now
-- IF W - all attempts over, answer shown
"""
question = models.ForeignKey(Question_Master)
user = models.ForeignKey(User)
answer = models.TextField(default="")
attempts = models.IntegerField(default=0)
marks = models.FloatField(default=0.0)
hint_taken = models.BooleanField(default=False)
explaination = models.TextField(default="")
NOT_ATTEMPTED = 'N'
ATTEMPTED = 'A'
CORRECT = 'C'
WRONG = 'W'
status_codes = (
(NOT_ATTEMPTED, 'Not Attempted'),
(ATTEMPTED, 'Attempted'),
(CORRECT, 'Correct'),
(WRONG, 'Wrong')
)
status = models.CharField(max_length=1, choices=status_codes, default='N')
def is_answer_shown(self):
if self.status == self.CORRECT or self.status == self.WRONG:
return True
else:
return False
class Meta:
"""
question and user combined should be unique
"""
unique_together = ("question", "user")
@receiver_subclasses(pre_save, Question_Master, "question_pre_save")
def update_question_stats_pre_save(sender, **kwargs):
""" Decrease by previous marks"""
instance = kwargs['instance']
if(type(instance) == Question_Master):
if instance.pk is not None:
instance.module.quiz.marks -= json.loads(instance.marks)[0]
instance.module.quiz.save()
@receiver_subclasses(post_save, Question_Master, "question_post_save")
def update_question_stats_post_save(sender, **kwargs):
""" Increase question count by 1 and max_marks"""
instance = kwargs['instance']
if(type(instance) == Question_Master):
if kwargs['created']:
instance.module.quiz.questions += 1
instance.module.quiz.marks += json.loads(instance.marks)[0]
instance.module.quiz.save()
@receiver_subclasses(pre_delete, Question_Master, "question_pre_delete")
def update_question_stats_on_delete(sender, **kwargs):
""" Decrease question count by 1 and max_marks"""
instance = kwargs['instance']
if (type(instance) == Question):
instance.module.quiz.questions -= 1
instance.module.quiz.marks -= json.loads(instance.marks)[0]
instance.module.quiz.save()
<file_sep>/elearning_academy/templates/elearning_academy/welcome.html
{% extends "elearning_academy/root.html" %}
{% block title %}{{MY_SITE_NAME}}{% endblock %}
{% block cssLinks %} {% endblock %}
{% block body %}
<div class="row">
<div class="col-md-10 col-md-offset-1 white-panel no-padding">
<div class="row">
<div class="col-md-8 upper-white-panel">
<img src="{{STATIC_URL}}elearning_academy/img/index_page_picture.jpg" />
</div>
<div class="col-md-4 right-white-panel">
<h3>{{MY_SITE_NAME}}</h3>
<h4>
Tell me and I forget, teach me and I may remember, involve me and I learn.
</h4>
<h5>- <NAME></h5>
</div>
</div>
<div class="row">
<div class="bottom-white-panel">
<p class="lead">Initiative for Online Classroom Learning by IIT Bombay.</p>
</div>
</div>
</div>
</div>
{% endblock %}
<file_sep>/courses/views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.http import HttpResponseForbidden
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404
from django.forms import model_to_dict
from django.template import RequestContext
from django.db.models import Q
from django.contrib.auth.decorators import login_required
import json
'''
from courses.models import CourseForm
from courses.forms import RoleForm, JoinCourseForm
from courses.models import Course
from courses.models import Role
'''
from courseware.views import student_course_list
@login_required
def index(request):
'''
if request.method == 'POST':
join_course_form = JoinCourseForm(request.POST)
join_course_form.current_user = request.user
join_course_form.course_class = Course
if join_course_form.is_valid():
role = Role(
user = request.user,
course = get_object_or_404(Course, name=request.POST.get('name_or_id')),
role = join_course_form.cleaned_data.get('role')
)
role.save()
return HttpResponseRedirect(reverse('courses.views.index'))
else:
a=2
else:
join_course_form = JoinCourseForm()
'''
allcourses = student_course_list(request)
#courseCreated = Course.objects.filter(creater=request.user)
#courseJoined = Role.objects.filter(user=request.user, role='S')
return render_to_response(
'courses/courses.html',
{'allcourses': allcourses},
context_instance=RequestContext(request)
)
'''
@login_required
def create_course(request):
if request.method == 'POST':
form = CourseForm(request.POST)
if form.is_valid():
newCourse = Course(**form.cleaned_data)
newCourse.creater = request.user
newCourse.save()
return HttpResponseRedirect(reverse('courses.views.index'))
else:
form = CourseForm()
#courseJoined = Course
return render_to_response(
'courses/create_course.html',
{'form':form},
context_instance=RequestContext(request)
)
@login_required
def all_courses(request):
courses = Course.objects.all()[:30]
return render_to_response(
'courses/all_courses.html',
{'courses': courses},
context_instance=RequestContext(request)
)
@login_required
def editCourse(request, courseid):
course = get_object_or_404(Course, pk=courseid)
if not request.user == course.creater:
return HttpResponseForbidden("Forbidden 403")
if request.method == 'POST':
form = CourseForm(request.POST, initial=model_to_dict(course))
if form.is_valid():
for key in form.cleaned_data.keys():
setattr(course, key, form.cleaned_data[key])
course.save()
return HttpResponseRedirect(reverse('assignments_index', kwargs={'courseID': courseid}))
else:
form = CourseForm(initial=model_to_dict(course))
return render_to_response(
'courses/edit_course.html',
{'form':form, 'course': course,},
context_instance=RequestContext(request)
)
@login_required
def delete_course(request, courseid):
course = get_object_or_404(Course, pk=courseid)
if not request.user == course.creater:
return HttpResponseForbidden("Forbidden 403")
course.delete()
return HttpResponseRedirect(reverse('courses_index'))
@login_required
def courseInfo(request, courseid):
course = get_object_or_404(Course, pk=courseid)
#Display course information in main div. In side bar show Course name and a form to join this course
#if it not joined already. We can also show unregister button for those who have registered.
return render_to_response(
'courses/courseDetails.html',
{'course': course},
context_instance=RequestContext(request)
)
@login_required
def joinCourse(request, courseid):
#return a page with sidebar updated. now show leave course button.#
course = get_object_or_404(Course, pk=courseid)
Role.objects.get_or_create(
user=request.user,
course=course,
role='S'
)
return HttpResponseRedirect(reverse('assignments.views.index', kwargs={'courseID': courseid}))
@login_required
def leaveCourse(request, courseid):
# TODO: Implement leaveCourse method.
#return a page with sidebar updated. now show join course button.#
course = get_object_or_404(Course, pk=courseid)
try:
role_obj = Role.objects.get(user=request.user, course=course, role='S')
role_obj.delete()
except Role.DoesNotExist:
pass
return HttpResponseRedirect(reverse('assignments.views.index', kwargs={'courseID': courseid}))
@login_required
def searchCourse(request):
#This view is to serve ajax auto-complete request only.
if request.is_ajax():
term = request.GET.get('term', '')
courses = Course.objects.filter(Q(name__icontains=term) | Q(code__icontains=term))[:10]
results = []
for course in courses:
course_json = {}
course_json['id'] = course.id
course_json['label'] = course.id + ", " + course.title
course_json['value'] = course.title
results.append(course_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
'''<file_sep>/scripts/register_accounts.py
#!/usr/bin/python
"""
Script to register user to a course given CSV
"""
import os
import csv
import sys
sys.path.append(os.getcwd())
os.environ['DJANGO_SETTINGS_MODULE'] = 'elearning_academy.settings'
from django.conf import settings
from courseware.models import Course, CourseHistory
from django.contrib.auth.models import User
from discussion_forum.models import UserSetting
def register_user(file_location, course_id):
reader = csv.DictReader(open(file_location, 'rb'), delimiter='\t')
course = Course.objects.get(pk=course_id)
for record in reader:
email = record['email']
try:
user = User.objects.get(email=email)
ch = CourseHistory(user=user, course=course, active='A')
ch.save()
usersetting = UserSetting(user=user, forum=course.forum, is_active=True)
usersetting.save()
except:
print "Error for ", email
if __name__ == "__main__":
register_user(sys.argv[1], sys.argv[2])
<file_sep>/grader/static/js/myJavaScript.js
function view_callback(data){
if (data.status == 'Success!'){
$('#contenthere').html(data.status);
}else{
for (message in data.status){
$('#contact_errors').append("<p><b>" + message + ":</b>" + data.status["message"] + "</p>");
}
}
}
function getView(ID){
data = $(ID).serializeObject();
Dajaxice.testing.send_message(view_callback, {'form':data});
return false;
}
//ajaxify anchors
$(function() {
$('a').click(function(e) {
if($(this).attr('ajaxify')) {
var newurl = this.href;
$.ajax({
url: $(this).attr('ajaxify'),
dataType:'html',
cache: false,
success : function(data){
history.pushState(null, "", newurl);
//Create jQuery object from the response HTML.
var $response=$(data);
//Query the jQuery object for the values
var oneval = $response.find('#contenthere');
var $title = $('title')
var doctitle = $response.filter('title').text();
document.title = doctitle;
//var subval = $response.filter('#sub').text();
$("#contenthere").html(oneval);
}
})
return false;
}
else {
return true;
}
});
});
// Ajax autocomplete
$(function() {
$("#id_name_or_id").autocomplete({
source: "/courses/searchcourses/"
});
});
<file_sep>/quiz_template/views.py
"""
Views for Quiz_Template
"""
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import link, action
from rest_framework.response import Response
from quiz_template.models import Quiz, Question_Module, Question_Master,\
Question_Mcq, Question_Scq, Question_Fix, Question_Des, User_Submissions
from quiz_template import serializers
from grader import Grader
def view(request):
""" Normal view """
return render(request, 'quiz_template/quiz.html', {})
class QuizViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuizViewSet
"""
model = Quiz
serializer_class = serializers.QuizSerializer
paginate_by = None
@link()
def get_question_modules(self, request, pk=None):
"""
Return list of question modules
"""
quiz = get_object_or_404(Quiz, pk=pk)
self.check_object_permissions(request, quiz)
question_modules = Question_Module.objects.filter(quiz=quiz)
serializer = serializers.QuestionModuleSerializer(question_modules,
many=True)
return Response(serializer.data)
class QuestionModuleViewSet(mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionModuleViewSet
"""
model = Question_Module
serializer_class = serializers.QuestionModuleSerializer
paginate_by = None
def get_question_and_submission_data(self, question, submission):
"""
Get a dict of user history of a question and question data
This function is meant for showing to user and not admin
"""
hint = None
if submission.hint_taken:
hint = question.hint
answer = None
question = Question_Master.objects.get_subclass(pk=question.pk)
if submission.is_answer_shown():
answer = question.get_answer()
data = {
'id': question.pk,
'marks': question.get_max_marks(),
'attempts': question.attempts,
'text': question.text,
'is_hint_available': question.is_hint_available(),
'type': question.type,
'user_attempts': submission.attempts,
'user_marks': submission.marks,
'user_status': submission.status,
'hint_taken': submission.hint_taken,
'hint': hint,
'answer_shown': submission.is_answer_shown(),
'answer': answer,
'explaination': submission.explaination
}
if question.type == question.SINGLE_CHOICE_QUESTION:
data['options'] = question.options
elif question.type == question.MULTIPLE_CHOICE_QUESTION:
data['options'] = question.options
return data
@link()
def get_questions(self, request, pk=None):
"""
Return list of questions
"""
question_module = get_object_or_404(Question_Module, pk=pk)
self.check_object_permissions(request, question_module)
questions = Question_Master.objects.filter(module=question_module)
data = []
for question in questions:
# print "found question ", question
user_submissions, created = User_Submissions.objects.get_or_create(
question=question,
user=request.user
)
user_submissions.save()
data.append(self.get_question_and_submission_data(
question, user_submissions))
serializer = serializers.FrontEndQuestionSerializer(data, many=True)
return Response(serializer.data)
class QuestionMasterViewSet(mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionMasterViewSet
"""
model = Question_Master
serializer_class = serializers.QuestionMasterSerializer
paginate_by = None
@link()
def get_hint(self, request, pk=None):
"""
Return the hint to the questions
"""
question = get_object_or_404(Question_Master, pk=pk)
self.check_object_permissions(request, question)
hint = {
'id': question.pk,
'hint': question.hint
}
try:
submission = User_Submissions.objects.get(
user=request.user,
question=question
)
submission.hint_taken = True
submission.save()
except:
error = {
'status': False,
'detail': 'Submission not found'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
return Response(hint)
@action()
def submit_answer(self, request, pk=None):
"""Submit an answer to a question"""
question = get_object_or_404(Question_Master, pk=pk)
self.check_object_permissions(request, question)
submission = User_Submissions.objects.get(
user=request.user,
question=question
)
if submission.status == submission.CORRECT or submission.status == submission.WRONG:
error = {
'status': False,
'detail': 'Question already answered'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
if submission.is_answer_shown():
error = {
'status': False,
'detail': 'Question already attempted',
}
return Response(error, status.HTTP_400_BAD_REQUEST)
if submission.attempts >= question.attempts:
error = {
'status': False,
'detail': 'Exceeded the maximum number of attempts'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
submission.attempts += 1
attempts_remaining = question.attempts - submission.attempts
serializer = serializers.AnswerSubmitSerializer(data=request.DATA)
print serializer
if serializer.is_valid():
submission.status = User_Submissions.ATTEMPTED
submission.answer = serializer.data['answer']
data = {
'status': submission.status,
'marks': submission.marks,
'attempts_remaining': attempts_remaining,
'explaination': submission.explaination
}
grader = Grader(submission=submission, question=question)
if grader.grade():
submission = grader.submission
data['status'] = submission.status
data['marks'] = submission.marks
data['explaination'] = submission.explaination
if attempts_remaining == 0 or submission.status == User_Submissions.CORRECT:
if grader.the_question is None:
the_question = Question.objects.get_subclass(
pk=submission.question.pk)
data['answer'] = \
the_question.get_answer()
else:
data['answer'] = \
grader.the_question.get_answer()
serializer = serializers.FrontEndSubmissionSerializer(data)
else:
serializer = serializers.FrontEndSubmissionSerializer(data)
# return the result of grading
return Response(serializer.data)
else:
submission.save()
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
class QuestionScqViewSet(mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionScqViewSet
"""
model = Question_Scq
serializer_class = serializers.QuestionScqSerializer
paginate_by = None
class QuestionMcqViewSet(mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionMcqViewSet
"""
model = Question_Mcq
serializer_class = serializers.QuestionMcqSerializer
paginate_by = None
class QuestionFixViewSet(mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionFixViewSet
"""
model = Question_Fix
serializer_class = serializers.QuestionFixSerializer
paginate_by = None
class QuestionDesViewSet(mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionDesViewSet
"""
model = Question_Des
serializer_class = serializers.QuestionDesSerializer
paginate_by = None
class UserSubmissionsViewSet(mixins.CreateModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionModuleViewSet
"""
model = User_Submissions
serializer_class = serializers.UserSubmissionsSerializer
paginate_by = None
<file_sep>/chat/viewsets/chatObj.py
__author__ = 'dheerendra'
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import detail_route
from chat.models import Chat, ChatRoom
from chat.serializers import ChatSerializers
from courseware.permissions import *
class ChatViewSet(viewsets.ModelViewSet):
model = Chat
serializer_class = ChatSerializers
permission_classes = [IsRegistered]
@detail_route(methods=['GET'], permission_classes=[IsRegistered])
def get(self, request, pk):
'''
:raise PermissionError: if user requesting chat isn't registered with course
:param request: django request object
:param pk: Primary key of Chatroom for which chats are being retrieved
:return: rest_framework response object with list of chats
'''
try:
limit = int(request.GET['limit'])
except:
limit = 50
try:
offset = int(request.GET['offset'])
if offset == -1:
raise Exception
except:
offset = 2147483647
''' INT_MAX '''
chatroom = get_object_or_404(ChatRoom, pk=pk)
self.check_object_permissions(request, chatroom.course)
queryset = Chat.objects.all().filter(chatroom=chatroom)\
.filter(parent__isnull=True).order_by('-id').filter(pk__lt=offset)[:limit]
serializer = ChatSerializers(queryset, many=True)
return Response(serializer.data)
@detail_route(methods=['GET'], permission_classes=[IsRegistered])
def reply(self, request, pk):
'''
:raise PermissionError if user requesting the list of chats of replies of another chat isn't registered with
course. (IsRegistered Permission class validates students and teachers)
:param request: Django request object
:param pk: primary key of parent chat
:return: List of chats which are replied to parent chat with pk
'''
try:
limit = int(request.GET['limit'])
except:
limit = 50
try:
offset = int(request.GET['offset'])
if offset == -1:
raise Exception
except:
offset = 2147483647
'''INT_MAX'''
chat = get_object_or_404(Chat, pk=pk)
self.check_object_permissions(request, chat.chatroom.course)
queryset = Chat.objects.all().filter(parent=chat).order_by('-id').filter(pk__lt=offset)[:limit]
serializer = ChatSerializers(queryset, many=True)
return Response(serializer.data)
@detail_route(methods=['POST'], permission_classes=[IsOwner])
def report(self, request, pk):
print pk
chat = get_object_or_404(Chat, pk=pk)
self.check_object_permissions(request, chat.chatroom.course)
chat.hidden, chat.message = chat.message, chat.hidden
chat.offensive = not chat.offensive
chat.save()
serializer = ChatSerializers(chat)
return Response(serializer.data)<file_sep>/courseware/views.py
"""
This file basically contains viewsets for the courseware API
Category API:
- List, Create, Update, Retrieve, Destroy, Partial Update Category
- Get all courses in a category
- Add a course in that category
Course API:
- Retrieve, Update, Partial Update, Destroy info of a course
- Retrieve, Update, Partial update courseinfo
- List all the students in a course with their history
- Create, update, parital update, Retrieve course history
- List all concepts in a course
- Create, Retrieve, Update, Partial Update a concept
CourseHistory API:
- List all the concept history in that coursehistory
Concept API:
- Destroy a concept
- Retrieve, Update Concept history
- playlist
- Create a learning element
"""
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from elearning_academy.permissions import InInstructorOrContentDeveloperMode, get_mode
from elearning_academy.permissions import InInstructorMode, InContentDeveloperMode
from courseware.models import Course, CourseHistory,Group
from courseware.vsserializers.course import CourseSerializer, CourseInfoSerializer
from rest_framework import status
from django.http import HttpResponse
import json
from django.utils import timezone
inInstructorOrContentDeveloperModeObject = InInstructorOrContentDeveloperMode()
inInstructorModeObject = InInstructorMode()
inContentDeveloperModeObject = InContentDeveloperMode()
def parent_categories(request):
"""
Serves parent_categories.html template
"""
context = {"request": request}
return render(request, "category/parent_categories.html", context)
def categories(request, pk):
"""
Serves categories.html template
"""
context = {"request": request, "pk": pk}
return render(request, "category/categories.html", context)
@login_required
def add_course(request):
"""
Serves course_admin.html template
"""
if request.user.get_profile().is_instructor:
context = {"request": request}
return render(request, "course/course_admin.html", context)
else:
context = {
"request": request,
"error": "You have to be an instructor to add a course."
}
return render(request, "error.html", context)
def courses(request, pk):
"""Serves categories courses"""
context = {"request": request, 'pk': pk}
return render(request, "category/courses.html", context)
@login_required
def course(request, pk=None, ref=None):
"""Serves a course main page"""
_course = get_object_or_404(Course, pk=pk)
context = {"request": request, "course": _course}
if ref is not None and len(ref) > 0:
context["ref"] = ref
else:
context["ref"] = "-1"
mode = get_mode(request)
history = CourseHistory.objects.filter(user=request.user, course=_course, active='A')
if mode == 'I' or mode == 'C':
if len(history) > 0:
if history[0].is_owner:
return render(request, "content_developer/course.html", context)
return render(request, "student/course.html", context)
#elif mode == 'S':
else:
if len(history) > 0:
return render(request, "student/course.html", context)
course_data = CourseSerializer(_course).data
if course_data['course_info']['start_time']:
s_date = course_data['course_info']['start_time'].strftime('%d %b,%Y')
course_data['course_info']['start_time'] = s_date
if course_data['course_info']['end_time']:
e_date = course_data['course_info']['end_time'].strftime('%d %b,%Y')
course_data['course_info']['end_time'] = e_date
if course_data['course_info']['end_enrollment_date']:
end_e_date = course_data['course_info']['end_enrollment_date'].strftime('%d %b,%Y')
course_data['course_info']['end_enrollment_date'] = end_e_date
context = {
"request": request,
"title": course_data['title'],
"course": json.dumps(course_data),
"course_info": course_data['course_info']
}
return render(request, "course/public_course_info.html", context)
return HttpResponse("Forbidden", status.HTTP_403_FORBIDDEN)
@login_required
def syllabus(request, pk=None):
"""Serves a course main page"""
_course = get_object_or_404(Course, pk=pk)
context = {"request": request, "course": _course}
if request.user.get_profile().is_instructor:
return render(request, "instructor/syllabus.html", context)
else:
context = {
"request": request,
"error": "You have to be an instructor to see syllabus."
}
return render(request, "error.html", context)
@login_required
def student_courses(request):
"""
Serve enrolled course list for a student
"""
response = student_course_list(request)
context = {"data": json.dumps(response)}
return render(request, "student/my_courses.html", context)
@login_required
def instructor_courses(request):
"""
Added by vinayak, needs to be verified from writer of instructor_course_list()
Serve offered course list for a instructor (?)
"""
if inInstructorModeObject.has_permission(request, None):
response = instructor_course_list(request)
context = {"data": json.dumps(response)}
return render(request, "instructor/my_offerings.html", context)
else:
context = {
"request": request,
"error": "Invalid Access. Change mode or contact admin"
}
return render(request, "error.html", context)
@login_required
def content_developer_courses(request):
"""
Serves textbook course list for a content developer
"""
if inContentDeveloperModeObject.has_permission(request, None):
response = content_developer_course_list(request)
context = {"data": json.dumps(response)}
#: Need to change the page for content developer courses
print "New Textbook Page"
return render(request, "content_developer/my_textbooks.html", context)
else:
context = {
"request": request,
"error": "Invalid Access.Change mode or contact admin"
}
return render(request, "error.html", context)
@login_required
def mycourselist(request):
"""
Obselete. Purpose not clear
Serves the enrolled course list for a student
"""
mode = get_mode(request)
if mode == 'I':
return instructor_courses(request)
elif mode == 'C':
return content_developer_courses(request)
#elif mode == 'S':
# return student_courses(request)
#return HttpResponse("Forbidden", status.HTTP_403_FORBIDDEN)
else:
return student_courses(request)
@login_required
def content_developer_course_list(request):
"""
Return a list of courses being developed by user as a content developer
"""
date_format = "%d %b, %Y"
history_list = CourseHistory.objects.filter(user=request.user, is_owner=True, course__type='T')
all_courses = []
for history in history_list:
if history.course.type == 'T':
all_courses.append(history.course)
all_courses_data = [CourseSerializer(c).data for c in all_courses]
cur_datetime = timezone.now().date()
##Course Current Status in coursetag.
## 1 => active
## 2 => Future
## 3 => past
all_coursetag = []
start_date = []
all_course_progress = []
for c_data in all_courses_data:
c_info = c_data['course_info']
if (c_info['end_time'] is None or cur_datetime < c_info['start_time']):
tag = 2
elif (cur_datetime > c_info['end_time']):
tag = 3
else:
tag = 1
all_coursetag.append({"is_published": c_info['is_published'], "coursetag": tag})
if c_info['end_time'] is None or c_info['start_time'] is None:
progress = 0
else:
elapsed_time = (cur_datetime - c_info['start_time']).days
total_time = (c_info['end_time'] - c_info['start_time']).days
progress = (float)(100 * elapsed_time / total_time)
if progress > 100:
progress = 100
elif progress < 0:
progress = 0
all_course_progress.append({"progress": progress})
if (c_info['start_time'] is not None):
s_date = c_info['start_time'].strftime(date_format)
c_data['course_info']['start_time'] = s_date
else:
s_date = "Not Decided"
if (c_info['end_time'] is not None):
e_date = c_info['end_time'].strftime(date_format)
c_data['course_info']['end_time'] = e_date
else:
e_date = "Not Decided"
start_date.append({
"start_date": s_date,
"end_date": e_date,
"start_time": s_date,
"end_time": e_date
})
if (c_info['end_enrollment_date']):
end_e_date = c_info['end_enrollment_date'].strftime(date_format)
c_data['course_info']['end_enrollment_date'] = end_e_date
response = []
for i in range(len(all_courses_data)):
response.append((dict(all_course_progress[i].items() + all_coursetag[i].items() +
all_courses_data[i].items() + start_date[i].items())))
response = sort_my_courses(response)
return response
@login_required
def instructor_course_list(request):
"""
Return a list of courses which are offered by the user as instructor
"""
date_format = "%d %b, %Y"
history_list = CourseHistory.objects.filter(user=request.user, is_owner=True, course__type='O')
all_courses = []
for history in history_list:
if history.course.type == 'O':
all_courses.append(history.course)
all_courses_data = [CourseSerializer(c).data for c in all_courses]
cur_datetime = timezone.now().date()
##Course Current Status in coursetag.
## 1 => active
## 2 => Future
## 3 => past
all_coursetag = []
start_date = []
all_course_progress = []
for c_data in all_courses_data:
c_info = c_data['course_info']
if (c_info['end_time'] is None or cur_datetime < c_info['start_time']):
tag = 2
elif (cur_datetime > c_info['end_time']):
tag = 3
else:
tag = 1
all_coursetag.append({"is_published": c_info['is_published'], "coursetag": tag})
if c_info['end_time'] is None or c_info['start_time'] is None:
progress = 0
else:
elapsed_time = (cur_datetime - c_info['start_time']).days
total_time = (c_info['end_time'] - c_info['start_time']).days
progress = (float)(100 * elapsed_time / total_time)
if progress > 100:
progress = 100
elif progress < 0:
progress = 0
all_course_progress.append({"progress": progress})
if (c_info['start_time'] is not None):
s_date = c_info['start_time'].strftime(date_format)
c_data['course_info']['start_time'] = s_date
else:
s_date = "Not Decided"
if (c_info['end_time'] is not None):
e_date = c_info['end_time'].strftime(date_format)
c_data['course_info']['end_time'] = e_date
else:
e_date = "Not Decided"
start_date.append({
"start_date": s_date,
"end_date": e_date,
"start_time": s_date,
"end_time": e_date
})
if c_info['end_enrollment_date']:
end_e_date = c_info['end_enrollment_date'].strftime(date_format)
c_data['course_info']['end_enrollment_date'] = end_e_date
response = []
for i in range(len(all_courses_data)):
response.append((dict(all_course_progress[i].items() + all_coursetag[i].items() +
all_courses_data[i].items() + start_date[i].items())))
response = sort_my_courses(response)
return response
@login_required
def student_course_list(request):
"""
Return a list of all courses where the student is enrolled
"""
date_format = "%d %b, %Y"
history_list = CourseHistory.objects.filter(user=request.user, active='A', is_owner=False)
all_courses = []
for history in history_list:
if history.course.type == 'O':
all_courses.append(history.course)
all_courses_data = [CourseSerializer(c).data for c in all_courses]
cur_datetime = timezone.now().date()
##Course Current Status in coursetag.
## 1 => active
## 2 => Future
## 3 => past
all_coursetag = []
start_date = []
all_course_progress = []
for c_data in all_courses_data:
c_info = c_data['course_info']
if (c_info['end_time'] is None or cur_datetime < c_info['start_time']):
tag = 2
elif (cur_datetime > c_info['end_time']):
tag = 3
else:
tag = 1
all_coursetag.append({"is_published": c_info['is_published'], "coursetag": tag})
if c_info['end_time'] is None or c_info['start_time'] is None:
progress = 0
else:
elapsed_time = (cur_datetime - c_info['start_time']).days
total_time = (c_info['end_time'] - c_info['start_time']).days
progress = (float)(100 * elapsed_time / total_time)
if progress > 100:
progress = 100
elif progress < 0:
progress = 0
all_course_progress.append({"progress": progress})
if (c_info['start_time'] is not None):
s_date = c_info['start_time'].strftime(date_format)
c_data['course_info']['start_time'] = s_date
else:
s_date = "Not Decided"
if (c_info['end_time'] is not None):
e_date = c_info['end_time'].strftime(date_format)
c_data['course_info']['end_time'] = e_date
else:
e_date = "Not Decided"
start_date.append({
"start_date": s_date,
"end_date": e_date,
"start_time": s_date,
"end_time": e_date
})
if c_info['end_enrollment_date']:
end_e_date = c_info['end_enrollment_date'].strftime(date_format)
c_data['course_info']['end_enrollment_date'] = end_e_date
response = []
for i in range(len(all_courses_data)):
response.append((dict(all_course_progress[i].items() + all_coursetag[i].items() +
all_courses_data[i].items() + start_date[i].items())))
response = sort_my_courses(response)
return response
def coursecmp(x, y):
if(x['coursetag'] > y['coursetag']):
return 1
elif(x['coursetag'] < y['coursetag']):
return -1
elif (x['start_time'] is not None) and (y['start_time'] is not None) and (x['start_time'] < y['start_time']):
return -1
return 1
def sort_my_courses(response):
#sorted_master_list = sorted(response, key=itemgetter('coursetag'))
sorted_master_list = sorted(response, cmp=coursecmp)
return sorted_master_list
def dateToString(start_date):
""" Convert the DateField to a printable string """
return start_date.strftime("%d %B")
def paginated_serializer(request=None, queryset=None, serializer=None, paginate_by=5):
"""
Returns the serializer containing objects corresponding to paginated page.
Abstract Functionality can be used by all.
"""
paginator = Paginator(queryset, paginate_by)
page = request.QUERY_PARAMS.get('page')
try:
items = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
items = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999),
# deliver last page of results.
items = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
return serializer(items, context=serializer_context)
def to_do(request):
"""
Functionality to be added
"""
return HttpResponse("Functionality to be added")
def instructor_course_list_old(request):
histories = CourseHistory.objects.filter(user=request.user, is_owner=True, course__type='O')
my_courses = [history.course for history in histories]
my_courses = [CourseSerializer(course).data for course in my_courses]
my_courses = [history.course for history in histories]
my_courses_info = [CourseInfoSerializer(course.course_info).data for course in my_courses]
current_datetime = timezone.now().date()
# Calculating CourseTag for all the courses. Coursetag = 1 => active course, coursetag = 2 =>
# future course
# and coursetag = 3 => past course
coursetag = [{"is_published": element['is_published'], "coursetag": 2 if (element['end_time'] == None or current_datetime < element['start_time']) else 3 if (current_datetime > element['end_time']) else 1} for element in my_courses_info]
# Calculating printable dates
start_date = [{"start_date": dateToString(element['start_time']) if element['start_time'] != None else "Not Decided" , "end_date": dateToString(element['end_time']) if element['end_time'] != None else "Not Decided"} for element in my_courses_info]
# Calculating the progress of every course on teh basis of current date, course start date and course end date
my_courses_progress = [0 if (element['end_time'] == None or element['start_time'] == None) else (float) (100*(current_datetime - element['start_time']).days/(element['end_time']-element['start_time']).days) for element in my_courses_info]
my_courses_progress = [{"progress": element if(element <= 100) else 100} for element in my_courses_progress]
my_courses = [CourseSerializer(course).data for course in my_courses]
# Appending the course progress and coursetag to the response
response = [(dict(my_courses_progress[i].items() + my_courses[i].items() + coursetag[i].items() + start_date[i].items())) for i in range(len(my_courses))]
# Converting teh start and end date of courses to string to make it JSOn serializable
my_courses_info = [{"start_time": str(element['start_time']), "end_time" : str(element['end_time'])} for element in my_courses_info]
# Appending the course end and start date to the response
response = [(dict(response[i].items() + my_courses_info[i].items())) for i in range(len(response))]
# Sorting the results
response = sort_my_courses(response)
return response
@login_required
def get_group(request, pk=None,ref = None):
"""Serves a course Group page"""
_group = get_object_or_404(Group, pk=pk)
_course = _group.course
context = {"request": request, "course": _course,"group":_group}
if ref is not None and len(ref) > 0:
context["ref"] = ref
else:
context["ref"] = "0"
mode = get_mode(request)
history = CourseHistory.objects.filter(user=request.user, course=_course, active='A')
if len(history) > 0:
if history[0].is_owner:
if mode == 'I' or mode == 'C':
return render(request, "content_developer/course.html", context)
else:
return render(request, "student/course.html", context)
else:
return render(request, "student/course.html", context)
else:
return HttpResponse("Forbidden", status.HTTP_403_FORBIDDEN)<file_sep>/elearning_academy/static/elearning_academy/js/main.js.original
// Showdown converter
var converter = new Showdown.converter();
/* Login **********************************************/
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function ajax_json_request(url, type, data) {
csrftoken = getCookie('csrftoken');
if (!(type=="GET" || type=="get")) {
data["csrfmiddlewaretoken"] = csrftokenValue;
}
var request = $.ajax({
url: url,
type: type,
data: data,
timeout: 5000,
contentType: "application/x-www-form-urlencoded",
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
dataType: "html"
});
//On failure display error message
request.fail(function(jqXHR, textStatus) {
if (jqXHR.status == 404) {
response = {detail: "Network error: Please check your internet connection"};
}
else {
response = jQuery.parseJSON(jqXHR.responseText);
}
display_global_message(response.detail, "error");
});
return request;
}
/*
Custom AJAX request (Supporting file upload)
Use this function to upload a file to server using
Ajax. Ideally, options.data should be a formData object.
It can be constructed, for example, as follows:
var formData = new FormData(formDOMNode);
For more details see:
http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery
Also see implementation of the ImageUploader component for sample usage
options = {
url: '..',
type: '..',
data: '...',
[beforeSend: function(xhr, settings),]
[success: function(response),]
[progressFunction: function(event),]
[error: function(xhr, textStatus)]
}
progressFunction can be used to track the progress of the upload. Example:
progressFunction = function (e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
*/
function ajax_custom_request(options){
// Get the csrftoken
csrftoken = getCookie('csrftoken');
if (!(options.type=="GET" || options.type=="get")) {
options.data["csrfmiddlewaretoken"] = csrftokenValue;
}
//atatch the progressHandlingFucntion at the right place
progressFunction = function(){};
if (options.progressFunction){
progressFunction = options.progressFunction;
delete options.progressFunction;
}
options.xhr = function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
// For handling the progress of the upload
myXhr.upload.addEventListener('progress',
progressFunction, false);
}
return myXhr;
};
// update beforeSend to send request header
beforeSend = function(){}
if (options.beforeSend) beforeSend = options.beforeSend;
options.beforeSend = function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
beforeSend(xhr, settings);
}
// Options to tell jQuery not to process
// data or worry about content-type.
options.cache = false;
options.contentType = false;
options.processData = false;
request = $.ajax(options);
return request;
}
/********* Message Info *****************/
function display_global_message(message, type) {
// Type can be : ["info", "success", "error", "warning"]
if(type=="error") {
type = "danger";
}
clearTimeout($("#message-text").stop().data('timer'));
$("#message-text").fadeOut(function() {
$("#message-text").html(message);
});
$("#message-text").removeClass().addClass("alert alert-" + type);
$("#message-text").fadeIn(function() {
var elem = $(this);
$.data(this, 'timer', setTimeout(function() {elem.fadeOut();}, 3000));
});
}
<file_sep>/quiz/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Quiz'
db.create_table(u'quiz_quiz', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.TextField')()),
('question_modules', self.gf('django.db.models.fields.IntegerField')(default=0)),
('questions', self.gf('django.db.models.fields.IntegerField')(default=0)),
('marks', self.gf('django.db.models.fields.FloatField')(default=0.0)),
('playlist', self.gf('django.db.models.fields.TextField')(default='[]')),
))
db.send_create_signal(u'quiz', ['Quiz'])
# Adding model 'QuestionModule'
db.create_table(u'quiz_questionmodule', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('quiz', self.gf('django.db.models.fields.related.ForeignKey')(related_name='QuestionModule_Quiz', to=orm['quiz.Quiz'])),
('title', self.gf('django.db.models.fields.TextField')()),
('playlist', self.gf('django.db.models.fields.TextField')(default='[]')),
('questions', self.gf('django.db.models.fields.IntegerField')(default=0)),
('dummy', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal(u'quiz', ['QuestionModule'])
# Adding model 'QuizHistory'
db.create_table(u'quiz_quizhistory', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('quiz', self.gf('django.db.models.fields.related.ForeignKey')(related_name='QuizHistory_Quiz', to=orm['quiz.Quiz'])),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='QuizHistory_User', to=orm['auth.User'])),
('current_question_module', self.gf('django.db.models.fields.related.ForeignKey')(related_name='QuizHistory_QuestionModule', null=True, to=orm['quiz.QuestionModule'])),
('marks', self.gf('django.db.models.fields.FloatField')(default=0.0)),
('solved', self.gf('django.db.models.fields.IntegerField')(default=0)),
('is_graded', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal(u'quiz', ['QuizHistory'])
# Adding unique constraint on 'QuizHistory', fields ['quiz', 'user']
db.create_unique(u'quiz_quizhistory', ['quiz_id', 'user_id'])
# Adding model 'Question'
db.create_table(u'quiz_question', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('hit_count', self.gf('django.db.models.fields.IntegerField')(default=0)),
('quiz', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Question_Quiz', to=orm['quiz.Quiz'])),
('question_module', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Question_QuestionModule', to=orm['quiz.QuestionModule'])),
('description', self.gf('django.db.models.fields.TextField')()),
('hint', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('grader_type', self.gf('django.db.models.fields.CharField')(default='D', max_length=1)),
('answer_description', self.gf('django.db.models.fields.TextField')(blank=True)),
('marks', self.gf('django.db.models.fields.FloatField')(default=0)),
('gradable', self.gf('django.db.models.fields.BooleanField')(default=True)),
('granularity', self.gf('django.db.models.fields.TextField')()),
('granularity_hint', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('type', self.gf('django.db.models.fields.CharField')(max_length=1)),
('attempts', self.gf('django.db.models.fields.IntegerField')(default=1)),
))
db.send_create_signal(u'quiz', ['Question'])
# Adding model 'DescriptiveQuestion'
db.create_table(u'quiz_descriptivequestion', (
(u'question_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['quiz.Question'], unique=True, primary_key=True)),
('answer', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal(u'quiz', ['DescriptiveQuestion'])
# Adding model 'SingleChoiceQuestion'
db.create_table(u'quiz_singlechoicequestion', (
(u'question_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['quiz.Question'], unique=True, primary_key=True)),
('options', self.gf('django.db.models.fields.TextField')()),
('answer', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal(u'quiz', ['SingleChoiceQuestion'])
# Adding model 'MultipleChoiceQuestion'
db.create_table(u'quiz_multiplechoicequestion', (
(u'question_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['quiz.Question'], unique=True, primary_key=True)),
('options', self.gf('django.db.models.fields.TextField')()),
('answer', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal(u'quiz', ['MultipleChoiceQuestion'])
# Adding model 'FixedAnswerQuestion'
db.create_table(u'quiz_fixedanswerquestion', (
(u'question_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['quiz.Question'], unique=True, primary_key=True)),
('answer', self.gf('django.db.models.fields.CharField')(max_length=128)),
))
db.send_create_signal(u'quiz', ['FixedAnswerQuestion'])
# Adding model 'ProgrammingQuestion'
db.create_table(u'quiz_programmingquestion', (
(u'question_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['quiz.Question'], unique=True, primary_key=True)),
('num_testcases', self.gf('django.db.models.fields.IntegerField')()),
('command', self.gf('django.db.models.fields.TextField')()),
('acceptable_languages', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal(u'quiz', ['ProgrammingQuestion'])
# Adding model 'Testcase'
db.create_table(u'quiz_testcase', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('question', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Testcase_ProgrammingQuestion', to=orm['quiz.ProgrammingQuestion'])),
('input_text', self.gf('django.db.models.fields.TextField')()),
('correct_output', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal(u'quiz', ['Testcase'])
# Adding model 'QuestionHistory'
db.create_table(u'quiz_questionhistory', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('question', self.gf('django.db.models.fields.related.ForeignKey')(related_name='QuestionHistory_Question', to=orm['quiz.Question'])),
('student', self.gf('django.db.models.fields.related.ForeignKey')(related_name='QuestionHistory_User', to=orm['auth.User'])),
('attempts', self.gf('django.db.models.fields.IntegerField')(default=0)),
('marks', self.gf('django.db.models.fields.FloatField')(default=0.0)),
('status', self.gf('django.db.models.fields.CharField')(default='N', max_length=1)),
('hint_taken', self.gf('django.db.models.fields.BooleanField')(default=False)),
('answer_shown', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal(u'quiz', ['QuestionHistory'])
# Adding unique constraint on 'QuestionHistory', fields ['question', 'student']
db.create_unique(u'quiz_questionhistory', ['question_id', 'student_id'])
# Adding model 'Queue'
db.create_table(u'quiz_queue', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)),
('object_id', self.gf('django.db.models.fields.TextField')()),
('is_processed', self.gf('django.db.models.fields.BooleanField')(default=False)),
('object_type', self.gf('django.db.models.fields.CharField')(default='E', max_length=1)),
('info', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal(u'quiz', ['Queue'])
# Adding model 'Submission'
db.create_table(u'quiz_submission', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)),
('question', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Submission_Question', to=orm['quiz.Question'])),
('student', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Submission_User', to=orm['auth.User'])),
('grader_type', self.gf('django.db.models.fields.CharField')(default='D', max_length=1)),
('answer', self.gf('django.db.models.fields.TextField')()),
('status', self.gf('django.db.models.fields.CharField')(default='A', max_length=1)),
('feedback', self.gf('django.db.models.fields.TextField')(default='')),
('result', self.gf('django.db.models.fields.FloatField')(default=0.0)),
('is_correct', self.gf('django.db.models.fields.BooleanField')(default=False)),
('is_plagiarised', self.gf('django.db.models.fields.BooleanField')(default=False)),
('has_been_checked', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal(u'quiz', ['Submission'])
def backwards(self, orm):
# Removing unique constraint on 'QuestionHistory', fields ['question', 'student']
db.delete_unique(u'quiz_questionhistory', ['question_id', 'student_id'])
# Removing unique constraint on 'QuizHistory', fields ['quiz', 'user']
db.delete_unique(u'quiz_quizhistory', ['quiz_id', 'user_id'])
# Deleting model 'Quiz'
db.delete_table(u'quiz_quiz')
# Deleting model 'QuestionModule'
db.delete_table(u'quiz_questionmodule')
# Deleting model 'QuizHistory'
db.delete_table(u'quiz_quizhistory')
# Deleting model 'Question'
db.delete_table(u'quiz_question')
# Deleting model 'DescriptiveQuestion'
db.delete_table(u'quiz_descriptivequestion')
# Deleting model 'SingleChoiceQuestion'
db.delete_table(u'quiz_singlechoicequestion')
# Deleting model 'MultipleChoiceQuestion'
db.delete_table(u'quiz_multiplechoicequestion')
# Deleting model 'FixedAnswerQuestion'
db.delete_table(u'quiz_fixedanswerquestion')
# Deleting model 'ProgrammingQuestion'
db.delete_table(u'quiz_programmingquestion')
# Deleting model 'Testcase'
db.delete_table(u'quiz_testcase')
# Deleting model 'QuestionHistory'
db.delete_table(u'quiz_questionhistory')
# Deleting model 'Queue'
db.delete_table(u'quiz_queue')
# Deleting model 'Submission'
db.delete_table(u'quiz_submission')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('<PASSWORD>', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'quiz.descriptivequestion': {
'Meta': {'object_name': 'DescriptiveQuestion', '_ormbases': [u'quiz.Question']},
'answer': ('django.db.models.fields.TextField', [], {}),
u'question_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['quiz.Question']", 'unique': 'True', 'primary_key': 'True'})
},
u'quiz.fixedanswerquestion': {
'Meta': {'object_name': 'FixedAnswerQuestion', '_ormbases': [u'quiz.Question']},
'answer': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
u'question_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['quiz.Question']", 'unique': 'True', 'primary_key': 'True'})
},
u'quiz.multiplechoicequestion': {
'Meta': {'object_name': 'MultipleChoiceQuestion', '_ormbases': [u'quiz.Question']},
'answer': ('django.db.models.fields.TextField', [], {}),
'options': ('django.db.models.fields.TextField', [], {}),
u'question_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['quiz.Question']", 'unique': 'True', 'primary_key': 'True'})
},
u'quiz.programmingquestion': {
'Meta': {'object_name': 'ProgrammingQuestion', '_ormbases': [u'quiz.Question']},
'acceptable_languages': ('django.db.models.fields.TextField', [], {}),
'command': ('django.db.models.fields.TextField', [], {}),
'num_testcases': ('django.db.models.fields.IntegerField', [], {}),
u'question_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['quiz.Question']", 'unique': 'True', 'primary_key': 'True'})
},
u'quiz.question': {
'Meta': {'object_name': 'Question'},
'answer_description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'attempts': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'description': ('django.db.models.fields.TextField', [], {}),
'gradable': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'grader_type': ('django.db.models.fields.CharField', [], {'default': "'D'", 'max_length': '1'}),
'granularity': ('django.db.models.fields.TextField', [], {}),
'granularity_hint': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'hint': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'hit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'marks': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'question_module': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Question_QuestionModule'", 'to': u"orm['quiz.QuestionModule']"}),
'quiz': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Question_Quiz'", 'to': u"orm['quiz.Quiz']"}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '1'})
},
u'quiz.questionhistory': {
'Meta': {'unique_together': "(('question', 'student'),)", 'object_name': 'QuestionHistory'},
'answer_shown': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'attempts': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'hint_taken': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'marks': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'QuestionHistory_Question'", 'to': u"orm['quiz.Question']"}),
'status': ('django.db.models.fields.CharField', [], {'default': "'N'", 'max_length': '1'}),
'student': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'QuestionHistory_User'", 'to': u"orm['auth.User']"})
},
u'quiz.questionmodule': {
'Meta': {'object_name': 'QuestionModule'},
'dummy': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'questions': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'quiz': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'QuestionModule_Quiz'", 'to': u"orm['quiz.Quiz']"}),
'title': ('django.db.models.fields.TextField', [], {})
},
u'quiz.queue': {
'Meta': {'object_name': 'Queue'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'info': ('django.db.models.fields.TextField', [], {}),
'is_processed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'object_id': ('django.db.models.fields.TextField', [], {}),
'object_type': ('django.db.models.fields.CharField', [], {'default': "'E'", 'max_length': '1'})
},
u'quiz.quiz': {
'Meta': {'object_name': 'Quiz'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'marks': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'question_modules': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'questions': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'title': ('django.db.models.fields.TextField', [], {})
},
u'quiz.quizhistory': {
'Meta': {'unique_together': "(('quiz', 'user'),)", 'object_name': 'QuizHistory'},
'current_question_module': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'QuizHistory_QuestionModule'", 'null': 'True', 'to': u"orm['quiz.QuestionModule']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_graded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'marks': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'quiz': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'QuizHistory_Quiz'", 'to': u"orm['quiz.Quiz']"}),
'solved': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'QuizHistory_User'", 'to': u"orm['auth.User']"})
},
u'quiz.singlechoicequestion': {
'Meta': {'object_name': 'SingleChoiceQuestion', '_ormbases': [u'quiz.Question']},
'answer': ('django.db.models.fields.IntegerField', [], {}),
'options': ('django.db.models.fields.TextField', [], {}),
u'question_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['quiz.Question']", 'unique': 'True', 'primary_key': 'True'})
},
u'quiz.submission': {
'Meta': {'object_name': 'Submission'},
'answer': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'feedback': ('django.db.models.fields.TextField', [], {'default': "''"}),
'grader_type': ('django.db.models.fields.CharField', [], {'default': "'D'", 'max_length': '1'}),
'has_been_checked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_correct': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_plagiarised': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Submission_Question'", 'to': u"orm['quiz.Question']"}),
'result': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '1'}),
'student': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Submission_User'", 'to': u"orm['auth.User']"})
},
u'quiz.testcase': {
'Meta': {'object_name': 'Testcase'},
'correct_output': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'input_text': ('django.db.models.fields.TextField', [], {}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Testcase_ProgrammingQuestion'", 'to': u"orm['quiz.ProgrammingQuestion']"})
}
}
complete_apps = ['quiz']<file_sep>/assignments/templates/assignments/readmeAssignmentMetaInterface.html
{% extends 'assignments/assignments_base.html' %}
{% block title %}README - Assignment Meta Interface{% endblock %}
{% block sidebar %}{% endblock %}
{% block main %}
<div>
<ul class="breadcrumb">
<li><a href="{% url 'assignments_readme' course.id "INDEX" %}">README</a><span class="divider">/</span></li>
<li>Assignment Upload Meta Interface<span class="divider">/</span></li>
</ul>
</div>
<div class="course-content" style="border:2px solid #ccc">
<h4 style="text-align:center;">Assignment Upload Meta Interface</h4>
<p>The following json template explains the json file structure for the meta interface. You can find examples for Python in the "Testbed/Assignment Meta/" folder.</p>
<pre style="font-size:10px">
{
"assignment_name":"Name of the assignment",
"soft_deadline":"YYYY MM DD HH:mm",
"hard_deadline":"YYYY MM DD HH:mm",
"late_submission":"Yes/No (this field not being present implies no late submission allowed)",
"language":"Name of the language (should be one of the languages in the LANGUAGES array of utils.filetypes file)",
"student_files":"List of files to be submitted by the student separated by spaces.",
"documents":"Path to the document file relative to the head of the assignment tar directory. OPTIONAL",
"helper_code":"Path to the helper code file relative to the head of the assignment tar directory. OPTIONAL",
"solution_code":"Path to the solution code file relative to the head of the assignment tar directory. OPTIONAL. But if not given then all testcases should have output files supplied.",
"publish_date":"YYYY MM DD HH:mm",
"asgn_description":"Description of the assignment",
"sections": [
{
"section_name":"Name of the section",
"section_type":"Evaluate/Practice",
"compilation_command":["compiler","compiler arguments (leave empty if no arguments are there)","files to be compiled"],
"execution_command":["interpreter","interpreter arguments (leave empty if no arguments are there)","files to be interpreted"],
"section_files":"Path to the section code file relative to the head of the assignment tar directory. OPTIONAL",
"sec_description":"Description of the section. OPTIONAL",
"testcases": [
{
"testcase_name":"Name of the testcase",
"command_line_args":"Command line arguments for the testcase. OPTIONAL",
"marks":"Marks of the testcase. Integer to be provided. OPTIONAL",
"input_files":"Path to the testcase input files relative to the head of the assignment tar directory. OPTIONAL",
"output_files":"Path to the testcase output files relative to the head of the assignment tar directory. OPTIONAL if solution code is provided.",
"std_in_file_name": "Name of the input file (in the input_files field file) to be used for the testcase. Should be provided iff input_files field is provided.",
"std_out_file_name": "Name of the output file (in the output_files field file) to be used for the testcase. Should be provided iff output_files field is provided.",
"test_description":"Description of the testcase. OPTIONAL"
}
]
}
]
}
</pre>
<p>Note that the files mentioned in the json file are to be in a folder which is tarred and submitted as the assignment archive. For example, if the input file for a testcase is at "in1" relative to the head of the assignment archive, then the following is to be done. <br>
Create a folder. This folder is the head of the assignment archive. Put the file in1 in this folder. Do the same for other file fields in the above json. Tar this folder and submit it as the assignment archive. <br>
Please have a look at the "Testbed/Assignment Meta/" folder for an example of the file organization.<br>
Please note that there <b>should not be any spaces in any file or folder names</b> inside the head folder of the assignment archive.
</p>
Regarding the compiler and execution command fields in each section object in the above json, please follow the following convention. <br>
<b>Compiler Command field</b> - Present in <b>C,C++,Java</b>. The compilers to be used are <b>gcc,g++,javac</b> respectively. <br>
<b>Execution Command field</b> - Present in <b>Java, Python, Bash</b>. The interpreters to be used are <b>java,python,bash</b> respectively.
</div>
{% endblock %}<file_sep>/elearning_academy/static/elearning_academy/js/mixins.jsx.original
/*
Mixin to store, access and modify the saved status
of components that are used to edit something saved on the sever.
-> Check and change the status directly using 'checkFor' and
'changeTo', or using the auxiliary functions.
-> Use 'savedIf' to set the status
subject to a conditon.
-> To trigger callbacks etc., define a function
onSavedStatusChange in your component and handle callbacks
there based on the changed state. It will be called every
time the status is changed.
-> Set the initial savedStatus in componentWillMount
-> Use selectBySavedStatus to pick one of three things based on satus
-> As far as possible, avoid setting this.state.savedStatus manually
*/
var SavedStatusMixin = {
componentWillMount: function() {
this.setState({savedStatus: 'saved'});
},
checkFor: function(status) {
return this.state.savedStatus == status;
},
changeTo: function(status) {
this.setState({savedStatus: status}, this.onSavedStatusUpdate);
},
savedIf: function (check) {
this.changeTo(check ? 'saved' : 'unsaved');
},
selectBySavedStatus: function(options){
return options[this.state.savedStatus];
},
isSaved: function() {
return this.checkFor('saved');
},
isUnsaved: function() {
return this.checkFor('unsaved');
},
isSaving: function() {
return this.checkFor('saving');
},
toSaved: function() {
this.changeTo('saved');
},
toSaving: function() {
this.changeTo('saving');
},
toUnsaved: function() {
this.changeTo('unsaved');
}
};
/*
Depends On : SavedStatusMixin
This mixin provides a style object that can be
applied to a div etc., to change its background-color
based on the savedStatus of the component.
To disable, sef noTransition to true
*/
var BackgroundTransitionMixin = {
getBackgroundTransitionStyle: function(colors, noTransition, duration){
if (noTransition) return {};
if (!colors) colors = {};
if (!duration) duration = 1000;
transition = 'background-color ' + duration + 'ms linear';
style = {
WebkitTransition: transition,
MozTransition: transition,
OTransition: transition,
MsTransition: transition,
'transition': transition
}
if (!colors.unsaved) colors.unsaved = '#e4f2ff';
if (!colors.saved) colors.saved = '#ffffff';
if (!colors.saving) colors.saving = '#f0f8ff';
style.backgroundColor = this.selectBySavedStatus(colors);
return style;
}
}
var StyleTransitionMixin = {
getStyleTransition: function(property, duration){
if (!duration) duration = 1000;
transition = property + ' ' + duration + 'ms linear';
return {
WebkitTransition: transition,
MozTransition: transition,
OTransition: transition,
MsTransition: transition,
'transition': transition
};
}
}
<file_sep>/scripts/restart.sh
DJANGODIR=/home/bodhitree/elearning_academy_main/elearning_academy/
NUM_WORKERS=1
DJANGO_WSGI_MODULE=elearning_academy.wsgi
PATH=127.0.0.1:8002
cd $DJANGODIR
/usr/local/bin/gunicorn ${DJANGO_WSGI_MODULE}:application --timeout 600 --workers $NUM_WORKERS --log-level=debug --bind=$PATH
<file_sep>/scripts/backup.sh
#!/bin/bash
# Database credentials
user=DBROOT
password=<PASSWORD>
db_name=DBNAME
# Other options
backup_path=BACKUP_FOLDER
mydate=$(date +"%d-%b-%Y")
# Set default file permissions
umask 177
# Dump database into SQL file
mysqldump --host=localhost --user=$user --password=$password $db_name > $backup_path/$db_name-$mydate.sql
#sending files to the remote server
sshpass -p 'password' scp -v $backup_path/$db_name-$mydate.sql user@server:BACKUP_PATH
# Delete files older than 5 days
find $backup_path/* -mtime +5 -exec rm {} \;
<file_sep>/chat/serializers.py
__author__ = 'dheerendra'
from rest_framework import serializers
from django.contrib.auth.models import User
from models import ChatRoom,Chat
from courseware.models import CourseHistory
class UserSerializers(serializers.ModelSerializer):
'''
Serializer for User
'''
class Meta:
model = User
fields = ('id', 'username')
class ChatRoomSerializers(serializers.ModelSerializer):
'''
Serializer for Chatroom
'''
class Meta:
model = ChatRoom
class RealTimeChatSerializers(serializers.ModelSerializer):
user = UserSerializers()
parent = serializers.SerializerMethodField('parent_null')
isTeacher = serializers.SerializerMethodField('is_sender_teacher')
replyCount = serializers.SerializerMethodField('reply_count')
message = serializers.SerializerMethodField('get_message')
def get_message(self, chat):
if chat.offensive:
return ""
return chat.message
def reply_count(self, chat):
return 0
def parent_null(self, chat):
if chat.parent is None:
return "-1"
else:
return str(chat.parent.id)
def is_sender_teacher(self, chat):
'''
Checks if user of the chat is teacher
:param chat: chat object
:return: bool. Whether chat.user is teacher
'''
user = chat.user
course = chat.chatroom.course
try:
courseHistory = CourseHistory.objects.get(user=user, course=course)
return courseHistory.is_owner
except:
return False
class Meta:
model = Chat
exclude = ('hidden',)
class ChatSerializers(RealTimeChatSerializers):
'''
Serializer for Chat
'''
def reply_count(self, chat):
replyCount = Chat.objects.all().filter(parent=chat).count()
return replyCount
<file_sep>/TestBed/Java/Teacher/requirements.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class requirements
{
private static Map <String, Long> solutions = new HashMap <String, Long> ();
private static boolean [][] constraints;
private static long solve (int n, int [] low, int [] high)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < n; i++)
{
sb.append (low [i]);
sb.append (high [i]);
}
String signature = sb.toString ();
Long result = solutions.get (signature);
if (result == null)
{
result = Long.valueOf (doSolve (n, low, high));
solutions.put (signature, result);
}
return result.longValue ();
}
private static long doSolve (int n, int [] low, int [] high)
{
if (n == 0) return 1;
else
{
long result = 0;
for (int i = low [n - 1]; i <= high [n - 1]; i++)
{
int [] l = new int [n - 1];
int [] h = new int [n - 1];
for (int j = 0; j < n - 1; j++)
{
l [j] = constraints [n - 1][j] ? Math.max (low [j], i) : low [j];
h [j] = constraints [j][n - 1] ? Math.min (high [j], i) : high [j];
}
result += solve (n - 1, l, h)%1007;
}
result %= 1007;
return result;
}
}
public static void main(String[] args) throws Exception
{
BufferedReader reader =
new BufferedReader (
new InputStreamReader(System.in));
String nm = reader.readLine ();
String [] pair = nm.split(" ");
int n = Integer.parseInt(pair [0]);
int m = Integer.parseInt(pair [1]);
constraints = new boolean [n][];
for (int i = 0; i < n; i++)
constraints [i] = new boolean [n];
int [] low = new int [n];
int [] high = new int [n];
for (int i = 0; i < n; i++)
high [i] = 9;
for (int i = 0; i < m; i++)
{
String ab = reader.readLine();
pair = ab.split (" ");
int a = Integer.parseInt(pair [0]);
int b = Integer.parseInt(pair [1]);
constraints [a][b] = true;
}
System.out.println(solve (n, low, high));
}
}<file_sep>/courseware/viewsets/course.py
"""
This file contain the viewsets for the course, offering, courseinfo and CourseHistory models.
Functionality Provided:
Course:
+ Add - (IsDeveloper)
+ Update, PartialUpdate, Delete - (IsCourseDeveloper)
+ List - (everyone allowed)
+ Retrieve - (IsRegisteredOrAnyInstructor)
- add_page - (IsOwner)
- pages - (IsRegisteredOrAnyInstructor)
- reorder_pages - (IsOwner)
- courseInfo - (None)
- pending_students, approve - (IsOwner)
- register - (None)
- deregister - (None)
- progress - (IsRegistered)
- get_all_marks - (IsOwner)
- groups - (IsRegisteredOrAnyInstructor)
- add_group - (IsOwner)
- reorder_groups - (IsOwner)
Offering:
+ Add: (IsInstructor)
+ Update, PartialUpdate, Delete: (IsCourseInstructor)
+ List: (None)
+ Retrieve: (IsRegistered)
- get_shortlisted_courses - (IsOwner)
- shortlist_course - (IsOwner)
"""
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.db.models import Q
from courseware.models import Course, Offering, CourseInfo, \
CourseHistory, Group, ConceptHistory, Concept
from courseware.vsserializers.course import CourseSerializer, \
CourseHistorySerializer, OfferingSerializer, CourseInfoSerializer
from courseware.serializers import GroupSerializer, AddGroupSerializer, \
ConceptHistorySerializer
from courseware import playlist
from courseware.permissions import IsInstructorOrReadOnly, IsRegistered, \
IsContentDeveloperOrReadOnly, IsOwnerOrReadOnly, IsOwner
from rest_framework import mixins, status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import link, action
from rest_framework.permissions import AllowAny
from discussion_forum.models import UserSetting
from document.models import Document
from document.serializers import DocumentSerializer
from discussion_forum.models import Tag
from elearning_academy.permissions import get_mode
from user_profile.models import UserProfile, Work
from quiz.models import Submission, Question, QuestionHistory, Quiz
from video.models import Video, VideoHistory, Marker, QuizMarker, SectionMarker, QuizMarkerHistory
from video.serializers import VideoSerializer, AddVideoSerializer, QuizMarkerHistorySerializer
from video.serializers import MarkerSerializer, SectionMarkerSerializer, QuizMarkerSerializer
import ast
import json
from django.db.models import Sum
from decimal import *
class CourseViewSet(viewsets.ModelViewSet):
"""
ViewSet for Course Class
"""
model = Course
serializer_class = CourseSerializer
permission_classes = [IsContentDeveloperOrReadOnly]
def get_queryset(self):
"""
Optionally restricts the returned courses to a given category.
"""
queryset = Course.objects.all()
category = self.request.QUERY_PARAMS.get('category', None)
if category is not None:
queryset = queryset.filter(category__id=category)
return queryset
def list(self, request):
"""
List all the courses for q queryset
"""
mode = get_mode(request)
queryset = Course.objects.all().select_related('course_info')
category = self.request.QUERY_PARAMS.get('category', None)
if category is not None:
queryset = queryset.filter(category__id=category)
if mode == 'I':
queryset = queryset.filter(type='T')
elif mode == 'C':
queryset = queryset.filter()
else:
queryset = queryset.filter(
type='O', course_info__is_published=True)
serializer = CourseSerializer(queryset, many=True)
response = {
"count": len(serializer.data),
"next": "null",
"previous": "null",
"results": serializer.data
}
return Response(response)
def create(self, request, *args):
"""
Function for creating a course in a category
"""
serializer = CourseSerializer(data=request.DATA, files=request.FILES)
if serializer.is_valid():
serializer.save()
coursehistory = CourseHistory(
user=request.user,
course=serializer.object,
active='A',
is_owner=True
)
coursehistory.save()
# Usersetting for the discussion forum
usersetting = UserSetting(
user=request.user,
forum=serializer.object.forum, super_user=True, moderator=True, badge='IN')
usersetting.save()
# send for approval now
return Response(serializer.data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
@action(methods=['POST'],
permission_classes=((IsOwnerOrReadOnly,)),
serializer_class=DocumentSerializer)
def add_page(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
serializer = DocumentSerializer(data=request.DATA)
if serializer.is_valid():
document = Document(
title=serializer.data['title'],
is_heading=True,
description=serializer.data['description']
)
document.save()
_course.pages.add(document)
_course.page_playlist = playlist.append(
document.id, _course.page_playlist)
_course.save()
return Response(DocumentSerializer(document).data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
@link(permission_classes=((IsOwnerOrReadOnly,)))
def pages(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
pages = _course.pages.all()
serializer = DocumentSerializer(pages, many=True)
page_playlist = playlist.to_array(_course.page_playlist)
N = len(page_playlist)
ordered_data = [""] * N
for i in range(N):
ordered_data[i] = serializer.data[page_playlist[i][1]]
return Response(ordered_data)
@action(
methods=['PATCH'],
permission_classes=((IsOwnerOrReadOnly,)),
serializer_class=CourseSerializer)
def reorder_pages(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
print request.DATA
myplaylist = request.DATA['playlist']
print myplaylist
newplaylist = playlist.is_valid(myplaylist, _course.page_playlist)
if newplaylist is not False:
_course.page_playlist = newplaylist
_course.save()
return Response(_course.page_playlist)
else:
content = "Given order data does not have the correct format"
return Response(content, status.HTTP_404_NOT_FOUND)
@link()
def courseInfo(self, request, pk=None):
"""
Function to get courseinfo, anyone can access courseinfo as it is public.
TODO: to add permission to avoid giving info to for a unpublished course.
"""
_course = get_object_or_404(Course, pk=pk)
#self.check_object_permissions(request, _course)
courseinfo = CourseInfo.objects.get(CourseInfo_Course=_course)
serializer = CourseInfoSerializer(courseinfo)
return Response(serializer.data)
@action(methods=['POST'], permission_classes=((IsOwner, )))
def publish(self, request, pk=None):
"""
Publish a course so that students can see it for enrollment
"""
course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, course)
courseinfo = course.course_info
if courseinfo.is_published:
return Response({"error": "Cannot unpublish course"}, status.HTTP_400_BAD_REQUEST)
courseinfo.is_published = True
courseinfo.save()
return Response({"msg": "Published Course"}, status.HTTP_200_OK)
@link(permission_classes=((IsOwner, )))
def approved_students(self, request, pk=None):
"""
List approved students in the course
"""
_course = get_object_or_404(Course, pk=pk)
if (_course.type == 'T'):
return Response({'response': False, 'students': []})
self.check_object_permissions(request, _course)
students = CourseHistory.objects.filter(
course=_course, active='A').select_related('user')
returned_data = []
for student in students:
returned_data.append({
"user": student.user.id,
"username": student.user.username,
"fullname": student.user.get_full_name(),
"email": student.user.email
})
return Response({'response': True, 'students': returned_data})
@action(methods=['POST','PATCH'], permission_classes=((IsOwner, )))
def course_type(self, request, pk=None):
"""
Return the course type: TextBook or Offering
If Offering: create entries in QuizMarkerHistory for all QuizMarkers and approved students
"""
_course = get_object_or_404(Course, pk=pk)
if (_course.type == 'T'):
return Response({'course_type': 'T'}, status.HTTP_200_OK)
elif (_course.type == 'O'):
return Response({'course_type': 'O'}, status.HTTP_200_OK)
else:
return Response({'course_type': 'T'}, status.HTTP_400_BAD_REQUEST)
@action(methods=['POST','PATCH'], permission_classes=((IsOwner, )))
def indivisual_video(self, request, pk=None):
"""
For a given video, returns list of students: last quiz marker seen, no of invideo quizzes seen
"""
videoId = request.DATA['videoId'];
video = get_object_or_404(Video, pk=videoId)
all_markers = video.markers.all()
_course = get_object_or_404(Course, pk=pk)
if (_course.type == 'T'):
return Response({'msg': False, 'students': []}, status.HTTP_400_BAD_REQUEST)
self.check_object_permissions(request, _course)
students = CourseHistory.objects.filter(
course=_course, active='A').select_related('user')
returned_data = []
for j in students:
latest_time = 0
for k in all_markers:
if k.type == 'Q':
if QuizMarkerHistory.objects.filter(quiz_marker=k, user=j.user).exists():
l = get_object_or_404(QuizMarkerHistory, quiz_marker=k, user=j.user)
if l.seen_status == True:
latest_time = l.quiz_marker.time
else:
break
count = 0
for k in all_markers:
if k.type == 'Q':
if QuizMarkerHistory.objects.filter(quiz_marker=k, user=j.user).exists():
l = get_object_or_404(QuizMarkerHistory, quiz_marker=k, user=j.user)
if l.seen_status == True:
count += 1
returned_data.append({
"user": j.user.id,
"username": j.user.username,
"fullname": j.user.get_full_name(),
"last_marker_seen": latest_time,
"invideo_quizzes": count
})
last_quiz_marker = 0
for k in all_markers:
if k.type == 'Q':
last_quiz_marker = k.time
total = 0
for k in all_markers:
if k.type == 'Q':
total += 1
return Response({'last_quiz_marker': last_quiz_marker,'total_invideo_quizzes': total, 'students': returned_data}, status.HTTP_200_OK)
@action(methods=['POST','PATCH'], permission_classes=((IsOwner, )))
def accross_all_videos(self, request, pk=None):
"""
Across all videos: average % video seen (based on quiz marker), average invideo quizzes seen
"""
_course = get_object_or_404(Course, pk=pk)
if (_course.type == 'T'):
return Response({'msg': False, 'students': []}, status.HTTP_400_BAD_REQUEST)
self.check_object_permissions(request, _course)
students = CourseHistory.objects.filter(
course=_course, active='A').select_related('user')
videolist = Concept.objects.filter(group__course=_course).values_list('videos', flat=True)
returned_data = []
total_invideo_quizzes = 0
for j in students:
total_percent_seen = Decimal(0)
count_of_videos = Decimal(0)
avg_percent_seen = Decimal(0)
for i in videolist:
if Video.objects.filter(pk=i).exists():
video = get_object_or_404(Video, pk=i)
last_existing_marker = Decimal(0)
latest_time = Decimal(0)
all_markers = video.markers.all()
for k in all_markers:
if k.type == 'Q':
if QuizMarkerHistory.objects.filter(quiz_marker=k, user=j.user).exists():
l = get_object_or_404(QuizMarkerHistory, quiz_marker=k, user=j.user)
last_existing_marker = l.quiz_marker.time
for k in all_markers:
if k.type == 'Q':
if QuizMarkerHistory.objects.filter(quiz_marker=k, user=j.user).exists():
l = get_object_or_404(QuizMarkerHistory, quiz_marker=k, user=j.user)
if l.seen_status == True:
latest_time = l.quiz_marker.time
else:
break
if(last_existing_marker != 0):
percent_seen = Decimal(latest_time*100 / last_existing_marker)
count_of_videos += Decimal(1)
total_percent_seen += Decimal(percent_seen)
if (count_of_videos != 0):
avg_percent_seen = Decimal(total_percent_seen / count_of_videos).quantize(Decimal("0.00"))
total_invideo_quizzes_seen = 0
total_invideo_quizzes = 0
for i in videolist:
if Video.objects.filter(pk=i).exists():
video = get_object_or_404(Video, pk=i)
all_markers = video.markers.all()
for k in all_markers:
if k.type == 'Q':
if QuizMarkerHistory.objects.filter(quiz_marker=k, user=j.user).exists():
total_invideo_quizzes += 1
for k in all_markers:
if k.type == 'Q':
if QuizMarkerHistory.objects.filter(quiz_marker=k, user=j.user).exists():
l = get_object_or_404(QuizMarkerHistory, quiz_marker=k, user=j.user)
if l.seen_status == True:
total_invideo_quizzes_seen +=1
returned_data.append({
"user": j.user.id,
"username": j.user.username,
"fullname": j.user.get_full_name(),
"avg_video_seen": avg_percent_seen,
"total_invideo_quizzes_seen": total_invideo_quizzes_seen
})
return Response({'total_invideo_quizzes': total_invideo_quizzes, 'students': returned_data}, status.HTTP_200_OK)
@action(methods=['POST','PATCH'], permission_classes=((IsOwner, )))
def get_all_videos(self, request, pk=None):
"""
Function to get all the videos in a course
"""
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
videos = Concept.objects.filter(group__course=_course).values_list('videos', flat=True)
returned_data = []
for video in videos:
if Video.objects.filter(pk=video).exists():
k = get_object_or_404(Video, pk=video)
returned_data.append({
"title": k.title,
"id":k.id
})
return Response({'videolist': returned_data}, status.HTTP_200_OK)
@link(permission_classes=((IsOwner, )))
def pending_students(self, request, pk=None):
"""
List the students which are pending approval in the course
"""
_course = get_object_or_404(Course, pk=pk)
if (_course.type == 'T'):
return Response({'response': False, 'students': []})
self.check_object_permissions(request, _course)
students = CourseHistory.objects.filter(course=_course, active='P')
returned_data = []
for student in students:
user = User.objects.get(pk=student.user.id)
returned_data.append({
"user": user.id,
"username": user.username,
"fullname": user.get_full_name(),
"email": user.email,
})
return Response({'response': True, 'students': returned_data})
@action(methods=['POST'], permission_classes=((IsOwner, )))
def approve(self, request, pk=None):
"""
- This function takes a list of student ids and
approve their request to register
- Also create QuizMarkerHistory entries for the approved students
"""
_course = get_object_or_404(Course, pk=pk, type='O')
self.check_object_permissions(request, _course)
videos = Concept.objects.filter(group__course=_course).values_list('videos', flat=True)
if 'students' in request.DATA:
# converting a string representation of array to
students = ast.literal_eval(request.DATA['students'])
for student in students:
try:
coursehistory = CourseHistory.objects.get(
course=_course,
user=student,
active='P'
)
coursehistory.active = 'A'
coursehistory.save()
for video in videos:
k = get_object_or_404(Video, pk=video)
all_markers = k.markers.all()
for m in all_markers:
if m.type == 'Q':
new_data = {
'quiz_marker': m,
'user': student,
'seen_status': False,
'times_seen': 0,
}
quiz_marker_history_serializer = QuizMarkerHistorySerializer(data=new_data)
if quiz_marker_history_serializer.is_valid():
quiz_marker_history_serializer.save()
else:
print quiz_marker_history_serializer.errors
except:
continue
return Response({"msg": 'Success'}, status.HTTP_200_OK)
else:
print request.DATA
return Response({"error": "Bad request format"}, status.HTTP_400_BAD_REQUEST)
@link()
def register(self, request, pk=None):
"""
Register a student to a course.
"""
course = get_object_or_404(Course, pk=pk, type='O')
try:
coursehistory = CourseHistory.objects.get(
course=course,
user=request.user,
)
if coursehistory.active == 'U':
coursehistory.active = 'A'
coursehistory.save()
# TODO: shift the usersetting to the approve function
usersetting = UserSetting.objects.filter(
user=request.user, forum=course.forum)
if len(usersetting) > 0:
usersetting = usersetting[0]
usersetting.is_active = True
usersetting.save()
return Response("Successfully registered", status.HTTP_202_ACCEPTED)
else:
return Response(
"Your approval is pending. Please contact instructor for your approval",
status.HTTP_400_BAD_REQUEST
)
except:
coursehistory = CourseHistory(
course=course,
user=request.user,
active='A'
)
if course.enrollment_type == 'M':
coursehistory.active = 'P'
coursehistory.save()
usersetting = UserSetting(user=request.user, forum=course.forum)
usersetting.save()
return Response("Successfully registered", status.HTTP_202_ACCEPTED)
# TODO : should be action and not link
# TODO : register and deregister should be sent to OfferingViewSet
# TODO : user active should also be made choice field
@link()
def deregister(self, request, pk=None):
course = get_object_or_404(Course, pk=pk, type='O')
try:
coursehistory = CourseHistory.objects.get(
course=course,
user=request.user,
# an owner cannot deregister himself from the course
is_owner=False
)
if coursehistory.active != 'U':
coursehistory.active = 'U'
coursehistory.save()
usersetting = UserSetting.objects.filter(
user=request.user, forum=course.forum)
if len(usersetting) > 0:
usersetting = usersetting[0]
usersetting.is_active = False
usersetting.save()
return Response(CourseSerializer(course).data)
except:
error = 'You were not registered in this course.'
return Response(error)
@link(permission_classes=((IsRegistered, )))
def progress(self, request, pk=None):
"""
Function to get marks in a course
"""
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
history = get_object_or_404(
CourseHistory,
course=_course,
user=request.user
)
return Response(history.progress())
@link(permission_classes=((IsRegistered,)))
def get_all_public_marks(self, request, pk=None):
"""
Function to get marks of all the students for whom show_marks is true
"""
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
histories = CourseHistory.objects.filter(
course=_course, is_owner=False, show_marks=True).select_related('user').order_by('score').select_related('user', 'course').reverse()
students = []
for history in histories:
students += [history.user.id]
quizzes = Concept.objects.filter(group__course=_course).values('quizzes')
questions = Question.objects.filter(quiz__in=quizzes).values('id')
videos = Concept.objects.filter(group__course=_course).values('videos')
# Markers needed to connect in video quiz to course
markers = Marker.objects.filter(video__in=videos).values('id')
in_video_quizzes=QuizMarker.objects.filter(id__in=markers).values('quiz')
in_video_questions = Question.objects.filter(quiz__in=in_video_quizzes).values('id')
quiz_submitted = QuestionHistory.objects.filter(student__in=students, question__in=questions).exclude(
status='N').select_related('question').values('student__id').annotate(Sum('question__marks'))
in_video_quiz_submitted = QuestionHistory.objects.filter(student__in=students,question__in=in_video_questions).select_related('question').exclude(status='N').values('student__id','marks')
work_info = Work.objects.filter(user__in=students).select_related(
'company', 'user').values_list('user__id', 'company__company')
data = {}
data['students'] = []
i = 0
for history in histories:
attempted_score = 0
new_attempted_score=0
for quiz in quiz_submitted:
if quiz['student__id'] == history.user.id:
attempted_score += quiz['question__marks__sum']
for quiz in in_video_quiz_submitted:
if quiz['student__id'] == history.user.id:
new_attempted_score += quiz['marks']
data['students'].append({})
data['students'][i]['score'] = history.score
# TODO: this is a hack to render max_score only once
data['max_score'] = history.course.max_score
data['students'][i]['attempted_score'] = attempted_score
data['students'][i]['user'] = history.user.username
data['students'][i]['id'] = history.user.id
data['students'][i]['in_video_quiz_score']=new_attempted_score
for work in work_info:
if work[0] == history.user.id:
data['students'][i]['work'] = work[1]
break
data['students'][i]['name'] = history.user.get_full_name()
i += 1
return Response(data)
@link(permission_classes=((IsRegistered,)))
def get_all_public_marks_student(self, request, pk=None):
"""
Function to get marks of a student for whom show_marks is true
"""
_course = get_object_or_404(Course, pk=pk)
studentID = self.request.QUERY_PARAMS.get('student', None)
_student = get_object_or_404(User, pk=studentID)
self.check_object_permissions(request, _course)
history = CourseHistory.objects.get(
course=_course, user=_student, is_owner=False, show_marks=True)
data = {}
data = (history.progress())
data['user'] = history.user.username
data['id'] = history.user.id
data['name'] = history.user.get_full_name()
return Response(data)
@link(permission_classes=((IsOwner,)))
def get_all_marks(self, request, pk=None):
"""
Function to get marks of all the students
"""
_course = get_object_or_404(Course, pk=pk)
remote_id = request.QUERY_PARAMS.get('remote_id', None)
self.check_object_permissions(request, _course)
if remote_id and remote_id!="all":
work_info = Work.objects.filter(company__company=remote_id).select_related('user__id', 'company__company').values_list('user__id', 'company__company')
students = [w[0] for w in work_info]
histories = CourseHistory.objects.filter(
course=_course, is_owner=False, user__in=students).order_by('score').reverse().select_related('user', 'course')
elif remote_id=="all":
histories = CourseHistory.objects.filter(
course=_course, is_owner=False).order_by('score').reverse().select_related('user', 'course')
students = [history.user.id for history in histories]
work_info = Work.objects.filter(user__in=students).select_related(
'company', 'user').values_list('user__id', 'company__company')
quizzes = Concept.objects.filter(group__course=_course).values('quizzes')
questions = Question.objects.filter(quiz__in=quizzes).values('id')
quiz_submitted = QuestionHistory.objects.filter(student__in=students, question__in=questions).exclude(
status='N').select_related('question').values('student__id').annotate(Sum('question__marks'))
data = {}
data['students'] = []
i = 0
for history in histories:
attempted_score = 0
for quiz in quiz_submitted:
if quiz['student__id'] == history.user.id:
attempted_score += quiz['question__marks__sum']
data['students'].append({})
data['students'][i]['score'] = history.score
# TODO: this is a hack to render max_score only once
data['max_score'] = history.course.max_score
data['students'][i]['attempted_score'] = attempted_score
data['students'][i]['user'] = history.user.username
data['students'][i]['id'] = history.user.id
for work in work_info:
if work[0] == history.user.id:
data['students'][i]['work'] = work[1]
break
data['students'][i]['name'] = history.user.get_full_name()
i += 1
return Response(data)
@link(permission_classes=((IsOwner,)))
def get_all_marks_student(self, request, pk=None):
"""
Function to get marks of a student
"""
_course = get_object_or_404(Course, pk=pk)
studentID = self.request.QUERY_PARAMS.get('student', None)
_student = get_object_or_404(User, pk=studentID)
self.check_object_permissions(request, _course)
history = CourseHistory.objects.get(
course=_course, user=_student, is_owner=False)
data = {}
data = (history.progress())
data['user'] = history.user.username
data['id'] = history.user.id
data['name'] = history.user.get_full_name()
return Response(data)
@link(permission_classes=((IsOwner,)))
def get_users(self, request, pk=None):
"""
Function to get user by name
"""
_course = get_object_or_404(Course, pk=pk)
name = self.request.QUERY_PARAMS.get('search_str', None)
data = {}
i=0
data['users'] = []
users = User.objects.all()
for term in name.split():
users = users.filter( Q(first_name__icontains = term) | Q(last_name__icontains = term) | Q(username__icontains = term))[0:10]
for user in users:
data['users'].append({})
data['users'][i]['id'] = user.id
data['users'][i]['username'] = user.username
data['users'][i]['fullname'] = user.get_full_name()
data['users'][i]['email'] = user.email
i += 1
return Response(data)
@action(methods=['POST'], permission_classes=((IsOwner, )))
def grant_instructor_permission(self, request, pk=None):
"""
"""
_course = get_object_or_404(Course, pk=pk, type='O')
self.check_object_permissions(request, _course)
ch = CourseHistory.objects.get(user=self.request.user,course=_course)
if ch.is_creator:
if 'users' in request.DATA:
# converting a string representation of array to
students = ast.literal_eval(request.DATA['users'])
for student in students:
try:
u = User.objects.get(pk=student)
coursehistory = CourseHistory.objects.filter(course=_course,user=u)
if len(coursehistory)>0:
coursehistory[0].is_owner = True
coursehistory[0].save()
else:
coursehistory = CourseHistory(
user=u,
course=_course,
active='A',
is_owner=True
)
coursehistory.save()
usersetting = Usersetting.objects.filter(forum=_course.forum,user=u)
if len(usersetting)>0:
usersetting[0].super_user=True
usersetting[0].moderator=True
else:
usersetting = UserSetting(
user=u,
forum=_course.forum, super_user=True, moderator=True, badge='IN')
usersetting.save()
except Exception,e:
print e
return Response({"msg": 'Success'}, status.HTTP_200_OK)
else:
print request.DATA
return Response({"error": "Bad request format"}, status.HTTP_400_BAD_REQUEST)
else:
return Response("Forbidden", status.HTTP_403_FORBIDDEN)
@link(permission_classes=((IsOwner,)))
def all_instructors(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk)
coursehistory = CourseHistory.objects.filter(course=_course)
data = {}
i=0
data['approvedInstructors'] = []
for ch in coursehistory:
if ch.is_owner==True:
user = ch.user
data['approvedInstructors'].append({})
data['approvedInstructors'][i]['id'] = user.id
data['approvedInstructors'][i]['username'] = user.username
data['approvedInstructors'][i]['fullname'] = user.get_full_name()
data['approvedInstructors'][i]['email'] = user.email
i += 1
return Response(data)
@action(methods=['POST'], permission_classes=((IsOwner, )))
def remove_instructor_permission(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk, type='O')
self.check_object_permissions(request, _course)
ch = CourseHistory.objects.get(user=self.request.user,course=_course)
if ch.is_creator:
if 'instructors' in request.DATA:
students = ast.literal_eval(request.DATA['instructors'])
for student in students:
try:
u = User.objects.get(pk=student)
if u==request.user:
return Response("Forbidden", status.HTTP_403_FORBIDDEN)
else:
coursehistory = CourseHistory.objects.get(course=_course,user=u)
coursehistory.is_owner = False
coursehistory.save()
usersetting = Usersetting.objects.get(forum=_course.forum,user=u)
usersetting.moderator=False
usersetting.super_user=False
usersetting.save()
except Exception,e:
print e
return Response({"msg": 'Success'}, status.HTTP_200_OK)
else:
print request.DATA
return Response({"error": "Bad request format"}, status.HTTP_400_BAD_REQUEST)
else:
return Response("Forbidden", status.HTTP_403_FORBIDDEN)
@link(permission_classes=((IsOwnerOrReadOnly, )))
def groups(self, request, pk=None):
"""
Function to get all the groups in a course
"""
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
_groups = Group.objects.filter(course=_course)
serializer = GroupSerializer(_groups, many=True)
_playlist = playlist.to_array(_course.playlist)
N = len(_playlist)
ordered_data = [""] * N
for i in range(N):
ordered_data[i] = serializer.data[_playlist[i][1]]
return Response(ordered_data)
@action(
methods=['POST'],
permission_classes=((IsOwnerOrReadOnly,)),
serializer_class=AddGroupSerializer)
def add_group(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
serializer = AddGroupSerializer(data=request.DATA)
if serializer.is_valid():
if request.FILES == {}:
group = Group(
course=_course,
title=serializer.data['title'],
description=serializer.data['description']
)
else:
group = Group(
course=_course,
title=serializer.data['title'],
description=serializer.data['description'],
image=request.FILES['image']
)
group.save()
_course.playlist = playlist.append(group.id, _course.playlist)
_course.save()
return Response(GroupSerializer(group).data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
@action(
methods=['PATCH'],
permission_classes=((IsOwnerOrReadOnly,)),
serializer_class=CourseSerializer)
def reorder_groups(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, _course)
myplaylist = request.DATA['playlist']
newplaylist = playlist.is_valid(myplaylist, _course.playlist)
if newplaylist is not False:
_course.playlist = newplaylist
_course.save()
return Response(_course.playlist)
else:
content = "Given order data does not have the correct format"
return Response(content, status.HTTP_404_NOT_FOUND)
@action(methods=['PATCH'], permission_classes=((IsRegistered,)))
def set_marks_setting(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk)
history = CourseHistory.objects.get(
course=_course, user=self.request.user)
show_marks = self.request.QUERY_PARAMS.get('show', None)
if(show_marks == 'true'):
history.show_marks = True
else:
history.show_marks = False
history.save()
return Response(history.show_marks)
@link(permission_classes=((IsRegistered,)))
def get_marks_setting(self, request, pk=None):
_course = get_object_or_404(Course, pk=pk)
history = CourseHistory.objects.get(
course=_course, user=self.request.user)
return Response(history.show_marks)
class OfferingViewSet(viewsets.ModelViewSet):
"""
ViewSet for model Offering
"""
model = Offering
serializer_class = OfferingSerializer
permission_classes = [IsInstructorOrReadOnly]
def get_queryset(self):
"""
Optionally restricts the returned courses to a given category.
"""
queryset = Offering.objects.all()
category = self.request.QUERY_PARAMS.get('category', None)
if category is not None:
queryset = queryset.filter(category__id=category)
return queryset
def create(self, request, pk=None, *args):
"""
Function for creating an offering in a category
"""
serializer = OfferingSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
coursehistory = CourseHistory(
user=request.user,
course=serializer.object,
active='A',
is_owner=True,
is_creator=True
)
coursehistory.save()
# usersetting for the discussion forum
usersetting = UserSetting(
user=request.user,
forum=serializer.object.forum, super_user=True, moderator=True, badge='IN')
usersetting.save()
# send for approval now
# Create a 'General' tag for each course
tag = Tag(forum=serializer.object.forum)
tag.tag_name = 'General'
tag.title = 'General'
tag.save()
return Response(serializer.data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
@link(permission_classes=((IsOwner, )))
def get_shortlisted_courses(self, request, pk=None):
mycourse = get_object_or_404(Offering, pk=pk)
self.check_object_permissions(request, mycourse)
shortlist = mycourse.shortlisted_courses.all()
serializer = CourseSerializer(shortlist, many=True)
return Response(serializer.data)
@action(methods=['POST'], permission_classes=((IsOwner, )))
def shortlist_course(self, request, pk=None):
mycourse = get_object_or_404(Offering, pk=pk)
self.check_object_permissions(request, mycourse)
try:
_course = Course.objects.get(pk=request.DATA['id'], type='T')
except:
return Response("Bad Request: No such textbook", status.HTTP_400_BAD_REQUEST)
mycourse.shortlisted_courses.add(_course)
return Response("Successfully shortlisted the course", status.HTTP_202_ACCEPTED)
class CourseHistoryViewSet(mixins.UpdateModelMixin, viewsets.GenericViewSet):
"""
ViewSet for CourseHistory. Only gives Update option
"""
model = CourseHistory
serializer_class = CourseHistorySerializer
permission_classes = [IsInstructorOrReadOnly]
@link(permission_classes=((IsRegistered, )))
def concept_history(self, request, pk=None):
coursehistory = get_object_or_404(CourseHistory, pk=pk)
self.check_object_permissions(request, coursehistory.course)
history = ConceptHistory.objects.filter(
user=request.user, course_history=coursehistory)
serializer = ConceptHistorySerializer(history, many=True)
return Response(serializer.data)
class CourseInfoViewSet(viewsets.ModelViewSet):
queryset = CourseInfo.objects.all()
serializer_class = CourseInfoSerializer
<file_sep>/courseware/static/courseware/js/content_developer/course_settings.jsx
/** @jsx React.DOM */
/**
* This allows instructor/content_developer to change the settings for course
*/
var CourseDetail = React.createClass ({
base_url: '/courseware/api/course/',
handleCategoryChange: function(category) {
this.setState({category: category});
return false;
},
getInitialState: function() {
return {
category: undefined,
};
},
update_course: function() {
url = this.base_url + this.props.data.id + "/?format=json";
var fd = new FormData();
fd.append('category', this.state.category);
fd.append('title', this.refs.title.getDOMNode().value.trim());
if(this.refs.image.getDOMNode().files[0]){
fd.append('image', this.refs.image.getDOMNode().files[0]);
}
if (this.props.data.type == 'O') {
fd.append('enrollment_type', this.refs.enrollment_type.getDOMNode().value.trim());
}
request = ajax_custom_request({
url: url,
type: "PATCH",
data: fd,
mimeType: 'multipart/form-data',
});
request.done(function(response) {
response = jQuery.parseJSON(response);
window.location = "/courseware/course/" + response.id;
}.bind(this));
return false;
},
render: function() {
data = this.props.data;
return (
<div class="panel panel-default">
<div class="panel-heading">
Update Details
</div>
<div class="panel-body">
<form id="update_course" role="form" class="form-horizontal">
<fieldset>
<CategoryLoader callback={this.handleCategoryChange}
defaultCategory={data.category}/>
</fieldset>
<div class="form-group">
<label class="control-label col-md-2 col-md-offset-1">
Title</label>
<div class="col-md-7 col-md-offset-1">
<input name="title" type="text" class="form-control"
ref="title" placeholder="Title"
defaultValue={data.title}></input>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-md-offset-1">
Course Image</label>
<div class="col-md-7 col-md-offset-1">
<input name="image" type="file" class="form-control"
ref="image"></input>
</div>
</div>
{data.type == 'O' ?
<div class="form-group">
<label class="control-label col-md-3 col-md-offset-0">
Enrollment Type</label>
<div class="col-md-7 col-md-offset-1">
{data.enrollment_type == 'O'?
<select ref="enrollment_type"
name="enrollment_type"
class="form-control">
<option value="O" selected="selected">
Open</option>
<option value="M">Moderated</option>
</select>
:
<select ref="enrollment_type"
name="enrollment_type"
class="form-control">
<option value="O">Open</option>
<option value="M" selected="selected">
Moderated</option>
</select>
}
</div>
</div>
: null
}
<div class="form-group">
<div class="col-md-2 col-md-offset-5 addcoursebutton">
<button ref="submit" class="btn btn-primary"
type="button" onClick={this.update_course}>
Update</button>
</div>
</div>
</form>
</div>
</div>
);
},
});
var CourseInfoEdit = React.createClass({
base_url: '/courseware/api/courseinfo/',
componentDidMount: function() {
course_info = this.props.data.course_info;
start_time = course_info.start_time? course_info.start_time : "+0d";
end_time = course_info.end_time? course_info.end_time : "+0d";
end_enrollment_date = course_info.end_enrollment_date? course_info.end_enrollment_date : "+0d";
$(function() {
$( "#start_time" ).datepicker({
dateFormat: "yy-mm-dd",
defaultDate: start_time,
minDate: "+0d",
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#end_time" ).datepicker( "option", "minDate", selectedDate );
$( "#end_enrollment_date" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#end_time" ).datepicker({
dateFormat: "yy-mm-dd",
defaultDate: end_time,
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#start_time" ).datepicker( "option", "maxDate", selectedDate );
$( "#end_enrollment_date" ).datepicker( "option", "maxDate", selectedDate );
}
});
$( "#end_enrollment_date" ).datepicker({
dateFormat: "yy-mm-dd",
defaultDate: end_enrollment_date,
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
});
});
},
update_info: function() {
url = this.base_url + this.props.data.course_info.id + "/?format=json";
data = {
start_time: this.refs.startTime.getDOMNode().value,
end_time: this.refs.endTime.getDOMNode().value,
end_enrollment_date: this.refs.endEnrollmentDate.getDOMNode().value,
description: this.refs.courseDescription.getDOMNode().value,
};
request = ajax_json_request(url, "PATCH", data)
request.done(function(response) {
response = jQuery.parseJSON(response);
display_global_message("Updated Course Information", "success");
});
request.fail(function() {
response = jQuery.parseJSON(response);
display_global_message("Unable to update. Check input or try later", "error");
});
},
render: function() {
course_info = this.props.data.course_info;
return (
<div class="panel panel-default">
<div class="panel-heading">
Update Settings
</div>
<div class="panel-body">
<form id="update_course" role="form" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-2 col-md-offset-1">
Start Date</label>
<div class="col-md-7 col-md-offset-1">
<input type="text" id="start_time" name="start_time"
class="form-control" ref="startTime"> </input>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-md-offset-1">
End Date</label>
<div class="col-md-7 col-md-offset-1">
<input type="text" id="end_time" name="end_time"
class="form-control" ref="endTime"> </input>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-md-offset-0">
Enrollment End Date</label>
<div class="col-md-7 col-md-offset-1">
<input type="text" id="end_enrollment_date"
name="end_enrollment_date"
class="form-control" ref="endEnrollmentDate"> </input>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-md-offset-1">
Description</label>
<div class="col-md-7 col-md-offset-1">
<div class="wmd-toolbox"></div>
<div>
<WmdTextarea name="course-description"
ref="courseDescription" style={{height: '150px'}}
placeholder="Description"
defaultValue={course_info.description} />
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-2 col-md-offset-5 addcoursebutton">
<button ref="submit" class="btn btn-primary"
type="button" onClick={this.update_info}>
Update</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
);
},
});
var CourseSettings = React.createClass({
mixins: [LoadMixin],
base_url: '/courseware/api/course/',
getUrl: function() {
url = this.base_url + this.props.courseid + "/?format=json";
return url;
},
getInitialState: function() {
return {
loaded: false,
data: undefined,
};
},
publish_course: function() {
url = this.base_url + this.props.courseid + "/publish/?format=json";
request = ajax_json_request(url, "POST", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
display_global_message(response.msg, "success");
$("#publish-course").fadeOut();
});
request.fail(function(response) {
response = jQuery.parseJSON(response);
display_global_message(response.error, "error");
})
return false;
},
render: function() {
if (this.state.loaded) {
data = this.state.data;
course_info = data.course_info;
return (
<div>
{!course_info.is_published ?
<div class="row">
<div class="col-md-2 col-md-offset-10">
<button class="btn btn-primary addgroup-button pull-right"
onClick={this.publish_course} id="publish-course">
Publish </button>
</div>
</div>
:
null
}
<div class="row">
<div class="col-md-12">
<CourseDetail data={data} />
<CourseInfoEdit data={data} />
</div>
</div>
</div>
);
} else {
return <LoadingBar />;
}
},
});
<file_sep>/progress/urls.py
"""
Progress URL resolver file
"""
from django.conf.urls import patterns, url
from progress import views
urlpatterns = patterns(
'',
url(r'^(?P<course>[1-9][0-9]*)$', views.view_progress)
)
<file_sep>/evaluate/templatetags/evaluatetags.py
'''
Created on Apr 19, 2014
@author: aryaveer
'''
from django import template
register = template.Library()
@register.filter
def getdictvalue(error_dict, key):
try:
return error_dict[key]
except KeyError:
return key
<file_sep>/discussion_forum/static/discussion_forum/js/forumentities.jsx
/** @jsx React.DOM */
var Reply = React.createClass({
mixins: [ContentUpdateMixin],
getInitialState: function() {
new_state = {
"data": this.props.data
};
return new_state;
},
render: function() {
if(this.state.deleted) {
return (
<div class="alert alert-info alert-dismissable forum-delete-info">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Reply has been removed !</strong>
</div>
)
}
return (
<Content current_user={this.props.current_user} type="reply" data={this.state.data} callback={this.updateContentData} remove={this.remove} />
)
}
});
var ReplyList = React.createClass({
mixins: [ListMixin],
render: function() {
var replyNodes = this.state.items.map(function (reply) {
return <tr><td><Reply current_user={this.props.current_user} data={reply} callback={this.props.callback} /></td></tr>;
}.bind(this));
var hasMore = <tr><td class="reply"><button class="btn btn-link" onClick={this.loadMore}>Load more replies</button></td></tr>;
return (
<div class="reply-list">
<table class="table">
{replyNodes}
{this.state.next ? hasMore : <tr></tr>}
<tr>
<td class="reply">
<ContentForm type="Reply" submit={this.submitContentForm} callback={this.props.callback} />
</td>
</tr>
</table>
</div>
)
}
});
var Comment = React.createClass({
mixins: [ContentUpdateMixin],
getUrl: function(_id) {
return "/forum/api/comment/" + _id + "/";
},
getInitialState: function() {
_url = this.getUrl(this.props.data.id);
new_state = {
"replies": _url + "replies/?format=json",
"add_reply": _url + "add_reply/?format=json",
"data": this.props.data
};
return new_state;
},
render: function() {
if(this.state.deleted) {
return (
<div class="alert alert-info alert-dismissable forum-delete-info">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Comment has been removed !</strong>
</div>
)
}
return (
<div>
<Content current_user={this.props.current_user} type="comment" data={this.state.data} callback={this.updateContentData} remove={this.remove} />
<div>
<ReplyList current_user={this.props.current_user} list={this.state.replies} add={this.state.add_reply} callback={this.updateChildrenCount} />
</div>
</div>
)
}
});
var CommentList = React.createClass({
mixins: [ListMixin],
render: function() {
var commentNodes = this.state.items.map(function (comment) {
return <tr><td><Comment key={"comment_"+comment.id} current_user={this.props.current_user} data={comment} callback={this.props.callback} /></td></tr>;
}.bind(this));
if(!commentNodes) {
commentNodes = <LoadingBar />;
}
var hasMore = <tr><td class="comment"><button class="btn btn-link" onClick={this.loadMore}>Load more comments</button></td></tr>;
return (
<table class="table comment-list">
{commentNodes}
{this.state.next ? hasMore : <tr></tr>}
<tr>
<td class="comment">
<div>
<ContentForm type="Comment" submit={this.submitContentForm} callback={this.props.callback} />
</div>
</td>
</tr>
</table>
);
}
});
var Thread = React.createClass({
mixins: [ContentUpdateMixin],
getUrl: function(_id) {
return "/forum/api/thread/" + _id + "/";
},
getInitialState: function() {
_url = this.getUrl(this.props.data.id);
new_state = {
"comments": _url + "comments/?format=json",
"add_comment": _url + "add_comment/?format=json",
"loaded": false,
"data": this.props.data
};
return new_state;
},
loadComments: function() {
var state = this.state;
if(state.loaded) {
return;
} else {
state.loaded = true;
this.setState(state);
}
},
render: function() {
if(this.state.deleted) {
return (
<div class="alert alert-info alert-dismissable forum-delete-info">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Thread has been removed !</strong>
</div>
)
}
var pinned = '';
if(this.state.data.pinned) {
pinned = <li><span class="glyphicon glyphicon-pushpin"></span></li>;
}
var comment_list = '';
if(this.state.loaded) {
comment_list = <CommentList current_user={this.props.current_user} list={this.state.comments} add={this.state.add_comment} callback={this.updateChildrenCount} />;
} else {
<LoadingBar />
}
return (
<div class="panel panel-default">
<div class="panel-heading">
<table class="thread-heading">
<tr>
<td>
<h4 class="panel-title">
<a onClick={this.loadComments} class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href={"#thread" + this.props.data.id}>
{this.props.data.title}
</a><br/>
<ul class="content-meta-info thread-meta-info">
{pinned}
<li><DynamicDateTime time={this.props.data.created} refreshInterval={20000} /></li>
<li>posted by - <UserLink data={this.props.data.author} /></li>
<li><span class="label label-default">{this.props.data.author_badge}</span></li>
<li><ThreadSubscription thread_id={this.props.data.id} subscribed={this.props.data.subscribed} /></li>
</ul>
</h4>
</td>
<td class="thread-vote-icon"><span class="glyphicon glyphicon-star"> {' ' + this.state.data.popularity}</span></td>
<td class="thread-vote-icon"><span class="glyphicon glyphicon-eye-open"> {' ' + this.state.data.hit_count}</span></td>
<td class="thread-vote-icon"><span class="glyphicon glyphicon-comment"> {' ' + this.state.data.children_count}</span></td>
</tr>
</table>
</div>
<div id={"thread" + this.props.data.id} class="panel-collapse collapse">
<div class="panel-body thread-panel-body">
<ThreadTagList thread_id={this.props.data.id} thread_tags={this.props.data.tags} forum_tags={this.props.forum_tags} />
<Content current_user={this.props.current_user} type="thread" data={this.state.data} callback={this.updateContentData} remove={this.remove}/>
{comment_list}
</div>
</div>
</div>
);
}
});
var ThreadList = React.createClass({
mixins: [ListMixin],
dummy: function(index) {
return;
},
render: function() {
var threadNodes = this.state.items.map(function (thread) {
return <Thread current_user={this.props.current_user} data={thread} forum_tags={this.props.forum_tags} callback={this.dummy} />;
}.bind(this));
var more = '';
if(this.state.next != null) {
more = <div><button class="btn btn-link" onClick={this.loadMore}>Load more threads</button></div>;
}
return (
<div class="thread-list">
<SortOrders order={this.updateSortOrder} />
<ThreadForm add={this.props.add} add_tag={this.props.add_tag} tags={this.props.forum_tags} submit={this.submitContentForm} callback={this.dummy} tid={this.props.tid} />
<hr/>
<div class="panel-group" id="accordion">
{threadNodes}
</div>
{more}
</div>
)
}
});
<file_sep>/discussion_forum/static/discussion_forum/js/mixins.jsx
/** @jsx React.DOM */
/*
Common Functionality for updating state of thread/comment/reply objects
*/
var ContentUpdateMixin = {
updateContentData: function(new_data) {
//Update thread-meta info
// We are not using title and tags in state
this.setState({data: new_data});
},
updateChildrenCount: function(val) {
var state = this.state;
if(state.data == null) {
return;
}
state.data.children_count += val; // We are not using title and tags in state
this.setState(state);
},
remove: function() {
var state = this.state;
state.deleted = true;
this.props.callback(-1);
this.setState(state);
}
};
/*
Abstracted common functionality of ThreadForm and ContentForm
*/
var FormMixin = {
getInitialState: function() {
return {loaded: false};
},
loadForm: function() {
this.setState({loaded: true});
},
removeForm: function() {
this.setState({loaded: false});
}
};
/*
Abstracted common functionality of ThreadList, CommentList, ReplyList
*/
var ListMixin = {
// Requied props: list, add (only if submit is allowed)
getInitialState: function() {
return {
count: 0, //Count of total items in database
next: this.props.list,
items: []
};
},
addItem: function(item) {
var items = this.state.items;
if(this.props.push == "front") {
items.unshift(item);
} else {
items.push(item);
}
var new_state = {
"count": this.state.count + 1,
"next": this.state.next,
"items": items
};
this.setState(new_state);
},
updateState: function(response) {
//Updates state after it gets list from server
var items = this.state.items;
items = items.concat(response.results);
var new_state = {
"count": response.count + this.state.count,
"next": response.next,
"items": items
};
this.setState(new_state);
},
loadMoreObjects: function(_url) {
var data = {};
//hack to replace local ip
_url = _url.replace("http://127.0.0.1:8000","");
console.log("NEXT_URL"+_url);
var request = ajax_json_request(_url, "GET", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
this.updateState(response);
}.bind(this));
},
loadMore: function() {
if (this.state.next == null) {
return;
}
this.loadMoreObjects(this.state.next);
},
componentDidMount: function() {
// Loads threads for the first time when component get mounted
this.loadMoreObjects(this.state.next);
},
componentWillReceiveProps: function (nextProps) {
/* Whenever list property is updated reset everything and load new \
* threads
*/
if(this.props.list == nextProps.list) {
return;
}
var _url_part = ((this.order == undefined) ? '' : '&order='+this.order);
var new_state = this.state;
new_state.count = 0; //Count of total items in database
new_state.next = nextProps.list + _url_part;
new_state.items = [];
this.setState(new_state, this.loadMoreObjects(new_state.next));
},
updateSortOrder: function(order) {
this.order = order;
var new_state = {
"count" : 0,
"next": this.props.list + "&order="+ order,
"items": [],
}
this.setState(new_state, this.loadMoreObjects(new_state.next));
},
submitContentForm: function(data) {
//Make a json call for validation
request = ajax_json_request(this.props.add, "POST", data);
request.done(function(response) {
item = jQuery.parseJSON(response);
if("tag_id" in data)
{
this.addTag(item['id'],data["tag_id"]);
}
this.addItem(item);
}.bind(this));
},
addTag: function(id, value){
url = "/forum/api/thread/"+id+"/add_tag/?format=json";
data = {'value': value};
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
item = jQuery.parseJSON(response);
}.bind(this));
}
};
<file_sep>/README.md
elearning-academy
=================
Online Learning platform mainly aimed for education in India
### Authors ###
1. [<NAME>][alankar]
2. [<NAME>][aakash]
3. [<NAME>][gagrani]
### Dependencies ###
- Django 1.5.2 (Used Python 2.7.3)
- django rest framework
- django-filter
- markdown
### Setting it all up ###
```bash
sudo apt-get install python-pip
sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo pip install virtualenv
virtualenv venv
source venv/bin/activate
mv elearning_academy/settings.ini.sample elearning-academy/settings.ini
```
### Must install ###
- ffprobe - http://ffmpeg.org/download.html
=======
### Setting up the server ###
http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/
This link guides you through the exact steps for setting up a gunicorn server.
### Notes ###
- Use django custom decorater wherever needed. e.g. for checking whether user \
is enrolled into Course or not ?
- whether to use Python-Makrdown, django-filter
- djagno REST API
- make requirement.txt which can be installed with pip
- django userena demo
- PIL installation might turn out to be non trivial, please refer to : http://askubuntu.com/questions/156484/how-do-i-install-python-imaging-library-pil
- For installing mysql-python you need to install python-dev.
- OperationalError: (2003, "Can't connect to MySQL server on 10.102.56.95") [10.102.56.95 is my IP]: Edit /etc/mysql/my.cnf 'bind-address' to '10.102.56.95'
[alankar]: https://facebook.com/alankar.saxena1
[aakash]: https://facebook.com/aakashns
[gagrani]: https://facebook.com/gagrani.vinayak
<file_sep>/video/views.py
"""
Views for Video
TODO
- import quiz from the camtasia xml file into our database
Video API :-
Since Video is always a part of some concept and does not exist standalone
so the add and remove functionality are part of Concept API.
Support following actions :-
1. Update Title (Cannot be empty)
2. Edit content
3. Add Marker
4. Delete Marker
5. Update Marker
"""
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.forms import ModelForm
from django.contrib.auth.models import User
from rest_framework import mixins, status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import action
from video.models import Video, VideoHistory, Marker, QuizMarker, SectionMarker, QuizMarkerHistory
from video.serializers import VideoSerializer, AddVideoSerializer, QuizMarkerHistorySerializer
from video.serializers import MarkerSerializer, SectionMarkerSerializer, QuizMarkerSerializer
from quiz.models import Quiz, QuestionModule, DescriptiveQuestion
from quiz.models import SingleChoiceQuestion, FixedAnswerQuestion
import math
import json
import xml.etree.ElementTree as ET
def import_quiz_camtasia8(con_file, video):
"""
Doc
"""
#tree = ET.parse(fname)
tree = ET.fromstring(con_file.read())
rdf = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'
tscIQ = '{http://www.techsmith.com/xmp/tscIQ/}'
xmpDM = '{http://ns.adobe.com/xmp/1.0/DynamicMedia/}'
quiz_xpath = ".//" + rdf + "Description[@" + tscIQ + "questionSetName]"
for quiz in tree.findall(quiz_xpath):
title = quiz.attrib[tscIQ + "questionSetName"]
startTime = int(math.floor(float(quiz.attrib[xmpDM + "startTime"])/1000))
question_xpath = ".//" + rdf + "Description[@" + tscIQ + "id]"
quiz_obj = Quiz(title=title)
quiz_obj.save()
try:
marker = QuizMarker(video=video, time=startTime, quiz=quiz_obj)
marker.save()
qmodule_obj = QuestionModule(
title='Dummy Title',
quiz=quiz_obj,
dummy=True
)
qmodule_obj.save()
except Exception, e:
quiz_obj.delete()
try:
marker = QuizMarker.objects.get(video=video, time=startTime)
quiz_obj = marker.quiz
qmodule_obj = QuestionModule.objects.filter(quiz=quiz_obj)[0]
if(qmodule_obj.dummy):
qmodule_obj.dummy = False
qmodule_obj.title = quiz_obj.title
qmodule_obj.save()
quiz_obj.title = "Quiz : Multiple Questions"
quiz_obj.save()
qmodule_obj = QuestionModule(
title=title,
quiz=quiz_obj,
dummy=False
)
qmodule_obj.save()
except Exception,e:
marker = None
print "Some other error in marker creation at %d, %d" %(startTime, video.id)
print(e)
for question in quiz.findall(question_xpath):
qtype = question.attrib[tscIQ + 'type']
qtext = question[0].text
if qtype == 'MC':
answer = 0
try:
answer = int(math.log(int(question[1].text), 2))
except:
answer = 0
options = json.dumps(
[opt.text for opt in
question.findall(".//" + tscIQ + "answer")]
)
q = SingleChoiceQuestion(
quiz=quiz_obj, question_module=qmodule_obj,
description=qtext, options=options, answer=answer, marks=1
)
q.save()
elif qtype == 'FITB':
answer = json.dumps(
[ans.text for ans in
question.findall(".//" + tscIQ + "answer")]
)
q = FixedAnswerQuestion(
quiz=quiz_obj, question_module=qmodule_obj,
description=qtext, answer=answer, marks=0
)
q.save()
elif qtype == 'SHORT':
q = DescriptiveQuestion(
quiz=quiz_obj, question_module=qmodule_obj,
description=qtext, answer="Enter Answer Here"
)
q.save()
else:
raise Exception("Unknown Question Type")
namespace = {
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'tscIQ': "http://www.techsmith.com/xmp/tscIQ/",
'xmpDM': "http://ns.adobe.com/xmp/1.0/DynamicMedia/",
}
s_xpath = ".//rdf:Description[@xmpDM:trackType='TableOfContents']//rdf:Description"
name_attrib = "{" + namespace['xmpDM'] + "}name"
time_attrib = "{" + namespace['xmpDM'] + "}startTime"
for section in tree.findall(s_xpath, namespaces=namespace):
title = section.attrib[name_attrib]
if ("quiz" not in title.lower()):
start_time = int(math.ceil(float(section.attrib[time_attrib])/1000))
marker = SectionMarker(video=video, time=start_time, title=title)
try:
marker.save()
except Exception, err:
print "marker repeated at %d for video %d - type Section" % (start_time, video.id)
print str(err)
class MarkerViewSet(mixins.RetrieveModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
"""
Marker for a video is created/updated/delete after checking the user has permission
to add marker to the video.
"""
#permission_classes = (IsVideoOwner, )
model = Marker
serializer_class = MarkerSerializer
def create(self, request):
"""
Create a Marker based on type in request.DATA
Create QuizMarkerHistory for all users if it is a Quiz Marker
"""
if request.DATA['type'] == Marker.SECTION_MARKER:
serializer = SectionMarkerSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
markers = []
for m in serializer.object.video.markers.all():
sub_m = Marker.objects.filter(pk=m.id).select_subclasses()[0]
if m.type == 'S':
markers.append(SectionMarkerSerializer(sub_m).data)
else:
markers.append(QuizMarkerSerializer(sub_m).data)
response = {'markers': markers}
return Response(response, status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
elif request.DATA['type'] == Marker.QUIZ_MARKER:
serializer = QuizMarkerSerializer(data=request.DATA)
if serializer.is_valid():
new_quiz_marker = serializer.save()
markers = []
for m in serializer.object.video.markers.all():
sub_m = Marker.objects.filter(pk=m.id).select_subclasses()[0]
if m.type == 'S':
markers.append(SectionMarkerSerializer(sub_m).data)
else:
markers.append(QuizMarkerSerializer(sub_m).data)
response = {'markers': markers}
users = User.objects.all()
for j in users:
new_data = {
'quiz_marker': new_quiz_marker,
'user': j.id,
'seen_status': False,
'times_seen': 0,
}
quiz_marker_history_serializer = QuizMarkerHistorySerializer(data=new_data)
if quiz_marker_history_serializer.is_valid():
quiz_marker_history_serializer.save()
else:
print quiz_marker_history_serializer.errors
return Response(response, status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
else:
return Response("Bad Type for Marker", status.HTTP_400_BAD_REQUEST)
#def update(self, request, pk=None):
# """
# Marker is never updated completely rather only partially
# """
# return Response("Update should not be called", status.HTTP_400_BAD_REQUEST)
def partial_update(self, request, pk=None):
"""
Update a Marker based on instance of Marker class
"""
marker = get_object_or_404(Marker, pk=pk)
sub_marker = Marker.objects.filter(pk=pk).select_subclasses()[0]
if (marker.type == Marker.SECTION_MARKER):
serializer = SectionMarkerSerializer(sub_marker, data=request.DATA, partial=True)
if serializer.is_valid():
serializer.save()
markers = []
for m in sub_marker.video.markers.all():
sub_m = Marker.objects.filter(pk=m.id).select_subclasses()[0]
if m.type == 'S':
markers.append(SectionMarkerSerializer(sub_m).data)
else:
markers.append(QuizMarkerSerializer(sub_m).data)
response = {'markers': markers}
return Response(response, status.HTTP_200_OK)
else:
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
elif marker.type == Marker.QUIZ_MARKER:
serializer = QuizMarkerSerializer(sub_marker, data=request.DATA, partial=True)
if serializer.is_valid():
serializer.save()
markers = []
for m in sub_marker.video.markers.all():
sub_m = Marker.objects.filter(pk=m.id).select_subclasses()[0]
if m.type == 'S':
markers.append(SectionMarkerSerializer(sub_m).data)
else:
markers.append(QuizMarkerSerializer(sub_m).data)
response = {'markers': markers}
return Response(response, status.HTTP_200_OK)
else:
return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
else:
return("Unknown Marker type", status.HTTP_400_BAD_REQUEST)
def destroy(self, request, pk=None):
"""
Destroy Marker
"""
marker = get_object_or_404(Marker, pk=pk)
video = marker.video
marker.delete()
markers = []
for m in video.markers.all():
sub_m = Marker.objects.filter(pk=m.id).select_subclasses()[0]
if m.type == 'S':
markers.append(SectionMarkerSerializer(sub_m).data)
else:
markers.append(QuizMarkerSerializer(sub_m).data)
response = {'markers': markers}
return Response(response, status.HTTP_200_OK)
@action(methods=['post', 'patch'])
def update_quiz_marker_status(self, request, pk=None):
"""
Update Status for QuizMarker
Create entries in QuizMarkerHistory for all QuizMarkers and this user
"""
quiz_marker = get_object_or_404(QuizMarker, pk=pk)
user = request.user
#for e in QuizMarker.objects.all():
#print (e.quiz.title)
#print QuizMarkerHistory.objects.count()
#for e in QuizMarkerHistory.objects.all():
#print e.quiz_marker.quiz.title, e.user.username, e.seen_status, e.times_seen
if QuizMarkerHistory.objects.filter(quiz_marker=quiz_marker, user=user).exists() == False:
new_data = {
'quiz_marker': quiz_marker,
'user': user.id,
'seen_status': False,
'times_seen': 0,
}
quiz_marker_history_serializer = QuizMarkerHistorySerializer(data=new_data)
if quiz_marker_history_serializer.is_valid():
quiz_marker_history_serializer.save()
for m in quiz_marker.video.markers.all():
if m.type == 'Q':
if QuizMarkerHistory.objects.filter(quiz_marker=m, user=user).exists() == False:
new_data = {
'quiz_marker': m,
'user': user.id,
'seen_status': False,
'times_seen': 0,
}
quiz_marker_history_serializer = QuizMarkerHistorySerializer(data=new_data)
if quiz_marker_history_serializer.is_valid():
quiz_marker_history_serializer.save()
else:
print quiz_marker_history_serializer.errors
quiz_marker_history = get_object_or_404(QuizMarkerHistory, quiz_marker=quiz_marker, user=user)
quiz_marker_history.seen_status = True
quiz_marker_history.times_seen += 1
quiz_marker_history.save()
return Response({'seen_status': True}, status.HTTP_200_OK)
class VideoViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
Video can be added only from a concept by content developer.
Videos can be removed from concept-video relationships. When a video
is not referenced by any concept then the video should be deleted
by a Garbage collection tool.
We allow :-
1. Get Video
2. Update Video (Title, Content)
3. Upvote/Downvote
"""
model = Video
serializer_class = VideoSerializer
def update(self, request, pk=None, **kwargs):
"""
Update and existing video. You can only partially update an existing video
"""
if (request.FILES.has_key('video_file')):
return Response({"msg": "Video File cannot be changed"}, status.HTTP_400_BAD_REQUEST)
return super(VideoViewSet, self).update(request, pk, **kwargs)
def partial_update(self, request, pk=None, **kwargs):
"""
Update the title and content of video
"""
if ('other_file' in request.FILES):
video = get_object_or_404(Video, pk=pk)
video.other_file = request.FILES['other_file']
video.save()
if (request.FILES.has_key('video_file')):
return Response({"msg": "Video File cannot be changed"}, status.HTTP_400_BAD_REQUEST)
return super(VideoViewSet, self).partial_update(request, pk, **kwargs)
# video = get_object_or_404(Video, pk=pk)
# serializer = AddVideoSerializer(video, data=request.DATA, partial=True)
# if serializer.is_valid():
# serializer.save()
# return Response("Video Updated", status.HTTP_200_OK)
# else:
# content = serializer.errors
# return Response(content, status.HTTP_400_BAD_REQUEST)
@action(methods=['post', 'patch'])
def vote(self, request, pk=None):
"""
Upvote for video
"""
video = get_object_or_404(Video, pk=pk)
user = request.user
video_history = get_object_or_404(VideoHistory, video=video, user=user)
if request.DATA['vote'] == 'up':
if video_history.vote == VideoHistory.UPVOTE:
video.upvotes = video.upvotes - 1
video.save()
video_history.vote = VideoHistory.NOVOTE
video_history.save()
elif video_history.vote == VideoHistory.DOWNVOTE:
video.downvotes = video.downvotes - 1
video.upvotes = video.upvotes + 1
video.save()
video_history.vote = VideoHistory.UPVOTE
video_history.save()
elif video_history.vote == VideoHistory.NOVOTE:
video.upvotes = video.upvotes + 1
video.save()
video_history.vote = VideoHistory.UPVOTE
video_history.save()
elif request.DATA['vote'] == 'down':
if video_history.vote == VideoHistory.DOWNVOTE:
video.downvotes = video.downvotes - 1
video.save()
video_history.vote = VideoHistory.NOVOTE
video_history.save()
elif video_history.vote == VideoHistory.UPVOTE:
video.downvotes = video.downvotes + 1
video.upvotes = video.upvotes - 1
video.save()
video_history.vote = VideoHistory.DOWNVOTE
video_history.save()
elif video_history.vote == VideoHistory.NOVOTE:
video.downvotes = video.downvotes + 1
video.save()
video_history.vote = VideoHistory.DOWNVOTE
video_history.save()
else:
return Response({'msg': "Bad Request"}, status.HTTP_400_BAD_REQUEST)
video = get_object_or_404(Video, pk=pk)
return Response({'vote': [video.upvotes, video.downvotes]}, status.HTTP_200_OK)
@action(methods=['post', 'patch'])
def ended(self, request, pk=None):
"""
This function updates the Video Seen status
when student has seen the video completely
"""
video = get_object_or_404(Video, pk=pk)
user = request.user
video_history = get_object_or_404(VideoHistory, video=video, user=user)
video_history.seen_status = True
video_history.times_seen += 1
video_history.save()
########################################################################################
# v = 'Video Ended, Times seen = %d,Seen status = %s' % (video_history.times_seen, str(video_history.seen_status))
# print v
#
#
# for e in VideoHistory.objects.all():
# print (e.video), (e.user), (e.seen_status), (e.times_seen), (e.vote)
# videos = Video.objects.all()
# users = User.objects.all()
# for j in users:
# print '\t\t%s' %(j.username),
#
# for i in videos:
# print
# print '%s' %(i.title),
# for j in users:
# if VideoHistory.objects.filter(video=i, user=j).exists():
# k = get_object_or_404(VideoHistory, video=i, user=j)
# print '\t\t%r' % (k.seen_status),
# else:
# print '\t\t%r' % (False),
# print
#
# ########################################################################################
## all_markers = video.markers.all()
## for k in all_markers:
## print k.time, k.type
#
# for j in users:
# print '\t\t%s' %(j.username),
#
# for i in videos:
# print
# print '%s' %(i.title),
# all_markers = i.markers.all()
# for j in users:
# count = 0
# for k in all_markers:
# if k.type == 'Q':
# if QuizMarkerHistory.objects.filter(quiz_marker=k, user=j).exists():
# l = get_object_or_404(QuizMarkerHistory, quiz_marker=k, user=j)
# if l.seen_status == True:
# count += 1
# print '\t\t%r' % (count),
#
# print
# ########################################################################################
## all_markers = video.markers.all()
## for k in all_markers:
## print k.time, k.type
#
# for j in users:
# print '\t\t%s' %(j.username),
#
# for i in videos:
# print
# print '%s' %(i.title),
# all_markers = i.markers.all()
# for j in users:
# latest_time = 0
# for k in all_markers:
# if k.type == 'Q':
# if QuizMarkerHistory.objects.filter(quiz_marker=k, user=j).exists():
# l = get_object_or_404(QuizMarkerHistory, quiz_marker=k, user=j)
# if l.seen_status == True:
# latest_time = l.quiz_marker.time
# else:
# break
# print '\t\t%r' % (latest_time),
#
# print
########################################################################################
return Response({'seen_status': True}, status.HTTP_200_OK)
@login_required
def play_video(request):
return render(request, "video/play_video.html")
@login_required
def edit_video(request):
return render(request, "video/edit_video.html")
class UploadVideoForm(ModelForm):
class Meta:
model = Video
fields = ['title', 'content', 'video_file']
@login_required
def upload_video(request):
if request.method == 'POST':
form = UploadVideoForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request, 'video/edit_video.html')
else:
form = UploadVideoForm()
return render(request, 'video/upload_video.html', {'form': form})
else:
form = UploadVideoForm()
return render(request, 'video/upload_video.html', {'form': form})
<file_sep>/chat/static/chat/js/chatrooms.jsx
/** @jsx React.DOM */
var Chatrooms = React.createClass({
/**
* Give the initial state for React class Chatrooms
* loaded: If list of chatrooms is loaded from server
* chatroomId: chatroomId for which warning needs to be shown in case
* of clicking delete chatroomButton
* update: Keeps track of whether to load Chatrooms in case of chatroom is deleted
* or added by Chatroom forms
* @see ChatroomForm
* @return {dict} initial state object
*/
getInitialState: function() {
return {
loaded: false,
chatroomId: "-1",
update: this.props.updateRoom,
};
},
/**
* load List of chatrooms from server and stores them in state key 'chatrooms'
* @return {void}
*/
loadChatrooms: function() {
url = "/chat/api/chatroom/" + this.props.course + "/get/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState['chatrooms']=response;
oldState['loaded']=true;
this.setState(oldState);
}.bind(this));
},
componentDidMount: function() {
if(!this.state.loaded) {
this.loadChatrooms();
}
},
componentDidUpdate: function() {
if (!this.state.loaded) {
this.loadChatrooms();
}
},
/**
* React call this function if props are updated by Parent Class
* if the prop updateRoom is changed in newProps then set loaded to false to re-render the page
* @param {dict} dictionary of new props
* @return {void}
*/
componentWillReceiveProps: function(newProps){
if (this.state.update != newProps.updateRoom){
oldState = this.state;
oldState['update'] = newProps.updateRoom;
oldState['loaded'] = false;
this.setState(oldState);
}
},
/**
* Sets the chatroomId for which warning needs to be displayed
* @param {integer}
* @return {void}
*/
deleteChatroom: function(chatroomId){
oldState = this.state;
oldState['chatroomId'] = chatroomId;
this.setState(oldState);
},
/**
* Calls the callback defined in ChatroomForm to delete chatroom
* @param {integer} chatrromId which needs to be deleted
* @return {void}
*/
confirmDeleteChatroom: function(chatroomId){
this.props.deleteCallback(chatroomId);
},
render: function(){
/**
* Returns the LoadingBar if list of chatrooms isn't loaded
* @see loadChatrooms
*/
if (!this.state.loaded){
return <LoadingBar/>;
}
var classes = "title ";
if (this.props.teacher){
classes += "col-md-8 ";
}
else{
classes += "col-md-9 ";
}
if (this.state.chatrooms.length > 0){
var rooms = this.state.chatrooms.map(function(room, index){
var date = new Date(room.createdOn);
date = date.toDateString();
var message = "";
if (room.id == this.state.chatroomId){
/**
* Warning Message
* @description This warning message will be displayed only if chatroomId is set
* in the this.state i.e. instructor wants to delete chat
* @example
* Chatroom Lab 01 will be deleted
* <Delete> <Cancel>
* @type {JSX}
*/
message = (
<div class="alert alert-dismissable alert-warning">
<h4>Chatroom <b>{room.title}</b> will be deleted!</h4>
<button type="button" class="btn btn-primary pull-right" data-dismiss="alert" aria-hidden="true">Cancel</button>
<div>
<button type="button" class="btn btn-danger" onClick={this.confirmDeleteChatroom.bind(this, this.state.chatroomId)}>Delete</button>
</div>
</div>
);
}
/**
* If displaying for teacher (this.props.teacher is true)
* then also displays the delete button
* @type {String}
*/
return (
<div>
{message}
<div class="row chatroom">
<a href={"/chat/" + room.id} target="_blank">
<div class={classes}>
{room.title}
</div>
<div class="col-md-3">
{date}
</div>
</a>
{(this.props.teacher
? <div class="col-md-1" onClick={this.deleteChatroom.bind(this, room.id)} value={room.id}><span class="glyphicon glyphicon-remove"></span></div>
: false
)}
</div>
</div>
);
}, this);
}
else{
var rooms = (
<div class="alert alert-warning">
No Chatrooms are present by now!
</div>
);
}
return (
<div>
{rooms}
</div>
);
}
});
/**
* @name ChatroomForm
* @description Displays a form to add chatroom with list of available chatroom to join or delete
*/
var ChatroomForm = React.createClass({
/**
* Initialize the state dictionary
* showMessage: if true then show the alert message on the top of form
* messageText: The text in the message
* messageAlertClass: Bootstrap class for alert type
* alert-success: if chatroom is added successfully
* alert-warning/alert-danger: otherwise
* updateRoom: state variable used as prop for Chatroom to update the list of chatrooms
* @see Chatrooms.componentWillReceiveProps
*/
getInitialState: function() {
return {
showMessage: false,
messageText: "",
messageAlertClass: "alert-success",
updateRoom: false,
};
},
/**
* Creates new chatroom after the title validation through ajax call to API
* @param {event} Form submit event
*/
createChatroom : function(e){
e.preventDefault();
$("#chatroomCreateButton").prop('disabled', true);
title = this.refs.title.getDOMNode().value.trim();
if (title == "" || title == undefined){
oldState = this.state;
oldState['showMessage'] = true;
oldState['messageAlertClass'] = "alert-danger";
oldState['messageText'] = "Title cannot be empty";
this.setState(oldState);
$("#chatroomCreateButton").prop('disabled', false);
return;
}
data = {
title: this.refs.title.getDOMNode().value.trim()
};
url = "/chat/api/chatroom/" + this.props.course + "/add/?format=json";
request = ajax_json_request(url, "POST", data);
request.done(function(response){
response = jQuery.parseJSON(response);
oldState = this.state;
oldState['showMessage'] = true;
oldState['messageAlertClass'] = "alert-success";
oldState['messageText'] = "Chatroom created Successfully";
oldState['updateRoom'] = !oldState['updateRoom'];
this.setState(oldState);
}.bind(this));
$("#chatroomCreateButton").prop('disabled', false);
$("#chatroomFormTitle").val("");
},
/**
* Callback for deleting chatroom.
* Passed as prop to Chatrooms
* @see {Chatrooms.confirmDeleteChatroom}
* @param {integer} Chatroom which needs to be deleted
*/
confirmDeleteChatroom: function(chatroomId){
url = "/chat/api/chatroom/" + chatroomId + "/delete/?format=json";
request = ajax_json_request(url, "POST", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState['updateRoom'] = !oldState['updateRoom'];
oldState['messageText'] = "Chatroom <b>" + response.title + "</b> deleted successfully";
oldState['showMessage'] = true;
oldState['messageAlertClass'] = "alert-success";
this.setState(oldState);
}.bind(this));
},
render: function(){
/**
* Alert message to be displayed over Form in case the state variable showMessage is true
* @type {JSX}
*/
var message="";
if (this.state.showMessage){
messageText = this.state.messageText;
message = (
<div class={"alert alert-dismissable " + this.state.messageAlertClass}>
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<span dangerouslySetInnerHTML={{__html: this.state.messageText}} ></span>
</div>);
}
/**
* For for creating chatroom.
* Should be displayed only for teacher. (insured via props and also insured in python API)
* @type {JSX}
*/
var form="";
if (this.props.teacher){
form = (
<form class="form-inline" role="form" onSubmit={this.createChatroom}>
<div class="form-group col-sm-10">
<label for="chatroomFormTitle" class="sr-only"></label>
<input type="text" class="form-control" id="chatroomFormTitle" ref="title" placeholder="Add Title"/>
</div>
<button ref="submit" id="chatroomCreateButton" type="submit" class="btn btn-success">Add Chatroom</button>
</form>
);
}
return (
<div>
<h3 class="contentheading">Chatrooms</h3>
{message}
{form}
<Chatrooms deleteCallback={this.confirmDeleteChatroom} updateRoom={this.state.updateRoom} teacher={this.props.teacher} course={this.props.course}/>
</div>
);
}
});<file_sep>/scripts/backup2.sh
#!/bin/bash
#syncing new files and sending them to remote server
rsync -rtvuc --delete --rsh="sshpass -p'<PASSWORD>' ssh -l'user'" MEDIA_PATH server:BACKUP_PATH/media
<file_sep>/quiz_old/grader.py
"""
Grader class to handle assessment of submissions
"""
from quiz.models import Question, QuestionHistory, Submission
class Grader():
"""
Grader class to handle assessment of submissions
"""
question = None
question_history = None
the_question = None
submission = None
def __init__(self, submission, question, question_history):
""" Initialize this class """
self.submission = submission
self.question = question
self.question_history = question_history
def update_marks(self, is_correct=True):
"""
Get and update the marks for this submission
Update question history
Applicable for Direct Grading ONLY
"""
if self.question is None:
self.question = \
Question.objects.get(question=self.submission.question)
if self.question_history is None:
self.question_history = QuestionHistory.objects.filter(
question=self.question,
user=self.submission.user)
if is_correct:
if self.question_history.hint_taken:
granularity = self.question.granularity_hint
else:
granularity = self.question.granularity
granularity = granularity.split(',')
if (self.question_history.attempts - 1) > len(granularity):
marks = granularity.pop()
else:
marks = granularity.pop(self.question_history.attempts - 1)
self.question_history.status = QuestionHistory.SOLVED
self.question_history.marks = marks
self.submission.result = marks
else:
self.question_history.status = QuestionHistory.ATTEMPTED_ONCE
if (self.question_history.attempts >= self.question.attempts or
self.question_history.status == QuestionHistory.SOLVED):
self.question_history.answer_shown = True
self.question_history.save()
self.submission.status = Submission.DONE
self.submission.is_correct = is_correct
self.submission.save()
return
def grade(self):
"""
Grade the submission or pass it appropriate grader
IMPORTANT: This method must save the submission and question_history
IMPORTANT: Ensure that update_marks() gets called
Return True if result is directly available, false otherwise
"""
if self.submission is None:
return False
if self.submission.grader_type == Question.MANUAL_GRADING:
self.submission.save()
return False
elif self.submission.grader_type == Question.DIRECT_GRADING:
answer = self.submission.answer
self.the_question = \
Question.objects.get_subclass(pk=self.submission.question.pk)
correct_answer = self.the_question.get_answer()
if self.submission.question.type == \
Question.SINGLE_CHOICE_QUESTION:
pass
elif self.submission.question.type == \
Question.MULTIPLE_CHOICE_QUESTION:
pass
elif self.submission.question.type == \
Question.FIXED_ANSWER_QUESTION:
self.grade_fixed_answer(answer, correct_answer)
return True
elif self.submission.question.type == \
Question.DESCRIPTIVE_ANSWER_QUESTION:
pass
elif self.submission.question.type == \
Question.PROGRAMMING_QUESTION:
pass
return True
def grade_fixed_answer(self, answer, correct_answer):
""" Grade fixed answer Question """
correct = False
for ans in correct_answer:
if ans == answer:
correct = True
break
self.update_marks(correct)
def grade_single_choice(self, answer, correct_answer, submission):
""" Grade single choice correct Question """
pass
def grade_multiple_choice(self, answer, correct_answer, submission):
""" Grade Multiple choice correct Question """
pass
def grade_descriptive_answer(self, answer, correct_answer, submission):
""" Grade Descriptive Question """
pass
def grade_programming(self, submission):
""" Grade Programming Question """
pass
<file_sep>/concept/views.py
"""
Views for Concept API
"""
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from elearning_academy.permissions import InInstructorOrContentDeveloperMode
from courseware.permissions import IsOwner
from courseware.models import Concept
from courseware.models import Course, CourseHistory
from discussion_forum.models import Tag
@login_required
def view_concept(request, concept_id):
"""
View Concept Page
"""
concept = get_object_or_404(Concept, pk=concept_id)
inInstructorOrContentDeveloperModeObject = InInstructorOrContentDeveloperMode()
isOwnerObj = IsOwner()
if inInstructorOrContentDeveloperModeObject.has_permission(request, None):
return view_content_developer(request, concept_id)
elif (concept.is_published or
isOwnerObj.has_object_permission(request=request, obj=concept.group.course, view=None)):
return view_student(request, concept_id)
else:
return render(request, 'error.html', {'error': 'Concept does not exist !'})
@login_required
def view_student(request, concept_id):
""" Course Progress of Student """
return render(request, 'concept/student.html', {'conceptId': concept_id})
#return render(request, 'concept/student.html', context)
@login_required
def view_content_developer(request, concept_id):
""" Concept edit page for content developer """
return render(request, 'concept/content_developer.html', {'conceptId': concept_id})
<file_sep>/quiz_old/views.py
"""
Views for the Quiz API
"""
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import link, action
from rest_framework.response import Response
from quiz.grader import Grader
from quiz.models import QuestionModule, Question, FixedAnswerQuestion, \
Submission, Quiz, QuestionHistory
from quiz import serializers
from quiz import permissions
@login_required
def view(request):
""" Normal view """
return render(request, 'quiz/quiz.html', {})
@login_required
def admin(request):
""" Admin view """
return render(request, 'quiz/quiz_admin.html', {})
class QuizViewSet(mixins.CreateModelMixin,
# TODO: remove CREATE when add_quiz is added to concept
# TODO: remove LIST when course API is complete
mixins.ListModelMixin,
mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuizViewSet:
- get_question_modules
- add_question_module
- get_questions_manual_grade
"""
model = Quiz
serializer_class = serializers.QuizSerializer
permission_classes = [permissions.IsCourseInstructor]
paginate_by = None
@link(permission_classes=(permissions.IsEnrolled,))
def get_question_modules(self, request, pk=None):
"""
Return list of question modules
"""
quiz = get_object_or_404(Quiz, pk=pk)
self.check_object_permissions(request, quiz)
question_modules = QuestionModule.objects.filter(quiz=quiz)
serializer = serializers.QuestionModuleSerializer(question_modules,
many=True)
return Response(serializer.data)
@action(permission_classes=(permissions.IsCourseInstructor,))
def add_question_module(self, request, pk=None):
"""
Add a question module
"""
quiz = get_object_or_404(Quiz, pk=pk)
self.check_object_permissions(request, quiz)
serializer = serializers.QuestionModuleSerializer(data=request.DATA)
if serializer.is_valid():
question_module = QuestionModule(
quiz=quiz,
title=serializer.data['title']
)
question_module.save()
serializer = serializers.QuestionModuleSerializer(question_module)
return Response(serializer.data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
@link(permission_classes=(permissions.IsCourseInstructor,))
def get_questions_manual_grade(self, request, pk=None):
"""
Return the list of questions which have to manually graded
"""
quiz = get_object_or_404(Quiz, pk=pk)
self.check_object_permissions(request, quiz)
questions = Question.objects.filter(quiz=quiz,
grader_type=Question.MANUAL_GRADING)
serializer = serializers.QuestionSerializer(questions, many=True)
return Response(serializer.data)
class QuestionModuleViewSet(mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionModuleViewSet:
- get_questions
- add_fixed_answer_question
"""
model = QuestionModule
serializer_class = serializers.QuestionModuleSerializer
permission_classes = [permissions.IsCourseInstructor]
paginate_by = None
def get_question_and_history_data(self, question, question_history):
"""
Get a dict of user history of a question and question data
This function is meant for showing to user and not admin
"""
hint = None
if question_history.hint_taken:
hint = question.hint
answer = None
answer_description = None
if question_history.answer_shown:
question = Question.objects.get_subclass(pk=question.pk)
answer = question.get_answer(showToUser=True)
if question.answer_description == '':
answer_description = None
else:
answer_description = question.answer_description
data = {
'id': question.pk,
'marks': question.marks,
'attempts': question.attempts,
'description': question.description,
'is_hint_available': question.is_hint_available(),
'type': question.type,
'user_attempts': question_history.attempts,
'user_marks': question_history.marks,
'user_status': question_history.status,
'hint_taken': question_history.hint_taken,
'hint': hint,
'answer_shown': question_history.answer_shown,
'answer': answer,
'answer_description': answer_description
}
return data
@link(permission_classes=(permissions.IsCourseInstructor,))
def get_questions_admin(self, request, pk=None):
"""
Return list of questions
"""
question_module = get_object_or_404(QuestionModule, pk=pk)
self.check_object_permissions(request, question_module)
questions = Question.objects.filter(question_module=question_module)
serializer = serializers.AdminQuestionSerializer(questions, many=True)
data = serializer.data
new_data = []
for question in data:
the_question = Question.objects.get_subclass(pk=question['id'])
answer_fields = the_question.get_answer_data()
question['answer_fields'] = answer_fields
new_data.append(question)
return Response(new_data)
@link(permission_classes=(permissions.IsEnrolled,))
def get_questions(self, request, pk=None):
"""
Return list of questions
"""
question_module = get_object_or_404(QuestionModule, pk=pk)
self.check_object_permissions(request, question_module)
questions = Question.objects.filter(question_module=question_module)
data = []
for question in questions:
question_history, created = QuestionHistory.objects.get_or_create(
question=question,
student=request.user
)
question_history.save()
data.append(self.get_question_and_history_data(
question, question_history))
serializer = serializers.FrontEndQuestionSerializer(data, many=True)
return Response(serializer.data)
@action(permission_classes=(permissions.IsCourseInstructor,))
def add_fixed_answer_question(self, request, pk=None):
"""
Add a question module
"""
question_module = get_object_or_404(QuestionModule, pk=pk)
self.check_object_permissions(request, question_module)
serializer = serializers.FixedAnswerQuestionSerializer(
data=request.DATA)
# Figure out a better way to set None values and modify incoming data
if serializer.is_valid():
serializer.data['question_module'] = question_module
serializer.data['quiz'] = question_module.quiz
serializer.data['type'] = Question.FIXED_ANSWER_QUESTION
question = FixedAnswerQuestion(**serializer.data)
question.save()
serializer = serializers.FixedAnswerQuestionSerializer(question)
return Response(serializer.data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
class FixedAnswerQuestionViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
FixedAnswerQuestionViewSet:
"""
model = FixedAnswerQuestion
serializer_class = serializers.FixedAnswerQuestionSerializer
permission_classes = [permissions.IsCourseInstructor]
paginate_by = None
class QuestionViewSet(mixins.DestroyModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
QuestionViewSet:
- get_hint
- get_answer
- submit_answer
- get_submissions_manual_grade
"""
model = Question
serializer_class = serializers.AdminQuestionSerializer
permission_classes = [permissions.IsCourseInstructor]
paginate_by = None
@link(permission_classes=(permissions.IsEnrolled,))
def get_hint(self, request, pk=None):
"""
Return the answers to the questions
"""
question = get_object_or_404(Question, pk=pk)
self.check_object_permissions(request, question)
hint = {
'id': question.pk,
'hint': question.hint
}
try:
question_history = QuestionHistory.objects.get(
student=request.user,
question=question
)
question_history.hint_taken = True
question_history.save()
except:
error = {
'status': False,
'detail': 'Question History not found'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
return Response(hint)
@link(permission_classes=(permissions.IsEnrolled,))
def get_answer(self, request, pk=None):
"""
Return the answers to the questions
"""
# Currently no UI uses this view
question = get_object_or_404(Question, pk=pk)
self.check_object_permissions(request, question)
try:
question_history = QuestionHistory.objects.get(
student=request.user,
question=question
)
if question_history.attempts < question.attempts:
remaining = question.attempts - question_history.attempts
error = {
'status': False,
'detail': str(remaining) + ' attempts still remaining'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
if question_history.status == QuestionHistory.AWAITING_RESULTS:
error = {
'status': False,
'detail': 'Please wait for some time'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
if question_history.status != QuestionHistory.SOLVED:
error = {
'status': False,
'detail': 'You have not solved the question yet'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
question_history.answer_shown = True
question_history.save()
except:
error = {
'detail': 'Internal error 3001'
}
return Response(error)
que = Question.objects.get_subclass(pk=question.pk)
answer = {
'id': que.pk,
'status': True,
'answer_description': que.answer_description,
'answer': que.get_answer(showToUser=True),
}
return Response(answer)
@action(permission_classes=(permissions.IsEnrolled,))
def submit_answer(self, request, pk=None):
""" Submit an answer to a question """
question = get_object_or_404(Question, pk=pk)
self.check_object_permissions(request, question)
question_history = QuestionHistory.objects.get(
student=request.user,
question=question
)
if question_history.status == QuestionHistory.AWAITING_RESULTS:
error = {
'status': False,
'detail': 'Please wait for some time'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
if question_history.status == QuestionHistory.SOLVED:
error = {
'status': False,
'detail': 'Question already answered'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
if question_history.answer_shown:
error = {
'status': False,
'detail': 'Correct answer already displayed'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
if question_history.attempts >= question.attempts:
error = {
'status': False,
'detail': 'Exceeded the maximum number of attempts'
}
return Response(error, status.HTTP_400_BAD_REQUEST)
question_history.attempts += 1
attempts_remaining = question.attempts - question_history.attempts
serializer = serializers.AnswerSubmitSerializer(data=request.DATA)
if serializer.is_valid():
# Evaluate the submission and put in the submission
question_history.status = QuestionHistory.AWAITING_RESULTS
submission = Submission(
#course=question.course,
question=question,
student=request.user,
grader_type=question.grader_type,
answer=serializer.data['answer']
)
# Optimization: let the grader save the submission
# submission.save()
data = {
'status': submission.status,
'is_correct': submission.is_correct,
'result': submission.result,
'attempts_remaining': attempts_remaining
}
grader = Grader(submission=submission,
question=question,
question_history=question_history)
if grader.grade():
submission = grader.submission
data['status'] = submission.status
data['is_correct'] = submission.is_correct
data['result'] = submission.result
if attempts_remaining == 0 or submission.is_correct:
if grader.the_question is None:
the_question = Question.objects.get_subclass(
pk=submission.question.pk)
data['answer'] = \
the_question.get_answer(showToUser=True)
else:
data['answer'] = \
grader.the_question.get_answer(showToUser=True)
data['answer_description'] = question.answer_description
serializer = serializers.FrontEndSubmissionSerializer(data)
else:
serializer = serializers.FrontEndSubmissionSerializer(data)
# return the result of grading
return Response(serializer.data)
else:
question_history.save()
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
@link(permission_classes=(permissions.IsCourseInstructor,))
def get_submissions_manual_grade(self, request, pk=None):
"""
Return the list of submissions which have to manually graded
"""
question = get_object_or_404(Question, pk=pk)
self.check_object_permissions(request, question)
submissions = Submission.objects.filter(question=question)
serializer = serializers.SubmissionSerializer(submissions, many=True)
return Response(serializer.data)
class SubmissionViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""
SubmissionViewSet:
- set_plagiarised
"""
model = Submission
serializer_class = serializers.SubmissionSerializer
permission_classes = [permissions.IsCourseInstructor]
paginate_by = None
@action(permission_classes=(permissions.IsCourseInstructor,))
def set_plagiarised(self, request, pk=None):
"""
Set the submission to be plagiarised
"""
serializer = serializers.PlagiarismSerializer(data=request.DATA)
if serializer.is_valid():
submission = get_object_or_404(Submission, pk=pk)
self.check_object_permissions(request, submission)
submission.is_plagiarised = serializer.data['is_plagiarised']
submission.has_been_checked = True
submission.save()
return Response(serializers.SubmissionSerializer(submission).data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
<file_sep>/cribs/cribs/cribs/create_crib.html
{% extends 'cribs/cribs_base.html' %}
{% block title %}Create new crib{% endblock %}
{% block main %}
<div>
<ul class="breadcrumb">
<li><a href="{% url 'assignments_index' assignment.course.id %}">{{ assignment.course.title }}</a> <span class="divider">/</span></li>
<li><a href="{% url 'assignments_details' assignment.id %}">{{ assignment.name }}</a> <span class="divider">/</span></li>
<li class="active">Register Crib</li>
</ul>
</div>
<form action "" method="post">
{% csrf_token %}
{{ form }}
<br/>
<input class="btn btn-medium btn-primary" type="submit" value="Create">
</form>
{% endblock %}<file_sep>/courseware/static/courseware/js/content_developer/course_page.jsx
/** @jsx React.DOM */
var AddSection = React.createClass({
addSection: function(data) {
url = "/document/api/page/" + this.props.pageid + "/add_section/?format=json";
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
this.props.callback(response);
display_global_message("Successfully added the section at the bottom", "success");
this.setState({showform: false});
}.bind(this));
request.fail(function(response) {
response = jQuery.parseJSON(response.responseText);
console.log(response);
msg = ''
for (k in response) {
if (msg != '') {
msg = msg + " \n" + k + ":" + response[k][0];
} else {
msg = k + ":" + response[k][0];
}
}
display_global_message(msg, "error");
});
},
getInitialState: function() {
return {
showform: false
};
},
handleAddClick: function() {
this.setState({showform: true});
},
handleCancelAdd: function() {
this.setState({showform: false});
},
render: function() {
if(this.state.showform) {
content = <GenericForm heading="Add Section" saveCallBack={this.addSection} cancelCallBack={this.handleCancelAdd}/>;
}
else {
content = (
<button onClick={this.handleAddClick} class="btn addSectionButton">
<span class="glyphicon glyphicon-plus-sign"></span>
Add Section
</button>
);
}
return (
<span>{content}</span>
);
}
});
var Section = React.createClass({
mixins: [MathJaxMixin,],
getInitialState: function() {
return {
showform: false,
title: this.props.section.title,
description: this.props.section.description
};
},
handleEdit: function(data) {
url = "/document/api/section/" + this.props.section.id + "/?format=json";
request = ajax_json_request(url, "PATCH", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
display_global_message("Successfully updated the section", "success");
oldState = this.state;
oldState['title'] = response.title;
oldState['description'] = response.description;
oldState['showform'] = false;
this.setState(oldState);
}.bind(this));
},
handleEditClick: function() {
this.setState({showform: true});
},
handleCancelEdit: function() {
this.setState({showform: false});
},
deleteSection: function() {
url = "/document/api/section/" + this.props.section.id + "/?format=json";
request = ajax_json_request(url, "DELETE",{});
request.done(function(response) {
display_global_message("Successfully deleted the section", "success");
sectionid = "section_"+this.props.section.id;
this.props.deleteCallBack(sectionid);
}.bind(this));
},
render: function() {
sectionid = "section_"+this.props.section.id;
modal = sectionid+"Modal";
href = "#"+modal;
label = modal + "Label";
if(this.state.showform) {
content = <GenericForm heading="Edit Section" title={this.state.title} description={this.state.description} saveCallBack={this.handleEdit} cancelCallBack={this.handleCancelEdit}/>;
}
else {
content = (
<div>
<h4>
{this.state.title}
<span class="glyphicon glyphicon-edit icon" onClick={this.handleEditClick}></span>
<validateDeleteBtn label={label} modal={modal} callback={this.deleteSection} heading="section" />
<a data-toggle="modal" href={href}>
<span class="glyphicon glyphicon-trash icon"></span>
</a>
</h4>
<p>
<span dangerouslySetInnerHTML={{__html: converter.makeHtml(this.state.description)}} />
</p>
</div>
);
}
return (
<li id={sectionid} class="section">
{content}
</li>
);
}
});
var Page = React.createClass({
mixins: [MathJaxMixin,],
handleSortClick: function() {
$( "#sortablesections" ).sortable({
axis: 'y',
cursor: "move",
//containment: "parent",
placeholder: "ui-state-highlight",
start: function( event, ui ) {
$(ui.item).addClass("ui-state-movable");
$(ui.placeholder).css("height", $(ui.item).css("height"));
},
stop: function( event, ui ) {
$(ui.item).removeClass("ui-state-movable");
}
});
$("#sortablesections").sortable("enable");
$( "#sortablesections" ).disableSelection();
oldState = this.state;
oldState['sectionorder'] = true;
this.setState(oldState);
},
saveOrder: function() {
v = $("#sortablesections").sortable("toArray");
a = v.length;
for(i=0; i< a;i++){
v[i]=v[i].substring(8);
v[i]=parseInt(v[i]);
}
data = {
playlist: JSON.stringify(v)
}
url = "/document/api/page/" + this.props.id + "/reorder_sections/?format=json";
request = ajax_json_request(url, "PATCH", data);
request.done(function(response) {
display_global_message("Successfully reordered the sections", "success");
$("#sortablesections").sortable("disable");
oldState = this.state;
oldState['sectionorder'] = false;
this.setState(oldState);
}.bind(this));
},
deletePage: function() {
url = "/document/api/page/" + this.props.id + "/?format=json";
request = ajax_json_request(url, "DELETE", {});
request.done(function(response) {
this.props.deleteCallBack(this.props.id);
display_global_message("The page was successfully deleted", "success");
}.bind(this));
request.complete(function(response) {
if (response.status != 204) {
display_global_message("The page could not be deleted", "error");
}
}.bind(this));
},
loadPage: function() {
url = "/document/api/page/" + this.props.id + "/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
this.setState({content: response, loaded: true});
}.bind(this));
},
getInitialState: function() {
return {
loaded: false,
content: undefined,
pageedit: false,
sectionorder: false
};
},
componentDidMount: function() {
if (!this.state.loaded) {
this.loadPage();
}
else {
$("#sectionOrderSave").hide();
}
},
componentDidUpdate: function() {
if (!this.state.loaded) {
this.loadPage();
}
else {
if(this.state.sectionorder)
{
$("#sectionReorder").hide();
$("#sectionOrderSave").show();
$(".section").addClass("sortable-items");
}
else {
$("#sectionReorder").show();
$("#sectionOrderSave").hide();
$(".section").removeClass("sortable-items");
}
}
},
componentWillReceiveProps: function() {
this.setState({
loaded: false,
content: undefined,
pageedit: false,
sectionorder: false
});
},
handleCancelEdit: function() {
oldState = this.state;
oldState['pageedit'] = false;
this.setState(oldState);
},
handleEdit: function(data) {
url = "/document/api/page/" + this.props.id + "/?format=json";
request = ajax_json_request(url, "PATCH", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
display_global_message("Successfully updated the page", "success");
oldState = this.state;
oldState['content'].title = response.title;
oldState['content'].description = response.description;
oldState['pageedit'] = false;
this.setState(oldState);
$("#sideList [value="+response.id+"]").text(response.title);
}.bind(this));
},
handleClickEdit: function() {
oldState = this.state;
oldState['pageedit'] = true;
this.setState(oldState);
},
handleAddSection: function(section) {
oldState = this.state;
oldState['content'].sections.push(section);
this.setState(oldState);
},
handleDeleteSection: function(sectionid) {
$("#"+sectionid).remove();
},
render: function() {
if (!this.state.loaded) {
return (
<LoadingBar />
);
}
else {
var sections = this.state.content.sections.map(function (section) {
return (
<Section section={section} deleteCallBack={this.handleDeleteSection}/>
);
}.bind(this)
);
var onemorebutton="";
if(sections.length > 4) {
onemorebutton = <AddSection pageid={this.props.id} callback={this.handleAddSection}/>;
}
if (this.state.pageedit) {
page_header = (
<div>
<GenericForm title={this.state.content.title} description={this.state.content.description} heading="Edit Page" saveCallBack={this.handleEdit} cancelCallBack={this.handleCancelEdit}/>
</div>
);
}
else {
page_header = (
<div>
<h3>{this.state.content.title}{" "}
<button onClick={this.handleClickEdit} class="btn btn-default">
<span class="glyphicon glyphicon-edit"></span>
Edit
</button>
<div class="pull-right">
<validateDeleteBtn modal="myModal" lable="myModalLabel" callback={this.deletePage} heading="page"/>
<a data-toggle="modal" href="#myModal" class="btn btn-danger">
<span class="glyphicon glyphicon-trash"></span>
Delete
</a>
</div>
</h3>
<div dangerouslySetInnerHTML={{__html: converter.makeHtml(this.state.content.description)}} />
</div>
);
}
return (
<div class="mydocument">
{page_header}
<AddSection pageid={this.props.id} callback={this.handleAddSection}/>
<button id="sectionReorder" onClick={this.handleSortClick} class="btn btn-default sort-btn">
<span class="glyphicon glyphicon-sort"></span>
Reorder Sections
</button>
<button id="sectionOrderSave" onClick={this.saveOrder} class="btn btn-primary sort-btn">
<span class="glyphicon glyphicon-save"></span>
Save Current Order
</button>
<ul id="sortablesections">
{sections}
</ul>
{onemorebutton}
</div>
);
}
}
});<file_sep>/elearning_academy/settings.py
"""
Django settings for elearning_academy project
"""
import os
import sys
from ConfigParser import ConfigParser
from datetime import datetime
# Location of main project directory which contains all apps
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__) + "/..")
##TODO
##All these GLOBAL 'constants' should be pushed at one place
COPYRIGHT_YEAR = datetime.today().year
config = ConfigParser()
config.read(os.path.join(PROJECT_DIR, 'elearning_academy/settings.ini'))
DEBUG = config.get('debug', 'debug')
TEMPLATE_DEBUG = config.get('debug', 'template_debug')
ADMINS = (
('<NAME>', '<EMAIL>'),
('<NAME>', '<EMAIL>'),
('<NAME>', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': config.get('database', 'engine'),
# Or path to database file if using sqlite3.
'NAME': config.get('database', 'db_name'),
# The following settings are not used with sqlite3:
'USER': config.get('database', 'user'),
'PASSWORD': config.get('database', 'password'),
# Empty for localhost through domain sockets or '127.0.0.1' for
# localhost through TCP.
'HOST': config.get('database', 'host'),
# Set to empty string for default.
'PORT': config.get('database', 'port'),
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Asia/Kolkata'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'elearning_academy/media/')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(PROJECT_DIR, 'elearning_academy/staticfiles')
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
#Admin Static File URL Prefix
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'elearning_academy/static'),
os.path.join(PROJECT_DIR, 'discussion_forum/static'),
os.path.join(PROJECT_DIR, 'concept/static'),
os.path.join(PROJECT_DIR, 'courseware/static'),
os.path.join(PROJECT_DIR, 'progress/static'),
os.path.join(PROJECT_DIR, 'quiz/static'),
os.path.join(PROJECT_DIR, 'user_profile/static'),
os.path.join(PROJECT_DIR, 'video/static'),
os.path.join(PROJECT_DIR, 'chat/static'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = config.get('secrets', 'secret_key')
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = config.get('server', 'root_urlconf')
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = config.get('server', 'wsgi_location')
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or
# "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'registration/templates'),
os.path.join(PROJECT_DIR, 'elearning_academy/templates'),
os.path.join(PROJECT_DIR, 'discussion_forum/templates'),
os.path.join(PROJECT_DIR, 'courseware/templates'),
os.path.join(PROJECT_DIR, 'concept/templates'),
os.path.join(PROJECT_DIR, 'quiz/templates'),
os.path.join(PROJECT_DIR, 'notification/templates'),
os.path.join(PROJECT_DIR, 'progress/templates'),
os.path.join(PROJECT_DIR, 'concept/templates'),
os.path.join(PROJECT_DIR, 'user_profile/templates'),
os.path.join(PROJECT_DIR, 'video/templates'),
os.path.join(PROJECT_DIR, 'courses/templates'),
os.path.join(PROJECT_DIR, 'assignments/templates'),
os.path.join(PROJECT_DIR, 'cribs/templates'),
os.path.join(PROJECT_DIR, 'evaluate/templates'),
os.path.join(PROJECT_DIR, 'upload/templates'),
#os.path.join(PROJECT_DIR, 'quiz_template/templates'),
os.path.join(PROJECT_DIR, 'chat/templates'),
)
TEMPLATE_CONTEXT_PROCESSORS = (
# default template context processors
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
# django 1.2 only
'django.contrib.messages.context_processors.messages',
# required by django-admin-tools
'django.core.context_processors.request',
'django.core.context_processors.static',
'elearning_academy.context_processor.my_global_name'
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.contrib.admin',
'django.contrib.admindocs',
#Project Apps
'util',
'registration',
'discussion_forum',
'user_profile',
'notification',
'courseware',
'quiz',
'video',
'concept',
'document',
'progress',
# 'quiz_template',
#Autograder
#'easy_thumbnails',
'guardian',
'south',
'djcelery',
'download',
'dajax',
'dajaxice',
'upload',
#'profiles',
'courses',
'assignments',
'evaluate',
'cribs',
'django.contrib.formtools',
# Third party apps
'rest_framework',
'gunicorn',
#chat
'chat'
)
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
###########################################################################
##TODO Alot of hard coding in the following sections, should be chucked off
###########################################################################
# Setting for Django Rest Framework
REST_FRAMEWORK = {
# Pagination Offset
'PAGINATE_BY': 10,
# Allow client to override, using `?page_size=xxx`.
'PAGINATE_BY_PARAM': 'page_size',
# Maximum limit allowed when using `?page_size=xxx`.
#'MAX_PAGINATE_BY': 100,
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS': (
'rest_framework.serializers.HyperlinkedModelSerializer',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
# Allowing only Authenticated users to read API
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
# Limiting access of User by throttling requests
'DEFAULT_THROTTLE_CLASSES': (
#'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'user': '200/min'
}
}
LOGIN_REDIRECT_URL = '/courseware/'
AUTH_PROFILE_MODULE = 'user_profile.CustomUser'
ANONYMOUS_USER_ID = -1
EMAIL_HOST = config.get('email', 'host')
EMAIL_PORT = config.get('email', 'port')
EMAIL_HOST_USER = config.get('email', 'user')
EMAIL_HOST_PASSWORD = config.get('email', 'password')
EMAIL_USE_TLS = config.get('email', 'use_TLS')
EMAIL_BACKEND = config.get('email', 'backend')
##TODO
##Hack to implement http for now, this should go to
##settings.ini
MY_SERVER = "http://" + config.get('server', 'ip')
MY_SITE_NAME = config.get('server', 'name')
DEFAULT_CONCEPT_IMAGE = config.get('server', 'default_concept_image')
TITLE_ICON = config.get('server', 'title_icon')
#for changing database of testing
# If manage.py test was called, use SQLite for faster testing
if 'test' in sys.argv:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test_sqlite.db'
}
}
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
)
else:
#added by Vinayak
#Fixtures to load data automatically when migrate is called
#gives error while runnint tests
FIXTURE_DIRS = (
os.path.join(PROJECT_DIR, 'elearning_academy/fixtures'),
os.path.join(PROJECT_DIR, 'user_profile/fixtures'),
os.path.join(PROJECT_DIR, 'courseware/fixtures'),
)
##Chat Settings
CHAT_SERVER = "ws://" + config.get('chatserver', 'ip')
TORNADO_PORT = config.get('chatserver', 'port')
<file_sep>/progress/static/progress/js/progress_entities.jsx
/** @jsx React.DOM */
var ProgressConcept = React.createClass({
render: function() {
var progressbar = 'Not Applicable';
if (parseInt(this.props.concept.max_score) != 0) {
widthvalue = parseFloat(this.props.concept.score)*100.0/parseFloat(this.props.concept.max_score);
progressbar = (
<div class="col-md-8 progress no-padding">
<div class="progress-bar progress-bar-success" style={{'width': widthvalue+'%'}}>
<span class='progressbar-text'>{this.props.concept.score}/{this.props.concept.max_score}</span>
</div>
<div class="progress-bar progress-bar-warning" style={{'width': '0%'}}>
</div>
</div>
);
}
return (
<div class="row">
<div class="col-md-4">
{this.props.concept.title}
</div>
{progressbar}
</div>
);
}
});
var ProgressGroup = React.createClass({
render: function() {
var concepts = this.props.group.concepts.map(function (object) {
return <ProgressConcept concept={object} />;
});
var progressbar = "Not Applicable";
if (parseInt(this.props.group.max_score) != 0) {
widthvalue = parseFloat(this.props.group.score)*100.0/parseFloat(this.props.group.max_score);
progressbar = (
<div class="col-md-8 progress no-padding">
<div class="progress-bar progress-bar-success" style={{'width': widthvalue+'%'}}>
<span class='progressbar-text'>{this.props.group.score}/{this.props.group.max_score}</span>
</div>
<div class="progress-bar progress-bar-warning" style={{'width': '0%'}}>
</div>
</div>
);
}
return (
<div class='panel panel-default'>
<div class='panel-heading' data-toggle='collapse' data-parent="#progressgroups"
data-target={'#progress-group-' + this.props.group.id}>
<div class="row panel-title">
<div class="col-md-4">
{this.props.group.title}
</div>
{progressbar}
</div>
</div>
<div id={'progress-group-'+this.props.group.id} class='progress-group-collapse-box panel-collapse collapse'>
<div class="panel-body">
<div class='panel-group progress-concepts'>
{concepts}
</div>
</div>
</div>
</div>
);
}
});
<file_sep>/progress/static/progress/js/student/progress.jsx
/** @jsx React.DOM */
var Progress = React.createClass({
mixins: [LoadMixin],
getUrl: function() {
return '/courseware/api/course/' + this.props.course + '/progress?format=json';
},
render: function() {
if (!this.state.loaded) {
return <LoadingBar />;
}
var progressgroups = this.state.data.groups.map(function (object) {
return <ProgressGroup group={object} />;
}.bind(this));
var progressbar = 'Not Applicable';
if (parseInt(this.state.data.max_score) != 0) {
widthvalue = parseFloat(this.state.data.score)*100.0/parseFloat(this.state.data.max_score);
progressbar = (
<div class="col-md-8 progress no-padding">
<div class="progress-bar progress-bar-success" style={{'width': widthvalue+'%'}}>
<span class='progressbar-text'>{this.state.data.score}/{this.state.data.max_score}</span>
</div>
<div class="progress-bar progress-bar-warning" style={{'width': '0%'}}>
</div>
</div>
);
}
return (
<div class="row">
<h3>
My Progress
</h3>
<div class="row">
<div class="col-md-4">
Overall Progress
</div>
{progressbar}
</div>
<div class='panel-group' id='progressgroups'>
{progressgroups}
</div>
</div>
);
}
});<file_sep>/download/views.py
from django.shortcuts import get_object_or_404 #render_to_response
#from django.template import RequestContext
from django.http import HttpResponseForbidden
from django.contrib.auth.decorators import login_required
from django.template.defaultfilters import slugify
from django.http import HttpResponse
from django.utils import timezone
from assignments.models import Assignment, Program, Testcase
from upload.models import Upload
from assignments.views import isCourseModerator
import os, tempfile, zipfile, StringIO, shutil
@login_required
def download_all_zipped(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
is_moderator = isCourseModerator(assignment.course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
all_submissions = Upload.objects.filter(assignment=assignment)
filenames = []
for a in all_submissions:
filenames += [(a.owner.username, a.filePath.file.name)]
a.filePath.close()
try:
zip_subdir = ""
zip_filename = slugify(assignment.name + "-all-submissions") + '.zip'
temp_dir = tempfile.mkdtemp(prefix="download_all")
for s_name, fpath in filenames:
_, fname = os.path.split(fpath)
z_f = zipfile.ZipFile(os.path.join(temp_dir, s_name + '.zip'), "w")
z_f.write(fpath, fname)
z_f.close()
# Open StringIO to grab in-memory ZIP contents
s = StringIO.StringIO()
zf = zipfile.ZipFile(s, "w")
for fname in os.listdir(temp_dir):
zip_path = os.path.join(zip_subdir, fname)
zf.write(os.path.join(temp_dir, fname), zip_path)
zf.close() # must close
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
# Grab ZIP file from in-memory, make response with correct MIME-type
resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed")
resp['Content-Length'] = s.tell()
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
return resp
@login_required
def download_assignment_files(request, assignmentID):
'''
This view let student download all assignment data
'''
assignment = get_object_or_404(Assignment, pk=assignmentID)
def file_name(fpath):
return os.path.split(fpath)[1]
is_moderator = isCourseModerator(assignment.course, request.user)
if is_moderator or timezone.now() > assignment.hard_deadline:
programs = Program.objects.filter(assignment=assignment)
else: # before deadline
programs = Program.objects.filter(assignment=assignment, program_type='Practice')
zip_filename = slugify(assignment.name + "-data") + '.zip'
zip_dir = assignment.name
s = StringIO.StringIO()
zf = zipfile.ZipFile(s, "w")
if assignment.document:
zip_path = os.path.join(zip_dir, "documents", file_name(assignment.document.file.name))
assignment.document.close()
zf.write(assignment.document.file.name, zip_path)
assignment.document.close()
if assignment.helper_code:
zip_path = os.path.join(zip_dir, "helper_code", file_name(assignment.helper_code.file.name))
assignment.helper_code.close()
zf.write(assignment.helper_code.file.name, zip_path)
assignment.helper_code.close()
for a_prgrm in programs:
if a_prgrm.program_files:
zip_path = os.path.join(zip_dir, a_prgrm.name, file_name(a_prgrm.program_files.file.name))
a_prgrm.program_files.close()
zf.write(a_prgrm.program_files.file.name, zip_path)
a_prgrm.program_files.close()
for test in Testcase.objects.filter(program=a_prgrm):
sub_path = os.path.join(zip_dir, a_prgrm.name, test.name + "_" + str(test.id))
if test.input_files:
f_name = test.input_files.file.name
test.input_files.close()
zip_path = os.path.join(sub_path, file_name(f_name))
zf.write(test.input_files.file.name, zip_path)
test.input_files.close()
if test.output_files:
f_name = test.output_files.file.name
test.output_files.close()
zip_path = os.path.join(sub_path, file_name(f_name))
zf.write(test.output_files.file.name, zip_path)
test.output_files.close()
zf.close()
resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed")
resp['Content-Length'] = s.tell()
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
return resp
<file_sep>/gunicorn.conf.py
"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
def max_workers():
return 2 * cpu_count() + 1
bind = '0.0.0.0:9090'
workers = 10 #max_workers()
worker_class = 'gevent'
#threads = 2
#timout = 120
<file_sep>/assignments/receivers.py
'''
Created on Jun 3, 2013
@author: aryaveer
'''
from elearning_academy.settings import MEDIA_ROOT
from evaluate.utils.executor import CommandExecutor
from assignments_utils.create_output import CreateOutput
from django.core.files import File
import os, shutil, pickle, tempfile
from utils.archives import Archive
from utils.filetypes import get_compiler_name, get_compilation_command, compile_required
from django.db import models
rootPath = os.path.realpath(os.path.dirname(__file__))
tmpDir = os.path.join(rootPath, "tmp")
# pre_delete receiver common for all models.
def delete_files(sender, instance, **kwargs):
for field in instance._meta.fields:
if isinstance(field, models.FileField):
filefield = getattr(instance, field.name)
if filefield:
filefield.delete(save=False)
# This receiver checks if the program solution is fine by compilation standards.
# post_save receiver.
def compile_solution(sender, instance, **kwargs):
# If the program language is an interpreted language, then we dont do anything
if not compile_required(instance.assignment.program_language) and not getattr(instance, 'execute_now', False):
instance.set_sane()
instance.delete_error_message()
return
if not compile_required(instance.assignment.program_language) :
old_pwd = os.getcwd()
instance.set_sane()
instance.UpdateOutput()
instance.delete_error_message()
os.chdir(old_pwd)
return
# instance.id would indicate that record was not created.
if not getattr(instance, 'compile_now', False) or instance.id is None:
return
# If solution is given then set the path, else do nothing
programFilePath = instance.program_files.name
if hasattr(instance.assignment.model_solution, 'file'):
ModelSolutionPath = instance.assignment.model_solution.file.name
instance.assignment.model_solution.close()
else:
instance.set_sane()
instance.delete_error_message()
return
# Model Solution was not provided hence do nothing.
if not os.path.isfile(ModelSolutionPath):
return
# Copying module solution to a temp directory for compilation
tmp_dir = tempfile.mkdtemp(prefix='grader')
old_pwd = os.getcwd()
os.chdir(tmp_dir)
currentDir = os.getcwd()
try:
# Copy model solution to temp directory.
with Archive(fileobj=instance.assignment.model_solution.file) as archive:
if archive.is_archive():
archive.extract(dest=currentDir)
else:
shutil.copy(src=os.path.join(MEDIA_ROOT, ModelSolutionPath), dst=currentDir)
# Change directory if solution tar contains a directory.
directories = [a for a in os.listdir('./') if os.path.isdir(a)]
if directories:
os.chdir(directories[0])
currentDir = os.getcwd()
# Copying the program files to the current directory
if instance.program_files:
with Archive(name=instance.program_files.file.name) as archive:
instance.program_files.close()
if archive.is_archive():
archive.extract(dest=currentDir)
else:
shutil.copy(src=os.path.join(MEDIA_ROOT, programFilePath), dst=currentDir)
# Setting up compilation process and calling the CommandExecutor with appropriate command
executor = CommandExecutor()
compiler_command = get_compilation_command(instance)
compileResult = executor.executeCommand(command=compiler_command)
# Compilation successful => Set the program to sane and delete errors, else report the errors.
if compileResult.returnCode == 0: # save exe file on success.
instance.is_sane = True
instance.UpdateOutput()
instance.delete_error_message()
else:
message = "Compilation failed.\nReturn code = {0}.\nError message={1}".format(compileResult.returnCode, "".join(compileResult.stderr))
print "Instructor solution not sane - " + message
instance.save_error(message)
shutil.rmtree(tmp_dir)
finally:
os.chdir(old_pwd)
# It is a post_save handler of Assignment model. This verifies all the programs of the assignment
def verify_all_programs(sender, instance, **kwargs):
if not getattr(instance, 'verify_programs', False):
return # nothing to do
all_programs = instance.program_model.objects.filter(assignment=instance)
msg = ""
for aprogram in all_programs:
# If assignment program language is changed then check if the program language is correct, else point the errors.
if 'program_language' in instance.changed_list:
if aprogram.language != instance.program_language:
aprogram.save_error("Programming language was changed in assignment. Please update this program accordingly.")
continue
else:
aprogram.is_sane = True
aprogram.save()
aprogram.delete_error_message()
# If the program files have been changed then, files in compiler command should either be in student program files
# or in additional files of program.
if 'student_program_files' in instance.changed_list:
file_list = []
if aprogram.program_files:
with Archive(fileobj=aprogram.program_files.file) as archive:
if archive.is_archive():
file_list = [a.split("/")[-1] for a in archive.getfile_members()]
else:
file_list = [aprogram.program_files.name.split("/")[-1]]
file_list.extend(instance.student_program_files.split())
file_to_compile = get_compilation_command_files(aprogram)
file_to_execute = get_execution_command_files(aprogram)
missing_file = set(file_to_compile) + set(file_to_execute) - set(file_list)
# Some files are missing
if missing_file:
msg = "Files {0} are missing form this program please upload these files.".format(" ".join(missing_file))
aprogram.save_error(msg)
continue
else:
aprogram.is_sane = True
aprogram.save()
aprogram.delete_error_message()
# If you reach here, everything is good. Now compile.
if 'model_solution' in instance.changed_list:
aprogram.compile_now = True
aprogram.execute_now = True
aprogram.save()
# Delete all content of testDir.
def cleanUp():
os.chdir(tmpDir)
for item in os.listdir(os.getcwd()):
if os.path.isfile(item): os.remove(item)
if os.path.isdir(item): shutil.rmtree(item)
# This creates the output of testcases if they are not provided. pre_save handler of Testcase model
def create_op_files(sender, instance, **kwargs):
# If output files are provided do save them as it.
if instance.output_files:
pass
# If they are not, then generate output file.
else:
print "CREATE OP FILES - ",instance.std_in_file_name
instance.gen_op_obj = CreateOutput(instance).get_output()
try:
with open(instance.gen_op_obj.out_file) as f:
instance.output_files = File(
f,
name=os.path.basename(instance.gen_op_obj.out_file)
)
instance.std_out_file_name = instance.gen_op_obj.get_stdout_file_name()
except:
pass
# post_save handler of Testcase model. This method effectively cleans temporary files created during automatic generation of output files.
def testcase_cleanup(sender, instance, **kwargs):
if hasattr(instance, 'gen_op_obj'):
# If object is saved and program has some error.
if instance.gen_op_obj.failed and hasattr(instance, 'id'):
instance.solution_ready = False
print "Saving error file"
instance.save_error(error_file=instance.gen_op_obj.get_stderr_file_path())
elif not instance.gen_op_obj.failed:
instance.solution_ready = True
instance.program.solution_ready = bool(instance.program.solution_ready and instance.solution_ready)
instance.clear_error()
print "Clear and set solution_ready to true!"
else:
instance.clear_error()
print "Clear and set solution_ready to true (last else)!"
instance.gen_op_obj.clean_up()
# output file was given.
else:
instance.clear_error()
print "Clear and set solution_ready to true (outer else)!"
<file_sep>/evaluate/utils/results.py
'''
This file is not being used in any module
'''
from django.core.files.storage import default_storage
from django.core.files import File
from assignments.models import Program
from assignments.models import Testcase
from elearning_academy.settings import MEDIA_ROOT
import tarfile, os
class TestResults(object):
def __init__(self, user):
self.user = user
def setSubmissionErrors(self):
self.file_found = False
self.compiled = False
self.test_passed = False
def setCompilationFailed(self, errorMessages):
self.file_found = True
self.compiled = False
self.test_passed = False
self.compiler_errors = errorMessages
def setTestcaseFailed(self):
self.file_found = True
self.compiled = True
self.test_passed = False
def saveAssignmentResults(self, assignment):
programs = Program.objects.filter(assignment=assignment)
for program in programs:
self.saveProgramResults(program)
def saveProgramResults(self, program):
testcases = Testcase.objects.filter(program=program)
for testcase in testcases:
self.saveTestcaseResults(testcase)
def saveTestcaseResults(self, testcase, testResult=None):
outputfiles = []
if testcase.program.outputFiles:
src = os.path.join(MEDIA_ROOT, testcase.program.outputFiles.name)
tar = tarfile.open(src)
outputfiles = [a.name for a in tar.getmembers() if a.isfile() and os.path.isfile(a.name)]
tar.close()
# Save results to database.
testcaseResult, created = Results.objects.get_or_create(
user = self.user,
testcase = testcase
)
testcaseResult.file_found = self.file_found if hasattr(self, 'file_found') else True
testcaseResult.compiled = self.compiled if hasattr(self, 'compiled') else True
testcaseResult.compiler_errors = "\n".join(self.compiler_errors) if hasattr(self, 'compiler_errors') else ""
testcaseResult.test_passed = self.test_passed if hasattr(self, 'test_passed') else True
if testResult is not None:
testResult.runtime_errors = "\n".join(testResult.stderr)
if not created:
default_storage.delete(testcaseResult.output_files.path)
testcaseResult.save()
# Now add output-files to database.
stdoutFileName = "standardOutput_" + str(testcase.id)
stdOutputofTestcase = open(stdoutFileName, 'w')
if testResult is not None:
stdOutputofTestcase.write("\n".join(testResult.stdout))
stdOutputofTestcase.close()
outputfiles.append(stdoutFileName)
tarname = "output_file_" + str(testcase.id) + ".tar.bz2"
outputFilesTar = tarfile.open(name=tarname, mode="w:bz2")
for afile in outputfiles:
outputFilesTar.add(afile)
outputFilesTar.close()
with open(tarname) as f:
testcaseResult.output_files.save(tarname, File(f) )
<file_sep>/evaluate/urls.py
'''
Created on May 22, 2013
@author: aryaveer
'''
from django.conf.urls import patterns, url
urlpatterns = patterns('evaluate.views',
url(r'^(?P<submissionID>\d+)$', 'evaluateAssignment', name='evaluate_evaluateassignment'),
url(r'^submission/(?P<submissionID>\d+)$', 'evaluateSubmission', name='evaluate_evaluatesubmission'),
url(r'^output/(?P<programID>\d+)$', 'checkOutput', name='evaluate_checkoutput'),
url(r'^result/(?P<submissionID>\d+)$', 'showResult', name='evaluate_showresult'),
url(r'^evalall/(?P<assignmentID>\d+)$', 'eval_all_submissions', name='evaluate_evalallsubmissions'),
url(r'^practice/(?P<submissionID>\d+)$', 'run_practice_test', name='evaluate_runpracticetest'),
url(r'^details/(?P<submissionID>\d+)$', 'evaluation_details', name='evaluate_evaluationdetails'),
url(r'^completedetails/(?P<assignmentID>\d+)$', 'complete_evaluation_details', name='evaluate_completeevaluationdetails'),
url(r'^completedetails/(?P<assignmentID>\d+)\.json$', 'get_evaluation_details_in_json', name='evaluate_completeevaluationdetails_json'),
url(r'^completedetails/(?P<assignmentID>\d+)\.csv$', 'get_evaluation_details_in_csv', name='evaluate_completeevaluationdetails_csv'),
url(r'^edit/marks$', 'edit_testcase_marks', name='edit_testcase_marks'),
url(r'^edit/comments$', 'edit_testcase_comments', name='edit_testcase_comments'),
)<file_sep>/upload/views.py
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponseNotFound, HttpResponseForbidden
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template.defaultfilters import slugify
from django.utils import timezone
from assignments.models import Assignment, Program
from assignments.views import isCourseModerator, isEnrolledInCourse, file_download
from courseware.models import Course
from evaluate.models import AssignmentResults
from upload.models import Upload
from upload.forms import UploadForm
from django.http import HttpResponse
import os, tempfile, zipfile, StringIO, shutil
@login_required
def upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Upload(filePath = request.FILES['docfile'])
newdoc.owner = request.user
#Overwrite file if already exist.
'''documents = Upload.objects.filter(owner=request.user)
if documents:
#print os.path.join(MEDIA_ROOT, documents[0].filePath.name)
os.remove(os.path.join(MEDIA_ROOT, documents[0].filePath.name))
documents.delete()'''
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('upload.views.upload'))
else:
form = UploadForm()
documents = Upload.objects.filter(owner=request.user)
return render_to_response(
'upload/upload.html',
{'form':form, 'documents': documents},
context_instance=RequestContext(request)
)
@login_required
def uploadAssignment(request, assignmentID):
if request.method == 'POST':
assignment = get_object_or_404(Assignment, pk=assignmentID)
form = UploadForm(request.POST, request.FILES, assignment_model_obj=assignment)
if form.is_valid():
newUpload = Upload(
owner = request.user,
assignment = assignment,
filePath = request.FILES['docfile']
)
newUpload.save()
else:
return form.errors
#return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID':assignmentID, 'form': form}))
@login_required
def showAllSubmissions(request, assignmentID):
if request.method == 'GET':
assignment=get_object_or_404(Assignment, pk=assignmentID)
course = assignment.course
all_assignments = Assignment.objects.filter(course=course).order_by('-serial_number')
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden('<h1>Forbidden 403</h1>')
if is_moderator:
assignments = all_assignments
leave_course = False
number_of_students = 0
else:
assignments = [a for a in all_assignments if a.publish_on <= timezone.now()]
leave_course = True
number_of_students = 0
allSubmission = Upload.objects.filter(assignment=assignment).order_by("-uploaded_on")
# paginator = Paginator(allSubmission, 20)
# page = request.GET.get('page')
# try:
# submission = paginator.page(page)
# except PageNotAnInteger:
# submission = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# submission = paginator.page(paginator.num_pages)
submission = allSubmission
disable = False
if submission:
programs = Program.objects.filter(assignment=assignment)
for aprogram in programs:
if not aprogram.is_sane:
disable = True
break
assignment_results = AssignmentResults.objects.filter(submission__in=submission)
#submisions_with_result = [(a.submission, a) for a in assignment_results]
for a_submission in submission:
marks = [s.get_marks() for s in assignment_results if s.submission == a_submission]
if marks: # means a_submission has result
a_submission.result_available_v = True
a_submission.marks_v = marks[0]
return render_to_response(
'upload/allSubmissions.html',
{'allSubmission': submission, 'assignment': assignment, 'disable': disable,
'course':course,'assignments':assignments,'date_time': timezone.now(),
'is_moderator':is_moderator},
context_instance=RequestContext(request)
)
else:
return HttpResponseNotFound('<h1>Page not found</h1>')
@login_required
def download_all_zipped(request, assignmentID):
assignment = get_object_or_404(Assignment, pk=assignmentID)
is_moderator = isCourseModerator(course, request.user)
if not is_moderator:
return HttpResponseForbidden("Forbidden 403")
all_submissions = Upload.objects.filter(assignment=assignment)
filenames = []
for a in all_submissions:
filenames += [(a.owner.username, a.filePath.file.name)]
a.filePath.close()
temp_dir = None
try:
zip_subdir = ""
zip_filename = slugify(assignment.name + "-all-submissions") + '.zip'
temp_dir = tempfile.mkdtemp(prefix="download_all")
for s_name, fpath in filenames:
_, fname = os.path.split(fpath)
z_f = zipfile.ZipFile(os.path.join(temp_dir, s_name + '.zip'), "w")
z_f.write(fpath, fname)
z_f.close()
# Open StringIO to grab in-memory ZIP contents
s = StringIO.StringIO()
zf = zipfile.ZipFile(s, "w")
for fname in os.listdir(temp_dir):
zip_path = os.path.join(zip_subdir, fname)
zf.write(os.path.join(temp_dir, fname), zip_path)
zf.close() # must close
except Exception as e:
print e.message
finally:
if temp_dir:
shutil.rmtree(temp_dir, ignore_errors=True)
# Grab ZIP file from in-memory, make response with correct MIME-type
resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed")
resp['Content-Length'] = s.tell()
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
return resp
@login_required
def my_submissions(request, courseID):
'''
List all submission of a current user for a given course.
'''
course = get_object_or_404(Course, pk=courseID)
all_assignments = Assignment.objects.filter(course=course)
all_uploads = Upload.objects.filter(assignment__in=all_assignments, owner=request.user).order_by("-uploaded_on")
return render_to_response(
'upload/my_submissions.html',
{'course': course, 'all_uploads': all_uploads},
context_instance=RequestContext(request)
)
@login_required
def submissionDownload(request, submissionID):
submission = get_object_or_404(Upload, pk=submissionID)
assignment = submission.assignment
course = assignment.course
if not isEnrolledInCourse(course, request.user):
return HttpResponseForbidden("Forbidden 403")
if not submission.filePath:
return HttpResponseNotFound("File not found")
is_moderator = isCourseModerator(course, request.user)
if(is_moderator or submission.owner==request.user):
return file_download(submission.filePath)
return HttpResponseForbidden("Forbidden 403")
<file_sep>/user_profile/models.py
"""
Contains database schema for user profile
"""
from django.db import models
from django.contrib.auth.models import User
from django.dispatch.dispatcher import receiver
from django.db.models.signals import post_save
from model_utils import Choices
from uuid import uuid4
from user_profile.countries import COUNTRIES
import json
# Constants
SHORT_TEXT = 63
LONG_TEXT = 255
GENDER_CHOICES = Choices(
('M', 'Male'),
('F', 'Female')
)
PRIVACY_CHOICES = (
('PB', 'Public'),
('PR', 'Private'),
('SU', 'Site Users')
)
DEGREE = Choices(
('BE', 'B.E.'),
('ME', 'M.E'),
('BTECH', 'B.Tech'),
('MTECH', 'M.Tech'),
('BTECH_MTECH', 'Dual Degree (B.Tech+M.Tech)'),
('BE_ME', 'Dual Degree (B.E.+M.E.)'),
('PHD', 'PhD'),
('MS', 'M.S.'),
('MS_PHD', 'Dual Degree (M.S.+PhD)'),
('MTECH_PHD', 'Dual Degree (M.Tech+PhD)')
)
class Major(models.Model):
"""
Class to store degree major of student
"""
major = models.CharField(max_length=SHORT_TEXT, null=False)
class College(models.Model):
"""
Class to store list of colleges
"""
college = models.CharField(max_length=LONG_TEXT, null=False)
#User Education model
class Education(models.Model):
"""
Class for User Education details
"""
user = models.ForeignKey(User)
degree = models.CharField(max_length=SHORT_TEXT, null=False, default=DEGREE.BTECH,
choices=DEGREE)
college = models.ForeignKey(College)
major = models.ForeignKey(Major)
start_date = models.DateField(blank=False, null=True)
end_date = models.DateField(blank=True, null=True)
def start_date_to_string(self):
"""
Return the start date for education in DD Month YYYY
"""
if self.start_date:
return self.start_date.strftime("%d %B %Y")
else:
return ""
def end_date_to_string(self):
"""
Return the end date for education in DD Month YYYY
"""
if self.end_date:
return self.end_date.strftime("%d %B %Y")
else:
return ""
def get_json(self):
"""
Return the education record in form of a json
"""
return {
'id': self.id,
'degree': self.get_degree_display(),
'college': self.college.college,
'major': self.major.major,
'start_date': self.start_date_to_string(),
'end_date': self.end_date_to_string()
}
#Company Names
class Company(models.Model):
"""
Various companies which a user can have worked previously
"""
company = models.CharField(max_length=SHORT_TEXT, blank=False)
company_description = models.CharField(max_length=SHORT_TEXT, blank=False)
#User Work Experience Model
class Work(models.Model):
"""
Class for User Work Experience details
"""
user = models.ForeignKey(User)
company = models.ForeignKey(Company)
position = models.CharField(max_length=SHORT_TEXT, blank=False)
description = models.CharField(max_length=LONG_TEXT)
start_date = models.DateField(blank=False, null=True)
end_date = models.DateField(blank=True, null=True)
def start_date_to_string(self):
"""
Return the start date for work in DD Month YYYY
"""
if self.start_date:
return self.start_date.strftime("%d %B %Y")
else:
return ""
def end_date_to_string(self):
"""
Return the end date for work in DD Month YYYY
"""
if self.end_date:
return self.end_date.strftime("%d %B %Y")
else:
return ""
def get_json(self):
"""
Return the Work record in form of a json
"""
return {
'id': self.id,
'company': self.company.company,
'company_description': self.company.company_description,
'position': self.position,
'description': self.description,
'start_date': self.start_date_to_string(),
'end_date': self.end_date_to_string()
}
# User profile model
class UserProfile(models.Model):
"""
Class of user profile details
"""
user = models.OneToOneField(User, primary_key=True,
related_name='User_UserProfile')
uid = models.CharField(max_length=32)
dob = models.DateField(blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True)
photo = models.ImageField(upload_to='static/img/', blank=True, null=True)
mobile = models.CharField(max_length=10, null=True)
place_city = models.CharField(max_length=SHORT_TEXT, blank=True, null=True)
place_state = models.CharField(max_length=SHORT_TEXT, blank=True, null=True)
place_country = models.CharField(max_length=SHORT_TEXT,
choices=COUNTRIES, blank=True, null=True)
privacy = models.CharField(max_length=2, choices=PRIVACY_CHOICES, blank=True, null=True)
about = models.CharField(max_length=LONG_TEXT, blank=True, null=True)
interests = models.CharField(max_length=LONG_TEXT, blank=True, null=True)
website_twitter = models.URLField(max_length=LONG_TEXT, blank=True, null=True)
website_facebook = models.URLField(max_length=LONG_TEXT, blank=True, null=True)
def generate_user_id(self):
""" Generate a random user id """
self.uid = uuid4().hex
def get_user_id(self):
""" Return the user's user id """
return self.uid
def get_user_address(self):
"""
Return the address of the user by concatenating city, state and country
"""
return self.place_city + ", " + self.place_state + ", "\
+ self.place_country
def dob_to_string(self):
""" Convert the DateField to a printable string """
if self.dob:
return self.dob.strftime("%d %B %Y")
else:
return ""
def education_list(self):
"""
Return a List of json of education record of the user
TODO(vgagrani): sort the list in terms of start time - Latest first
"""
education_records = Education.objects.filter(user=self.user)
education_list = []
for record in education_records:
education_list.append(record.get_json())
return education_list
def work_list(self):
"""
Return a list of json of work record of the user
TODO(vgagrani): sort the list in terms of start time - Latest first
"""
work_records = Work.objects.filter(user=self.user)
work_list = []
for record in work_records:
work_list.append(record.get_json())
return work_list
def toJson(self):
""" Convert a UserProfile object to a json object """
context = {}
context["dob"] = self.dob_to_string()
context["gender"] = self.get_gender_display()
context["city"] = self.place_city
context["state"] = self.place_state
context["country"] = self.get_place_country_display()
context["about"] = self.about
context["interests"] = self.interests
context["education_list"] = self.education_list()
context["work_list"] = self.work_list()
context["photo"] = "/media/" + str(self.photo)
context["website_twitter"] = self.website_twitter
context["website_facebook"] = self.website_facebook
return json.dumps(context)
class CustomUser(models.Model):
"""
Wrapper over django user to store the user mode of operation
"""
STUDENT_MODE = 'S'
INSTRUCTOR_MODE = 'I'
CONTENT_DEVELOPER_MODE = 'C'
MODE = (
(STUDENT_MODE, 'Student Mode'),
(INSTRUCTOR_MODE, 'Instructor Mode'),
(CONTENT_DEVELOPER_MODE, 'Content Developer Mode')
)
user = models.OneToOneField(User)
is_instructor = models.BooleanField(default=False)
is_content_developer = models.BooleanField(default=False)
default_mode = models.CharField(max_length=1, choices=MODE,
help_text="Mode of Operation",
default=STUDENT_MODE)
class GetInstructorPrivileges(models.Model):
user = models.OneToOneField(User)
@receiver(post_save, sender=User)
def create_custom_user(sender, **kwargs):
instance = kwargs['instance']
if kwargs['created']: # create
customuser, created = CustomUser.objects.get_or_create(
user=instance,
)
<file_sep>/courseware/models.py
"""
This file contains the course related models
"""
from django.db import models
from django.contrib.auth.models import User
from video.models import Video
from quiz.models import Quiz, QuizHistory
from discussion_forum.models import DiscussionForum, Tag
from document.models import Document
import json
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
SHORT_TEXT = 255
LARGE_TEXT = 1023
UUID_TEXT = 32
COURSE_CHOICES = (
('T', 'Textbook'),
('O', 'Offering'),
)
GRADE_CHOICES = (
('FR', 'Fail'),
('AA', '10'),
('AB', '9'),
('BB', '8'),
('BC', '7'),
('CC', '6'),
('CD', '5'),
('DD', '4'),
('PP', 'Pass'),
('DN', 'Did not Complete'),
)
ENROLLMENT_TYPE_CHOICES = (
('O', 'Open'),
('M', 'Moderated'),
)
ENROL_CHOICES = (
('A', 'Active'),
('P', 'Pending Approval'),
('U', 'Unenrolled')
)
class ParentCategory(models.Model):
"""Model for storing the parent categories"""
title = models.CharField(max_length=SHORT_TEXT, blank=False, unique=True)
def __unicode__(self):
return self.title
class Category(models.Model):
"""
This class contains all the category of courses
"""
parent = models.ForeignKey(
ParentCategory,
related_name="Parent",
db_index=True
)
title = models.CharField(max_length=SHORT_TEXT)
image = models.ImageField(upload_to='uploads/category_image', null=True, blank=True)
content_developers = models.ManyToManyField(
User,
related_name="Category_User"
)
def __unicode__(self):
return self.title
class CourseInfo(models.Model):
"""
This class stores the general information about the course
"""
start_time = models.DateField(db_index=True, null=True, blank=True)
end_time = models.DateField(null=True, blank=True)
# This field is used by the instructor/content dev. to publish any course.
# Only if it is true can a course/offering be visible to others
# When the field is false, instructor has the option to delete the course.
# Once this field is made true the instructor can no longer change it. He will have to mail
# the admin
is_published = models.BooleanField(default=False)
description = models.TextField(default='')
end_enrollment_date = models.DateField(null=True, blank=True)
# Default granularity to use for all questions of this course
# default_granularity = models.TextField(null=True)
# Default granularity to use for all questions of this course after hint
# default_granularity_hint = models.TextField(null=True)
class Course(models.Model):
"""
This class contains information about a course
"""
# Indexed for efficient querying of courses
category = models.ForeignKey(
Category,
related_name="Category_Course",
db_index=True
)
#Course details for the front page
title = models.CharField(max_length=SHORT_TEXT)
image = models.ImageField(upload_to='uploads/course_image', blank=True)
type = models.CharField(max_length=1, choices=COURSE_CHOICES, default='T')
playlist = models.TextField(default="[]")
forum = models.ForeignKey(DiscussionForum, related_name='Course_Forum')
#Documents attached to course
pages = models.ManyToManyField(Document, related_name='Course_Document')
page_playlist = models.TextField(default="[]")
max_score = models.IntegerField(default=0)
course_info = models.OneToOneField(
CourseInfo,
related_name="CourseInfo_Course",
null=True,
blank=True
)
# Field to see if open registrations are allowed or moderator has to \
# approve. Who approves and where it will be stored and then to send a \
# notification is still left to do.
enrollment_type = models.CharField(
max_length=1,
choices=ENROLLMENT_TYPE_CHOICES,
default='M'
)
def save(self, *args, **kwargs):
""" overriding save method """
if self.pk is None:
forum = DiscussionForum()
forum.save()
course_info = CourseInfo()
course_info.save()
self.forum = forum
self.course_info = course_info
super(Course, self).save(*args, **kwargs)
def update_score(self, difference):
self.max_score += difference
self.save()
class Offering(Course):
"""
This class extends the Course class. This has offering specific related fields
"""
shortlisted_courses = models.ManyToManyField(Course, related_name='shortlistedCourses')
def save(self, *args, **kwargs):
self.type = 'O'
super(Offering, self).save(*args, **kwargs)
class CourseHistory(models.Model):
"""
This class contains history of the user in a course
"""
course = models.ForeignKey(
Course,
related_name="CourseHistory_Course",
db_index=True
)
user = models.ForeignKey(User, related_name="CourseHistory_User")
# Details of the user
grade = models.CharField(
max_length=2,
choices=GRADE_CHOICES,
null=True
)
score = models.FloatField(default=0.0, null=True)
# To see whether user is enrolled or not or the approval is pending, do not delete objects
active = models.CharField(max_length=1, choices=ENROL_CHOICES, default='U')
is_moderator = models.BooleanField(default=False)
is_owner = models.BooleanField(default=False)
is_creator = models.BooleanField(default=False)
show_marks = models.BooleanField(default=True)
class Meta:
"""
Course and user combined should be unique
"""
unique_together = ("course", "user")
index_together = [
['user', 'course'],
]
def progress(self):
data = {}
data['score'] = self.score
data['max_score'] = self.course.max_score
groups = Group.objects.filter(course=self.course)
_playlist = json.loads(self.course.playlist)
data['groups'] = []
for groupid in _playlist:
gh, created = GroupHistory.objects.get_or_create(
group=groups[groupid[1]], user=self.user)
data['groups'].append(gh.progress())
return data
def update_score(self, difference):
self.score += difference
self.save()
class Group(models.Model):
course = models.ForeignKey(
Course,
related_name="Group_Course",
db_index=True
)
# Details of the concept
title = models.CharField(max_length=SHORT_TEXT, blank=False)
image = models.ImageField(
upload_to='uploads/group_image', blank=True)
pages = models.ManyToManyField(Document)
max_score = models.IntegerField(default=0)
playlist = models.TextField(default="[]")
description = models.TextField(blank=True)
def update_score(self, difference):
self.max_score += difference
self.save()
self.course.update_score(difference)
class GroupHistory(models.Model):
"""
This class contains history of the user in a course
"""
group = models.ForeignKey(
Group,
related_name="GroupHistory_Group",
db_index=True
)
user = models.ForeignKey(User, related_name="GroupHistory_User")
score = models.FloatField(default=0.0, null=True)
#course_history = models.ForeignKey(
# CourseHistory,
# related_name="CourseHistory_GroupHistory",
# db_index=True
#)
class Meta:
"""
Course and user combined should be unique
"""
unique_together = ("group", "user")
index_together = [
['user', 'group'],
]
def progress(self):
data = {}
data['id'] = self.id
data['title'] = self.group.title
data['score'] = self.score
data['max_score'] = self.group.max_score
concepts = Concept.objects.filter(group=self.group)
_playlist = json.loads(self.group.playlist)
data['concepts'] = []
for conceptid in _playlist:
ch, created = ConceptHistory.objects.get_or_create(
concept=concepts[conceptid[1]], user=self.user)
data['concepts'].append(ch.progress())
return data
def update_score(self, difference):
self.score += difference
self.save()
ch, created = CourseHistory.objects.get_or_create(course=self.group.course, user=self.user)
ch.update_score(difference)
class Concept(models.Model):
"""
This class contains the details about a concept
"""
group = models.ForeignKey(
Group,
related_name="Concept_Group",
db_index=True
)
# Details of the concept
title_document = models.ForeignKey(Document, related_name='Concept_Title')
title = models.CharField(max_length=SHORT_TEXT)
image = models.ImageField(
upload_to='uploads/concept_image', blank=True, null=True)
max_score = models.IntegerField(default=0)
playlist = models.TextField(default="[]")
description = models.TextField(blank=True, null=True)
#Many to many relations for the learning elements in the playlist
videos = models.ManyToManyField(Video, related_name='Concept_Video')
quizzes = models.ManyToManyField(Quiz, related_name='Concept_Quiz')
pages = models.ManyToManyField(Document, related_name='Concept_Document')
is_published = models.BooleanField(default=False)
tag = models.ForeignKey(Tag, null=True, default=None)
def update_score(self, difference):
self.max_score += difference
self.save()
self.group.update_score(difference)
class ConceptHistory(models.Model):
"""
This class contains history of the user in a concept
"""
concept = models.ForeignKey(
Concept,
related_name="ConceptHistory_Concept",
)
user = models.ForeignKey(
User,
related_name="User_Concept"
)
#group_history = models.ForeignKey(
# GroupHistory,
# related_name="GroupHistory_ConceptHistory",
# db_index=True
# )
score = models.FloatField(default=0.0)
class Meta:
"""
Concept and user combined should be unique
"""
unique_together = ("concept", "user")
index_together = [
['user', 'concept'],
]
def progress(self):
data = {}
data['id'] = self.concept.id
data['title'] = self.concept.title
data['score'] = self.score
data['max_score'] = self.concept.max_score
quizzes = self.concept.quizzes.all()
#_playlist = json.loads(self.group.playlist)
data['quizzes'] = []
for quizid in quizzes:
qh, created = QuizHistory.objects.get_or_create(
quiz=quizid, user=self.user)
data['quizzes'].append(qh.progress())
return data
def update_score(self, difference):
self.score += difference
self.save()
gh, created = GroupHistory.objects.get_or_create(group=self.concept.group, user=self.user)
gh.update_score(difference)
class LearningElement(models.Model):
"""
The abstract class for a learning element. Will be inherited by quiz and \
video classes.
"""
course = models.ForeignKey(
Course,
related_name="LearningElement_Course",
db_index=True
)
concept = models.ForeignKey(
Concept,
related_name="LearningElement_Concept",
db_index=True
)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
is_public = models.BooleanField()
#publish_time = models.DateTimeField()
is_hidden = models.BooleanField(default=False)
class Meta:
"""
Making abstract = True
"""
abstract = True
@receiver(pre_delete, sender=Concept)
def delete_quizzes_on_delete(sender, **kwargs):
""" Delete all quizzes related to Concept and decrease max_score"""
print "CALLING PRE DELETE"
instance = kwargs['instance']
# instance.group.update_score((-1*(instance.max_score)))
# WARNING : This might not work
instance.quizzes.all().delete()
<file_sep>/courseware/static/courseware/js/student/course_page.jsx
/** @jsx React.DOM */
var Section = React.createClass({
mixins: [MathJaxMixin,],
render: function() {
return (
<div class="section">
<div>
<h4>
{this.props.section.title}
</h4>
<p><span dangerouslySetInnerHTML={{__html: converter.makeHtml(this.props.section.description)}} /></p>
</div>
</div>
);
}
});
var Page = React.createClass({
mixins: [MathJaxMixin,],
loadPage: function() {
url = "/document/api/page/" + this.props.id + "/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
this.setState({content: response, loaded: true});
}.bind(this));
},
getInitialState: function() {
return {
loaded: false,
content: undefined,
};
},
componentDidMount: function() {
if (!this.state.loaded) {
this.loadPage();
}
},
componentDidUpdate: function() {
if (!this.state.loaded) {
this.loadPage();
}
},
componentWillReceiveProps: function() {
this.setState({
loaded: false,
content: undefined,
});
},
render: function() {
if (!this.state.loaded) {
return (
<LoadingBar />
);
}
else {
var sections = this.state.content.sections.map(function (section) {
return (
<Section section={section}/>
);
}.bind(this));
return (
<div class="mydocument">
<h3>{this.state.content.title}</h3>
<p><span dangerouslySetInnerHTML={{__html: converter.makeHtml(this.state.content.description)}} />
</p>
<div>
{sections}
</div>
</div>
);
}
}
});<file_sep>/assignments/widgets.py
from django.forms import FileInput, CheckboxInput
from django import forms
from django.utils.html import conditional_escape, format_html
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext, ugettext_lazy
import os
class SecureFileInput(FileInput):
initial_text = ugettext_lazy('Currently')
input_text = ugettext_lazy('Change')
clear_checkbox_label = ugettext_lazy('Clear')
template_with_initial = 'Currently: %(initial)s %(clear_template)s<br />%(input_text)s: %(input)s'
template_with_clear = '%(clear)s <label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>'
def __init__(self, data_source_url, attrs=None):
self.data_source_url = data_source_url
super(SecureFileInput, self).__init__(attrs)
def render(self, name, value, attrs=None):
substitutions = {
'initial_text': self.initial_text,
'input_text': self.input_text,
'clear_template': '',
'clear_checkbox_label': self.clear_checkbox_label,
}
template = '%(input)s'
substitutions['input'] = super(SecureFileInput, self).render(name, value, attrs)
if value and hasattr(value, "url"):
template = self.template_with_initial
substitutions['initial'] = format_html('<a href="{0}">{1}</a>',
force_text(self.data_source_url),
force_text(os.path.basename(value.name)))
if not self.is_required:
checkbox_name = self.clear_checkbox_name(name)
checkbox_id = self.clear_checkbox_id(checkbox_name)
substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
substitutions['clear_template'] = self.template_with_clear % substitutions
return mark_safe(template % substitutions)
def clear_checkbox_name(self, name):
"""
Given the name of the file input, return the name of the clear checkbox
input.
"""
return name + '-clear'
def clear_checkbox_id(self, name):
"""
Given the name of the clear checkbox input, return the HTML id for it.
"""
return name + '_id'
def value_from_datadict(self, data, files, name):
upload = super(SecureFileInput, self).value_from_datadict(data, files, name)
if not self.is_required and CheckboxInput().value_from_datadict(
data, files, self.clear_checkbox_name(name)):
if upload:
# If the user contradicts themselves (uploads a new file AND
# checks the "clear" checkbox), we return a unique marker
# object that FileField will turn into a ValidationError.
return FILE_INPUT_CONTRADICTION
# False signals to clear any existing value, as opposed to just None
return False
return upload<file_sep>/concept/urls.py
"""
Concept URL resolver file
"""
from django.conf.urls import include, patterns, url
from concept import views
from courseware.viewsets.vconcept import ConceptViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'concept', ConceptViewSet)
urlpatterns = patterns(
'',
url(r'^api/', include(router.urls)),
url(r'^(\d+)/$', views.view_concept, name="view"),
#url(r'^(\d+)/edit/$', views.view_content_developer,
# name="edit_concept_content_developer"),
)
<file_sep>/chat/views.py
__author__ = 'dheerendra'
from django.shortcuts import render_to_response, get_object_or_404
from django.http.response import HttpResponseForbidden
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required
from django.conf import settings
from models import ChatRoom
from models import Chat
from courseware.permissions import IsRegistered, IsOwner
def check_permission(request, course):
# checks if user is registered in the course. owner is also registered
isRegistered = IsRegistered()
return isRegistered.has_object_permission(request, None, course)
def is_teacher(request, course):
isOwner = IsOwner()
return isOwner.has_object_permission(request, None, course)
@login_required
def index(request, chatroom):
context = RequestContext(request)
theChatRoom = get_object_or_404(ChatRoom, pk=chatroom)
permission = check_permission(request, theChatRoom.course)
if not permission:
# throw 404 if user is not registered
return HttpResponseForbidden()
isTeacher = is_teacher(request, theChatRoom.course)
context_dict = {
'page_title': 'Chatroom: ' + theChatRoom.title,
'home_url': '/courseware/course/' + str(theChatRoom.course.id),
'home_title': theChatRoom.course.title,
'parent_url': '/chat/' + str(chatroom),
'parent_title': theChatRoom.title,
'chaturl': "%s/wschat/%s/-1" % (settings.CHAT_SERVER, chatroom),
'apiurl': "/chat/api/chat/" + str(chatroom) + "/get/?format=json",
'parentId': "-1",
'teacher': isTeacher,
}
return render_to_response('chat.html', context_dict, context)
@login_required
def reply(request, chatId):
context = RequestContext(request)
theChat = get_object_or_404(Chat, pk=chatId)
theChatRoom = theChat.chatroom
permission = check_permission(request, theChatRoom.course)
if not permission:
return HttpResponseForbidden()
isTeacher = is_teacher(request, theChatRoom.course)
parent = theChat.parent
if parent is None:
parent_url = '/chat/' + str(theChatRoom.id)
# if parent is None then parent_url will direct to chatroom url like /chat/1
parent_title = theChat.message
else:
parent_url = '/chat/reply/'+ str(parent.id)
parent_title = theChat.message
context_dict = {
'page_title': 'Reply: ' + str(theChat.id),
'home_url': '/chat/' + str(theChatRoom.id),
'home_title': theChatRoom.title,
'parent_url': parent_url,
'parent_title': parent_title,
'chaturl': "%s/wschat/%d/%d" % (settings.CHAT_SERVER, theChatRoom.id, theChat.id),
'apiurl': "/chat/api/chat/" + str(theChat.id) + "/reply/?format=json",
'parentId': str(theChat.id),
'teacher': isTeacher,
}
return render_to_response('chat.html', context_dict, context)<file_sep>/TestBed/Bash/Student/Syntax/friends.sh
# This is a program that keeps your address book up to date.
friends="<NAME>"
echo $friend
read name
read gender
if [[ $friends == *"$name"* ]]; then
echo "You are already there!"
elif [ "$gender" == "m" ]; then
echo "You are added to Michel's friends list."
else
echo "You are added to Michel's friends list. Thank you so much!"
fi<file_sep>/TestBed/Bash/Student/Correct/friends.sh
# This is a program that keeps your address book up to date.
friends="<NAME>"
echo $friends
read name
read gender
if [[ $friends == *"$name"* ]]; then
echo "You are already there!"
exit 1
elif [ "$gender" == "m" ]; then
echo "You are added to Michel's friends list."
exit 1
else
echo "You are added to Michel's friends list. Thank you so much!"
fi<file_sep>/courseware/serializers.py
"""
Serializers for the courseware API
"""
from rest_framework import serializers
from courseware import models
from video.serializers import VideoSerializer
from quiz.serializers import QuizSerializer
from document.serializers import DocumentSerializer
class AddGroupSerializer(serializers.ModelSerializer):
class Meta:
model = models.Group
exclude = ('pages', 'course')
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = models.Group
exclude = ('pages',)
class ConceptSerializer(serializers.ModelSerializer):
"""
Serializer for Concept
"""
videos = VideoSerializer(many=True)
quizzes = QuizSerializer(many=True)
pages = DocumentSerializer(many=True)
class Meta:
"""
Defining model
"""
model = models.Concept
fields = ('id', 'title', 'description', 'image', 'playlist', 'is_published')
#fields = ('id', 'group', 'title', 'image', 'playlist')
class ConceptDataPlaylistSerializer(serializers.Serializer):
"""
Serializer to create the playlist to send to the concept page
"""
id = serializers.IntegerField()
title = serializers.CharField(default='title not specified')
seen_status = serializers.BooleanField(default=False)
toc = serializers.CharField()
url = serializers.CharField()
class GroupPlaylistSerializer(serializers.Serializer):
"""
Serializer for the playlist of a group_playlist
"""
id = serializers.IntegerField()
title = serializers.CharField()
class ConceptDataSerializer(serializers.Serializer):
"""
Selrializer to send the data required for the
concept page
"""
id = serializers.IntegerField()
title = serializers.CharField(default='title_not_specified')
description = serializers.CharField(default='description_not_provided')
group = serializers.IntegerField(default=0)
group_title = serializers.CharField(default='group_not_spefified')
course = serializers.IntegerField(default=0)
course_title = serializers.CharField(default='course_not_specified')
playlist = ConceptDataPlaylistSerializer(many=True)
current_video = serializers.IntegerField(default=-1)
group_playlist = GroupPlaylistSerializer(many=True)
course_playlist = GroupPlaylistSerializer(many=True)
title_document = DocumentSerializer()
class ConceptHistorySerializer(serializers.ModelSerializer):
"""
Serializer for ConceptHistory
"""
class Meta:
"""
Defining model
"""
model = models.ConceptHistory
class AddQuizSerializer(serializers.Serializer):
title = serializers.CharField(max_length=models.SHORT_TEXT)
<file_sep>/courseware/vsserializers/course.py
"""
Serializers for Course, CourseHistory and CourseInfo Models
"""
from rest_framework import serializers
from courseware.models import Course, Offering, CourseHistory, CourseInfo
class CourseInfoSerializer(serializers.ModelSerializer):
"""serializer for the courseinfo class"""
class Meta:
"""Meta"""
model = CourseInfo
read_only_fields = ('is_published',)
class CourseSerializer(serializers.ModelSerializer):
"""serializer for the course class"""
course_info = CourseInfoSerializer(required=False)
class Meta:
"""Meta"""
model = Course
exclude = ('pages', 'max_score')
read_only_fields = ('forum', 'type', 'playlist', 'page_playlist')
class OfferingSerializer(serializers.ModelSerializer):
"""Serializer for the offering model"""
course_info = CourseInfoSerializer(required=False)
class Meta:
model = Offering
exclude = ('pages', 'shortlisted_courses', 'max_score')
read_only_fields = ('forum', 'type', 'playlist', 'page_playlist')
class CourseHistorySerializer(serializers.ModelSerializer):
"""Serializer for CourseHistory Model"""
class Meta:
"""Meta"""
model = CourseHistory
fields = ('course', 'user', 'grade', 'score')
<file_sep>/util/views.py
"""
Contains views served by Util app
"""
<file_sep>/courseware/viewsets/vconcept.py
"""
Functionality provided:
Concept:
+ retrieve: (IsRegisteredOrAnyInstructor)
+ update, delete: (IsOwner)
- playlist - (IsRegisteredOrAnyInstructor)
- reorder - (IsOwner)
- add_video, add_element, add_quiz, add_document - (IsOwner)
- add_existing_quiz, add_existing_document - (IsOwner)
- delete_element - (IsOwner)
- get_concept_page_data - (IsRegisteredOrAnyInstructor)
- quizzes - (IsRegisteredOrAnyInstructor) (TODO)
"""
from django.shortcuts import get_object_or_404
from elearning_academy.settings import DEFAULT_CONCEPT_IMAGE
from courseware.models import Course, Group, Concept
from courseware.serializers import ConceptSerializer, AddQuizSerializer, GroupSerializer
from courseware import playlist, typed_playlist
from courseware.permissions import IsOwnerOrReadOnly, IsOwner
from rest_framework import mixins, status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import link, action
from concept.models import ConceptQuizHistory, ConceptDocumentHistory
from concept.serializers import ConceptDocumentHistorySerializer, \
ConceptQuizHistorySerializer
from discussion_forum.models import DiscussionForum, Tag
from document.models import Document
from document.serializers import DocumentSerializer
from video.models import Video, VideoHistory
from video.serializers import VideoSerializer, AddVideoSerializer, VideoHistorySerializer
from quiz.serializers import QuizSerializer
from quiz.models import Quiz, Question, Submission, QuizHistory, QuestionHistory
from video.views import import_quiz_camtasia8
from elearning_academy.permissions import InInstructorOrContentDeveloperMode
import json
class ConceptViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
"""
ViewSet for Concept class
"""
queryset = Concept.objects.all()
serializer_class = ConceptSerializer
permission_classes = [IsOwnerOrReadOnly]
def destroy(self, request, pk=None):
"""
Delete a Concept if owned by user and in playlist of its group
"""
concept = get_object_or_404(Concept, pk=pk)
group = concept.group
new_playlist = playlist.delete(group.playlist, pk=pk)
if not new_playlist:
return Response({
"detail": "Object not found in your Group"
}, status.HTTP_404_NOT_FOUND)
group.playlist = new_playlist
group.save()
return super(ConceptViewSet, self).destroy(request, pk)
def playlist_as_array(self, request, pk=None, with_history=False, instructor=False):
"""
Gets all the elements in the playlist
"""
concept = get_object_or_404(Concept.objects.select_related('videos','quizzes','pages'), pk=pk)
videos_obj = concept.videos.all()
# videos_obj = []
# for elem in json.loads(concept.playlist):
# if elem[2] == 0:
# videos_obj.append(Video.objects.get(pk=elem[0]))
pages_obj = concept.pages.all()
#pages_obj = []
#for elem in json.loads(concept.playlist):
# if elem[2] == 2:
# pages_obj.append(Document.objects.get(pk=elem[0]))
quizzes_obj = concept.quizzes.all()
videos = VideoSerializer(videos_obj, many=True)
pages = [page.to_dict() for page in pages_obj]
quizzes = QuizSerializer(quizzes_obj, many=True)
_playlist = typed_playlist.to_array(concept.playlist)
if with_history:
videos_history = []
for video in videos_obj:
videohistory = VideoHistory.objects.filter(video=video,
user=request.user)
if (len(videohistory) == 0):
videohistory = VideoHistory(video=video, user=request.user)
videohistory.save()
else:
videohistory = videohistory[0]
videos_history.append(
VideoHistorySerializer(videohistory).data)
quizzes_history = []
for quiz in quizzes_obj:
quizhistory = ConceptQuizHistory.objects.filter(
quiz=quiz,
user=request.user)
if (len(quizhistory) == 0):
quizhistory = ConceptQuizHistory(
quiz=quiz,
user=request.user)
quizhistory.save()
else:
quizhistory = quizhistory[0]
quizzes_history.append(
ConceptQuizHistorySerializer(quizhistory).data)
pages_history = []
for document in pages_obj:
documenthistory = ConceptDocumentHistory.objects.filter(
document=document,
user=request.user)
if (len(documenthistory) == 0):
documenthistory = ConceptDocumentHistory(
document=document,
user=request.user)
documenthistory.save()
else:
documenthistory = documenthistory[0]
pages_history.append(
ConceptDocumentHistorySerializer(documenthistory).data)
ordered_data = []
for elem in _playlist:
if elem[2] == 0:
next_item = {
'type': 'video',
'content': videos.data[elem[1]]
}
if with_history:
next_item['history'] = videos_history[elem[1]]
elif elem[2] == 1:
if not quizzes.data[elem[1]]['is_published'] and not instructor:
continue
next_item = {
'type': 'quiz',
'content': quizzes.data[elem[1]]
}
if with_history:
next_item['history'] = quizzes_history[elem[1]]
elif elem[2] == 2:
next_item = {
'type': 'document',
'content': pages[elem[1]]
}
if with_history:
next_item['history'] = pages_history[elem[1]]
ordered_data.append(next_item)
return ordered_data
@action(methods=['POST'], permission_classes=((IsOwner, )))
def publish(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
concept.is_published = not concept.is_published
if concept.is_published:
msg = "Published " + concept.title
## Create a tag by the same name as the concept name
## TODO: Better way to do this?
## TODO: What diff b/w tag_name and tag_title?
## TODO: Delete tag on un-publish
group = get_object_or_404(Group, pk=concept.group_id)
course_id = group.course_id
forum = get_object_or_404(DiscussionForum,pk=course_id)
if not concept.tag:
tag = Tag(forum=forum)
tag.tag_name = concept.title
tag.title = concept.title
tag.save()
concept.tag = tag
else:
msg = "Un-Published " + concept.title
concept.save()
return Response({"msg": msg}, status.HTTP_200_OK)
@link(permission_classes=((IsOwnerOrReadOnly, )))
def playlist(self, request, pk=None):
""" Return the playlist as a response"""
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
isOwnerObj = IsOwner()
inInstructorOrContentDeveloperModeObj = InInstructorOrContentDeveloperMode()
isIorC = inInstructorOrContentDeveloperModeObj.has_permission(request, None)
isOwnerCourse = isOwnerObj.has_object_permission(request=request, view=None, obj=concept.group.course)
return Response(self.playlist_as_array(request, pk, False, isIorC and isOwnerCourse))
@action(methods=['PATCH'], permission_classes=((IsOwnerOrReadOnly,)))
def reorder(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
myplaylist = request.DATA['playlist']
print myplaylist
newplaylist = typed_playlist.is_valid(myplaylist, concept.playlist)
if newplaylist is not False:
concept.playlist = newplaylist
concept.save()
return self.playlist(request, pk)
else:
content = "Given order data does not have the correct format"
return Response(content, status.HTTP_400_BAD_REQUEST)
@action(methods=['POST'],
permission_classes=((IsOwnerOrReadOnly, )),
serializer_class=VideoSerializer)
def add_video(self, request, pk=None):
"""
Add video in the given concept
"""
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
serializer = AddVideoSerializer(data=request.DATA)
if serializer.is_valid():
if 'other_file' in request.FILES:
video = Video(
title=serializer.data['title'],
content=serializer.data['content'],
video_file=request.FILES['video_file'],
other_file=request.FILES['other_file'],
#duration=duration
)
else:
video = Video(
title=serializer.data['title'],
content=serializer.data['content'],
video_file=request.FILES['video_file'],
#duration=duration
)
video.save()
duration = video.get_length()
video.duration = duration
video.save()
try:
if 'video_config_file' in request.FILES:
import_quiz_camtasia8(request.FILES['video_config_file'], video)
concept.playlist = typed_playlist.append(video.id, concept.playlist, 0)
concept.videos.add(video)
concept.save()
return Response(VideoSerializer(video).data)
except Exception, e:
print "Camtasia 8 exception : " + str(e)
video.delete()
return Response({"error": "Cannot parse Config File"}, status.HTTP_400_BAD_REQUEST)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
@action(methods=['POST'], permission_classes=((IsOwnerOrReadOnly, )))
def add_element(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
concept.playlist.append()
return Response(ConceptSerializer(concept))
def remove_video(self, concept, id):
concept.videos.remove(Video.objects.get(pk=id))
def remove_quiz(self, concept, id):
all_questions_under_quiz = Question.objects.filter(quiz_id=id)
for question in all_questions_under_quiz:
submission = Submission.objects.filter(question=question).delete()
marks = question.marks
concept.max_score = concept.max_score - marks
QuestionHistory.objects.filter(question=question).delete()
all_questions_under_quiz.delete()
concept.quizzes.remove(Quiz.objects.get(pk=id))
def remove_document(self, concept, id):
concept.pages.remove(Document.objects.get(pk=id))
@action(methods=['POST'], permission_classes=((IsOwnerOrReadOnly, )))
def delete_element(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
_id = int(request.DATA['id'])
_type = int(request.DATA['type'])
print "old playlist was : ", concept.playlist
print "will delete ", _id, " ", _type
new_playlist = typed_playlist.delete(concept.playlist, _id, _type)
print "new plalist is : ", new_playlist
if new_playlist is not False:
concept.playlist = new_playlist
if _type == 0:
self.remove_video(concept, _id)
elif _type == 1:
self.remove_quiz(concept, _id)
elif _type == 2:
self.remove_document(concept, _id)
concept.save()
return Response(ConceptSerializer(concept).data)
@action(methods=['POST'],
permission_classes=((IsOwnerOrReadOnly, )),
serializer_class=QuizSerializer)
def add_quiz(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
serializer = AddQuizSerializer(data=request.DATA)
if serializer.is_valid():
quiz = Quiz(
title=serializer.data['title'])
quiz.save()
concept.playlist = typed_playlist.append(quiz.id, concept.playlist, 1)
concept.quizzes.add(quiz)
concept.save()
return Response(QuizSerializer(quiz).data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
@action(methods=['POST'])
def add_existing_quiz(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
quiz = get_object_or_404(Quiz, int(request.DATA['pk']))
concept.playlist = typed_playlist.append(quiz.id, concept.playlist, 1)
concept.quizzes.add(quiz)
concept.save()
return Response(ConceptSerializer(concept).data)
@action(methods=['POST'],
permission_classes=((IsOwnerOrReadOnly, )),
serializer_class=DocumentSerializer)
def add_document(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
serializer = DocumentSerializer(data=request.DATA)
if serializer.is_valid():
document = Document(
title=serializer.data['title'],
description=serializer.data['description']
)
document.save()
concept.playlist = typed_playlist.append(document.id, concept.playlist, 2)
concept.pages.add(document)
concept.save()
return Response(document.to_dict())
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
# TODO: check if the document is not already added in the concept
@action(methods=['POST'], permission_classes=((IsOwnerOrReadOnly, )))
def add_existing_document(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request, concept.group.course)
document = get_object_or_404(Document, int(request.DATA['pk']))
concept.playlist = typed_playlist.append(document.id, concept.playlist, 2)
concept.pages.add(document)
concept.save()
return Response(ConceptSerializer(concept).data)
# TODO: Test whether this function works correctly
@link()
def quizzes(self, request, pk=None):
concept = get_object_or_404(Concept, pk=pk)
self.check_object_permissions(request=request, obj=concept.group.course)
serializer = QuizSerializer(concept.quizzes.all(), many=True)
_playlist = typed_playlist.to_array(concept.playlist)
ordered_data = []
for elem in _playlist:
if elem[2] == 1:
ordered_data.append(serializer.data[elem[1]])
return Response(ordered_data)
@link(permission_classes=((IsOwnerOrReadOnly, )))
def get_concept_page_data(self, request, pk=None):
concept = get_object_or_404(Concept.objects.select_related('group', 'title_document'), pk=pk)
self.check_object_permissions(request, concept.group.course)
isOwnerObj = IsOwner()
inInstructorOrContentDeveloperModeObj = InInstructorOrContentDeveloperMode()
isIorC = inInstructorOrContentDeveloperModeObj.has_permission(request, None)
isOwnerCourse =isOwnerObj.has_object_permission(request=request, view=None, obj=concept.group.course)
if not isIorC:
if (not concept.is_published and not isOwnerCourse):
return Response({"error": "Concept does not exist"}, status.HTTP_400_BAD_REQUEST)
data = {}
data['id'] = concept.id
data['title'] = concept.title
data['description'] = concept.description
data['title_document'] = concept.title_document.to_dict()
if concept.image:
data['image'] = concept.image.url
else:
data['image'] = DEFAULT_CONCEPT_IMAGE
group = concept.group
course1 = group.course
data['forum'] = course1.forum.id
if concept.tag:
data['tag'] = concept.tag.id
data['group'] = group.id
data['group_title'] = group.title
data['course'] = course1.id
data['course_title'] = course1.title
data['group_playlist'] = []
concepts = Concept.objects.filter(group=group)
serializer = ConceptSerializer(concepts, many=True)
_playlist = json.loads(group.playlist)
for i in range(len(_playlist)):
concept = serializer.data[_playlist[i][1]]
if concept['is_published'] or (isIorC and isOwnerCourse):
data['group_playlist'].append(concept)
_groups = Group.objects.filter(course=course1)
serializer = GroupSerializer(_groups, many=True)
_playlist = playlist.to_array(course1.playlist)
N = len(_playlist)
course_playlist = []
for i in range(N):
course_playlist.append(serializer.data[_playlist[i][1]])
course_playlist[i]['concept'] = []
concepts = Concept.objects.filter(group=course_playlist[i]['id'])
serializer_concept = ConceptSerializer(concepts, many=True)
_playlist_group = json.loads(course_playlist[i]['playlist'])
for j in range(len(_playlist_group)):
concept = serializer_concept.data[_playlist_group[j][1]]
if concept['is_published'] or (isIorC and isOwnerCourse):
course_playlist[i]['concept'].append(concept)
data['course_playlist'] = course_playlist
data['playlist'] = self.playlist_as_array(request, pk, True, isIorC and isOwnerCourse)
data['current_element'] = int(request.GET.get('item', 0))
return Response(data)
<file_sep>/courseware/static/courseware/js/student/course_info.jsx
/** @jsx React.DOM */
var CourseInfo = React.createClass({
mixins: [LoadMixin, MathJaxMixin],
getUrl: function() {
return '/courseware/api/course/'+this.props.course+'/courseInfo/?format=json';
},
render: function() {
if (!this.state.loaded) {
return <LoadingBar />;
}
course_info = this.state.data;
var st = '';
var et = '';
var eed = '';
if (course_info.start_time) {
st = (
<div class="row">
<div class="col-md-4 lead no-margin">
Start Date
</div>
<div class="col-md-7">
{course_info.start_time}
</div>
</div>
);
}
if (course_info.end_time) {
et = (
<div class="row">
<div class="col-md-4 lead no-margin">
End Date
</div>
<div class="col-md-7">
{course_info.end_time}
</div>
</div>
);
}
if (course_info.end_enrollment_date) {
eed = (
<div class="row">
<div class="col-md-4 lead no-margin">
Enrollment End Date
</div>
<div class="col-md-7">
{course_info.end_enrollment_date}
</div>
</div>
);
}
return (
<div class="panel panel-default">
<div class="panel-heading lead no-margin">
Course Info
</div>
<div class="panel-body">
<div class="lead no-margin">
Description
</div>
<div>
<span dangerouslySetInnerHTML={{__html: converter.makeHtml(this.state.data.description)}} />
</div>
<br />
{st}
{et}
{eed}
</div>
</div>
);
},
});<file_sep>/start.sh
#!/bin/sh
#Kill old gunicorn server
pkill gunicorn
#Kill old tornado server i.e. chatserver.py
pkill -9 -f chatserver.py
#Start gunicorn Server
nohup gunicorn elearning_academy.wsgi --daemon -c gunicorn.conf.py --log-level debug --reload &
#Start Chat Server - Tornado
nohup python chatserver.py &
##### Manual conf of Gunicorn #####
#gunicorn elearning_academy.wsgi:application --timeout 600 --workers 10 --log-level=debug --reload --bind=0.0.0.0:9090
<file_sep>/chat/viewsets/chatroom.py
__author__ = 'dheerendra'
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.exceptions import ParseError
from rest_framework.decorators import detail_route
from django.shortcuts import get_object_or_404
from chat.models import ChatRoom
from chat.serializers import ChatRoomSerializers
from courseware.permissions import *
from courseware.models import Course
class ChatRoomViewSet(viewsets.ModelViewSet):
'''
Viewset for Chatroom
:model Chatroom (Deprecated for new rest_framework)
:serializer_class ChatRoomSerializers
:permission_classes Basic permission classes
'''
model = ChatRoom
serializer_class = ChatRoomSerializers
permission_classes = [IsOwner]
@detail_route(methods=['GET'], permission_classes=[IsRegistered])
def get(self, request, pk):
'''
:param request: Django request
:param pk: primary key of course for which list of chatrooms are requested
:return: list of Chatroom objects for course = pk
'''
course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, course)
queryset = ChatRoom.objects.all().filter(course=course).order_by('-createdOn')
serializer = ChatRoomSerializers(queryset, many=True)
return Response(serializer.data)
@detail_route(methods=['POST'], permission_classes=[IsOwner])
def add(self, request, pk):
'''
Check if user is owner of course and create Chatroom
:param request: Django request object
:param pk: primary key of the course for which new chatroom is created
:return: New created chatroom object as json serialized
'''
course = get_object_or_404(Course, pk=pk)
self.check_object_permissions(request, course)
data = request.POST
try:
title = data['title']
if title == "":
raise KeyError()
except KeyError:
raise ParseError("Title not present or Title is empty")
chatroom = ChatRoom(course=course, title=title)
chatroom.save()
serializer = ChatRoomSerializers(chatroom)
return Response(serializer.data)
@detail_route(methods=['POST'], permission_classes=[IsOwner])
def delete(self, request, pk):
'''
Check if user is owner of course and delete the chatroom specified by pk
:param request: Django request object
:param pk: primary key for the chatroom to be deleted
:return: Deleted Chatroom as json serialized
'''
chatroom = get_object_or_404(ChatRoom, pk=pk)
course = chatroom.course
self.check_object_permissions(request, course)
chatroom.delete()
serializer = ChatRoomSerializers(chatroom)
return Response(serializer.data)
<file_sep>/courseware/migrations/0003_auto__add_field_concept_tag.py
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Concept.tag'
db.add_column(u'courseware_concept', 'tag',
self.gf('django.db.models.fields.related.ForeignKey')(default=None, to=orm['discussion_forum.Tag'], null=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Concept.tag'
db.delete_column(u'courseware_concept', 'tag_id')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('<PASSWORD>', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'courseware.category': {
'Meta': {'object_name': 'Category'},
'content_developers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Category_User'", 'symmetrical': 'False', 'to': u"orm['auth.User']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Parent'", 'to': u"orm['courseware.ParentCategory']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'courseware.concept': {
'Meta': {'object_name': 'Concept'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Concept_Group'", 'to': u"orm['courseware.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'max_score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'pages': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Concept_Document'", 'symmetrical': 'False', 'to': u"orm['document.Document']"}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'quizzes': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Concept_Quiz'", 'symmetrical': 'False', 'to': u"orm['quiz.Quiz']"}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': u"orm['discussion_forum.Tag']", 'null': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'title_document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Concept_Title'", 'to': u"orm['document.Document']"}),
'videos': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Concept_Video'", 'symmetrical': 'False', 'to': u"orm['video.Video']"})
},
u'courseware.concepthistory': {
'Meta': {'unique_together': "(('concept', 'user'),)", 'object_name': 'ConceptHistory', 'index_together': "[['user', 'concept']]"},
'concept': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'ConceptHistory_Concept'", 'to': u"orm['courseware.Concept']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'score': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'User_Concept'", 'to': u"orm['auth.User']"})
},
u'courseware.course': {
'Meta': {'object_name': 'Course'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Category_Course'", 'to': u"orm['courseware.Category']"}),
'course_info': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'CourseInfo_Course'", 'unique': 'True', 'null': 'True', 'to': u"orm['courseware.CourseInfo']"}),
'enrollment_type': ('django.db.models.fields.CharField', [], {'default': "'M'", 'max_length': '1'}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Course_Forum'", 'to': u"orm['discussion_forum.DiscussionForum']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'max_score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'page_playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'pages': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Course_Document'", 'symmetrical': 'False', 'to': u"orm['document.Document']"}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'type': ('django.db.models.fields.CharField', [], {'default': "'T'", 'max_length': '1'})
},
u'courseware.coursehistory': {
'Meta': {'unique_together': "(('course', 'user'),)", 'object_name': 'CourseHistory', 'index_together': "[['user', 'course']]"},
'active': ('django.db.models.fields.CharField', [], {'default': "'U'", 'max_length': '1'}),
'course': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'CourseHistory_Course'", 'to': u"orm['courseware.Course']"}),
'grade': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_creator': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_moderator': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_owner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'score': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True'}),
'show_marks': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'CourseHistory_User'", 'to': u"orm['auth.User']"})
},
u'courseware.courseinfo': {
'Meta': {'object_name': 'CourseInfo'},
'description': ('django.db.models.fields.TextField', [], {'default': "''"}),
'end_enrollment_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'end_time': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'start_time': ('django.db.models.fields.DateField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'})
},
u'courseware.group': {
'Meta': {'object_name': 'Group'},
'course': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Group_Course'", 'to': u"orm['courseware.Course']"}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'max_score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'pages': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['document.Document']", 'symmetrical': 'False'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'courseware.grouphistory': {
'Meta': {'unique_together': "(('group', 'user'),)", 'object_name': 'GroupHistory', 'index_together': "[['user', 'group']]"},
'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'GroupHistory_Group'", 'to': u"orm['courseware.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'score': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'GroupHistory_User'", 'to': u"orm['auth.User']"})
},
u'courseware.offering': {
'Meta': {'object_name': 'Offering', '_ormbases': [u'courseware.Course']},
u'course_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['courseware.Course']", 'unique': 'True', 'primary_key': 'True'}),
'shortlisted_courses': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'shortlistedCourses'", 'symmetrical': 'False', 'to': u"orm['courseware.Course']"})
},
u'courseware.parentcategory': {
'Meta': {'object_name': 'ParentCategory'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
u'discussion_forum.discussionforum': {
'Meta': {'object_name': 'DiscussionForum'},
'abuse_threshold': ('django.db.models.fields.IntegerField', [], {'default': '5'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'review_threshold': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'thread_count': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'discussion_forum.tag': {
'Meta': {'unique_together': "(('forum', 'tag_name'),)", 'object_name': 'Tag'},
'auto_generated': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Forum_Tag'", 'to': u"orm['discussion_forum.DiscussionForum']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'tag_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'document.document': {
'Meta': {'object_name': 'Document'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_heading': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_link': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'link': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'uid': ('django.db.models.fields.CharField', [], {'max_length': '32'})
},
u'quiz.quiz': {
'Meta': {'object_name': 'Quiz'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'marks': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'question_modules': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'questions': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'title': ('django.db.models.fields.TextField', [], {})
},
u'video.video': {
'Meta': {'object_name': 'Video'},
'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'downvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'duration': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'other_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'upvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'video_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'})
}
}
complete_apps = ['courseware']<file_sep>/grader/static/js/majquery.js
function Test()
{
document.write("hihi")
}
<file_sep>/video/models.py
"""
Models for Video
"""
from django.db import models
from django.contrib.auth.models import User
from model_utils.managers import InheritanceManager
from quiz.models import Quiz
from elearning_academy.settings import PROJECT_DIR
import subprocess, os
import json
SHORT_TEXT = 63
LONG_TEXT = 255
class Video(models.Model):
"""
Class for Video. Video though does not have a concept in it but it not
independent from concept.
"""
title = models.CharField(max_length=255)
content = models.TextField(blank=True)
upvotes = models.IntegerField(default=0)
downvotes = models.IntegerField(default=0)
video_file = models.FileField(upload_to='static/video/')
other_file = models.FileField(upload_to='uploads/video_other/',
null=True, blank=True)
duration = models.IntegerField(default=0)
def __unicode__(self):
return self.title
def get_video_file(self):
""" Return the URL for Video File """
return "/media/" + str(self.video_file)
def get_other_file(self):
""" Return URL for Slides """
return "/media/" + str(self.other_file)
def get_length(self):
"""
Extract Duration of the video
"""
root = os.path.join(PROJECT_DIR, os.path.normpath('elearning_academy/'))
filename = os.path.join(root, os.path.normpath(self.get_video_file()[1:]))
result = subprocess.Popen(['ffprobe', filename, "-v", "quiet", "-print_format", "json", "-show_format"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
line = [x for x in result.stdout.readlines() if "duration" in x]
return int(float(line[0].strip(" \r\n,").split(":")[1].strip(" \"")))
def get_markers(self):
markers = Marker.objects.filter(video=self.id).select_subclasses()
json_markers = []
for marker in markers:
m = marker.to_json()
m['video'] = self.id
json_markers.append(m)
return json_markers
class VideoHistory(models.Model):
"""
Class for Video History
"""
UPVOTE = 'U'
DOWNVOTE = 'D'
NOVOTE = 'N'
VOTE_CHOICES = ((UPVOTE, "upvote"), (DOWNVOTE, 'downvote'), (NOVOTE, 'not voted'))
video = models.ForeignKey(Video)
user = models.ForeignKey(User, db_index=True)
seen_status = models.BooleanField(default=False)
times_seen = models.IntegerField(default=0)
vote = models.CharField(max_length=1, choices=VOTE_CHOICES, help_text="Vote Type", default=NOVOTE)
class Marker(models.Model):
"""
Class for a marker in Video. Each marker can be associated with atmost
one Video.
"""
SECTION_MARKER = 'S'
QUIZ_MARKER = 'Q'
MARKER_TYPES = (
(SECTION_MARKER, 'Section Marker'),
(QUIZ_MARKER, 'Quiz Marker')
)
video = models.ForeignKey(Video, related_name='markers')
time = models.IntegerField(default=0, null=False)
type = models.CharField(max_length=1, choices=MARKER_TYPES, help_text="Type of Marker")
objects = InheritanceManager()
class Meta:
#abstract = True
unique_together = ('video', 'time', 'type')
ordering = ['time']
def __unicode__(self):
return 'Marker Id: %s, Video Id: %s, time: %d' % (self.id, self.video.id, self.time)
class SectionMarker(Marker):
"""
Class for Section Marker
"""
title = models.CharField(max_length=SHORT_TEXT, null=False)
# set the type of marker in parent class
def save(self, *args, **kwargs):
self.type = self.SECTION_MARKER
super(SectionMarker, self).save(*args, **kwargs)
def to_json(self):
section_marker = {'id':self.id, 'time':self.time, 'type':self.type, 'title': self.title}
return section_marker
class QuizMarker(Marker):
"""
Class for Quiz type marker. It refers to a Quiz type object.
"""
quiz = models.ForeignKey(Quiz)
# set the type of marker in parent class
def save(self, *args, **kwargs):
self.type = self.QUIZ_MARKER
super(QuizMarker, self).save(*args, **kwargs)
def get_quiz_title(self):
return self.quiz.title
def to_json(self):
quiz_marker = {'id':self.id, 'time':self.time, 'type':self.type, 'quiz': self.quiz.id, 'quiz_title': self.quiz.title}
return quiz_marker
class QuizMarkerHistory(models.Model):
"""
Class for QuizMarker History. It stores if a Quiz Marker has been seen by a User.
"""
quiz_marker = models.ForeignKey(QuizMarker)
user = models.ForeignKey(User, db_index=True)
seen_status = models.BooleanField(default=False)
times_seen = models.IntegerField(default=0)
<file_sep>/evaluate/utils/evaluator.py
from elearning_academy.settings import PROJECT_DIR, MEDIA_ROOT
from evaluate.models import AssignmentResults
from evaluate.models import ProgramResults
from evaluate.models import TestcaseResult
from assignments.models import Testcase, SafeExec
from assignments.models import Program as ProgramModel
from assignments.models import Checker as CheckerModel
from assignments.models import CheckerErrors
from evaluate.utils.executor import CommandExecutor
from utils.archives import get_file_name_list, extract_or_copy, read_file
from utils.filetypes import COMPILED_LANGUAGES, INTERPRETED_LANGUAGES, compile_required, get_execution_command, get_compilation_command
from django.core.files import File
from django.core.files.storage import default_storage
import os, shutil, tarfile, pickle, tempfile
# Class to manage execution of student submission on a testcase.
# The class members are the testcase, the program result of the section, the name of the testcase, the input file of the testcase, and a command executor.
class TestCase(object):
def __init__(self, testcase, program_result):
self.testcase = testcase
self.program_result = program_result
self.name = testcase.name
self.stdInFile = str(testcase.std_in_file_name)
self.commandExecutor = CommandExecutor()
# Function to get resource limit for the testcase. During the creation of the testcase a Resource limit object with limits for various features
# is also created (with default values if the instructor does not change this).
# This function returns the dictionary mapping the attributes to their respective limits for this testcase.
def get_resource_limit(self):
try:
resource = {}
safeexec_obj = SafeExec.objects.get(testcase=self.testcase)
attrs = ['cpu_time', 'clock_time', 'memory', 'stack_size', 'child_processes', 'open_files', 'file_size']
for attr in attrs:
val = getattr(safeexec_obj, attr)
if val is not None:
resource[attr] = val
return resource
except SafeExec.DoesNotExist:
return {}
# Function to make a tarfile of all output files and return the name of this file.
def make_tar(self):
# Create the file containing std output with a certain pattern in its name. "standardOutput_testcase-id"
stdoutFileName = "standardOutput_" + str(self.testcase.id)
shutil.move(self.std_out, stdoutFileName)
outputfiles = [stdoutFileName]
# Set the name of the tarfile which is going to contain the output files.
tarname = "output_file_" + str(self.testcase.id) + ".tar.bz2"
outputFilesTar = tarfile.open(name=tarname, mode="w:bz2")
# Add the std output file and all the other files that were created by the student solution (typically the files to which the student solution
# wrote to other than the std output) to the tarfile.
for afile in outputfiles + self.output_files:
if os.path.isfile(afile):
outputFilesTar.add(afile)
outputFilesTar.close()
return tarname
# Function which is going to run the execution command on the input file of the testcase. Note that compilation if needed is done at the section
# level itself.
def run(self, exeCommand):
# Create the output file to capture the std output in the current directory.
t_file, self.std_out = tempfile.mkstemp()
os.close(t_file)
print t_file, self.std_out
os.chmod(self.std_out, 0777)
command = exeCommand
# Add the command line arguments if any.
if self.testcase.command_line_args:
command = command + self.testcase.command_line_args
# Then redirect the std input to the input file.
if os.path.isfile(self.stdInFile):
command = command + " < " + self.stdInFile
# Execute the resulting command with the appropriate resource limits and the output file created above.
self.testResults = self.commandExecutor.safe_execute(
command=command,
limits=self.get_resource_limit(),
outfile=self.std_out
)
# Check if the testcase has passed.
self.passed = self.test_passed()
marks = self.testcase.marks if self.passed else 0
# Incase the testcase has not passed the attrs dictionary below holds needed error messages and return code for the testcase.
attrs = {'error_messages': "".join(self.testResults.stderr),
'return_code': int(self.testResults.returnCode),
'test_passed': self.passed,'marks':marks}
# This dictionary is used to filter out any existing testcase result for the submission so as to update it with the new results in attrs above.
filter_attrs = {'test_case': self.testcase, 'program_result': self.program_result}
# If any Testcase Results exist with the filter_attrs attributes, then update if with the new attributes.
# Remove the older output file.
# Else if none exist, then store the current result with the filter_attrs added to the attrs dictionary.
try:
obj = TestcaseResult.objects.filter(**filter_attrs)
obj.update(**attrs)
test_result = obj[0:1].get()
default_storage.delete(test_result.output_files.path) # Remove older file.
except TestcaseResult.DoesNotExist:
attrs.update(filter_attrs)
#adding marks to the attr variable
attrs.update({"marks":marks})
test_result = TestcaseResult.objects.create(**attrs)
except:
pass
# Make a tar file of the std output file and the other files which have been written to by the student submission.
# Update the test result (updated or newly created) with this tar file as the output file.
tar_name = self.make_tar()
print "GETTER - ",tar_name, os.getcwd()
try:
a = open(tar_name)
test_result.output_files.save(tar_name, File(a))
test_result.output_files.close()
a.close()
except:
pass
return self
# Function to check if the student submission has passed the testcase.
def test_passed(self):
# Create a temporary directory and copy the expected output of the testcase to this file.
temp_dir = tempfile.mkdtemp(prefix="grader_op_files")
extract_or_copy(src=self.testcase.output_files.file.name, dest=temp_dir)
self.testcase.output_files.close()
std_output_file = str(self.testcase.std_out_file_name)
# Other output files are stored in this variable.
self.output_files = os.listdir(temp_dir)
self.output_files.remove(std_output_file)
# Now check for the status of the testcase. Call compare_output().
is_passed = False
print "Testcase return code is - ", self.testResults.returnCode
if self.testResults.returnCode == 0: # Exited normally.
is_passed = self.compare_output(temp_dir, std_output_file)
# Remove the temporary directory and return the status of the testcase.
shutil.rmtree(temp_dir, ignore_errors=True)
return is_passed
# Function to compare output of the standard output file and the actual output.
# Takes as input the actual output file and expected output in that order.
def compare_output(self, temp_dir, std_output_file):
if not self.compare_file(os.path.join(temp_dir, std_output_file), self.std_out):
return False
for afile in self.output_files: # compare all O/P files.
if not self.compare_file(afile, afile.split('/')[-1]):
return False
return True
# Function to compare 2 files.
# Takes as input the expected output and actual output file in that order.
def compare_file(self, expectedop, actualop):
# If the actual output is not valid return false.
if not os.path.isfile(actualop):
return False
# Open both the files and see if they have the same length. If true proceed else return false.
with open(expectedop) as file1:
with open(actualop) as file2:
if(len(list(file1)) > len(list(file2))):
return False
with open(expectedop) as file1:
with open(actualop) as file2:
# Compare the 2 files line by line.
for line1, line2 in zip(file1, file2):
if line1.strip() != line2.strip():
return False
for line2 in file2:
if line2.strip() != "":
return False
return True
# Class to manage the checker code. This class manages the execution of the checker code on the user submission.
# The class members are the checker object, the execution command for the checker code, the program result which relates to the submission,
# a command executor to manage the command execution and the program/section to which the checker code belongs to.
class Checker(object):
def __init__(self, checker, program_result):
self.checker = checker
self.execution_command = " ".join(pickle.loads(checker.execution_command))
self.program_result = program_result
self.commandExecutor = CommandExecutor()
self.program = program_result.program
# Function to copy the output files and the source code of the submission.
def setup(self):
currentDir = os.getcwd()
# Copy the checker file.
extract_or_copy(src=self.checker.checker_files.file.name, dest=currentDir)
self.checker.checker_files.close()
# Copy the output files of the submission. This is done by the filtering out the testcases of the program for which the checker has been
# written, then retrieving the program result for each testcase and copying the output files for the submission to the current directory.
try:
testcases = Testcase.objects.filter(program=self.program)
for test in testcases:
test_result = TestcaseResult.objects.get(test_case=test,program_result=self.program_result)
if test_result.output_files:
extract_or_copy(src=test_result.output_files.file.name, dest=currentDir)
test_result.output_files.close()
except Testcase.DoesNotExist:
pass
# Copy the source code of the submission. The submission id can be retrieved from the assignment_result which in turn can be gotten from
# the program_result.
upload = self.program_result.assignment_result.submission
if upload.filePath:
extract_or_copy(src=upload.filePath.file.name, dest=currentDir)
upload.filePath.close()
# Function to run the checker code on the output files and the source code of the submission.
def run(self):
# Create a directory for running the checker code and change to that directory.
oldpwd = os.getcwd()
self.temp_dir = tempfile.mkdtemp(prefix="checker", dir=oldpwd)
os.chdir(self.temp_dir)
# Copy the output files and the source code to the current directory.
self.setup()
# Create the output file to capture the std output in the current directory. This stores the checker code output.
_, self.std_out = tempfile.mkstemp()
os.chmod(self.std_out, 0777)
command = self.execution_command
# Execute the checker command with the appropriate resource limits and the output file created above.
self.checkerResults = self.commandExecutor.safe_execute(
command=command,
limits={},
outfile=self.std_out
)
# Some debugging to check if the checker code is working.
print self.checkerResults.printResult()
print "--> ", " ".join(self.checkerResults.get_stdout())
# Incase the checker code has not executed correcty the attrs dictionary below holds needed error messages.
attrs = {'error_message': "".join(self.checkerResults.stderr)}
# This dictionary is used to filter out any existing checker code errors for the checker code so as to update it with the
# new results in attrs above. If there are no error messages then update the checker output to the program result.
filter_attrs = {'checker': self.checker}
if self.checkerResults.stderr:
try:
obj = CheckerErrors.objects.filter(**filter_attrs)
obj.update(**attrs)
except TestcaseResult.DoesNotExist:
attrs.update(filter_attrs)
checker_error = CheckerErrors.objects.create(**attrs)
else:
self.program_result.checker_result = " ".join(self.checkerResults.get_stdout())
self.program_result.save()
# Change back to the old directory.
os.chdir(oldpwd)
return self
# Class to manage execution of student submissions at the section level.
# Stores as class members the assignment result, program model instance, files relevant to this section, language of the section, compilation and
# execution command of the section, and a command executor to take care of compilation if necessary.
class Program(object):
def __init__(self, program, assignment_result):
self.assignment_result = assignment_result
self.program = program
# Extracting the list of files relevant to only this section.
if program.program_files:
prgrm_files = get_file_name_list(name=program.program_files.file.name)
program.program_files.close()
prgrm_files = " ".join(prgrm_files)
else:
prgrm_files = ""
# Adding the list of files in the assignment model solution to the above list.
self.programFiles = program.assignment.student_program_files + " " + prgrm_files
self.language = program.assignment.program_language
self.compiler_command = get_compilation_command(program)
self.execution_command = get_execution_command(program)
self.commandExecutor = CommandExecutor()
# Function to check if any files are missing.
def fileExist(self):
self.missingFiles = []
# Checking if each file in the self.programFiles variable is valid. If not add to the missing files array.
for aFile in self.programFiles.split():
if not os.path.isfile(aFile):
self.missingFiles.append(aFile)
# If there are any missing files, then either retrieve existing program result object or create one with the assignment result, section
# and the missing files. If the object was not created, then update the missing files attribute of the program result.
# Save the new or existing program result object after this, and return if there were any files missing.
if self.missingFiles:
self.programResult, created = ProgramResults.objects.get_or_create(
assignment_result = self.assignment_result,
program = self.program,
defaults = {'missing_file_names': "\n".join(self.missingFiles)}
)
if not created:
self.programResult.missing_file_names = "\n".join(self.missingFiles)
self.programResult.save()
return bool(self.missingFiles)
# Function to handle compilation of the section.
def compile(self):
# If any files are missing then return failure of compilation. Appropriate program result is created.
if self.fileExist():
return False
# If the language of the section/assignment needs compilation, then go ahead and compile. Set program result attributes accordingly.
# If compilation is not needed then proceed.
if compile_required(self.language):
compilation_command = self.compiler_command
self.compileResult = self.commandExecutor.executeCommand(command=compilation_command)
attrs = {'missing_file_names': "\n".join(self.missingFiles),
'compiler_errors': "".join(self.compileResult.stderr),
'compiler_output': "\n".join(self.compileResult.get_stdout()),
'compiler_return_code': int(self.compileResult.returnCode)}
else:
attrs = {'missing_file_names': "\n".join(self.missingFiles),
'compiler_errors': "",
'compiler_output': "",
'compiler_return_code': 0}
filter_attrs = {'assignment_result': self.assignment_result, 'program': self.program}
# Create or update program result object with the result of compilation process for the section. The attributes of the program result object
# are the same as the result of the compilation process.
try: # create_or_update equivalent.
obj = ProgramResults.objects.filter(**filter_attrs)
obj.update(**attrs)
self.programResult = obj[0:1].get()
except ProgramResults.DoesNotExist:
attrs.update(filter_attrs)
self.programResult = ProgramResults.objects.create(**attrs)
# If compilation is successful or if compilation is not needed then return true. Else return false.
if compile_required(self.language) == False or self.compileResult.returnCode == 0:
return True
else:
return False
# Function to run the student solution on all the testcases of the section.
def run(self):
# Filter out the testcases of the section.
testcases = Testcase.objects.filter(program=self.program)
# Run the execution command on each of the testcases. Compilation (if needed) is already taken care of.
for test in testcases:
testcase = TestCase(test, self.programResult)
testcase.run(self.execution_command)
# If any checker object exists for this program, then setup that checker object and run it. Else do not do anything.
# The program result is passed to the checker object created to run the checker model instance. The results of the checker code
# will be updated to the program result.
try:
checkerobj = CheckerModel.objects.get(program=self.program)
checker = Checker(checkerobj,self.programResult)
checker.run()
except CheckerModel.DoesNotExist:
pass
# Class to manage evaluation of a submission. The submission id is passed during the creation of the Evaluate object.
# Class members are the submission, command executor and evaluation directory.
class Evaluate(object):
def __init__(self, submission):
print(PROJECT_DIR)
self.commandExecutor = CommandExecutor()
self.submission = submission
self.eval_dir = os.path.join(PROJECT_DIR, 'evaluate/safeexec')
# Function to setup the evaluation directory.
def setup(self, submission, program_type):
# Create a temporary directory inside the evaluation directory. Copy the submission files into this directory.
src = os.path.join(MEDIA_ROOT,submission.filePath.name) # gives absolute path
self.temp_dir = tempfile.mkdtemp(prefix="grader", dir=self.eval_dir)
os.chdir(self.temp_dir)
extract_or_copy(src=src, dest=self.temp_dir)
# Update or create the assignment result for the submission. Update the submitted files for existing assignment results.
self.submittedFiles = get_file_name_list(name=src)
self.assignment_result, _ = AssignmentResults.objects.get_or_create(
submission=submission,
defaults={'submitted_files': "\n".join(self.submittedFiles)}
)
self.assignment_result.is_stale = False
self.assignment_result.save()
# Assuming only 1 directory level, cd to that directory. If the student submitted only 1 file, then dont do anything.
directories = [a for a in os.listdir('./') if os.path.isdir(a)]
if directories:
os.chdir(directories[0])
currentDir = os.getcwd()
# Copy the program files (of all sections) to this directory. Note that the solution file is still student's submission.
programs = ProgramModel.objects.filter(assignment=submission.assignment)
testcaseList = []
for program in programs:
testcaseList.append(Testcase.objects.filter(program=program))
if program.program_files:
extract_or_copy(src=os.path.join(MEDIA_ROOT,program.program_files.name), dest=currentDir)
# Copy input-output files for all testcases. Now we are ready for the evaluation process.
for testcase in testcaseList:
for test in testcase:
if test.input_files:
extract_or_copy(src=os.path.join(MEDIA_ROOT,test.input_files.name), dest=currentDir)
# Function to clean up the directories setup for the evaluation process.
def cleanUp(self):
shutil.rmtree(self.temp_dir, ignore_errors=True)
# Function called to retrieve the results of the student submission once the Evaluate object is created.
def getResults(self, program_type="Evaluate"):
# Setup the directories for the evaluation process.
self.setup(self.submission, program_type)
# Collect the section for the assignment.
allPrograms = ProgramModel.objects.filter(assignment=self.submission.assignment, program_type=program_type)
# For each section, compile the section if needed and if compilation is successful then execute the solution on all testcases of the section.
# The assignment result is sent an argument when creating the Program object to keep track of the submission.
for program in allPrograms:
prgrmObject = Program(program, self.assignment_result)
if prgrmObject.compile():
prgrmObject.run()
# Clean up the temp directories and return the results.
self.cleanUp()
return Results(self.submission, program_type=program_type)
# Same as the above though frankly I dont know why this is here!! :O
def eval(self, program_type):
self.setup(self.submission, program_type)
allPrograms = ProgramModel.objects.filter(assignment=self.submission.assignment, program_type=program_type)
for program in allPrograms:
prgrmObject = Program(program, self.assignment_result)
if prgrmObject.compile():
prgrmObject.run()
self.cleanUp()
# Class to manage the results of a student submission. This is used to transfer data from the server to the client. This has nothing to do with the
# storing the results to the database.
class Results(object):
def __init__(self, submission, program_type):
self.assignment_result = AssignmentResults.objects.get(submission=submission)
program_objects = ProgramResults.objects.filter(assignment_result=self.assignment_result)
self.program_results = []
for aProgramResult in program_objects:
if aProgramResult.program.program_type == program_type:
self.program_results.append(self.ProgramResultSaved(aProgramResult, program_type))
self.marks = reduce(lambda x,y: x + y.marks, self.program_results, 0)
class ProgramResultSaved(object):
def __init__(self, program_result, program_type):
self.program_result = program_result # Used in template.
self.compiler_command = get_compilation_command(program_result.program)
self.execution_command = get_execution_command(program_result.program)
all_obj = TestcaseResult.objects.filter(program_result=program_result)
test_type_obj = [a for a in all_obj]
self.testResults = [Results.TestcaseResultSaved(obj) for obj in test_type_obj]
self.marks = reduce(lambda x,y: x + y.marks, self.testResults, 0)
class TestcaseResultSaved(object):
def __init__(self, test_case_result):
self.id = test_case_result.id
self.test_case = test_case_result.test_case
self.program_result = test_case_result.program_result
self.error_messages = test_case_result.error_messages
self.return_code = test_case_result.return_code
self.test_passed = test_case_result.test_passed
self.output_files = test_case_result.output_files
std_output_file_name = "standardOutput_" + str(self.test_case.id)
tar = tarfile.open(self.output_files.file.name)
self.output_files.close()
currentFile = tar.extractfile(std_output_file_name)
self.actual_output = currentFile.readlines()
currentFile.close()
self.expected_output = read_file(self.test_case.std_out_file_name, name=self.test_case.output_files.file.name)
self.test_case.output_files.close()
self.marks = (test_case_result.marks or 0)
tar.close()
<file_sep>/quiz_old/permissions.py
""""
Handles permission for Quiz API
Permission Classes:
IsEnrolled
- Any course instructor or student of the course had the permission to
fetch the quiz
IsCourseInstructor
- the course instructors have full access to adding, deleting, editing a
quiz and its questions
Quiz
+ create: IsCourseInstructor
+ destroy: IsCourseInstructor
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
- get_question_modules: IsEnrolled
- add_question_module: IsCourseInstructor
- get_questions_manual_grade: IsCourseInstructor
QuestionModule
+ destroy: IsCourseInstructor
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
- get_questions: IsEnrolled
- add_fixed_answer_question: IsCourseInstructor
FixedAnswerQuestion
+ destroy: IsCourseInstructor
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
Question
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
- get_answer: IsCourseInstructorOrMaxAttempted
- submit_answer: IsEnrolled
- get_submissions_manual_grade: IsCourseInstructor
Submission
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
- set_plagiarised: IsCourseInstructor
"""
from rest_framework import permissions
from courseware import models
from quiz import models
class IsEnrolled(permissions.BasePermission):
"""
Allows view permission to anyone enrolled
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
return True
if not request.user.is_authenticated():
return False
try:
#course = obj.course
course = models.Course.objects.get(pk=1)
course_history = models.CourseHistory.objects.get(
course=course,
user=request.user)
return True
except:
return False
if request.method in permissions.SAFE_METHODS:
return True
else:
return False
class IsCourseInstructor(permissions.BasePermission):
"""
Allows complete permission to course instructor
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
return True
if not request.user.is_authenticated():
return False
try:
#course = obj.course
course = models.Course.objects.get(pk=1)
course_history = models.CourseHistory.objects.get(
course=course,
user=request.user)
if course_history.is_instructor:
return True
else:
return False
except:
return False
<file_sep>/courses/templates/courses/trash_base_courses.html
{% extends "base.html" %}
{% block sidebar %}
{% if courseCreated %}
<h4>Course Created</h4>
<ul>
{% for course in courseCreated %}
<li><a href="{% url 'assignments_index' course.id %}">{{ course.id }} {{ course.title }}</a></li>
{% endfor %}
</ul>
{% else %}
<h4>No Course Created</h4>
{% endif %}
{% if courseJoined %}
<h4>Course Joined</h4>
<ul>
{% for course in courseJoined %}
<li><a href="{% url 'assignments_index' course.course.id %}">{{ course.course.id }} {{ course.course.title }}</a></li>
{% endfor %}
</ul>
{% else %}
<h4>No Course Joined</h4>
{% endif %}
{% block addtosidebar %}{% endblock %}
{% endblock %}
<file_sep>/quiz/static/quiz/js/main.jsx
/** @jsx React.DOM */
React.renderComponent(
<QuizList />,
document.getElementById('quiz')
);<file_sep>/courseware/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ParentCategory'
db.create_table(u'courseware_parentcategory', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255)),
))
db.send_create_signal(u'courseware', ['ParentCategory'])
# Adding model 'Category'
db.create_table(u'courseware_category', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('parent', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Parent', to=orm['courseware.ParentCategory'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('image', self.gf('django.db.models.fields.files.ImageField')(max_length=100, null=True, blank=True)),
))
db.send_create_signal(u'courseware', ['Category'])
# Adding M2M table for field content_developers on 'Category'
m2m_table_name = db.shorten_name(u'courseware_category_content_developers')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('category', models.ForeignKey(orm[u'courseware.category'], null=False)),
('user', models.ForeignKey(orm[u'auth.user'], null=False))
))
db.create_unique(m2m_table_name, ['category_id', 'user_id'])
# Adding model 'CourseInfo'
db.create_table(u'courseware_courseinfo', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('start_time', self.gf('django.db.models.fields.DateField')(db_index=True, null=True, blank=True)),
('end_time', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
('is_published', self.gf('django.db.models.fields.BooleanField')(default=False)),
('description', self.gf('django.db.models.fields.TextField')(default='')),
('end_enrollment_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
))
db.send_create_signal(u'courseware', ['CourseInfo'])
# Adding model 'Course'
db.create_table(u'courseware_course', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('category', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Category_Course', to=orm['courseware.Category'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('image', self.gf('django.db.models.fields.files.ImageField')(max_length=100, blank=True)),
('type', self.gf('django.db.models.fields.CharField')(default='T', max_length=1)),
('playlist', self.gf('django.db.models.fields.TextField')(default='[]')),
('forum', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Course_Forum', to=orm['discussion_forum.DiscussionForum'])),
('page_playlist', self.gf('django.db.models.fields.TextField')(default='[]')),
('max_score', self.gf('django.db.models.fields.IntegerField')(default=0)),
('course_info', self.gf('django.db.models.fields.related.OneToOneField')(blank=True, related_name='CourseInfo_Course', unique=True, null=True, to=orm['courseware.CourseInfo'])),
('enrollment_type', self.gf('django.db.models.fields.CharField')(default='M', max_length=1)),
))
db.send_create_signal(u'courseware', ['Course'])
# Adding M2M table for field pages on 'Course'
m2m_table_name = db.shorten_name(u'courseware_course_pages')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('course', models.ForeignKey(orm[u'courseware.course'], null=False)),
('document', models.ForeignKey(orm[u'document.document'], null=False))
))
db.create_unique(m2m_table_name, ['course_id', 'document_id'])
# Adding model 'Offering'
db.create_table(u'courseware_offering', (
(u'course_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['courseware.Course'], unique=True, primary_key=True)),
))
db.send_create_signal(u'courseware', ['Offering'])
# Adding M2M table for field shortlisted_courses on 'Offering'
m2m_table_name = db.shorten_name(u'courseware_offering_shortlisted_courses')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('offering', models.ForeignKey(orm[u'courseware.offering'], null=False)),
('course', models.ForeignKey(orm[u'courseware.course'], null=False))
))
db.create_unique(m2m_table_name, ['offering_id', 'course_id'])
# Adding model 'CourseHistory'
db.create_table(u'courseware_coursehistory', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('course', self.gf('django.db.models.fields.related.ForeignKey')(related_name='CourseHistory_Course', to=orm['courseware.Course'])),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='CourseHistory_User', to=orm['auth.User'])),
('grade', self.gf('django.db.models.fields.CharField')(max_length=2, null=True)),
('score', self.gf('django.db.models.fields.FloatField')(default=0.0, null=True)),
('active', self.gf('django.db.models.fields.CharField')(default='U', max_length=1)),
('is_moderator', self.gf('django.db.models.fields.BooleanField')(default=False)),
('is_owner', self.gf('django.db.models.fields.BooleanField')(default=False)),
('show_marks', self.gf('django.db.models.fields.BooleanField')(default=True)),
))
db.send_create_signal(u'courseware', ['CourseHistory'])
# Adding unique constraint on 'CourseHistory', fields ['course', 'user']
db.create_unique(u'courseware_coursehistory', ['course_id', 'user_id'])
# Adding index on 'CourseHistory', fields ['user', 'course']
db.create_index(u'courseware_coursehistory', ['user_id', 'course_id'])
# Adding model 'Group'
db.create_table(u'courseware_group', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('course', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Group_Course', to=orm['courseware.Course'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('image', self.gf('django.db.models.fields.files.ImageField')(max_length=100, blank=True)),
('max_score', self.gf('django.db.models.fields.IntegerField')(default=0)),
('playlist', self.gf('django.db.models.fields.TextField')(default='[]')),
('description', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal(u'courseware', ['Group'])
# Adding M2M table for field pages on 'Group'
m2m_table_name = db.shorten_name(u'courseware_group_pages')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('group', models.ForeignKey(orm[u'courseware.group'], null=False)),
('document', models.ForeignKey(orm[u'document.document'], null=False))
))
db.create_unique(m2m_table_name, ['group_id', 'document_id'])
# Adding model 'GroupHistory'
db.create_table(u'courseware_grouphistory', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('group', self.gf('django.db.models.fields.related.ForeignKey')(related_name='GroupHistory_Group', to=orm['courseware.Group'])),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='GroupHistory_User', to=orm['auth.User'])),
('score', self.gf('django.db.models.fields.FloatField')(default=0.0, null=True)),
))
db.send_create_signal(u'courseware', ['GroupHistory'])
# Adding unique constraint on 'GroupHistory', fields ['group', 'user']
db.create_unique(u'courseware_grouphistory', ['group_id', 'user_id'])
# Adding index on 'GroupHistory', fields ['user', 'group']
db.create_index(u'courseware_grouphistory', ['user_id', 'group_id'])
# Adding model 'Concept'
db.create_table(u'courseware_concept', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('group', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Concept_Group', to=orm['courseware.Group'])),
('title_document', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Concept_Title', to=orm['document.Document'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('image', self.gf('django.db.models.fields.files.ImageField')(max_length=100, null=True, blank=True)),
('max_score', self.gf('django.db.models.fields.IntegerField')(default=0)),
('playlist', self.gf('django.db.models.fields.TextField')(default='[]')),
('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('is_published', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal(u'courseware', ['Concept'])
# Adding M2M table for field videos on 'Concept'
m2m_table_name = db.shorten_name(u'courseware_concept_videos')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('concept', models.ForeignKey(orm[u'courseware.concept'], null=False)),
('video', models.ForeignKey(orm[u'video.video'], null=False))
))
db.create_unique(m2m_table_name, ['concept_id', 'video_id'])
# Adding M2M table for field quizzes on 'Concept'
m2m_table_name = db.shorten_name(u'courseware_concept_quizzes')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('concept', models.ForeignKey(orm[u'courseware.concept'], null=False)),
('quiz', models.ForeignKey(orm[u'quiz.quiz'], null=False))
))
db.create_unique(m2m_table_name, ['concept_id', 'quiz_id'])
# Adding M2M table for field pages on 'Concept'
m2m_table_name = db.shorten_name(u'courseware_concept_pages')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('concept', models.ForeignKey(orm[u'courseware.concept'], null=False)),
('document', models.ForeignKey(orm[u'document.document'], null=False))
))
db.create_unique(m2m_table_name, ['concept_id', 'document_id'])
# Adding model 'ConceptHistory'
db.create_table(u'courseware_concepthistory', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('concept', self.gf('django.db.models.fields.related.ForeignKey')(related_name='ConceptHistory_Concept', to=orm['courseware.Concept'])),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='User_Concept', to=orm['auth.User'])),
('score', self.gf('django.db.models.fields.FloatField')(default=0.0)),
))
db.send_create_signal(u'courseware', ['ConceptHistory'])
# Adding unique constraint on 'ConceptHistory', fields ['concept', 'user']
db.create_unique(u'courseware_concepthistory', ['concept_id', 'user_id'])
# Adding index on 'ConceptHistory', fields ['user', 'concept']
db.create_index(u'courseware_concepthistory', ['user_id', 'concept_id'])
def backwards(self, orm):
# Removing index on 'ConceptHistory', fields ['user', 'concept']
db.delete_index(u'courseware_concepthistory', ['user_id', 'concept_id'])
# Removing unique constraint on 'ConceptHistory', fields ['concept', 'user']
db.delete_unique(u'courseware_concepthistory', ['concept_id', 'user_id'])
# Removing index on 'GroupHistory', fields ['user', 'group']
db.delete_index(u'courseware_grouphistory', ['user_id', 'group_id'])
# Removing unique constraint on 'GroupHistory', fields ['group', 'user']
db.delete_unique(u'courseware_grouphistory', ['group_id', 'user_id'])
# Removing index on 'CourseHistory', fields ['user', 'course']
db.delete_index(u'courseware_coursehistory', ['user_id', 'course_id'])
# Removing unique constraint on 'CourseHistory', fields ['course', 'user']
db.delete_unique(u'courseware_coursehistory', ['course_id', 'user_id'])
# Deleting model 'ParentCategory'
db.delete_table(u'courseware_parentcategory')
# Deleting model 'Category'
db.delete_table(u'courseware_category')
# Removing M2M table for field content_developers on 'Category'
db.delete_table(db.shorten_name(u'courseware_category_content_developers'))
# Deleting model 'CourseInfo'
db.delete_table(u'courseware_courseinfo')
# Deleting model 'Course'
db.delete_table(u'courseware_course')
# Removing M2M table for field pages on 'Course'
db.delete_table(db.shorten_name(u'courseware_course_pages'))
# Deleting model 'Offering'
db.delete_table(u'courseware_offering')
# Removing M2M table for field shortlisted_courses on 'Offering'
db.delete_table(db.shorten_name(u'courseware_offering_shortlisted_courses'))
# Deleting model 'CourseHistory'
db.delete_table(u'courseware_coursehistory')
# Deleting model 'Group'
db.delete_table(u'courseware_group')
# Removing M2M table for field pages on 'Group'
db.delete_table(db.shorten_name(u'courseware_group_pages'))
# Deleting model 'GroupHistory'
db.delete_table(u'courseware_grouphistory')
# Deleting model 'Concept'
db.delete_table(u'courseware_concept')
# Removing M2M table for field videos on 'Concept'
db.delete_table(db.shorten_name(u'courseware_concept_videos'))
# Removing M2M table for field quizzes on 'Concept'
db.delete_table(db.shorten_name(u'courseware_concept_quizzes'))
# Removing M2M table for field pages on 'Concept'
db.delete_table(db.shorten_name(u'courseware_concept_pages'))
# Deleting model 'ConceptHistory'
db.delete_table(u'courseware_concepthistory')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'courseware.category': {
'Meta': {'object_name': 'Category'},
'content_developers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Category_User'", 'symmetrical': 'False', 'to': u"orm['auth.User']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Parent'", 'to': u"orm['courseware.ParentCategory']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'courseware.concept': {
'Meta': {'object_name': 'Concept'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Concept_Group'", 'to': u"orm['courseware.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'max_score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'pages': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Concept_Document'", 'symmetrical': 'False', 'to': u"orm['document.Document']"}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'quizzes': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Concept_Quiz'", 'symmetrical': 'False', 'to': u"orm['quiz.Quiz']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'title_document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Concept_Title'", 'to': u"orm['document.Document']"}),
'videos': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Concept_Video'", 'symmetrical': 'False', 'to': u"orm['video.Video']"})
},
u'courseware.concepthistory': {
'Meta': {'unique_together': "(('concept', 'user'),)", 'object_name': 'ConceptHistory', 'index_together': "[['user', 'concept']]"},
'concept': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'ConceptHistory_Concept'", 'to': u"orm['courseware.Concept']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'score': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'User_Concept'", 'to': u"orm['auth.User']"})
},
u'courseware.course': {
'Meta': {'object_name': 'Course'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Category_Course'", 'to': u"orm['courseware.Category']"}),
'course_info': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'CourseInfo_Course'", 'unique': 'True', 'null': 'True', 'to': u"orm['courseware.CourseInfo']"}),
'enrollment_type': ('django.db.models.fields.CharField', [], {'default': "'M'", 'max_length': '1'}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Course_Forum'", 'to': u"orm['discussion_forum.DiscussionForum']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'max_score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'page_playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'pages': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Course_Document'", 'symmetrical': 'False', 'to': u"orm['document.Document']"}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'type': ('django.db.models.fields.CharField', [], {'default': "'T'", 'max_length': '1'})
},
u'courseware.coursehistory': {
'Meta': {'unique_together': "(('course', 'user'),)", 'object_name': 'CourseHistory', 'index_together': "[['user', 'course']]"},
'active': ('django.db.models.fields.CharField', [], {'default': "'U'", 'max_length': '1'}),
'course': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'CourseHistory_Course'", 'to': u"orm['courseware.Course']"}),
'grade': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_moderator': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_owner': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'score': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True'}),
'show_marks': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'CourseHistory_User'", 'to': u"orm['auth.User']"})
},
u'courseware.courseinfo': {
'Meta': {'object_name': 'CourseInfo'},
'description': ('django.db.models.fields.TextField', [], {'default': "''"}),
'end_enrollment_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'end_time': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'start_time': ('django.db.models.fields.DateField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'})
},
u'courseware.group': {
'Meta': {'object_name': 'Group'},
'course': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Group_Course'", 'to': u"orm['courseware.Course']"}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'max_score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'pages': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['document.Document']", 'symmetrical': 'False'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'courseware.grouphistory': {
'Meta': {'unique_together': "(('group', 'user'),)", 'object_name': 'GroupHistory', 'index_together': "[['user', 'group']]"},
'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'GroupHistory_Group'", 'to': u"orm['courseware.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'score': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'GroupHistory_User'", 'to': u"orm['auth.User']"})
},
u'courseware.offering': {
'Meta': {'object_name': 'Offering', '_ormbases': [u'courseware.Course']},
u'course_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['courseware.Course']", 'unique': 'True', 'primary_key': 'True'}),
'shortlisted_courses': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'shortlistedCourses'", 'symmetrical': 'False', 'to': u"orm['courseware.Course']"})
},
u'courseware.parentcategory': {
'Meta': {'object_name': 'ParentCategory'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
u'discussion_forum.discussionforum': {
'Meta': {'object_name': 'DiscussionForum'},
'abuse_threshold': ('django.db.models.fields.IntegerField', [], {'default': '5'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'review_threshold': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'thread_count': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'document.document': {
'Meta': {'object_name': 'Document'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_heading': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_link': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'link': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'uid': ('django.db.models.fields.CharField', [], {'max_length': '32'})
},
u'quiz.quiz': {
'Meta': {'object_name': 'Quiz'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'marks': ('django.db.models.fields.FloatField', [], {'default': '0.0'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'question_modules': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'questions': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'title': ('django.db.models.fields.TextField', [], {})
},
u'video.video': {
'Meta': {'object_name': 'Video'},
'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'downvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'duration': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'other_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'upvotes': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'video_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'})
}
}
complete_apps = ['courseware']<file_sep>/user_profile/static/user_profile/js/settings.jsx
/** @jsx React.DOM */
var SettingsBody = React.createClass({
handleClicks: function(event) {
url = "/user/get-privileges";
request = ajax_json_request(url,"GET",{});
request.done(function(response){
response = jQuery.parseJSON(response);
display_global_message(response.message,"success")
});
},
render: function() {
return (
<div>
<a onClick ={this.handleClicks} class="btn btn-primary tool-tip enrollbtn">
Request for Instructor Privileges
</a>
</div>
);
}
});
<file_sep>/courses/templates/courses/trash_all_courses.html
{% extends 'courses/base_courses.html' %}
{% block title %}Available Courses{% endblock %}
{% block sidebar %}
<h4>Available Courses</h4>
{% endblock%}
{% block main %}
<div>
<ul class="breadcrumb">
<li class="active">Available Courses</li>
</ul>
</div>
{% if courses %}
<ul>
{% for acourse in courses %}
<li><a href="{% url 'assignments_index' acourse.id %}">{{ acourse.id }}, {{ acourse.title }}</a></li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}<file_sep>/quiz/permissions.py
""""
Handles permission for Quiz API
Permission Classes:
IsEnrolled
- Any course instructor or student of the course had the permission to
fetch the quiz
IsCourseInstructor
- the course instructors have full access to adding, deleting, editing a
quiz and its questions
Quiz
+ create: IsCourseInstructor
+ destroy: IsCourseInstructor
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
- get_question_modules: IsEnrolled
- add_question_module: IsCourseInstructor
- get_questions_manual_grade: IsCourseInstructor
QuestionModule
+ destroy: IsCourseInstructor
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
- get_questions: IsEnrolled
- add_fixed_answer_question: IsCourseInstructor
FixedAnswerQuestion
+ destroy: IsCourseInstructor
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
Question
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
- get_answer: IsCourseInstructorOrMaxAttempted
- submit_answer: IsEnrolled
- get_submissions_manual_grade: IsCourseInstructor
Submission
+ retrieve: IsEnrolled
+ update: IsCourseInstructor
- set_plagiarised: IsCourseInstructor
"""
from rest_framework import permissions
from courseware import models
from video.models import QuizMarker
from quiz.models import Quiz, QuestionModule, Question, Submission
class IsEnrolled(permissions.BasePermission):
"""
Allows view permission to anyone enrolled
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
if not request.user.is_authenticated():
return False
try:
if type(obj) == Question:
obj = obj.quiz
elif type(obj) == QuestionModule:
obj = obj.quiz
elif type(obj) == Submission:
obj = obj.questions.quiz
concept = models.Concept.objects.select_related('group').filter(quizzes__pk=obj.id)
if len(concept) > 0:
concept = concept[0]
else:
marker = QuizMarker.objects.get(quiz__pk=obj.id)
concept = models.Concept.objects.select_related('group').get(videos__pk=marker.video.id)
course = concept.group.course
course_history = models.CourseHistory.objects.get(
course=course,
user=request.user)
if not ((concept.is_published and obj.is_published) or course_history.is_owner):
return False
return True
except Exception as e:
return False
if request.method in permissions.SAFE_METHODS:
return True
else:
return False
class IsCourseInstructor(permissions.BasePermission):
"""
Allows complete permission to course instructor
"""
def has_permission(self, request, view):
"""
Allow loggedIn users only
"""
return request.user.is_authenticated()
def has_object_permission(self, request, view, obj):
"""
Returns whether user has permission on this object or not
"""
if not request.user.is_authenticated():
return False
try:
if type(obj) == Question:
obj = obj.quiz
elif type(obj) == QuestionModule:
obj = obj.quiz
elif type(obj) == Submission:
obj = obj.questions.quiz
concept = models.Concept.objects.select_related('group').filter(quizzes__pk=obj.id)
if len(concept) > 0:
concept = concept[0]
else:
marker = QuizMarker.objects.get(quiz__pk=obj.id)
concept = models.Concept.objects.select_related('group').get(videos__pk=marker.video.id)
course = concept.group.course
course_history = models.CourseHistory.objects.get(
course=course,
user=request.user)
if course_history.is_owner:
return True
if request.method in permissions.SAFE_METHODS:
if not ((concept.is_published and obj.is_published) or course_history.is_owner):
return False
return True
return False
except Exception as e:
return False
<file_sep>/install.sh
#/usr/bin/bash
sudo apt-get install python-dev libmysqlclient-dev mysql-server python-pip && \
sudo pip install virtualenv && \
## Change to directory location of this script
cd "$(dirname "$0")"
virtualenv venv && \
source venv/bin/activate && \
pip install -r requirements.txt
<file_sep>/courseware/static/courseware/js/content_developer/course_instructors.jsx
/** @jsx React.DOM */
var SearchBarInstructor = React.createClass({
searchForum: function() {
var search_str = this.refs.search.getDOMNode().value.trim();
search_str = encodeURIComponent(search_str);
this.props.load( search_str);
return false;
},
render: function() {
return (
<form onSubmit={this.searchForum}>
<div class="input-group col-md-4">
<input type="text" ref="search" placeholder="Search here" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default" value="submit" type="button" onClick={this.searchForum}>
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
);
}
});
var AddInstructor = React.createClass({
url : '/courseware/api/course/',
getUrl: function() {
return this.url;
},
updateUrl: function(search_str) {
this.url = "/courseware/api/course/" + this.props.course+"/get_users/?format=json&search_str="+search_str;
this.loadData();
},
approveRequests: function() {
users = []
pending_approvals = this.state.data.users;
selected = $('input[name=user]').map(function(node, i) {
return this.checked
});
for (var i = 0; i < selected.length; i++) {
if (selected[i]) {
users.push(pending_approvals[i]["id"]);
}
}
data = {users: JSON.stringify(users)};
console.log(data);
url = "/courseware/api/course/" + this.props.course + "/grant_instructor_permission/?format=json";
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
this.state.loaded = false;
display_global_message(response.msg,"success");
this.props.updateApprovedInstructors();
console.log("Instructor List should reload now")
}.bind(this));
request.fail(function(response) {
display_global_message("Not allowed. Only course creator has permission","error")
}.bind(this));
},
toggleAll: function() {
check = $('input[name=heading]')[0].checked;
nodes = $('input[name=user]');
for (var i = 0; i < nodes.length; i++) {
nodes[i].checked = check;
};
},
handleChange: function(event) {
if (! event.target.checked) {
$('input[name=heading]')[0].checked = false;
}
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
loadData: function() {
request = ajax_json_request(this.getUrl(), "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
state = this.state;
state['loaded'] = true;
state['data'] = response;
this.setState(state);
}.bind(this));
request.fail(function(response) {
console.log("Load data failed for " + this.getUrl());
console.log(response);
}.bind(this));
},
render: function() {
console.log(this.state)
if (this.state.loaded) {
if (! this.state.data.users) {
return (
<div class="row" style={{'margin-top':'15px'}}>
<div class="panel-body">
<div class="row">
<SearchBarInstructor load={this.updateUrl}/>
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger">
No user with matching name or username
</div>
</div>
</div>
);
}
pending_approvals = this.state.data.users;
pending_approvals = pending_approvals.map( function(user, i) {
return (
<div class="checkbox-row">
<div class="col-md-1 col-md-offset-0 checkbox-container">
<input onChange={this.handleChange} type="checkbox" name="user" key={"pending_student_" + i}> </input>
</div>
<div class="col-md-3 col-md-offset-0 username"> {user["username"]} </div>
<div class="col-md-4 col-md-offset-0 fullname"> {user["fullname"]} </div>
<div class="col-md-4 col-md-offset-0 email"> {user["email"]} </div>
</div>
);
}.bind(this));
if (pending_approvals.length > 0) {
return (
<div>
<div class="panel-body">
<div class="row">
<SearchBarInstructor load={this.updateUrl}/>
</div>
</div>
<div class="panel-collapse collapse in" id="pending-students">
<div class="row">
<div class="col-md-offset-9 col-md-2 no-padding">
<button ref="approve" onClick={this.approveRequests}
class="btn btn-primary approve-btn" type="button"> Approve </button>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1 no-padding student-container">
<div class="student-heading">
<div class="col-md-1 col-md-offset-0 checkbox-container">
<input type="checkbox" name="heading" key="student_heading"
onChange={this.toggleAll}>
</input>
</div>
<div class="col-md-3 col-md-offset-0 username">
User Name </div>
<div class="col-md-4 col-md-offset-0 fullname">
Full Name </div>
<div class="col-md-4 col-md-offset-0 email">
Email </div>
</div>
{pending_approvals}
</div>
</div>
</div>
</div>
);
} else {
return (
<div>
<div class="panel-body">
<div class="row">
<SearchBarInstructor load={this.updateUrl}/>
</div>
</div>
<div class="panel-collapse collapse in" id="pending-students">
<div class="col-md-offset-7 col-md-2">
<button ref="approve" onClick={this.approveRequests}
class="btn btn-primary approve-btn" type="button"> Approve </button>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
No Users to approve.
</div>
</div>
</div>
</div>
</div>
);
}
} else {
return (
<div class="panel-body">
<div class="row">
<SearchBarInstructor load={this.updateUrl}/>
</div>
</div>
);
}
}
});
var ApprovedInstructors = React.createClass({
base_url: '/courseware/api/course/',
getUrl: function() {
url = this.base_url + this.props.course + "/all_instructors/?format=json";
return url;
},
discardRequests: function() {
instructors = []
approved_instructors = this.state.data.approvedInstructors;
selected = $('input[name=instructor]').map(function(node, i) {
return this.checked
});
for (var i = 0; i < selected.length; i++) {
if (selected[i]) {
instructors.push(approved_instructors[i]["id"]);
}
}
data = {instructors: JSON.stringify(instructors)};
console.log(data);
url = "/courseware/api/course/" + this.props.course + "/remove_instructor_permission/?format=json";
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
this.loadData();
this.forceUpdate();
display_global_message(response.msg,"success")
this.props.updateApprovedInstructors();
console.log("Instructor List should reload now")
}.bind(this));
request.fail(function(response) {
display_global_message("Not allowed. Only course creator has permission","error")
}.bind(this));
},
toggleAll: function() {
check = $('input[name=heading]')[0].checked;
nodes = $('input[name=instructor]');
for (var i = 0; i < nodes.length; i++) {
nodes[i].checked = check;
};
},
handleChange: function(event) {
if (! event.target.checked) {
$('input[name=heading]')[0].checked = false;
}
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
componentWillReceiveProps: function(nextProps) {
if (this.state.loaded){
this.loadData();
console.log("Updated Approved Instructors");
}
},
getInitialState: function() {
return {
loaded: false,
data: undefined
};
},
componentWillMount: function() {
loaded = false;
data = undefined;
this.setState({loaded: loaded, data: data}, this.loadData);
},
loadData: function() {
request = ajax_json_request(this.getUrl(), "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
state = this.state;
state['loaded'] = true;
state['data'] = response;
this.setState(state);
}.bind(this));
request.fail(function(response) {
console.log("Load data failed for " + this.getUrl());
console.log(response);
}.bind(this));
},
render: function() {
console.log(this.state)
if (this.state.loaded) {
if (! this.state.data.approvedInstructors) {
return (
<div class="row" style={{'margin-top':'15px'}}>
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger">
No instruct
</div>
</div>
</div>
);
}
approved_instructors = this.state.data.approvedInstructors;
approved_instructors = approved_instructors.map( function(instructor, i) {
return (
<div class="checkbox-row">
<div class="col-md-1 col-md-offset-0 checkbox-container">
<input onChange={this.handleChange} type="checkbox" name="instructor" key={"pending_student_" + i}> </input>
</div>
<div class="col-md-3 col-md-offset-0 username"> {instructor["username"]} </div>
<div class="col-md-4 col-md-offset-0 fullname"> {instructor["fullname"]} </div>
<div class="col-md-4 col-md-offset-0 email"> {instructor["email"]} </div>
</div>
);
}.bind(this));
if (approved_instructors.length > 0) {
return (
<div>
<div class="panel-collapse collapse in" id="pending-students">
<div class="row">
<div class="col-md-offset-9 col-md-2 no-padding">
<button ref="approve" onClick={this.discardRequests}
class="btn btn-primary approve-btn" type="button"> Remove </button>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1 no-padding student-container">
<div class="student-heading">
<div class="col-md-1 col-md-offset-0 checkbox-container">
<input type="checkbox" name="heading" key="student_heading"
onChange={this.toggleAll}>
</input>
</div>
<div class="col-md-3 col-md-offset-0 username">
User Name </div>
<div class="col-md-4 col-md-offset-0 fullname">
Full Name </div>
<div class="col-md-4 col-md-offset-0 email">
Email </div>
</div>
{approved_instructors}
</div>
</div>
</div>
</div>
);
} else {
return (
<div>
<div class="panel-collapse collapse in" id="pending-students">
<div class="col-md-offset-7 col-md-2">
<button ref="approve" onClick={this.discardRequests}
class="btn btn-primary approve-btn" type="button"> Approve </button>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
No Instructors
</div>
</div>
</div>
</div>
</div>
);
}
} else {
return (
<div class="panel-body">
<div class="row">
No instructor
</div>
</div>
);
}
}
});
var CourseInstructors = React.createClass({
updateApprovedInstructors: function() {
console.log("Sending signal to Approved Instructors");
this.setState({loaded: false});
},
getInitialState: function(){
return {
loaded:false,
};
},
render: function() {
approved_students = <div>Some other content</div>;
return (
<div id="student" class="col-md-12">
<div class="panel panel-default pending-students" id="pending-student-container">
<div class="panel-heading" data-toggle="collapse" data-parent="#student"
data-target="#pending-students" id="pending-student-heading">
<span class="heading"> Add Instructor </span>
</div>
<AddInstructor course={this.props.course} updateApprovedInstructors={this.updateApprovedInstructors}/>
</div>
<div class="panel panel-default approved-students" id="approved-student-container">
<div class="panel-heading" data-toggle="collapse" data-parent="#student"
data-target="#approved-students" id="approved-student-heading">
<span class="heading"> Current Instructors </span>
</div>
<div class="panel-collapse collapse" id="approved-students">
<ApprovedInstructors course={this.props.course} updateApprovedInstructors={this.updateApprovedInstructors} loaded={this.state.loaded}/>
</div>
</div>
</div>);
}
});<file_sep>/scripts/copy_offering.py
# script to copy an offering from old database to new
# Uses multiple database connection feture of django
# first add a database in other the defaut in settings.py
# this script also assumes only one user is important so
# useful only at start of course(assignments not included)
from courseware.models import *
from quiz.models import *
from document.models import *
from video.models import *
from discussion_forum.models import *
from django.contrib.auth.models import User
from courseware import playlist
import json
from sets import Set
category = Category.objects.get(pk=1)
parent_category = ParentCategory.objects.get(pk=1)
user = User.objects.get(pk=1)
files = Set()
def copy_document(pk, dbName):
doc = Document.objects.filter(pk=pk).using(dbName)[0]
d = Document(title=doc.title, uid=doc.uid, is_heading=doc.is_heading, is_link=doc.is_link, link=doc.link, description=doc.description, playlist=doc.playlist)
d.save()
sections = Section.objects.filter(document=pk).using(dbName)
for section in sections:
s = Section(document=d, title=section.title, description=section.description, file=section.file)
s.save()
files.add(section.file)
return d
def copy_quiz(pk, dbName):
quiz = Quiz.objects.filter(pk=pk).using(dbName)[0]
q = Quiz(title=quiz.title)
q.save()
question_modules = QuestionModule.objects.filter(quiz=pk).using(dbName)
for question_module in question_modules:
qm = QuestionModule(quiz=q, title=question_module.title, dummy=question_module.dummy)
qm.save()
questions = DescriptiveQuestion.objects.filter(quiz=pk, question_module=question_module).using(dbName)
for question in questions:
qu = DescriptiveQuestion(quiz=q, question_module=qm, description=question.description, hint=question.hint, grader_type=question.grader_type, answer_description=question.answer_description, marks=question.marks, gradable=question.gradable, granularity=question.granularity, granularity_hint=question.granularity_hint, type=question.type, attempts=question.attempts, answer=question.answer)
qu.save()
questions = SingleChoiceQuestion.objects.filter(quiz=pk, question_module=question_module).using(dbName)
for question in questions:
qu = SingleChoiceQuestion(quiz=q, question_module=qm, description=question.description, hint=question.hint, grader_type=question.grader_type, answer_description=question.answer_description, marks=question.marks, gradable=question.gradable, granularity=question.granularity, granularity_hint=question.granularity_hint, type=question.type, attempts=question.attempts, answer=question.answer, options=question.options)
qu.save()
questions = MultipleChoiceQuestion.objects.filter(quiz=pk, question_module=question_module).using(dbName)
for question in questions:
qu = MultipleChoiceQuestion(quiz=q, question_module=qm, description=question.description, hint=question.hint, grader_type=question.grader_type, answer_description=question.answer_description, marks=question.marks, gradable=question.gradable, granularity=question.granularity, granularity_hint=question.granularity_hint, type=question.type, attempts=question.attempts, answer=question.answer, options=question.options)
qu.save()
questions = FixedAnswerQuestion.objects.filter(quiz=pk, question_module=question_module).using(dbName)
for question in questions:
qu = FixedAnswerQuestion(quiz=q, question_module=qm, description=question.description, hint=question.hint, grader_type=question.grader_type, answer_description=question.answer_description, marks=question.marks, gradable=question.gradable, granularity=question.granularity, granularity_hint=question.granularity_hint, type=question.type, attempts=question.attempts, answer=question.answer)
qu.save()
return q
def copy_video(pk, dbName):
video = Video.objects.filter(pk=pk).using(dbName)[0]
v = Video(title=video.title, content=video.content, video_file=video.video_file, other_file=video.other_file, duration=video.duration)
v.save()
files.add(video.video_file)
files.add(video.other_file)
markers = SectionMarker.objects.filter(video=pk).using(dbName)
for marker in markers:
m = SectionMarker(video=v, time=marker.time, type=marker.type, title=marker.title)
m.save()
markers = QuizMarker.objects.filter(video=pk).using(dbName)
for marker in markers:
m = QuizMarker(video=v, time=marker.time, type=marker.type, quiz=copy_quiz(marker.quiz.pk, dbName))
m.save()
return v
def copy_forum(pk1, pk2, dbName):
forum = DiscussionForum.objects.filter(pk=pk1).using(dbName)[0]
forum2 = DiscussionForum.objects.filter(pk=pk2)[0]
forum2.abuse_threshold = forum.abuse_threshold
forum2.review_threshold = forum.review_threshold
forum2.save()
user_setting = UserSetting.objects.filter(user=1, forum=pk1).using(dbName)[0]
u_s = UserSetting(user=user, forum=forum2, is_active=user_setting.is_active, email_digest=user_setting.email_digest, super_user=user_setting.super_user, moderator=user_setting.moderator, badge=user_setting.badge)
u_s.save()
tags = Tag.objects.filter(forum=pk1).using(dbName)
for tag in tags:
t = Tag(forum=forum2, title=tag.title, tag_name=tag.tag_name, auto_generated=tag.auto_generated)
t.save()
def copy_concept(pk, group, dbName):
concept = Concept.objects.filter(pk=pk).using(dbName)[0]
t_d = copy_document(concept.title_document.pk, dbName)
c = Concept(group=group, title_document=t_d, title=concept.title, image=concept.image, description=concept.description, is_published=concept.is_published, max_score=concept.max_score)
files.add(concept.image)
c.save()
concept_playlist = playlist.to_array(concept.playlist)
concept_hash = {}
for doc in concept.pages.all():
new_doc = copy_document(doc.pk, dbName)
c.pages.add(new_doc)
concept_hash[doc.pk] = new_doc.pk
for vid in concept.videos.all():
new_vid = copy_video(vid.pk, dbName)
c.videos.add(new_vid)
concept_hash[vid.pk] = new_vid.pk
for quiz in concept.quizzes.all():
new_quiz = copy_quiz(quiz.pk, dbName)
c.quizzes.add(new_quiz)
concept_hash[quiz.pk] = new_quiz.pk
for i in range(len(concept_playlist)):
concept_playlist[i][0] = concept_hash[int(concept_playlist[i][0])]
c.playlist = json.dumps(concept_playlist)
c.save()
ch = ConceptHistory(concept=c, user=user)
ch.save()
return c
def copy_group(pk, course, dbName):
group = Group.objects.filter(pk=pk).using(dbName)[0]
g = Group(course=course, title=group.title, image=group.image, description=group.description, max_score=group.max_score)
files.add(group.image)
g.save()
for doc in group.pages.all():
g.pages.add(copy_document(doc.pk, dbName))
gh = GroupHistory(group=g, user=user)
gh.save()
concept_playlist = playlist.to_array(group.playlist)
concept_hash = {}
concepts = Concept.objects.filter(group=group).using(dbName)
for concept in concepts:
new_concept = copy_concept(concept.pk, g, dbName)
concept_hash[concept.pk] = new_concept.pk
for i in range(len(concept_playlist)):
concept_playlist[i][0] = concept_hash[int(concept_playlist[i][0])]
g.playlist = json.dumps(concept_playlist)
g.save()
return g
def copy_offering(pk, dbName):
off = Offering.objects.filter(pk=pk).using(dbName)[0]
o = Offering(category=category, title=off.title, image=off.image, type=off.type, playlist=off.playlist, enrollment_type=off.enrollment_type, max_score=off.max_score)
files.add(off.image)
o.save()
o.course_info.start_time = off.course_info.start_time
o.course_info.end_time = off.course_info.end_time
o.course_info.is_published = off.course_info.is_published
o.course_info.description = off.course_info.description
o.course_info.end_enrollment_date = off.course_info.end_enrollment_date
o.course_info.save()
copy_forum(off.forum.pk, o.forum.pk, dbName)
page_playlist = playlist.to_array(off.page_playlist)
page_hash = {}
for doc in off.pages.all():
new_doc = copy_document(doc.pk, dbName)
page_hash[doc.pk] = new_doc.pk
o.pages.add(new_doc)
for i in range(len(page_playlist)):
page_playlist[i][0] = page_hash[int(page_playlist[i][0])]
o.page_playlist = json.dumps(page_playlist)
course_history = CourseHistory.objects.filter(user=1,course=off).using(dbName)[0]
ch = CourseHistory(user=user, course=o, grade=course_history.grade, active=course_history.active, is_moderator=course_history.is_moderator, is_owner=course_history.is_owner, is_creator=True, show_marks=course_history.show_marks)
ch.save()
groups = Group.objects.filter(course=off).using(dbName)
group_playlist = playlist.to_array(off.playlist)
group_hash = {}
for group in groups:
new_group = copy_group(group.pk, o, dbName)
group_hash[group.pk] = new_group.pk
for i in range(len(group_playlist)):
group_playlist[i][0] = group_hash[int(group_playlist[i][0])]
o.playlist = json.dumps(group_playlist)
o.save()
# copy_offering(2, 'bodhi2') #if the other database is bodhi2
# f = open('filelist1', 'w')
# for item in files:
# f.write("%s\n" % item)
# f.close()
# files = Set()
# copy_offering(14, 'bodhi1')
# f = open('filelist2', 'w')
# for item in files:
# f.write("%s\n" % item)
# f.close()<file_sep>/notification/urls.py
"""
URL mappings for Notifications
"""
from django.conf.urls import patterns, url
from notification import views
from elearning_academy import settings
urlpatterns = patterns('',
)
<file_sep>/user_profile/serializers.py
"""
Serializers for user profile API
"""
from rest_framework import serializers
from user_profile import models
class UserProfileCompanySerializer(serializers.ModelSerializer):
class Meta:
model = models.Company
fields = ('company')
class UserProfileUserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserProfile
fields = ('about', 'interests', 'gender',
'place_city', 'place_country',
'dob', 'place_state','interests',
'website_facebook', 'website_twitter',
'photo',
)
class UserProfileEducationSerializer(serializers.ModelSerializer):
class Meta:
model = models.Education
class UserProfileCollegeSerializer(serializers.ModelSerializer):
class Meta:
model = models.College
class UserProfileWorkSerializer(serializers.ModelSerializer):
class Meta:
model = models.Work
fields = ('username', 'first_name', 'last_name', 'email', 'password')
##TODO More Validation
def validate(self, attrs):
try:
email = attrs['email']
except KeyError:
raise serializers.ValidationError("Email field is required")
return attrs
##TODO: This is a hack to throw in validation errors
## else the user is returned a empty string
def get_validation_exclusions(self):
pass
<file_sep>/chatserver.py
#!/usr/bin/env python
__author__ = 'dheerendra'
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'elearning_academy.settings'
from tornado.options import options, define, parse_command_line
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.wsgi
from django.conf import settings
from chat.websocket.wsChat import ChatSocketHandler
define("port", type=int, default=settings.TORNADO_PORT)
def main():
parse_command_line()
tornado_app = tornado.web.Application(
[
(r"/wschat/(\d+)/([-]?[0-9]+)", ChatSocketHandler)
],
debug=True
)
server = tornado.httpserver.HTTPServer(tornado_app)
server.listen(options.port, address="0.0.0.0")
print "server started. Press Ctrl-C to close"
tornado.ioloop.IOLoop.instance().start()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print "You Pressed Ctrl-C. Closing server"<file_sep>/assignments/forms.py
'''
Created on May 20, 2013
@author: aryaveer
'''
from django import forms
import pickle
from django.forms.util import ErrorList
from django.utils import timezone
from django.forms import widgets
from utils.archives import Archive
from utils.archives import get_file_name_list, extract_or_copy
from utils.filetypes import is_valid, VALID_EXTENSIONS_COMPILERS, VALID_EXTENSIONS_INTERPRETERS, LANGUAGES, get_extension, get_compiler_name, get_interpreter_name, compile_required, execution_command_required
from assignments.models import Assignment
from assignments.assignments_utils.meta_script_schema import meta_script_schema_str
from jsonschema.validators import Draft4Validator
import json, tempfile, os
import datetime as DateTime
from widgets import SecureFileInput
class DivErrorList(ErrorList):
def __unicode__(self):
return self.as_divs()
def as_divs(self):
if not self: return u''
return u'<div class="alert alert-danger">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])
# IMPORTANT: make sure all form fields are exactly the same as corresponding model fields.
# TODO: May be try writing a method to do the above check.
class AssignmentForm(forms.Form):
name = forms.CharField(label="Assignment Name")
deadline = forms.DateTimeField(
input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%Y/%m/%d %H:%M'],
label="Soft Deadline",
help_text="Students can submit after this date if late submission is allowed."
)
hard_deadline = forms.DateTimeField(
input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%Y/%m/%d %H:%M'],
label="Hard Deadline",
help_text="Students can not submit after this date, if late submission is allowed."
)
late_submission_allowed = forms.BooleanField(
required=False,
label="Late Submission Allowed?",
help_text="If checked, students will be able to submit until hard deadline",
)
choices = [(a, a) for a in LANGUAGES]
program_language = forms.ChoiceField(
choices=choices,
label="Choose programming language",
)
student_program_files = forms.CharField(
label="List of files name that student must submit",
help_text="File names separated by space.\
(File name shouldn't have space.)"
)
force_upload = forms.BooleanField(
required=False,
label="Allow all extensions",
help_text="If checked, all other file extensions will be allowed to upload",
)
document = forms.FileField(
required=False,
label="Documents",
help_text="e.g. Some tutorial."
)
helper_code = forms.FileField(
required=False,
label="Helper Code",
help_text="Provide students with code template or libraries."
)
model_solution = forms.FileField(
error_messages={'invalid': 'File was not a valid tar file.'},
required=False,
label="Solution Code(if any)",
help_text="Accepted archives are tar, tar.gz, tar.bz2, zip."
)
publish_on = forms.DateTimeField(
label="Publish this assignment on",
input_formats=['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%Y/%m/%d %H:%M']
)
description = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
kwargs['error_class']=DivErrorList
super(AssignmentForm, self).__init__(*args, **kwargs)
try:
self.assignmentId = kwargs['initial']['id']
except:
self.assignmentId = -1
self.fields['document'].widget=SecureFileInput(data_source_url='/assignments/document/download/' + str(self.assignmentId))
self.fields['model_solution'].widget=SecureFileInput(data_source_url='/assignments/solution/download/' + str(self.assignmentId))
self.fields['helper_code'].widget=SecureFileInput(data_source_url='/assignments/helpercode/download/' + str(self.assignmentId))
def clean_name(self):
if not hasattr(self, 'this_course'):
return self.cleaned_data['name']
try:
_ = Assignment.objects.get(name=self.cleaned_data['name'], course=self.this_course)
raise forms.ValidationError('This assignment already exists in this course.')
except Assignment.DoesNotExist:
pass
return self.cleaned_data['name']
def clean_deadline(self):
deadline = self.cleaned_data['deadline']
if deadline and deadline < timezone.now():
raise forms.ValidationError('Deadline can not be in past.')
return self.cleaned_data['deadline']
def check_model_solution(self, data):
self._solution_file = []
if 'model_solution' in self.changed_data:
if data.get('model_solution', ""):
with Archive(fileobj=data['model_solution']) as archive:
if not archive.is_archive():
if not is_valid(filename=data['model_solution'].name, lang=data['program_language']):
self._errors['model_solution'] = self.error_class(["This file was not valid."])
del data['model_solution']
else:
self._solution_file = [data['model_solution'].name]
else:
self._solution_file = [a.split("/")[-1] for a in archive.getfile_members()]
else: # File is being deleted.
pass
else: # No change in file field. Check if file exist in database.
if not hasattr(self, 'assignment_model'):
return # Assignment is created without model solution.
if not self.assignment_model.model_solution: return # no file in database.
with Archive(fileobj=self.assignment_model.model_solution.file) as archive:
if archive.is_archive():
self._solution_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
file_name = self.assignment_model.model_solution.name.split("/")[-1]
self._solution_file = [file_name]
def check_student_program_files(self, data):
file_list = data.get('student_program_files').split()
language = data.get('program_language')
for afile in file_list:
if not is_valid(afile, language):
if not data.get('force_upload'):
self._errors['student_program_files'] = self.error_class(["Only {1} files are accepted for {0} language.\
".format(language, " ".join(get_extension(language)))])
del data['student_program_files']
break
try:
del data['force_upload']
except:
pass
def clean(self):
cleaned_data = super(AssignmentForm, self).clean()
if self.errors: return cleaned_data
self.check_student_program_files(cleaned_data)
if self.errors: return cleaned_data
self.check_model_solution(cleaned_data)
if self._errors: return cleaned_data
# file name to be compiled -- program files submitted by student should be in Teacher supplied tar.
students_file_name = cleaned_data.get('student_program_files', "")
students_file = set(students_file_name.split())
missing_file = students_file - set(self._solution_file)
if missing_file and self._solution_file:
self._errors['model_solution'] = self.error_class(["{0} was not found. Please upload {1}".format(" ".join(missing_file), students_file_name)])
del cleaned_data['model_solution']
if cleaned_data.get('deadline') > cleaned_data.get('hard_deadline'):
self._errors['hard_deadline'] = self.error_class(['Hard deadline should be later than soft deadline'])
return cleaned_data
class CompilerCommandWidget(widgets.MultiWidget):
def __init__(self, *args, **kwargs):
widgets = [forms.TextInput(attrs={'readonly':'True'}),
forms.TextInput,
forms.TextInput]
super(CompilerCommandWidget, self).__init__(widgets, *args, **kwargs)
def decompress(self, value):
if value:
return pickle.loads(value)
else:
return ['', '', '',]
class CompilerCommand(forms.fields.MultiValueField):
widget = CompilerCommandWidget
def __init__(self, *args, **kwargs):
list_fields = [forms.fields.CharField(max_length=512, widget=forms.TextInput(attrs={'readonly':'True'}), required=False),
forms.fields.CharField(max_length=512, required=False),
forms.fields.CharField(max_length=512)]
super(CompilerCommand, self).__init__(list_fields, *args, **kwargs)
self.widget = CompilerCommandWidget()
def compress(self, values):
if values:
if values[0] in forms.fields.EMPTY_VALUES:
raise forms.fields.ValidationError("Please provide compiler name")
if values[2] in forms.fields.EMPTY_VALUES:
raise forms.fields.ValidationError("Please provide file names.")
return pickle.dumps(values)
class ExecutionCommandWidget(widgets.MultiWidget):
def __init__(self, *args, **kwargs):
widgets = [forms.TextInput(attrs={'readonly':'True'}),
forms.TextInput,
forms.TextInput]
super(ExecutionCommandWidget, self).__init__(widgets, *args, **kwargs)
def decompress(self, value):
if value:
return pickle.loads(value)
else:
return ['', '', '',]
class ExecutionCommand(forms.fields.MultiValueField):
widget = ExecutionCommandWidget
def __init__(self, *args, **kwargs):
list_fields = [forms.fields.CharField(max_length=512, widget=forms.TextInput(attrs={'readonly':'True'}), required=False),
forms.fields.CharField(max_length=512, required=False),
forms.fields.CharField(max_length=512)]
super(ExecutionCommand, self).__init__(list_fields, *args, **kwargs)
self.widget = ExecutionCommandWidget()
def compress(self, values):
if values:
if values[0] in forms.fields.EMPTY_VALUES:
raise forms.fields.ValidationError("Please provide name of the interpreter")
if values[2] in forms.fields.EMPTY_VALUES:
raise forms.fields.ValidationError("Please provide file names.")
return pickle.dumps(values)
class ProgramFormCNotE(forms.Form):
#error_css_class = 'alert-danger'
#required_css_class = 'alert-danger'
PROGRAM_TYPES = (
('Evaluate', 'Evaluate'),
('Practice', 'Practice'),
)
name = forms.CharField()
program_type = forms.ChoiceField(choices=PROGRAM_TYPES)
compiler_command = CompilerCommand(
help_text="Give compiler flags in second field and file names in third field. File names can be any of the files from student submission provided in assignment details.\
If you provide other file names, upload those files in additional files below.",
required=False
)
program_files = forms.FileField(
error_messages={'invalid': 'File was not a valid tar file.',},
required = False,
label="Additional Source Files",
help_text="Provide additional source files here.\
Accepted archives are tar, tar.gz, tar.bz2, zip."
)
makefile = forms.FileField(
required=False,
help_text="Must be a text file."
)
description = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
kwargs['error_class']=DivErrorList
super(ProgramFormCNotE, self).__init__(*args, **kwargs)
try:
self.programId = kwargs['initial']['id']
except:
self.programId = -1
self.fields['program_files'].widget=SecureFileInput(data_source_url='/assignments/program/programfile/download/' + str(self.programId))
self.fields['makefile'].widget=SecureFileInput(data_source_url='/assignments/program/makefile/download/' + str(self.programId))
def check_compiler_command(self, data):
compiler_command = pickle.loads(data.get('compiler_command'))
if get_compiler_name(self.assignment.program_language) != compiler_command[0]:
self._errors['compiler_command'] = self.error_class(["Invalid compiler for {0} language .\
".format(self.assignment.program_language)])
del data['compiler_command']
return
for afile in compiler_command[2].split():
if not is_valid(filename=afile, compiler=compiler_command[0]):
self._errors['compiler_command'] = self.error_class(["Only {1} files are accepted for {0} compiler.\
".format(compiler_command[0], " ".join(get_extension(compiler_command[0])))])
del data['compiler_command']
def check_program_files(self, data):
self.__teachers_file = []
if 'program_files' in self.changed_data:
if data.get('program_files', ""):
with Archive(fileobj=data['program_files']) as archive:
if archive.is_archive():
self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
if is_valid(filename=data['program_files'].name, compiler=pickle.loads(data['compiler_command'])[0]):
self.__teachers_file = [data['program_files'].name]
else:
self._errors['program_files'] = self.error_class(["This file was not valid."])
del data['program_files']
else: # file is being deleted.
pass
else: # No change in file field. Check if file exist in database.
if not hasattr(self, 'program_model'):
return # Assignment is created without model solution.
if not self.program_model.program_files: return # no file in database.
with Archive(fileobj=self.program_model.program_files.file) as archive:
if archive.is_archive():
self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
if is_valid(filename=self.program_model.program_files.name, compiler=pickle.loads(data['compiler_command'])[0]):
self.__teachers_file = [self.program_model.program_files.name.split("/")[-1]]
else:
file_name = self.program_model.program_files.name.split("/")[-1]
self._errors['program_files'] = self.error_class(["File {0} is not valid. Please upload a valid file\
".format(file_name)])
del data['program_files']
def clean(self):
cleaned_data = super(ProgramFormCNotE, self).clean()
if self.errors: return cleaned_data
self.check_compiler_command(cleaned_data)
if self._errors: return cleaned_data
self.check_program_files(cleaned_data)
if self._errors: return cleaned_data
compiler_command = pickle.loads(cleaned_data.get('compiler_command'))
# file name to be compiled -- program files submitted by student should be in Teacher supplied tar.
file_to_compile = set(compiler_command[2].split())
students_file = cleaned_data.get('student_program_files', "")
students_file = set(students_file.split())
missing_file = file_to_compile - set(self.__teachers_file) - set(self.assignment.student_program_files.split())
if missing_file:
self._errors['program_files'] = self.error_class(["{0} is missing. It is one of the file in compilation command".format(" ".join(missing_file))])
del cleaned_data['program_files']
else:
#Compile Program now.
pass
return cleaned_data
class ProgramFormCandE(forms.Form):
#error_css_class = 'alert-danger'
#required_css_class = 'alert-danger'
PROGRAM_TYPES = (
('Evaluate', 'Evaluate'),
('Practice', 'Practice'),
)
name = forms.CharField()
program_type = forms.ChoiceField(choices=PROGRAM_TYPES)
compiler_command = CompilerCommand(help_text="Give compiler flags in second field and file names in third field. File names can be any of the files from student submission provided in assignment details.\
If you provide other file names, upload those files in additional files below.",
required=False
)
execution_command = ExecutionCommand(help_text="Give the execution command in this textbox",
required=False)
program_files = forms.FileField(
error_messages={'invalid': 'File was not a valid tar file.',},
required = False,
label="Additional Source Files",
help_text="Provide additional source files here.\
Accepted archives are tar, tar.gz, tar.bz2, zip."
)
makefile = forms.FileField(
required=False,
help_text="Must be a text file."
)
description = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
kwargs['error_class']=DivErrorList
super(ProgramFormCandE, self).__init__(*args, **kwargs)
try:
self.programId = kwargs['initial']['id']
except:
self.programId = -1
self.fields['program_files'].widget=SecureFileInput(data_source_url='/assignments/program/programfile/download/' + str(self.programId))
self.fields['makefile'].widget=SecureFileInput(data_source_url='/assignments/program/makefile/download/' + str(self.programId))
def check_compiler_command(self, data):
compiler_command = pickle.loads(data.get('compiler_command'))
if get_compiler_name(self.assignment.program_language) != compiler_command[0]:
self._errors['compiler_command'] = self.error_class(["Invalid compiler for {0} language .\
".format(self.assignment.program_language)])
del data['compiler_command']
return
for afile in compiler_command[2].split():
if not is_valid(filename=afile, compiler=compiler_command[0]):
self._errors['compiler_command'] = self.error_class(["Only {1} files are accepted for {0} compiler.\
".format(compiler_command[0], " ".join(get_extension(compiler_command[0])))])
del data['compiler_command']
def check_execution_command(self, data):
execution_command = pickle.loads(data.get('execution_command'))
if get_interpreter_name(self.assignment.program_language) != execution_command[0]:
self._errors['execution_command'] = self.error_class(["Invalid interpreter for {0} language .\
".format(self.assignment.program_language)])
del data['execution_command']
return
for afile in execution_command[2].split():
if not is_valid(filename=afile, interpreter=execution_command[0]):
self._errors['execution_command'] = self.error_class(["Only {1} files are accepted for {0} interpreter.\
".format(execution_command[0], " ".join(get_extension(execution_command[0])))])
del data['execution_command']
def check_program_files(self, data):
self.__teachers_file = []
if 'program_files' in self.changed_data:
if data.get('program_files', ""):
with Archive(fileobj=data['program_files']) as archive:
if archive.is_archive():
self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
if is_valid(filename=data['program_files'].name, compiler=pickle.loads(data['compiler_command'])[0]):
self.__teachers_file = [data['program_files'].name]
else:
self._errors['program_files'] = self.error_class(["This file was not valid."])
del data['program_files']
else: # file is being deleted.
pass
else: # No change in file field. Check if file exist in database.
if not hasattr(self, 'program_model'):
return # Assignment is created without model solution.
if not self.program_model.program_files: return # no file in database.
with Archive(fileobj=self.program_model.program_files.file) as archive:
if archive.is_archive():
self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
if is_valid(filename=self.program_model.program_files.name, compiler=pickle.loads(data['compiler_command'])[0]):
self.__teachers_file = [self.program_model.program_files.name.split("/")[-1]]
else:
file_name = self.program_model.program_files.name.split("/")[-1]
self._errors['program_files'] = self.error_class(["File {0} is not valid. Please upload a valid file\
".format(file_name)])
del data['program_files']
def clean(self):
cleaned_data = super(ProgramFormCandE, self).clean()
if self.errors: return cleaned_data
self.check_compiler_command(cleaned_data)
if self._errors: return cleaned_data
self.check_execution_command(cleaned_data)
if self._errors: return cleaned_data
self.check_program_files(cleaned_data)
if self._errors: return cleaned_data
compiler_command = pickle.loads(cleaned_data.get('compiler_command'))
execution_command = pickle.loads(cleaned_data.get('execution_command'))
# file name to be compiled -- program files submitted by student should be in Teacher supplied tar.
file_to_compile = set(compiler_command[2].split())
students_file = cleaned_data.get('student_program_files', "")
students_file = set(students_file.split())
missing_file = file_to_compile - set(self.__teachers_file) - set(self.assignment.student_program_files.split())
if missing_file:
self._errors['program_files'] = self.error_class(["{0} is missing. It is one of the file in compilation command".format(" ".join(missing_file))])
del cleaned_data['program_files']
else:
#Compile Program now.
pass
return cleaned_data
class ProgramFormE(forms.Form):
#error_css_class = 'alert-danger'
#required_css_class = 'alert-danger'
PROGRAM_TYPES = (
('Evaluate', 'Evaluate'),
('Practice', 'Practice'),
)
name = forms.CharField()
program_type = forms.ChoiceField(choices=PROGRAM_TYPES)
execution_command = ExecutionCommand(help_text="Give the execution command in this textbox",
required=False)
program_files = forms.FileField(
error_messages={'invalid': 'File was not a valid tar file.',},
required = False,
label="Additional Source Files",
help_text="Provide additional source files here.\
Accepted archives are tar, tar.gz, tar.bz2, zip."
)
makefile = forms.FileField(
required=False,
help_text="Must be a text file."
)
description = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
kwargs['error_class']=DivErrorList
super(ProgramFormE, self).__init__(*args, **kwargs)
try:
self.programId = kwargs['initial']['id']
except:
self.programId = -1
self.fields['program_files'].widget=SecureFileInput(data_source_url='/assignments/program/programfile/download/' + str(self.programId))
self.fields['makefile'].widget=SecureFileInput(data_source_url='/assignments/program/makefile/download/' + str(self.programId))
def check_execution_command(self, data):
execution_command = pickle.loads(data.get('execution_command'))
if get_interpreter_name(self.assignment.program_language) != execution_command[0]:
self._errors['execution_command'] = self.error_class(["Invalid interpreter for {0} language .\
".format(self.assignment.program_language)])
del data['execution_command']
return
for afile in execution_command[2].split():
if not is_valid(filename=afile, interpreter=execution_command[0]):
self._errors['execution_command'] = self.error_class(["Only {1} files are accepted for {0} interpreter.\
".format(execution_command[0], " ".join(get_extension(execution_command[0])))])
del data['execution_command']
def check_program_files(self, data):
self.__teachers_file = []
if 'program_files' in self.changed_data:
if data.get('program_files', ""):
with Archive(fileobj=data['program_files']) as archive:
if archive.is_archive():
self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
if is_valid(filename=data['program_files'].name, interpreter=pickle.loads(data['execution_command'])[0]):
self.__teachers_file = [data['program_files'].name]
else:
self._errors['program_files'] = self.error_class(["This file was not valid."])
del data['program_files']
else: # file is being deleted.
pass
else: # No change in file field. Check if file exist in database.
if not hasattr(self, 'program_model'):
return # Assignment is created without model solution.
if not self.program_model.program_files: return # no file in database.
with Archive(fileobj=self.program_model.program_files.file) as archive:
if archive.is_archive():
self.__teachers_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
if is_valid(filename=self.program_model.program_files.name, interpreter=pickle.loads(data['execution_command'])[0]):
self.__teachers_file = [self.program_model.program_files.name.split("/")[-1]]
else:
file_name = self.program_model.program_files.name.split("/")[-1]
self._errors['program_files'] = self.error_class(["File {0} is not valid. Please upload a valid file\
".format(file_name)])
del data['program_files']
def clean(self):
cleaned_data = super(ProgramFormE, self).clean()
if self.errors: return cleaned_data
self.check_execution_command(cleaned_data)
if self._errors: return cleaned_data
self.check_program_files(cleaned_data)
if self._errors: return cleaned_data
execution_command = pickle.loads(cleaned_data.get('execution_command'))
# file name to be compiled -- program files submitted by student should be in Teacher supplied tar.
file_to_execute = set(execution_command[2].split())
students_file = cleaned_data.get('student_program_files', "")
students_file = set(students_file.split())
missing_file = file_to_execute - set(self.__teachers_file) - set(self.assignment.student_program_files.split())
if missing_file:
self._errors['program_files'] = self.error_class(["{0} is missing. It is one of the file in execution command".format(" ".join(missing_file))])
del cleaned_data['program_files']
else:
#Compile Program now.
pass
return cleaned_data
class TestcaseForm(forms.Form):
name = forms.CharField(label="Testcase Name")
command_line_args = forms.CharField(
label="Command Line Arguments",
required=False
)
marks = forms.IntegerField(label="Marks", required=False)
input_files = forms.FileField(
error_messages={'invalid': 'File was not a valid archive file.'},
required=False,
label="Input Files",
help_text="File used for program as input. Accepted archives are tar, tar.gz, tar.bz2, zip.",
allow_empty_file=True,
)
output_files = forms.FileField(
error_messages={'invalid': 'File was not a valid tar file.'},
required=False,
label="Output Files",
help_text="Expected output files produced by program. Accepted archives are tar, tar.gz, tar.bz2, zip.",
allow_empty_file=True,
)
description = forms.CharField(
widget=forms.Textarea,
required=False
)
def __init__(self, *args, **kwargs):
kwargs['error_class'] = DivErrorList
self.solution_ready = kwargs.pop('solution_ready', False)
super(TestcaseForm, self).__init__(*args, **kwargs)
try:
self.testcaseId = kwargs['initial']['id']
except:
self.testcaseId = -1
self.fields['input_files'].widget=SecureFileInput(data_source_url='/assignments/testcase/input/download/' + str(self.testcaseId))
self.fields['output_files'].widget=SecureFileInput(data_source_url='/assignments/testcase/output/download/' + str(self.testcaseId))
def clean_input_files(self):
data = self.cleaned_data
# TODO: check if files are not tar it must be text file.
return data['input_files']
def clean_output_files(self):
# TODO: check if files are not tar it must be text file.
data = self.cleaned_data
return data['output_files']
def clean(self):
cleaned_data = super(TestcaseForm, self).clean()
if cleaned_data['marks'] is None: # cleaned_data['test_type'] == "Evaluate" and
self._errors['marks'] = self.error_class(['This field is required.'])
# if solution executable is not available make output file required.
if (not self.solution_ready) and cleaned_data['output_files'] is None:
self._errors['output_files'] = self.error_class(['Solution code for this assignment is not available/broken please upload output files.'])
return cleaned_data
class TestcaseForm2(forms.Form):
std_in_file_name = forms.ChoiceField(
label="Select File for Standard input",
widget=forms.RadioSelect(),
choices=((("None", "None"),)),
help_text="Content will be supplied as standard input."
)
std_out_file_name = forms.ChoiceField(
label="Select File for Standard output",
widget=forms.RadioSelect(),
choices=((("None", "None"),)),
help_text="File's content will used to compare standard output of program."
)
def __init__(self, *args, **kwargs):
in_file_name = kwargs.pop('in_file_choices', (("None", "None"),))
out_file_name = kwargs.pop('out_file_choices', (("None", "None"),))
kwargs['error_class'] = DivErrorList
super(TestcaseForm2, self).__init__(*args, **kwargs)
self.fields['std_in_file_name'].choices = in_file_name
self.fields['std_out_file_name'].choices = out_file_name
class SafeExecForm(forms.Form):
cpu_time = forms.IntegerField(label="CPU time", help_text='Default is 10 seconds.')
clock_time = forms.IntegerField(label="Clock time", help_text='Default is 60 seconds.')
memory = forms.IntegerField(label="Memory limit", help_text='Default is 32768 kbytes.')
stack_size = forms.IntegerField(label="Stack size limit", help_text='Default is 8192 kbytes.')
child_processes = forms.IntegerField(label="Number of child processes", help_text='Number of child processes it can create. Default is 0.')
open_files = forms.IntegerField(
label="Number of open files",
help_text='Number of files the program can open. Default value is 512. Do not set this too\
low otherwise program will not be able to open shared libraries.'
)
file_size = forms.IntegerField(label="Max file size", help_text='Maximum size of file the program can write. Default size is 0 kbytes.')
env_vars = forms.CharField(label="Environment variables", required=False)
class CheckerCodeForm(forms.Form):
name = forms.CharField()
execution_command = ExecutionCommand(help_text="Give the execution command in this textbox. Please note that the only language supported right now is Python.",
required=False)
checker_files = forms.FileField(
error_messages={'invalid': 'File was not a valid tar file.',},
label="Checker Code files",
help_text="Please upload the checker code here. Accepted archives are tar, tar.gz, tar.bz2, zip."
)
description = forms.CharField(required=False,widget=forms.Textarea)
def __init__(self, *args, **kwargs):
kwargs['error_class']=DivErrorList
super(CheckerCodeForm, self).__init__(*args, **kwargs)
try:
self.checkerId = kwargs['initial']['id']
except:
self.checkerId = -1
self.fields['checker_files'].widget=SecureFileInput(data_source_url='/assignments/checker/download/' + str(self.checkerId))
def check_execution_command(self, data):
execution_command = pickle.loads(data.get('execution_command'))
for afile in execution_command[2].split():
if not is_valid(filename=afile, interpreter=execution_command[0]):
self._errors['execution_command'] = self.error_class(["Only {1} files are accepted for {0} interpreter.\
".format(execution_command[0], " ".join(get_extension(execution_command[0])))])
del data['execution_command']
def check_checker_files(self, data):
self.__checker_file = []
if 'checker_files' in self.changed_data:
if data.get('checker_files', ""):
with Archive(fileobj=data['checker_files']) as archive:
if archive.is_archive():
self.__checker_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
if is_valid(filename=data['checker_files'].name, interpreter=pickle.loads(data['execution_command'])[0]):
self.__checker_file = [data['checker_files'].name]
else:
self._errors['checker_files'] = self.error_class(["This file was not valid."])
del data['checker_files']
else: # file is being deleted.
pass
else: # No change in file field. Check if file exist in database.
if not hasattr(self, 'checker_model'):
return # Assignment is created without model solution.
if not self.checker_model.checker_files: return # no file in database.
with Archive(fileobj=self.checker_model.checker_files.file) as archive:
if archive.is_archive():
self.__checker_file = [a.split("/")[-1] for a in archive.getfile_members()]
else:
if is_valid(filename=self.checker_model.checker_files.name, interpreter=pickle.loads(data['execution_command'])[0]):
self.__checker_file = [self.checker_model.checker_files.name.split("/")[-1]]
else:
file_name = self.checker_model.checker_files.name.split("/")[-1]
self._errors['checker_files'] = self.error_class(["File {0} is not valid. Please upload a valid file\
".format(file_name)])
del data['checker_files']
def clean(self):
cleaned_data = super(CheckerCodeForm, self).clean()
if self.errors: return cleaned_data
self.check_execution_command(cleaned_data)
if self._errors: return cleaned_data
self.check_checker_files(cleaned_data)
if self._errors: return cleaned_data
execution_command = pickle.loads(cleaned_data.get('execution_command'))
file_to_execute = set(execution_command[2].split())
missing_file = file_to_execute - set(self.__checker_file)
if missing_file:
self._errors['checker_files'] = self.error_class(["{0} is missing. It is one of the file in execution command".format(" ".join(missing_file))])
del cleaned_data['checker_files']
return cleaned_data
class AssignmentMetaForm(forms.Form):
meta_file = forms.FileField(
required=True,
label="Meta file",
help_text="Please upload the meta file (in JSON format) that explains the structure of the assignment archive. For reference example please look at the link given above."
)
assignment_archive = forms.FileField(
required=True,
label="Assignment Archive",
help_text="Please upload the assignment archive that follows the structure given in the above uploaded meta file. Accepted archives are tar, tar.gz, tar.bz2, zip."
)
def __init__(self, *args, **kwargs):
kwargs['error_class']=DivErrorList
super(AssignmentMetaForm, self).__init__(*args, **kwargs)
def date_time_format(self, deadline_str):
year = int(deadline_str.split()[0])
month = int(deadline_str.split()[1])
day = int(deadline_str.split()[2])
hour = int(deadline_str.split()[3].split(":")[0])
minute = int(deadline_str.split()[3].split(":")[1])
dateobj = DateTime.datetime(year,month,day,hour,minute)
return dateobj
def check_assignment(self, data, jsondata):
asgn_errors = []
error_flag = False
if jsondata["language"] not in LANGUAGES:
asgn_errors.append("language field can take values in {0}<br>".format(", ".join(LANGUAGES)))
error_flag = True
student_files = jsondata["student_files"].split()
language = jsondata["language"]
for afile in student_files:
if not is_valid(afile, language):
asgn_errors.append("Only {1} files are accepted for {0} language.<br>".format(language, " ".join(get_extension(language))))
error_flag = True
break
soft_deadline = self.date_time_format(jsondata["soft_deadline"])
hard_deadline = self.date_time_format(jsondata["hard_deadline"])
publish_date = self.date_time_format(jsondata["publish_date"])
if soft_deadline > hard_deadline:
asgn_errors.append("Hard deadline should be after soft deadline!")
error_flag = True
if soft_deadline < DateTime.datetime.now() or hard_deadline < DateTime.datetime.now():
asgn_errors.append("The deadlines should be later than the current time!")
error_flag = True
if publish_date > soft_deadline or publish_date > hard_deadline or publish_date < DateTime.datetime.now():
asgn_errors.append("The publish date should be before the deadlines and after the current time!")
error_flag = True
if error_flag:
self._errors['meta_file'] = self.error_class(asgn_errors)
'''
Here we are not checking if each of the below files in the assignment_archive are proper files (archives or individual files).
The meta file fields could as well mention the path to a folder and if the folder is present in the assignment_archive we proceed here
without popping errors.
But this scenario will break the code in the views functions when creating instances of the assignment, section and testcases in the database.
The same applies to the check_sections() function below.
'''
os.chdir(self.archive_dir)
if "solution_code" in jsondata:
solution_code = os.path.join(os.getcwd(),jsondata["solution_code"])
if not os.path.exists(solution_code):
asgn_errors.append("Solution code file path relative to the top of assignment archive is not correct!!")
else:
solution_code = None
if "helper_code" in jsondata:
helper_code = os.path.join(os.getcwd(),jsondata["helper_code"])
if not os.path.exists(helper_code):
asgn_errors.append("Helper code file path relative to the top of assignment archive is not correct!!")
if "documents" in jsondata:
documents = os.path.join(os.getcwd(),jsondata["documents"])
if not os.path.exists(documents):
asgn_errors.append("Documents file path relative to the top of assignment archive is not correct!!")
with Archive(name=solution_code) as archive:
if not archive.is_archive():
if not is_valid(filename=solution_code.split("/")[-1], lang=language):
asgn_errors.append("This file was not valid.")
del data['model_solution']
else:
self._solution_file = [solution_code.split("/")[-1]]
else:
self._solution_file = [a.split("/")[-1] for a in archive.getfile_members()]
def check_meta_file_structure(self, jsondata):
jsonschema = json.loads(meta_script_schema_str)
json_validator = Draft4Validator(jsonschema)
meta_errors = []
error_flag = False
for error in json_validator.iter_errors(jsondata):
meta_errors.append(str(error))
error_flag = True
if error_flag:
self._errors['meta_file'] = self.error_class(meta_errors)
def clean(self):
cleaned_data = super(AssignmentMetaForm, self).clean()
if self.errors: return cleaned_data
try:
jsondata = json.load(cleaned_data['meta_file'])
self.check_meta_file_structure(jsondata)
if self.errors: return cleaned_data
_,temp_file = tempfile.mkstemp(prefix="temp_dir", dir=os.getcwd())
dest_file = open(temp_file,"w")
for chunk in cleaned_data['assignment_archive'].chunks():
dest_file.write(chunk)
dest_file.close()
temp_dir = tempfile.mkdtemp(prefix="solution")
os.chdir(temp_dir)
extract_or_copy(src=temp_file, dest=os.getcwd())
next_dir = os.listdir(os.getcwd())
os.chdir(next_dir[0])
print os.listdir(os.getcwd())
self.archive_dir = os.getcwd()
'''
self.check_assignment(cleaned_data, jsondata)
if self.errors: return cleaned_data
self.check_sections(cleaned_data)
if self._errors: return cleaned_data
'''
except (ValueError, TypeError) as err:
self._errors['meta_file'] = self.error_class([err])
return cleaned_data<file_sep>/courseware/static/courseware/js/components/generic.jsx
/** @jsx React.DOM */
var GenericForm = React.createClass({
handleSave: function() {
//disable the save button
//this.refs.submit.getDOMNode().disable()
data = {
title: this.refs.title.getDOMNode().value.trim(),
description: this.refs.description.getDOMNode().value.trim()
};
this.props.saveCallBack(data);
},
render: function() {
return (
<div class="panel panel-default">
<div class="panel-heading">
{this.props.heading}
<span class="pull-right">
<button type="button" onClick={this.props.cancelCallBack} class="close">
×
</button>
</span>
</div>
<div class="panel-body">
<form role="form">
<div class="form-group">
<label class="control-label">Title</label>
<input name="title" type="text" class="form-control" ref="title" defaultValue={this.props.title} placeholder="Title"></input>
</div>
<div class="form-group">
<label class="control-label">Description</label>
<WmdTextarea class="form-control" rows="2" ref="description" defaultValue={this.props.description} placeholder="Add description here..." />
</div>
<div class="col-md-1 no-padding">
<button ref="submit" class="btn btn-primary" type="button" onClick={this.handleSave}>
Save
</button>
</div>
<div class="col-md-1">
<button type="button" onClick={this.props.cancelCallBack} class="btn btn-danger">
Cancel
</button>
</div>
</form>
</div>
</div>
);
}
});
var AddPageForm = React.createClass({
handleSave: function() {
//disable the save button
//this.refs.submit.getDOMNode().disable()
data = {
title: this.refs.title.getDOMNode().value.trim(),
description: this.refs.description.getDOMNode().value.trim()
};
this.props.saveCallBack(data);
},
render: function() {
return (
<div class="panel panel-default">
<div class="panel-heading">
{this.props.heading}
</div>
<div class="panel-body">
<form role="form">
<div class="form-group">
<label class="control-label">Title</label>
<input name="title" type="text" class="form-control" ref="title" placeholder="Title"></input>
</div>
<div class="form-group">
<label class="control-label">Description</label>
<WmdTextarea ref="description" placeholder="Add description here..." />
</div>
<br></br>
<div class="col-md-1 no-padding">
<button ref="submit" class="btn btn-primary" type="button" onClick={this.handleSave}>
Save
</button>
</div>
</form>
</div>
</div>
);
}
});
var validateDeleteBtn = React.createClass({
handleYes: function() {
$(".modal-backdrop").remove();
$("body").removeClass("modal-open");
this.props.callback();
},
render: function () {
return (
<div class="modal fade" id={this.props.modal} tabindex="-1" role="dialog" aria-labelledby={this.props.label} aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirm Deletion</h4>
</div>
<div class="modal-body">
Sure about deleting the {this.props.heading}?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No
</button>
<button type="button" data-dismiss="modal" onClick={this.handleYes} class="btn btn-danger">
Yes
</button>
</div>
</div>
</div>
</div>
);
}
});
var DeregisterModal = React.createClass({
handleYes: function() {
$("body").removeClass("modal-open");
$(".modal-backdrop").remove();
this.props.callback();
},
render: function () {
return (
<div class="modal fade" id={this.props.modal} tabindex="-1" role="dialog" aria-labelledby={this.props.label} aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirm unregistration</h4>
</div>
<div class="modal-body">
Sure about unregistering from {this.props.title}?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No
</button>
<button type="button" data-dismiss="modal" onClick={this.handleYes} class="btn btn-danger">
Yes
</button>
</div>
</div>
</div>
</div>
);
}
});
var CourseDeleteModal = React.createClass({
handleYes: function() {
$("body").removeClass("modal-open");
$(".modal-backdrop").remove();
this.props.callback();
},
render: function () {
return (
<div class="modal fade" id={this.props.modal} tabindex="-1" role="dialog" aria-labelledby={this.props.label} aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirm Deletion</h4>
</div>
<div class="modal-body">
Sure about deleting {this.props.title}?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No
</button>
<button type="button" data-dismiss="modal" onClick={this.handleYes} class="btn btn-danger">
Yes
</button>
</div>
</div>
</div>
</div>
);
}
});<file_sep>/quiz/static/quiz/js/quiz.jsx
/** @jsx React.DOM */
var Paginator = React.createClass({
setPage: function(event) {
element_a = $(event.target);
element_li = element_a.parent();
pos = element_li.index();
if (this.props.totalPages <= this.props.maxPages) {
this.props.callback(this.state.start + pos);
element_list = element_li.parent().children();
for(var i=0; i < element_list.length; i++) {
$(element_list[i]).removeClass('active');
}
$(element_li[0]).addClass('active');
}
else {
if (pos == 0) {
start_ = (this.state.start == 1) ? 1 : (this.state.start - 1);
end_ = start_ + this.props.maxPages - 1;
this.setState({start: start_, end: end_});
}
else if (pos == (this.props.maxPages + 1)) {
end_ = (this.state.end == this.props.totalPages) ? this.state.end : (this.state.end + 1);
start_ = end_ - this.props.maxPages + 1;
this.setState({start: start_, end: end_});
}
else {
this.props.callback(this.state.start + pos - 1);
element_list = element_li.parent().children();
for(var i=0; i < element_list.length; i++) {
$(element_list[i]).removeClass('active');
}
$(element_li[0]).addClass('active');
}
}
},
getInitialState: function() {
return {
start: 0,
end: 0
};
},
componentWillMount: function() {
start_ = 1;
end_ = this.props.totalPages > this.props.maxPages ?
this.props.maxPages :
this.props.totalPages;
this.setState({start: start_, end: end_});
},
render: function() {
// parameters:
// maxPages
// totalPages
// callback function
var prev;
var next;
if (this.props.totalPages > this.props.maxPages) {
prev = <li><a href="javascript:void(0);" refs="prev" onClick={this.setPage}>«</a></li>;
next = <li><a href="javascript:void(0);" refs="next" onClick={this.setPage}>»</a></li>;
}
pages = [];
for (var i = this.state.start; i <= this.state.end; i++) {
element = <li><a href="javascript:void(0);" refs={i} onClick={this.setPage}>{i}</a></li>;
pages[i-1] = element;
}
return (
<ul class="pagination">
{prev}
{pages}
{next}
</ul>
);
}
});
var QUESTION_TYPES = {
SINGLE_CHOICE_QUESTION: 'S',
MULTIPLE_CHOICE_QUESTION: 'M',
FIXED_ANSWER_QUESTION: 'F',
DESCRIPTIVE_ANSWER_QUESTION: 'D',
PROGRAMMING_QUESTION: 'P'
};
// FixedAnswerQuestion
var FixedAnswerQuestion = React.createClass({
disableSubmit: function() {
$(this.refs.submit.getDOMNode()).attr('disabled','disabled');
},
enableSubmit: function() {
$(this.refs.submit.getDOMNode()).removeAttr('disabled');
},
submitAnswer: function() {
answer = this.refs.answer.getDOMNode().value.trim();
if (answer == '') return;
this.disableSubmit();
this.props.submitCallback(answer, this.enableSubmit);
},
render: function() {
return (
<form role="form">
<div class="col-md-4 no-padding">
<div class="input-group">
<input type="text" class="form-control" ref="answer" placeholder="Answer" />
<span class="input-group-btn">
<button ref="submit" onClick={this.submitAnswer} class="btn btn-primary" type="button">Submit</button>
</span>
</div>
</div>
</form>
);
}
});
// SingleChoiceQuestion
//*
var SingleChoiceQuestion = React.createClass({
disableSubmit: function() {
$(this.refs.submit.getDOMNode()).attr('disabled','disabled');
},
enableSubmit: function() {
$(this.refs.submit.getDOMNode()).removeAttr('disabled');
},
submitAnswer: function() {
//answer = this.refs.option_group.getDOMNode().getElementById("options_" + this.props.id);
// TODO :temporary fix, figure out a way of doing using React
answer = $('input[name=options_'+this.props.id+']:checked').val();
console.log(answer)
if (answer == '') return;
this.disableSubmit();
this.props.submitCallback(answer, this.enableSubmit);
},
render: function() {
var group_name = "options_" + this.props.id
var options = jQuery.parseJSON(this.props.options);
var optionNodes = options.map(function(option, i) {
return <div class="radio"><label><input type="radio" name={group_name} value={i}>{option}</input></label></div>
});
return(
<form role="form" ref="option_group">
<div class="col-md-4 no-padding">
{optionNodes}
<button ref="submit" onClick={this.submitAnswer} class="btn btn-primary" type="button">Submit</button>
</div>
</form>
);
}
});
//*/
// MultipleChoiceQuestion
//*
var MultipleChoiceQuestion = React.createClass({
disableSubmit: function() {
$(this.refs.submit.getDOMNode()).attr('disabled','disabled');
},
enableSubmit: function() {
$(this.refs.submit.getDOMNode()).removeAttr('disabled');
},
submitAnswer: function() {
//answer = this.refs.option_group.getDOMNode().getElementById("options_" + this.props.id);
// TODO :temporary fix, figure out a way of doing using React
selected = $('input[name=options_'+this.props.id+']').map(function(node) {
return this.checked;
});
var options = jQuery.parseJSON(this.props.options);
answer = []
for (var i = 0; i < options.length; i++){
answer[i] = selected[i];
}
console.log(JSON.stringify(answer))
if (answer == '') return;
this.disableSubmit();
this.props.submitCallback(JSON.stringify(answer), this.enableSubmit);
},
render: function() {
var group_name = "options_" + this.props.id
var options = jQuery.parseJSON(this.props.options);
// console.log(options);
var optionNodes = options.map(function(option, i) {
return <div class="checkbox"><label><input type="checkbox" name={group_name}>{option}</input></label></div>
});
return(
<form role="form" ref="option_group">
<div class="col-md-4 no-padding">
{optionNodes}
<button ref="submit" onClick={this.submitAnswer} class="btn btn-primary" type="button">Submit</button>
</div>
</form>
);
}
});
//*/
var StatusBar = React.createClass({
mixins: [MathJaxMixin,],
getInitialState: function() {
show = true;
if (this.props.show != undefined) {
show = this.props.show;
}
return {
show: show
};
},
show: function() {
state = this.state;
state.show = true;
this.setState(state);
},
render: function() {
class_name = "alert alert-sm alert-" + this.props.type;
text = "";
bold_text = <strong>{this.props.bold_text}</strong>;
if (this.state.show) {
text = this.props.text;
}
else {
bold_text =
<a href="javascript:void(0)" class="link-normal-text" onClick={this.show}>
{bold_text}
</a>;
}
return (
<div class={class_name}>
{bold_text}
<br/>
<div class="muted">
<span dangerouslySetInnerHTML={{__html: text}} />
</div>
</div>
);
}
});
var Question = React.createClass({
mixins: [MathJaxMixin,],
base_url: "/quiz/api/",
loadHint: function() {
url = this.base_url + "question/" + this.props.data.id + "/get_hint/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState["hint"] = response;
this.setState(oldState);
}.bind(this));
},
loadAnswer: function() {
url = this.base_url + "question/" + this.props.data.id + "/get_answer/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState["answer"] = response;
this.setState(oldState);
}.bind(this));
},
submitAnswer: function(answer, callback) {
url = this.base_url + "question/" + this.props.data.id + "/submit_answer/?format=json";
request = ajax_json_request(url, "POST", {"answer": answer});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.data.attempts += 1;
oldState.data.marks = response.result;
if (response.status == 'D') { // correct answer
console.log('got correct answer')
oldState.answer = {};
if (response.is_correct) {
if (this.props.data.marks == 0) {
oldState.answer["bold_text"] = 'Did you get it right ?';
oldState.answer["text"] = '';
oldState.answer["type"] = 'info';
} else {
oldState.answer["bold_text"] = 'Correct!';
oldState.answer["text"] = response.answer;
oldState.answer["type"] = 'success';
}
}
else {
if (this.props.data.marks != 0) {
oldState.answer["bold_text"] = 'Wrong answer!';
oldState.answer["text"] = '';
oldState.answer["type"] = 'danger';
} else {
oldState.answer["bold_text"] = 'Did you get it right ?';
oldState.answer["text"] = '';
oldState.answer["type"] = 'info';
}
}
if (response.attempts_remaining == 0 || response.is_correct || this.props.data.marks == 0) {
oldState.answer["answer"] = response.answer;
oldState.answer["answer_description"] = response.answer_description;
prefix = "The correct answer is ";
if ((oldState.answer["answer"].length - 1) > 1) {
prefix = "The correct answer is ";
}
oldState.answer["text"] = prefix + response.answer;
}
oldState["showRefresh"] = false;
this.setState(oldState);
console.log('set the state')
}
else if (response.status == 'A') { // Awaiting results
oldState.answer = {};
oldState.answer["bold_text"] = 'Awaiting evaluation!';
oldState.answer["text"] = '';
oldState.answer["type"] = 'info';
oldState["showRefresh"] = true;
this.setState(oldState);
}
}.bind(this));
request.complete(function() {
if (callback != undefined) {
callback();
}
}.bind(this));
},
getInitialState: function() {
console.log(this.props.data);
state = {
data: {
attempts: this.props.data.user_attempts,
marks: this.props.data.user_marks,
},
status: this.props.data.user_status
};
if (this.props.data.answer_shown) {
state["answer"] = {
//text: "Already answered",
//type: "info",
answer: "" + this.props.data.answer,
answer_description: this.props.data.answer_description
};
}
if (this.props.data.hint_taken) {
state["hint"] = {
hint: this.props.data.hint
};
}
return state;
},
render: function() {
answer_box = <div></div>;
if (this.props.data.type == QUESTION_TYPES.FIXED_ANSWER_QUESTION) {
answer_box = <FixedAnswerQuestion submitCallback={this.submitAnswer}/>;
}
else if (this.props.data.type == QUESTION_TYPES.SINGLE_CHOICE_QUESTION){
answer_box = <SingleChoiceQuestion submitCallback={this.submitAnswer}
options={this.props.data.options} id={this.props.data.id}/>;
}
else if (this.props.data.type == QUESTION_TYPES.MULTIPLE_CHOICE_QUESTION){
answer_box = <MultipleChoiceQuestion submitCallback={this.submitAnswer}
options={this.props.data.options} id={this.props.data.id}/>;
}
answer_status = <div></div>;
answer_description = <div></div>;
hint = <div></div>;
hint_button = <div></div>;
// If there exists some status message for the answer then show it
// If there exists the answer_description then show it
if (this.state.answer != undefined && this.state.answer.text != undefined) {
if (this.state.answer.bold_text == undefined) this.state.answer.bold_text = '';
answer_status = <StatusBar type={this.state.answer.type} text={this.state.answer.text} bold_text={this.state.answer.bold_text} />;
if (this.state.answer.answer != undefined && this.state.answer.answer_description != undefined && this.state.answer.answer_description != null) {
answer_description = <StatusBar type="info" text={converter.makeHtml(this.state.answer.answer_description)} bold_text="Answer Description" />;
}
}
// If the answer has been shown, show the answer and the description
if (this.props.data.answer_shown) {
answer_status = <StatusBar show={false} type="success" text={this.state.answer.answer} bold_text="Answer" />
if(this.state.answer.answer_description != undefined && this.state.answer.answer_description != null) {
answer_description = <StatusBar show={false} type="info" text={converter.makeHtml(this.state.answer.answer_description)} bold_text="Answer Description" />;
}
}
if (this.state.hint != undefined && this.state.hint.hint != undefined) {
if (this.props.data.hint != undefined) {
hint = <StatusBar type="warning" text={this.state.hint.hint} bold_text="Hint" show={false} />;
}
else {
hint = <StatusBar type="warning" text={this.state.hint.hint} bold_text="Hint" />;
}
}
else if (this.props.data.is_hint_available) {
hint_button = <button type="button" class="btn btn-warning" onClick={this.loadHint} >Hint</button>
}
var _description = converter.makeHtml(this.props.data.description);
return (
<div class="question">
<div class="question-metadata quiz-text-mute">
{this.state.data.marks} / {this.props.data.marks} points
<div class="pull-right">
{this.state.data.attempts} / {this.props.data.attempts} attempts
</div>
</div>
<div class="question-text">
<span dangerouslySetInnerHTML={{__html: _description}} />
</div>
<div class="question-submit">
{answer_box}
<div class="pull-right">
{hint_button}
</div>
</div>
<div class="question-hint">
{hint}
</div>
<div class="question-status">
{answer_status}
{answer_description}
</div>
</div>
);
}
});
var QuestionModule = React.createClass({
mixins: [MathJaxMixin,],
base_url: "/quiz/api/",
loadQuestions: function(callback) {
url = this.base_url + "question_module/" + this.props.data.id + "/get_questions/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState["questions"] = response;
oldState["loaded"] = true;
this.setState(oldState);
if (callback != undefined) {
callback();
}
}.bind(this));
},
getInitialState: function() {
return {loaded: false};
},
render: function() {
if (!this.props.visible) {
return (<div></div>);
}
else if (!this.state.loaded) {
this.loadQuestions();
return (
<ul class="list-group">
<li class="list-group-item text-center">
<LoadingBar />
</li>
</ul>
);
}
questions = this.state.questions.map(function(q) {
return <li class="list-group-item"><Question data={q} /></li>;
});
var _title = converter.makeHtml(this.props.data.title);
var titlenode = null;
if (!this.props.data.dummy)
titlenode = (
<li class="list-group-item">
<span dangerouslySetInnerHTML={{__html: _title}} />
</li>
);
return (
<ul class="list-group">
{titlenode}
{questions}
</ul>
);
}
});
/*
Component : Quiz
*/
var Quiz = React.createClass({
base_url: "/quiz/api/",
setPage: function(action) {
oldState = this.state;
oldState.current = (action - 1);
this.setState(oldState);
},
loadQuiz: function() {
url = this.base_url + "quiz/" + this.props.id + "/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.data = response;
oldState.current = 0;
oldState.quiz_loaded = true;
if (this.state.questionModules != undefined) {
oldState.loaded = true;
}
else {
oldState.loaded = false;
}
this.setState(oldState);
}.bind(this));
},
loadQuestionModules: function() {
url = this.base_url + "quiz/" + this.props.id + "/get_question_modules/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
// Do NOT name it question_modules
oldState.questionModules = response;
oldState.loaded = true;
this.setState(oldState);
}.bind(this));
},
getInitialState: function() {
return {
loaded: false,
quiz_loaded: false,
current: undefined,
questionModules: undefined,
data: undefined
};
},
render: function() {
modules = null;
if (this.state.quiz_loaded) {
if (this.state.loaded) {
if(this.state.questionModules.length > this.state.current){
currentId = this.state.questionModules[this.state.current]["id"];
modules = this.state.questionModules.map(function(module) {
visible = false;
if (module.id == currentId) visible = true;
return (<QuestionModule data={module} visible={visible}/>);
}.bind(this));
}
}
else {
modules =
<div class="panel panel-default">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>;
this.loadQuestionModules();
}
var paginator = null;
if (this.state.data.question_modules > 1)
paginator = (
<div class="panel-body text-center">
<Paginator
totalPages={this.state.data.question_modules}
maxPages={15}
callback={this.setPage} />
</div>
);
return (
<div class="panel panel-default quiz-panel">
<div class="panel-heading">
<div class="col-md-4"> {this.state.data.title} </div>
<div class="pull-right">
Maximum points: {this.state.data.marks}
</div>
</div>
{paginator}
{modules}
</div>
);
}
else {
this.loadQuiz();
return (
<div class="panel panel-default quiz-panel">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>
);
}
}
});
//*
var QuizList = React.createClass({
base_url : "/quiz/api/",
loadQuizList: function() {
url = this.base_url + "quiz/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.quiz_list = response;
oldState.list_loaded = true;
this.setState(oldState);
}.bind(this));
},
getInitialState: function() {
return {
list_loaded: false,
quiz_list : []
}
},
render: function() {
if (this.state.list_loaded) {
var quizNodes = this.state.quiz_list.map(function(quiz) {
return <Quiz id={quiz.id} />
});
return (
<div>
{quizNodes}
</div>
)
}
else {
this.loadQuizList();
return(
<div>
<LoadingBar />
</div>
)
}
}
});
//*/
/*
React.renderComponent(
<QuizList />,
document.getElementById('quiz')
);
*/
var ConceptQuiz = React.createClass({
base_url: "/quiz/api/",
componentWillReceiveProps: function(nextProps) {
this.setState({
id: nextProps.id,
// loaded: false,
// quiz_loaded: false,
// current: undefined,
// questionModules: undefined,
// data: undefined
});
},
setPage: function(action) {
oldState = this.state;
oldState.current = (action - 1);
this.setState(oldState);
},
loadQuiz: function() {
url = this.base_url + "quiz/" + this.state.id + "/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.data = response;
oldState.current = 0;
oldState.quiz_loaded = true;
if (this.state.questionModules != undefined) {
oldState.loaded = true;
}
else {
oldState.loaded = false;
}
this.setState(oldState);
}.bind(this));
},
loadQuestionModules: function() {
url = this.base_url + "quiz/" + this.state.id + "/get_question_modules/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
// Do NOT name it question_modules
oldState.questionModules = response;
oldState.loaded = true;
this.setState(oldState);
}.bind(this));
},
getInitialState: function() {
return {
id: this.props.id,
loaded: false,
quiz_loaded: false,
current: undefined,
questionModules: undefined,
data: undefined
};
},
close: function(){
if (this.props.closeCallback) this.props.closeCallback();
},
render: function() {
modules = null;
if (this.state.quiz_loaded) {
if (this.state.loaded) {
if(this.state.questionModules.length > this.state.current){
currentId = this.state.questionModules[this.state.current]["id"];
modules = this.state.questionModules.map(function(module) {
visible = false;
if (module.id == currentId) visible = true;
return (<QuestionModule data={module} visible={visible}/>);
}.bind(this));
}
}
else {
modules =
<div class="panel panel-default">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>;
this.loadQuestionModules();
}
var paginator = null;
if (this.state.data.question_modules > 1)
paginator = (
<div class="panel-body text-center">
<Paginator
totalPages={this.state.data.question_modules}
maxPages={15}
callback={this.setPage} />
</div>
);
marksString = "Maximum points:" + this.state.data.marks;
close_button = "";
if (this.props.closeCallback) {
close_button = <button type="button"
class="btn btn-primary btn-sm"
onClick={this.close}>
Resume Video
</button>;
} else {
close_button = <button type="button"
class="btn btn-primary btn-sm"
onClick={this.close}>
Done
</button>;
}
return (
<div class="panel panel-default quiz-panel">
<div class="panel-heading" style={{"overflow":"auto"}}>
<div class="col-md-4"> {this.state.data.title} </div>
<div class="pull-right">
{this.props.inVideo ?
marksString :
close_button
}
</div>
</div>
{paginator}
{modules}
</div>
);
}
else {
this.loadQuiz();
return (
<div class="panel panel-default quiz-panel">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>
);
}
},
componentDidMount: function() {
$(this.getDOMNode()).hide().fadeIn();
$('html,body').animate({
scrollTop: $(this.getDOMNode()).offset().top - 60
}, 1000).bind(this);
}
});
<file_sep>/courseware/static/courseware/js/content_developer/my_textbooks.jsx
/** @jsx React.DOM */
var CourseCreate = React.createClass({
base_url: "/courseware/api/",
getInitialState: function() {
return {
category: undefined
};
},
handleCategoryChange: function(category) {
oldState = this.state;
oldState.category = category;
this.setState(oldState)
},
add_course: function() {
url = this.base_url + "course/?format=json";
var fd = new FormData();
fd.append('category', this.state.category);
fd.append('title', this.refs.title.getDOMNode().value.trim());
if(this.refs.image.getDOMNode().files[0]){
fd.append('image', this.refs.image.getDOMNode().files[0]);
}
request = ajax_custom_request({
url: url,
type: "POST",
data: fd,
mimeType: 'multipart/form-data',
});
request.done(function(response) {
response = jQuery.parseJSON(response);
window.location = "/courseware/course/" + response.id;
}.bind(this));
return false;
},
render: function() {
return (
<form id="addcourse" role="form" class="form-horizontal" enctype="multipart/form-data" ref="courseForm">
<fieldset>
<CategoryLoader callback={this.handleCategoryChange} />
<div class="form-group">
<label class="control-label col-md-2 col-md-offset-1">Title</label>
<div class="col-md-7 col-md-offset-1">
<input name="title" type="text" class="form-control" ref="title" placeholder="Title"></input>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-md-offset-1">Course Image</label>
<div class="col-md-7 col-md-offset-1">
<input name="image" type="file" class="form-control" ref="image"></input>
</div>
</div>
<div class="form-group">
<div class="col-md-2 col-md-offset-2 addcoursebutton">
<button ref="submit" class="btn btn-primary" type="button" onClick={this.add_course}>Add Course</button>
</div>
<div class="col-md-1">
<button type="button" onClick={this.props.closeCallBack} class="btn btn-danger">
Close
</button>
</div>
</div>
</fieldset>
</form>
);
}
});
var AddCourseForm = React.createClass({
closeCallBack: function() {
this.props.closeCallBack;
},
render: function() {
return (
<div class="panel panel-default">
<div class="panel-heading">
Add Course
<span class="pull-right">
<button type="button" onClick={this.props.closeCallBack} class="close">×</button>
</span>
</div>
<div class="panel-body">
<CourseCreate closeCallBack={this.props.closeCallBack}/>
</div>
</div>
);
}
});
var Concept = React.createClass({
loadConcepts: function() {
url = "/courseware/api/course/"+this.props.courseid+"/groups/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
this.setState({concepts: response, loaded: true});
}.bind(this));
},
getInitialState: function() {
return {
loaded: false,
concepts: undefined
};
},
componentDidMount: function() {
this.loadConcepts();
},
render: function(){
if(!this.state.loaded) {
return (
<LoadingBar />
);
}
else {
var concept = this.state.concepts.map(
function (concept_name) {
return <div class = "conceptname"> {concept_name.title} </div>;
}.bind(this));
return (
<div>
{concept}
</div>
);
}
}
});
var Course = React.createClass({
deleteCourse: function(){
url = "/courseware/api/course/" + this.props.course.id;
request = ajax_json_request(url, "DELETE", {});
request.done(function(response) {
display_global_message("The course was successfully deleted", "success");
$("#" + "course" + this.props.course.id).remove();
}.bind(this));
request.complete(function(response) {
if (response.status != 200) {
display_global_message("The course could not be deleted", "error");
}
}.bind(this));
},
setProgress: function() {
course = this.props.course;
var div = document.getElementById("pgbar" + course.id);
div.style.width = course.progress + "%";
},
showDelete: function(){
course = this.props.course;
if(course.is_published === true){
var div = document.getElementById("delete" + course.id);
div.style.visibility = 'hidden';
}
},
handleClicks: function(event){
element = $(event.target);
id = element.context.id;
if(id == "-1") {
window.location.href = "/courseware/course/" + this.props.course.id;
}
else if(id == "-2"){
window.location.href = "/courseware/course/" + this.props.course.id + "/-8";
}
else if(id == "-4"){
window.location.href = "/courseware/course/" + this.props.course.id;
}
else{
}
},
componentDidMount: function() {
this.setProgress();
this.showDelete();
$( "#accordion" ).accordion({
animate: 100,
collapsible: true,
heightStyle: "content"
});
},
render: function(){
course = this.props.course;
var progress = course.progress + "%"
var url = "/courseware/course/" + course.id;
var pgbarid = "pgbar" + course.id;
var start_msg = "";
var button_msg = "";
var label = "label" + course.id;
var modal = "modal" + course.id;
var mymodal = "#" + modal;
var courseid = "course" + course.id;
/** Only courses which have is_published = false would be shown the delele option **/
var deletediv = "delete" + course.id;
if(course.coursetag == 1){
start_msg = "Course Started : " + course.start_date;
button_msg = "Take Class";
}
else if(course.coursetag == 2){
start_msg = "Course Starts : " + course.start_date;
button_msg = "Prepare Class";
}
else {
start_msg = "Course Ended : " + course.end_date;
button_msg = "Take a tour";
}
var concepts = function () {
return <Concept courseid={course.id} />;
}.bind(this);
return (<li id={courseid} class = "myofferingBox">
<div >
<div class = "header row" >
<CourseDeleteModal label={label} modal={modal} title={course.title} callback={this.deleteCourse} />
<div class = "col-md-5 myofferingHeading">
IIT BOMBAY
</div>
<div class = "col-md-6">
<div class = "myofferingDate">
{start_msg}
</div>
</div>
<div id={deletediv} class = "col-md-1 myofferingDate">
<a data-toggle="modal" href={mymodal}>
<span class="glyphicon glyphicon-trash icon"></span>
</a>
</div>
</div>
<div class = "row myofferingTitle">
<a onClick ={this.handleClicks} id="-1"> {course.title}
</a>
</div>
<div class = "row myofferingActions">
<div class = "col-md-1 myschedule mycourseLink">
<a onClick ={this.handleClicks} id="-2"> Settings </a>
</div>
<div class = "col-md-2 col-md-offset-2">
<a onClick ={this.handleClicks} id="-4" class="btn btn-primary tool-tip mybtn">
{button_msg}
</a>
</div>
<div class = "col-md-5">
<div class = "mycourseProgress">
Course Progress
</div>
<div class="progress progress-striped pgdiv">
<div id = {pgbarid} class="progress-bar pgbar" role="progressbar"
aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
</div>
</div>
</div>
<div>
<div class = "row detailsrow">
<div class = "myconcepts col-md-5">
<div class = "concepts">
Groups
</div>
<div class = "conceptbox">
{concepts()}
</div>
</div>
<div class = "myofferingDetails col-md-5 col-md-offset-2">
<div >
<span class="glyphicon glyphicon-user"></span>
<a class = "detaillink"
href={"/courseware/course/" + this.props.course.id + "/-6"}>
Students </a>
</div>
<div>
<span class="glyphicon glyphicon-envelope"></span>
<a class = "detaillink" href= "" > News Feed
</a>
</div>
<div>
<span class="glyphicon glyphicon-globe"></span>
<a class = "detaillink" href= {"/courseware/course/" + this.props.course.id + "/-3"} > Discussion Forum
</a>
</div>
<div>
<span class="glyphicon glyphicon-book"></span>
<a class = "detaillink" href= {"/courseware/course/" + this.props.course.id + "/-4"} > Wiki
</a>
</div>
</div>
</div>
</div>
</li>
);
}
});
var MyCourseBody = React.createClass({
getInitialState: function() {
return {
loaded: false,
showform: false,
};
},
addcourseform: function() {
oldState = this.state;
oldState['showform'] = true;
this.setState(oldState);
},
closePanel: function() {
oldState = this.state;
oldState['showform'] = false;
this.setState(oldState);
},
componentDidMount: function() {
if (document.contains($("#accordion"))) {
$("#accordion").accordion("destroy");
$( "#accordion" ).accordion({
animate: 100,
collapsible: true,
heightStyle: "content"
});
}
},
render: function() {
courses = jQuery.parseJSON(this.props.courses);
var addcourseform =<div></div>
if(this.state.showform) {
addcourseform = <AddCourseForm closeCallBack={this.closePanel}/>;
}
if(courses == ""){
courses = (<div class="alert alert-danger alert-dismissable">No courses offered yet</div>);
}
else{
var courses = courses.map(
function (course) {
return <Course course={course} />;
}.bind(this));
}
return (<div>
<div id="courseBar" class="row coursebar">
<div class="col-md-8 offeringTitle offeringTitlemessage">
MY COURSES
</div>
<div class="col-md-4 offeringTitle ">
<button class="btn btn-primary addcourse-button pull-right" onClick={this.addcourseform}>
<span class="glyphicon glyphicon-plus-sign"></span>
Add Course
</button>
</div>
</div>
<div class = "courseContainer">
<div>
<div id="addcourseform">
{addcourseform}
</div>
<ul id="accordion">
{courses}
</ul>
</div>
</div>
</div>
);
}
});
<file_sep>/TestBed/Checker Code/naive.py
f = open("standardOutput_3",'r')
print f.read()
<file_sep>/courseware/urls.py
"""
URL Mapping for Courseware API
This is API for accessing course information
"""
from django.conf.urls import include, patterns, url
from rest_framework.routers import DefaultRouter
from courseware.viewsets.category import ParentCategoryViewSet, CategoryViewSet
from courseware.viewsets.course import CourseViewSet, CourseInfoViewSet, OfferingViewSet
from courseware.viewsets.group import GroupViewSet
from courseware.viewsets.vconcept import ConceptViewSet
from courseware import views
# Configuring ROUTERs
router = DefaultRouter()
router.register(r'parent_category', ParentCategoryViewSet)
router.register(r'category', CategoryViewSet)
router.register(r'course', CourseViewSet)
router.register(r'offering', OfferingViewSet)
router.register(r'courseinfo', CourseInfoViewSet)
router.register(r'group', GroupViewSet)
router.register(r'concept', ConceptViewSet)
router.register(r'all_courses', CourseViewSet)
urlpatterns = patterns(
'',
url(r'^api/', include(router.urls)),
url(r'^api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.parent_categories, name='parent_categories'),
url(r'^(?P<pk>[1-9][0-9]*)$', views.categories, name='categories'),
url(r'^category/(?P<pk>[1-9][0-9]*)$', views.courses, name='courses'),
url(r'^course/(?P<pk>[1-9][0-9]*)/(?P<ref>-?[0-9]*)$', views.course, name='course'),
url(r'^add_course', views.add_course, name='add_course'),
url(r'^pastcourses/', views.to_do, name="pastcourses"),
url(r'^courseslist/', views.mycourselist, name='mycourselist'),
url(r'^myofferings/', views.instructor_courses, name="myofferings"),
url(r'^mytextbooks/', views.content_developer_courses, name="mytextbooks"),
url(r'^mycourses/', views.student_courses, name='mycourses'),
url(r'^syllabus/(?P<pk>[1-9][0-9]*)$', views.syllabus, name='syllabus'),
url(r'^group/(?P<pk>[1-9][0-9]*)$',views.get_group,name='get_group')
)
<file_sep>/utils/archives.py
'''
This is the file containing functions related to archiving of files.
'''
import tarfile, zipfile
import os, shutil
# Function to find the XOR of 2 objects (true if exactly one of them is not null).
def xor(a, b):
return bool(a) != bool(b)
# Class that acts as an API for archived files. Uses the built-in tarfile and zipfile libraries to build a layer that acts as a common interface for
# both the file types. Functions of the class are self explanatory.
class Archive(object):
def __init__(self, name=None, fileobj=None):
if not xor(name, fileobj):
raise ValueError("Provide exactly one argument 'name' or 'fileobj' not both.")
self.name = name
self.fileobj = fileobj
try: # check for tarfile.
self.archive = tarfile.open(name=self.name, fileobj=self.fileobj)
self.filetype = "tar"
# following line is a workaround to for CRC check failed ERROR
[a.name for a in self.archive.getmembers()]
if fileobj:
fileobj.seek(0)
except tarfile.ReadError:
pass
try: # zipfile.
self.archive = zipfile.ZipFile(self.name or self.fileobj)
self.filetype = "zip"
except zipfile.BadZipfile:
pass
self.is_valid = hasattr(self, 'filetype')
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if hasattr(self, 'archive'):
self.archive.close() # method implemented by both zip and tar.
def is_archive(self):
return self.is_valid
def _get_tarmembers(self):
return [a.name for a in self.archive.getmembers()]
def _get_tarfiles(self):
return [a.name for a in self.archive.getmembers() if a.isfile()]
def _get_zipmembers(self):
return self.archive.namelist()
def _get_zipfiles(self):
return [a for a in self.archive.namelist() if not a[-1]=="/"]
def getfile_members(self):
return getattr(self, "_get_{0}files".format(self.filetype))()
def getall_members(self):
return getattr(self, "_get_{0}members".format(self.filetype))()
def open_file(self, name):
''' '''
if self.filetype == "tar":
return self.archive.extractfile(name)
if self.filetype == "zip":
return self.archive.open(name)
def extract(self, dest):
if self.filetype == "tar":
self.archive.extractall(path=dest)
if self.filetype == "zip":
self.archive.extractall(path=dest)
# Function to return the list of files present in the input arguments. An Archive object is created with the given arguments and then the functions of
# the Archive class are used to list the files present in the Archive object (individual file or an archived file).
def get_file_name_list(name=None, fileobj=None):
# returns name of file members of archive or file name only if not archive.
if not xor(name, fileobj):
raise ValueError("Provide exactly one argument 'name' or 'fileobj' not both.")
with Archive(name=name, fileobj=fileobj) as archive:
if archive.is_archive():
file_list = [a.split("/")[-1] for a in archive.getfile_members()]
else:
file_name = (fileobj.name if fileobj else name).split("/")[-1]
file_list = [file_name]
if fileobj:
fileobj.seek(0)
return file_list
# Function to copy/extract as is the case from the source directory to the destination directory.
# Takes as input the source and the destination paths. If the source is a single file then it is copied to the destination, else if the source path is
# an archive then it is extracted to the destination path.
def extract_or_copy(src, dest):
# Checking if src is valid path.
if not os.path.isfile(src):
raise ValueError("{0} is not a valid file.")
with Archive(name=src) as archive:
if archive.is_archive():
archive.extract(dest=dest)
else:
shutil.copy(src, dst=dest)
# Function to read a file from an archive/file.
# Takes as input the filename to be read, name of the file to be read from, and the file object of the file to be read from (either the name or the file
# object should be provided not both). If the file to be read from is a single file then the whole file is read. If it is an archive the file (given
# as readthis) is read from the archive file.
def read_file(readthis, name=None, fileobj=None):
if not xor(name, fileobj):
raise ValueError("Provide exactly one argument 'name' or 'fileobj' not both.")
lines = ""
with Archive(name=name, fileobj=fileobj) as archive:
if archive.is_archive():
lines = archive.open_file(readthis).readlines()
else:
if fileobj:
lines = fileobj.readlines()
else:
fobj = open(name)
lines = fobj.readlines()
fobj.close()
if fileobj:
fileobj.seek(0)
return lines
# Function to retrieve the files present in the filename/path given. If the input file is an archive then the files in the archive are returned.
# If the input file is a stand-alone file then it is returned.
# Takes as input the file name for which the file members are needed.
def archive_filepaths(name):
file_names = []
with Archive(name=name) as archive:
if archive.is_archive():
if archive.filetype == "tar":
file_names = archive._get_tarfiles()
if archive.filetype == "zip":
file_names = archive._get_zipfiles()
else:
file_names.append(name.split("/")[-1])
return file_names
# Function to copy/extract (as is the case) the file given in file_path from the source directory to the destination directory.
# Takes as input the source and the destination paths. If the source is a single file then it is copied to the destination, else if the source path is
# an archive then the file_path file is extracted to the destination path.
def extract_or_copy_singlefile(src, dest, file_path):
if not os.path.isfile(src):
raise ValueError("{0} is not a valid file.")
with Archive(name=src) as archive:
if archive.is_archive():
if archive.filetype == "tar":
member = archive.archive.getmember(file_path)
archive.archive.extract(member=member, path=dest)
if archive.filetype == "zip":
member = archive.archive.getinfo(file_path)
archive.archive.extract(member=member, path=dest)
else:
shutil.copy(src, dst=dest)
# Function to retrieve the ith element in the array a_list.
def get_element(a_list, i):
try:
return a_list[i]
except IndexError:
return ''
# Function to retrieve the missing files in an archive file given the list of required files.
# Takes as input the list of required files, and the file object in which the missing files in an archive file.
def get_missing_files(required_files, fileobj):
# Check if all required files are at level 1 in archive
file_list = []
with Archive(fileobj=fileobj) as archive:
if archive.is_archive():
print archive.getfile_members()
file_list = [a.split("/")[0] for a in archive.getfile_members()]
else:
file_name = (fileobj.name).split("/")[-1]
file_list = [file_name]
if fileobj:
fileobj.seek(0)
missing_files = set(required_files) - set(file_list)
# Return all files are found at level 1
if not missing_files:
return
# Check if all required files are at level 2 in archive
with Archive(fileobj=fileobj) as archive:
if archive.is_archive():
file_list = [get_element(a.split("/"), 1) for a in archive.getfile_members()]
else:
file_name = (fileobj.name).split("/")[-1]
file_list = [file_name]
if fileobj:
fileobj.seek(0)
# Return the missing files at the level 2.
return set(required_files) - set(file_list)<file_sep>/elearning_academy/__init__.py
"""
init file. Not being used currently
"""
<file_sep>/assignments/templatetags/assignmentTags.py
'''
Created on May 30, 2013
@author: aryaveer
'''
from django.template.defaultfilters import stringfilter
from django.utils.encoding import smart_str
from django.template.base import kwarg_re
#from django.utils.html import conditional_escape
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from django import template
import os, urllib
register = template.Library()
@register.filter
def getlen(value):
return len(value)
@register.filter
def getfilename(value):
return os.path.basename(value.name)
@register.filter
@stringfilter
def spacify(value):
result = ''
prev = None
for ch in value:
if ch == ' ' and (prev == ' ' or prev == '\n'):
result += " "
prev = ' '
elif ch == '\n':
result += "</br>"
prev = '\n'
else:
result += ch
prev = ''
return mark_safe(result)
'''if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(re.sub('\s', '&'+'nbsp;', esc(value)))'''
#spacify.needs_autoescape = True
@register.tag(name="urlwithgetparam")
def urlwithgetparam(parser, token):
bits = token.split_contents()
viewname = bits[1]
args = []
kwargs = {}
bits = bits[2:]
if len(bits):
for bit in bits:
match = kwarg_re.match(bit)
if not match:
raise Exception("Malformed arguments to url tag")
name, value = match.groups()
if name:
kwargs[name] = parser.compile_filter(value)
else:
args.append(parser.compile_filter(value))
return MyUrlNode(viewname, args, kwargs, legacy_view_name=True)
class MyUrlNode(template.Node):
def __init__(self, view_name, args, kwargs, legacy_view_name=True):
self.view_name = view_name
self.legacy_view_name = legacy_view_name
self.args = args
self.kwargs = kwargs
def render(self, context):
args = [arg.resolve(context) for arg in self.args]
kwargs = dict([(smart_str(k, 'ascii'), v.resolve(context))
for k, v in self.kwargs.items()])
view_name = self.view_name
if not self.legacy_view_name:
view_name = view_name.resolve(context)
url = reverse(view_name, args=args, current_app=context.current_app)
if not isinstance(kwargs['get_params'], dict):
raise Exception("get_params must be a dictionary")
return url + '?' + urllib.urlencode(kwargs['get_params'])<file_sep>/progress/static/progress/js/instructor/progress.jsx
/** @jsx React.DOM */
var SearchBarProgress = React.createClass({
getUrl: function() {
url = '/courseware/api/course/' + this.props.course + "/get_all_marks/?format=json&remote_id=" ;
return url;
},
searchForum: function() {
search_url = this.getUrl();
var search_str = this.refs.search.getDOMNode().value.trim();
search_str = encodeURIComponent(search_str);
this.props.load(search_url+ search_str +"&format=json");
return false;
},
render: function() {
return (
<form onSubmit={this.searchForum}>
<div class="input-group col-md-4">
<input type="text" ref="search" placeholder="Search here" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default" value="submit" type="button" onClick={this.searchForum}>
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
);
}
});
var StudentProgress = React.createClass({
getInitialState: function() {
return {
course: this.props.id,
id: this.props.student.id,
name: this.props.student.name,
user: this.props.student.user,
attempted_score: this.props.student.attempted_score,
score: this.props.student.score,
profileurl: '/user/view-profile/'+this.props.student.id,
groups: undefined,
loaded: false
};
},
componentWillReceiveProps: function(nextProps) {
this.setState({
course: nextProps.id,
id: nextProps.student.id,
name: nextProps.student.name,
user: nextProps.student.user,
profileurl: '/user/view-profile/' + nextProps.student.id,
attempted_score: nextProps.student.attempted_score,
score: nextProps.student.score,
groups: undefined,
loaded: false,
});
},
loadData: function(){
if(!this.state.loaded){
url = '/courseware/api/course/' + this.state.course + "/get_all_marks_student/?format=json&student=" + this.state.id;
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState = response;
oldState.loaded = true;
this.setState(oldState);
}.bind(this));
}
},
render: function() {
var progressgroups = null;
var profileurl = '/user/view-profile/'+this.props.student.id;
if(this.state.loaded){
progressgroups = this.state.groups.map(function (object) {
return <ProgressGroup group={object} course={this.state.course}/>;
});
}
return (
<div onClick={this.loadData} class='panel panel-default'>
<div class='panel-heading' data-toggle='collapse' data-parent="#studentmarks"
data-target={'#student-' + this.props.student.id}>
<div class="row panel-title">
<div class="col-md-3">
{this.props.student.user}
</div>
<div class="col-md-3">
<a href={profileurl}>{this.props.student.name}</a>
</div>
<div class="col-md-2 text-center">
<div class="row">
<div class="col-md-6">
{this.props.student.score}
</div>
<div class="col-md-6">
{this.props.student.attempted_score}
</div>
</div>
</div>
<div class="col-md-2 text-center">
<div class="row">
<div class="col-md-6">
{this.props.student.in_video_quiz_score}
</div>
<div class="col-md-6">
{this.props.student.in_video_quiz_attempted}
</div>
</div>
</div>
<div class="col-md-2 text-center">
<div class="row">
<div class="col-md-6">
{this.props.student.total_score}
</div>
<div class="col-md-6">
{this.props.student.total_attempted}
</div>
</div>
</div>
</div>
</div>
<div id={'student-'+this.props.student.id} class='panel-collapse collapse'>
<div class="panel-body">
<div class='panel-group'>
{progressgroups}
</div>
</div>
</div>
</div>
);
}
});
Progress = React.createClass({
mixins: [LoadMixin, SortableMixin],
dynamicSort: function(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var x = a[property];
var y = b[property];
if(isNaN(x)){
x = x.toLowerCase();
y = y.toLowerCase();
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}else{
x = +x;
y = +y;
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
},
sort: function(sortBy) {
var that = this;
return function(){
oldState = that.state;
if(oldState.sortBy == sortBy){
oldState.data.students.sort(that.dynamicSort("-" + sortBy));
oldState.sortBy = "-" + sortBy;
}
else{
oldState.data.students.sort(that.dynamicSort(sortBy));
oldState.sortBy = sortBy;
}
that.setState(oldState);
};
},
getFetchUrl: function(url){
var that = this;
data = '';
request = ajax_json_request(url, "GET", {});
oldState = this.state;
request.done(function(response) {
data = jQuery.parseJSON(response);
that.state.loaded = false;
oldState["studentmarks"] = data.students;//studentmarks;
oldState["max_score"] = data.max_score;
oldState.loaded = true;
oldState.show = true;
//console.log("DDD"+studentmarks)
this.setState(oldState);
}.bind(this));
},
getUrl: function(){
return '/courseware/api/course/' + this.props.course + '/get_all_marks/?format=json';
},
render: function() {
if (!this.state.loaded) {
return <LoadingBar />;
}
var that = this;
var max_score = this.state.data.max_score;
var studentmarks = this.state.data.students.map(function (object) {
return <StudentProgress student={object} id={that.props.course}/>;
});
var icon = {
name: null,
work: null,
score: null,
attempted_score: null,
in_video_quiz_score: null,
in_video_quiz_attempted: null,
total_score: null,
total_attempted: null
}
if(this.state.sortBy){
if(this.state.sortBy[0] == "-"){
icon[this.state.sortBy.substr(1)] = (<span class="glyphicon glyphicon glyphicon-chevron-down"></span>);
}
else{
icon[this.state.sortBy] = (<span class="glyphicon glyphicon glyphicon-chevron-up"></span>);
}
}
return (
<div class="row">
<h3>
Scorecard
</h3>
<h4>
Max Score: {max_score}
</h4>
<div class="row panel-heading">
<div class="col-md-3">
<a href="#" onClick = {this.sort("user")}> Roll No. </a>
{icon["user"]}
</div>
<div class="col-md-3">
<a href="#" onClick = {this.sort("name")}> Name </a>
{icon["name"]}
</div>
<div class="col-md-2 text-center">
<div class="row"> <a href="#" class="center">Out-Video Quiz</a></div>
<div class="row">
<div class="col-md-6">
<a href="#" onClick={this.sort("score")}>S</a>
{icon["score"]}
</div>
<div class="col-md-6">
<a href="#" onClick={this.sort("attempted_score")}>A</a>
{icon["attempted_score"]}
</div>
</div>
</div>
<div class="col-md-2 text-center">
<div class="row"> <a href="#" class="center">In-Video Quiz</a></div>
<div class="row">
<div class="col-md-6">
<a href="#" onClick={this.sort("in_video_quiz_score")}>S</a>
{icon["in_video_quiz_score"]}
</div>
<div class="col-md-6">
<a href="#" onClick={this.sort("in_video_quiz_attempted")}>A</a>
{icon["in_video_quiz_attempted"]}
</div>
</div>
</div>
<div class="col-md-2 text-center">
<div class="row"> <a href="#" class="center">Total</a></div>
<div class="row">
<div class="col-md-6">
<a href="#" onClick={this.sort("total_score")}>S</a>
{icon["total_score"]}
</div>
<div class="col-md-6">
<a href="#" onClick={this.sort("total_attempted")}>A</a>
{icon["total_attempted"]}
</div>
</div>
</div>
</div>
<div class='panel-group' id='studentmarks'>
{studentmarks}
</div>
</div>);
}
});
<file_sep>/courseware/static/courseware/js/mycourses.jsx
/** @jsx React.DOM */
/** Author : <NAME> **/
var Course = React.createClass({
unRegister: function() {
console.log("IN Unregister");
url = "/courseware/api/course/" + this.props.course.id + "/deregister";
request = ajax_json_request(url, "GET", {});
console.log("Asds");
request.done(function(response) {
console.log("ass");
display_global_message("The course was successfully unenrolled", "success");
$("#" + "course" + this.props.course.id).remove();
}.bind(this));
request.complete(function(response) {
console.log("ss")
if (response.status != 200) {
display_global_message("The course could not be unenrolled", "error");
}
}.bind(this));
},
setProgress: function() {
course = this.props.course;
var div = document.getElementById("pgbar" + course.id);
div.style.width = course.progress + "%";
if(course.coursetag == 2){
$('#' + "button" + course.id).attr("disabled", true);
}
},
showProgress: function() {
$('.mycourseProgress').tooltip({
show: {
effect: "slideDown",
delay: 250
}
});
},
componentDidMount: function() {
this.setProgress();
this.showProgress();
},
render: function(){
course = this.props.course;
var progress = course.progress + "%"
var url = "/courseware/course/" + course.id;
var buttonurl = "/courseware/course/" + course.id;
var pgbarid = "pgbar" + course.id;
var buttonid = "button" + course.id;
var label = "label" + course.id;
var modal = "modal" + course.id;
var courseid = "course" + course.id;
var mymodal = "#" + modal;
var start_msg = "";
var button_msg = "";
var is_disabled = "";
if(course.coursetag == 1){
start_msg = "Course Started : " + course.start_date;
button_msg = "Take Class";
}
else if(course.coursetag == 2){
start_msg = "Course Starts : " + course.start_date;
button_msg = "Take Class";
buttonurl = "";
}
else {
start_msg = "Course Ended : " + course.end_date;
buttonurl = "/courseware/course/" + course.id +"/grades";
button_msg = "View Grades";
}
return <div id={courseid} class = "row mycourseBox">
<div class = "row" >
<div class = "col-md-6 mycourseHeading">
IIT BOMBAY
</div>
<div class = "col-md-6">
<div class = "mycourseDate">
{start_msg}
</div>
</div>
</div>
<div class = "row mycourseTitle">
<a href= {url}> {course.title}
</a>
</div>
<div class = "row mycourseActions">
<DeregisterModal label={label} modal={modal} title={course.title} callback={this.unRegister} />
<div class = "col-md-1 mycourseLink">
<a data-toggle="modal" href={mymodal}> Unregister
</a>
</div>
<div class = "col-md-2 mycourseLink">
<a href =""> Course Information
</a>
</div>
<div class = "col-md-2 col-md-offset-1">
<a id = {buttonid} href={buttonurl} class="btn btn-primary tool-tip mybtn" data-original-title="" >
{button_msg}
</a>
</div>
<div class = "col-md-5">
<div title = {progress} class = "mycourseProgress">
Course Progress
</div>
<div class="progress progress-striped pgdiv">
<div id= {pgbarid} class="progress-bar pgbar" role="progressbar" aria-valuenow={progress} aria-valuemin="0" aria-valuemax="100">
</div>
</div>
</div>
</div>
</div>;
}
});
var MyCourseBody = React.createClass({
getInitialState: function() {
console.log("enter the dragon");
return {
loaded: false,
};
},
render: function() {
console.log(this.props.courses);
console.log("Hello");
courses = jQuery.parseJSON(this.props.courses);
console.log(courses);
if(courses == ""){
courses = (<div class="alert alert-danger alert-dismissable">No courses enrolled yet</div>);
}
else {
var courses = courses.map(
function (course) {
return <Course course={course} />;
}.bind(this));
}
return (
<div>
<div>
{courses}
</div>
</div>
);
}
});
<file_sep>/document/views.py
from django.shortcuts import get_object_or_404
from document.models import Document, Section
from document.serializers import DocumentSerializer, SectionSerializer, AddSectionSerializer
from courseware import playlist
from courseware.models import Course
from rest_framework import mixins, status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import action
# Create your views here.
class DocumentViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
model = Document
serializer_class = DocumentSerializer
def retrieve(self, request, pk=None, *args):
d = get_object_or_404(Document, pk=pk)
obj = d.to_dict()
return Response(obj)
def destroy(self, request, pk=None, *args):
document = get_object_or_404(Document, pk=pk)
_course = Course.objects.filter(pages__pk=pk)
if len(_course) > 0:
_course = _course[0]
_course.page_playlist = playlist.delete(_course.page_playlist,
pk=pk)
_course.save()
return super(DocumentViewSet, self).destroy(request, pk, *args)
@action(methods=['PATCH'], serializer_class=DocumentSerializer)
def reorder_sections(self, request, pk=None):
document = get_object_or_404(Document, pk=pk)
#self.check_object_permissions(request, _course)
myplaylist = request.DATA['playlist']
newplaylist = playlist.is_valid(myplaylist, document.playlist)
if newplaylist is not False:
document.playlist = newplaylist
document.save()
return Response(document.to_dict())
else:
content = "Given order data does not have the correct format"
return Response(content, status.HTTP_404_NOT_FOUND)
@action(methods=['POST'], serializer_class=AddSectionSerializer)
def add_section(self, request, pk=None):
document = get_object_or_404(Document, pk=pk)
serializer = AddSectionSerializer(data=request.DATA)
if serializer.is_valid():
if request.FILES and request.FILES['file']:
section = Section(
document=document,
title=serializer.data['title'],
description=serializer.data['description'],
file=request.FILES['file'])
else:
section = Section(
document=document,
title=serializer.data['title'],
description=serializer.data['description'])
section.save()
document.playlist = playlist.append(section.id, document.playlist)
document.save()
return Response(SectionSerializer(section).data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
class SectionViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
"""ViewSet for section class"""
model = Section
serializer_class = SectionSerializer
def partial_update(self, request, pk=None, *args):
if 'file' in request.DATA:
request.DATA.pop('file', None)
return super(SectionViewSet, self).partial_update(request, pk, *args)
def destroy(self, request, pk=None, *args):
section = get_object_or_404(Section, pk=pk)
document = section.document
document.playlist = playlist.delete(document.playlist, pk=pk)
document.save()
return super(SectionViewSet, self).destroy(request, pk, *args)
<file_sep>/elearning_academy/static/elearning_academy/js/components.jsx
/** @jsx React.DOM */
var WmdTextarea = React.createClass({
componentDidMount: function(root) {
$(root).wmd();
},
render: function() {
return this.transferPropsTo(
<textarea class="form-control wmd-input" />
)
}
});
var UserLink = React.createClass({
render: function() {
if(this.props.data == null) {
return (<span><strong>Anonymous</strong></span>);
}
return (
<a href={"/profile/" + this.props.data.username}>
<strong>
{this.props.data.first_name + ' ' + this.props.data.last_name}
</strong>
</a>
);
}
});
var DynamicDateTime = React.createClass({
//props: time(date-time format), refreshInterval(seconds)
getInitialState: function() {
var time = moment(new Date(this.props.time)).fromNow();
return {"time": time};
},
updateTime: function() {
var time = moment(new Date(this.props.time)).fromNow();
this.setState({"time": time});
},
componentDidMount: function() {
this.updateTime();
var intervalid = window.setInterval(this.updateTime, this.props.refreshInterval);
},
componentWillUnMount: function() {
//window.clearInterval(this.state.intervalid);
},
render: function() {
return (
<span>{this.state.time}</span>
)
}
});
var LoadingBar = React.createClass({
render: function() {
return (
<div class="progress progress-striped active">
<div class="progress-bar loading-bar" role="progressbar">
Loading ...
</div>
</div>
)
}
});
/* Ajax Image Uploader
Props:
url: URL to which the image should be sent
showProgress: Boolean to indicate if a progress bar should be shown
noBackgroundTransition: Boolean, if this is set to true, then there
are no background transitions based on the saved status
BackTransitionColors: Pass an object of the following form:
{
'saved': '#color1'.
'saving': '#color2'.
'unsaved': '#color3'
}
These will be used for background transitions (see BackgroundTransitionMixin)
*/
var ImageUploader = React.createClass({
mixins: [SavedStatusMixin, BackgroundTransitionMixin, StyleTransitionMixin],
getInitialState: function() {
return {
image: this.props.image
};
},
getDefaultProps: function() {
return {
showProgress: true,
BackgroundTransitionColors: {},
noBackgroundTransition: false,
name: 'image',
isFile: false
};
},
showProgressBar: function() {
if (this.props.showProgress)
this.refs.imageUploadProgressBar.getDOMNode().style.display = 'block';
},
hideProgressBar: function() {
if (this.props.showProgress){
this.refs.imageUploadProgressBar.getDOMNode().style.display = 'none';
this.refs.imageUploadProgress.getDOMNode().style.width = 0;
}
},
progressHandlingFunction: function(event) {
if (this.props.showProgress)
if(event.lengthComputable){
percent = 100*(event.loaded/event.total)+"%";
this.refs.imageUploadProgress.getDOMNode().style.width = percent;
}
},
changeImage: function() {
var getExtension = function (filename) {
var parts = filename.split('.');
return parts[parts.length - 1];
};
var isImage = function (filename) {
var ext = getExtension(filename);
switch (ext.toLowerCase()) {
case 'jpg':
case 'gif':
case 'bmp':
case 'png':
return true;
}
return false;
};
var formData = new FormData(this.refs.imageForm.getDOMNode());
if (!this.props.isFile){
if(!isImage(this.refs.imageUploadInput.getDOMNode().files[0].name)) {
display_global_message("Invalid File Format", "error");
$(this.refs.resetImageUploader.getDOMNode()).click();
return false;
}
}
ajax_custom_request({
url: this.props.url,
type: 'PATCH',
data: formData,
beforeSend: function(xhr, settings){
this.toSaving();
this.showProgressBar();
}.bind(this),
success: function(response){
if (this.props.isFile){
this.setState({image: response[this.props.name]});
}
else{
this.setState({image: '/media/' + response[this.props.name]});
}
this.toSaved();
setTimeout(function(){
this.hideProgressBar();
$(this.refs.resetImageUploader.getDOMNode()).click();
}.bind(this), 1000);
}.bind(this),
error: function(xhr, textStatus, errorThrown){
msg = "Unable to upload image";
if (xhr.responseText) msg += " - " + jQuery.parseJSON(xhr.responseText).detail;
display_global_message(msg , "error");
this.hideProgressBar();
this.toUnsaved();
}.bind(this),
progressFunction: this.progressHandlingFunction
});
},
onSavedStatusUpdate: function() {
if (this.isSaved() && this.props.changeCallback)
this.changeCallback(this.state.image);
},
render: function() {
saveBtnClass = this.selectBySavedStatus({
'saved': 'btn-success disabled',
'saving': 'btn-primary disabled',
'unsaved': 'btn-primary'
});
saveBtnText = this.selectBySavedStatus({
'saved': 'Saved',
'saving': 'Saving..',
'unsaved': 'Save'
})
return(
<div style={this.getBackgroundTransitionStyle(
this.props.BackgroundTransitionColors,
this.props.noBackgroundTransition)} >
<form enctype="multipart/form-data" ref="imageForm">
<div class="fileinput fileinput-new image-upload-box" data-provides="fileinput">
<div class="fileinput-new thumbnail">
{this.props.isFile ?
<a href={this.state.image} target="_blank">Slides</a>
: <img src={this.state.image}
alt="Unable to display image" />
}
</div>
<div class="fileinput-preview fileinput-exists thumbnail">
</div>
<div>
<span class="btn btn-primary btn-file">
<span class="fileinput-new">Change</span>
<span class="fileinput-exists">Change</span>
<input type="file" name={this.props.name}
ref="imageUploadInput"
onChange={this.toUnsaved} />
</span>
<button type="button" class="btn btn-danger fileinput-new">
Remove
</button>
<button type="button" class={"btn fileinput-exists " + saveBtnClass}
onClick={this.changeImage} >
{saveBtnText}
</button>
<button type="button" class="btn btn-warning fileinput-exists"
data-dismiss="fileinput" ref="resetImageUploader"
onClick={this.toSaved}>
Revert
</button>
</div>
{this.props.showProgress ?
<div class="progress fileinput-exists" ref="imageUploadProgressBar" style={{display: "none"}}>
<div class="progress-bar progress-bar-success" role="progressbar" ref="imageUploadProgress" style={{width: 0}}>
<span class="sr-only">60% Complete</span>
</div>
</div>
: null }
</div>
</form>
</div>
);
}
});
<file_sep>/discussion_forum/models.py
"""
Contains overall database schema for Discussion Forum
"""
#from django.contrib.auth.models import User
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from model_utils.managers import InheritanceManager
from util.models import HitCounter, TimeKeeper, Subscription
# Length for CharField
SHORT_TEXT = 255
LONG_TEXT = 1023
BADGE_CHOICES = (
('CT', 'Course Staff'),
('IN', 'Instructor'),
('MO', 'Moderator'),
('ST', 'Student'),
('TA', 'Teaching Assistant'),
('AN', 'Anonymous')
)
class ActivityOperation:
""" Meta attributes for Activity.operation """
add = "add"
delete = "delete"
edit = "edit"
update = "update"
upvote = "upvote"
downvote = "downvote"
spam = "spam"
class ActivityObject:
""" Meta attributes for Activity.object_type """
thread = "thread"
comment = "comment"
reply = "reply"
def get_user_info(user):
""" Returns user information in dictionary object """
ret = {"username": user.username}
ret["first_name"] = user.first_name
ret["last_name"] = user.last_name
ret["id"] = user.pk
return ret
class DiscussionForum(TimeKeeper):
"""
Main root object for a particular discussion forum.
Each offering/course will have OneToOne relationship with \
this forum object
"""
thread_count = models.IntegerField(default=0)
abuse_threshold = models.IntegerField(
default=5,
help_text="Maximum abuse count after which content will be \
marked as Spam"
)
review_threshold = models.IntegerField(
default=2,
help_text="Abuse count after which content will be displayed for \
moderator's review"
)
def tags(self):
""" Returns all tags associated with self """
return list(Tag.objects.filter(forum=self))
def register(self, user):
""" Register user for the forum if user is not enrolled """
obj, created = UserSetting.objects.get_or_create(forum=self, user=user)
obj.save()
def unregister(self, user):
""" UnRegister user from the current forum """
obj, created = UserSetting.objects.get_or_create(forum=self, user=user)
obj.delete()
class Tag(models.Model):
""" Tag corresponding to a forum """
forum = models.ForeignKey(DiscussionForum, related_name='Forum_Tag')
title = models.CharField(
max_length=SHORT_TEXT,
help_text="Title for Tag for display. Should be unique for Course"
)
tag_name = models.CharField(
max_length=SHORT_TEXT,
help_text="Alias for above title in lowercase satisfying \
regular_expression='[a-z0-9_-]+.' Should be unique for Course"
)
# This is to distinguish tags which are generated by Admin and the ones
# which are generated automatically.
# auto_generated tags can't be deleted or modified by admin
auto_generated = models.BooleanField(default=True)
# Each Learning Element will have a OneToOne relationship with this
# Class and forum will be same as of corresponding Course/Offering
class Meta: # pylint: disable=W0232, C0111
unique_together = ("forum", "tag_name")
class UserSetting(TimeKeeper):
"""
This class stores user settings for a particular Forum
"""
user = models.ForeignKey(User, related_name="UserSetting_User")
forum = models.ForeignKey(
DiscussionForum,
related_name="UserSetting_Forum"
)
# To check whether the user is still registered in the forum or not
is_active = models.BooleanField(default=True)
# Email subscription for daily forum activity
email_digest = models.BooleanField(default=True)
# Provide administration privileges. Can make changes on moderator \
# user control and
super_user = models.BooleanField(default=False)
# Moderation privileges over forum. Can delete post/comment
moderator = models.BooleanField(default=False)
# Current badge of user will be embedded with content generated by user
badge = models.CharField(
max_length=2,
choices=BADGE_CHOICES,
default='ST'
)
class Meta:
""" Specifying index and primary key property """
unique_together = ('user', 'forum')
index_together = [
['user', 'forum'],
]
class Activity(models.Model):
"""
Stores activity of forum. Aimed to retrieve the activity happened in a \
particular time period
"""
forum = models.ForeignKey(
DiscussionForum,
db_index=True,
related_name="forum_activity"
)
actor = models.ForeignKey(
User,
db_index=True,
related_name='user_activity'
)
happened_at = models.DateTimeField(auto_now_add=True, db_index=True)
operation = models.CharField(max_length=32) # add/delete/like/edit
object_type = models.CharField(max_length=32) # post/thread/reply
object_id = models.IntegerField(default=0) # primary key of object
@staticmethod
def activity(
forum=None,
user=None,
operation=None,
object_type=None,
object_id=None):
""" Generate a new activity record """
act = Activity(
forum=forum,
actor=user,
operation=operation,
object_type=object_type,
object_id=object_id
)
act.save()
# TODO: Function for activity of specified time till now
# TODO: Wrapper function for activity of last day, week and month
class Content(TimeKeeper, HitCounter):
"""
Abstracted class used for storing common content related information \
generated by user
Votable Functionality included within for performance issues
"""
forum = models.ForeignKey(DiscussionForum, related_name="Content_Forum")
author = models.ForeignKey(User, related_name="Content_User")
children_count = models.IntegerField(default=0)
# The badge of author at the creation time of this content. Badge of \
# author may change but this will remain same
author_badge = models.CharField(max_length=2, choices=BADGE_CHOICES)
content = models.TextField()
pinned = models.BooleanField(default=False) # Only moderator has access
anonymous = models.BooleanField(default=False) # Posted as Anonymous ?
# If many people mark this content as Spam then content will be disabled\
# and will be listed for moderator's action
disabled = models.BooleanField(default=False)
spam_count = models.IntegerField(default=0)
# Indexed for efficient sorting on colum
upvotes = models.IntegerField(default=0, db_index=True)
downvotes = models.IntegerField(default=0, db_index=True)
# upvotes-downvotes
popularity = models.IntegerField(default=0, db_index=True)
# Helps in selecting subclasses directly
objects = InheritanceManager()
class Meta:
""" Meta attributes for this class """
abstract = False
def mark_spam(self, user):
"""
Check if user has already marked Spam or not and mark accordingly.
Returns True if spamming for the first time.
Returns False if already marked spam
"""
vote, created = Vote.objects.get_or_create(content=self, user=user)
if vote.spam_moderated:
# If spam flag was moderated. You can't operate again
return
if vote.spam:
# If already marked spam. Clear the spam
vote.spam = False
self.spam_count -= 1
else:
vote.spam = True
self.spam_count += 1
vote.save()
self.save()
def reset_spam_flags(self):
"""
Resets spam counter and mark all spam flag's moderation to True
"""
spammers = Vote.objects.filter(content=self, spam=True)
spammers.update(spam_moderated=True)
self.spam_count = 0
self.save()
def vote_up(self, user):
"""
Voting is like toggle button. Voting twice will clear your vote
"""
vote, created = Vote.objects.get_or_create(content=self, user=user)
if vote.downvote:
# If downvoted
vote.upvote = True
vote.downvote = False
self.upvotes += 1
self.downvotes -= 1
elif vote.upvote:
vote.upvote = False
self.upvotes -= 1
else:
vote.upvote = True
self.upvotes += 1
self.popularity = self.upvotes - self.downvotes
vote.save()
self.save()
def vote_down(self, user):
"""
Voting is like toggle button. Voting twice will clear your vote
"""
vote, created = Vote.objects.get_or_create(content=self, user=user)
if vote.upvote:
# If downvoted
vote.downvote = True
vote.upvote = False
self.downvotes += 1
self.upvotes -= 1
elif vote.downvote:
vote.downvote = False
self.downvotes -= 1
else:
vote.downvote = True
self.downvotes += 1
self.popularity = self.upvotes - self.downvotes
vote.save()
self.save()
def pre_delete(self):
""" Dummy function """
print "Dummy content delete"
def get_author(self):
""" Returns none if anonymous is True else returns author object """
if self.anonymous:
return None
else:
return get_user_info(self.author)
class Thread(Content):
""" Thread for a discussion Forum """
title = models.CharField(max_length=SHORT_TEXT)
# Tags
tags = models.ManyToManyField(Tag, related_name="thread_tags")
subscription = models.OneToOneField(
Subscription,
related_name="thread_subscribers"
)
def save(self, *args, **kwargs):
""" overriding save method """
if self.pk is None:
subscription = Subscription()
subscription.save()
self.subscription = subscription
super(Thread, self).save(*args, **kwargs)
class Comment(Content):
""" Comment class for discussion forum """
thread = models.ForeignKey(Thread, related_name="Comment_Thread")
class Reply(Content):
""" Reply class for discussion forum """
# Used for directly getting parent of parent for reply
thread = models.ForeignKey(Thread, related_name="Thread_Reply")
comment = models.ForeignKey(Comment, related_name="Reply_Comment")
class Vote(models.Model):
"""
Table for storing vote and spam for specific content by specific user
"""
user = models.ForeignKey(User, related_name="vote_user", db_index=True)
content = models.ForeignKey(Content, related_name="vote_content",
db_index=True)
upvote = models.BooleanField(default=False)
downvote = models.BooleanField(default=False)
# spam_moderated will be enabled once moderated approve the spammed \
# content and User spam flag won't count toward spam count then onwards
spam = models.BooleanField(default=False, db_index=True)
spam_moderated = models.BooleanField(default=False)
class Meta:
""" Meta """
unique_together = ("user", "content")
class Notification(TimeKeeper):
""" Table for storing notifications. This class/interface may change """
subscription = models.ForeignKey(Subscription)
notif_type = models.CharField(
max_length=32,
help_text="Help in grouping of notifications later on"
)
# Notification related info, link, users, reply/comment/thread object \
# as appropriate
info = models.TextField()
is_processed = models.BooleanField(default=False)
@receiver(pre_delete, sender=Thread)
def update_thread_counter(sender, **kwargs):
""" Decrease thread count by 1 """
instance = kwargs['instance']
instance.forum.thread_count -= 1
instance.forum.save()
@receiver(pre_delete, sender=Comment)
def update_comment_counter(sender, **kwargs):
""" Decrease thread count by 1 """
instance = kwargs['instance']
instance.thread.children_count -= 1
instance.thread.save()
@receiver(pre_delete, sender=Reply)
def update_reply_counter(sender, **kwargs):
""" Decrease thread count by 1 """
instance = kwargs['instance']
instance.comment.children_count -= 1
instance.comment.save()
<file_sep>/discussion_forum/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'DiscussionForum'
db.create_table(u'discussion_forum_discussionforum', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)),
('thread_count', self.gf('django.db.models.fields.IntegerField')(default=0)),
('abuse_threshold', self.gf('django.db.models.fields.IntegerField')(default=5)),
('review_threshold', self.gf('django.db.models.fields.IntegerField')(default=2)),
))
db.send_create_signal(u'discussion_forum', ['DiscussionForum'])
# Adding model 'Tag'
db.create_table(u'discussion_forum_tag', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('forum', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Forum_Tag', to=orm['discussion_forum.DiscussionForum'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('tag_name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('auto_generated', self.gf('django.db.models.fields.BooleanField')(default=True)),
))
db.send_create_signal(u'discussion_forum', ['Tag'])
# Adding unique constraint on 'Tag', fields ['forum', 'tag_name']
db.create_unique(u'discussion_forum_tag', ['forum_id', 'tag_name'])
# Adding model 'UserSetting'
db.create_table(u'discussion_forum_usersetting', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='UserSetting_User', to=orm['auth.User'])),
('forum', self.gf('django.db.models.fields.related.ForeignKey')(related_name='UserSetting_Forum', to=orm['discussion_forum.DiscussionForum'])),
('is_active', self.gf('django.db.models.fields.BooleanField')(default=True)),
('email_digest', self.gf('django.db.models.fields.BooleanField')(default=True)),
('super_user', self.gf('django.db.models.fields.BooleanField')(default=False)),
('moderator', self.gf('django.db.models.fields.BooleanField')(default=False)),
('badge', self.gf('django.db.models.fields.CharField')(default='ST', max_length=2)),
))
db.send_create_signal(u'discussion_forum', ['UserSetting'])
# Adding unique constraint on 'UserSetting', fields ['user', 'forum']
db.create_unique(u'discussion_forum_usersetting', ['user_id', 'forum_id'])
# Adding index on 'UserSetting', fields ['user', 'forum']
db.create_index(u'discussion_forum_usersetting', ['user_id', 'forum_id'])
# Adding model 'Activity'
db.create_table(u'discussion_forum_activity', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('forum', self.gf('django.db.models.fields.related.ForeignKey')(related_name='forum_activity', to=orm['discussion_forum.DiscussionForum'])),
('actor', self.gf('django.db.models.fields.related.ForeignKey')(related_name='user_activity', to=orm['auth.User'])),
('happened_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
('operation', self.gf('django.db.models.fields.CharField')(max_length=32)),
('object_type', self.gf('django.db.models.fields.CharField')(max_length=32)),
('object_id', self.gf('django.db.models.fields.IntegerField')(default=0)),
))
db.send_create_signal(u'discussion_forum', ['Activity'])
# Adding model 'Content'
db.create_table(u'discussion_forum_content', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)),
('hit_count', self.gf('django.db.models.fields.IntegerField')(default=0)),
('forum', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Content_Forum', to=orm['discussion_forum.DiscussionForum'])),
('author', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Content_User', to=orm['auth.User'])),
('children_count', self.gf('django.db.models.fields.IntegerField')(default=0)),
('author_badge', self.gf('django.db.models.fields.CharField')(max_length=2)),
('content', self.gf('django.db.models.fields.TextField')()),
('pinned', self.gf('django.db.models.fields.BooleanField')(default=False)),
('anonymous', self.gf('django.db.models.fields.BooleanField')(default=False)),
('disabled', self.gf('django.db.models.fields.BooleanField')(default=False)),
('spam_count', self.gf('django.db.models.fields.IntegerField')(default=0)),
('upvotes', self.gf('django.db.models.fields.IntegerField')(default=0, db_index=True)),
('downvotes', self.gf('django.db.models.fields.IntegerField')(default=0, db_index=True)),
('popularity', self.gf('django.db.models.fields.IntegerField')(default=0, db_index=True)),
))
db.send_create_signal(u'discussion_forum', ['Content'])
# Adding model 'Thread'
db.create_table(u'discussion_forum_thread', (
(u'content_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['discussion_forum.Content'], unique=True, primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('subscription', self.gf('django.db.models.fields.related.OneToOneField')(related_name='thread_subscribers', unique=True, to=orm['util.Subscription'])),
))
db.send_create_signal(u'discussion_forum', ['Thread'])
# Adding M2M table for field tags on 'Thread'
m2m_table_name = db.shorten_name(u'discussion_forum_thread_tags')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('thread', models.ForeignKey(orm[u'discussion_forum.thread'], null=False)),
('tag', models.ForeignKey(orm[u'discussion_forum.tag'], null=False))
))
db.create_unique(m2m_table_name, ['thread_id', 'tag_id'])
# Adding model 'Comment'
db.create_table(u'discussion_forum_comment', (
(u'content_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['discussion_forum.Content'], unique=True, primary_key=True)),
('thread', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Comment_Thread', to=orm['discussion_forum.Thread'])),
))
db.send_create_signal(u'discussion_forum', ['Comment'])
# Adding model 'Reply'
db.create_table(u'discussion_forum_reply', (
(u'content_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['discussion_forum.Content'], unique=True, primary_key=True)),
('thread', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Thread_Reply', to=orm['discussion_forum.Thread'])),
('comment', self.gf('django.db.models.fields.related.ForeignKey')(related_name='Reply_Comment', to=orm['discussion_forum.Comment'])),
))
db.send_create_signal(u'discussion_forum', ['Reply'])
# Adding model 'Vote'
db.create_table(u'discussion_forum_vote', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='vote_user', to=orm['auth.User'])),
('content', self.gf('django.db.models.fields.related.ForeignKey')(related_name='vote_content', to=orm['discussion_forum.Content'])),
('upvote', self.gf('django.db.models.fields.BooleanField')(default=False)),
('downvote', self.gf('django.db.models.fields.BooleanField')(default=False)),
('spam', self.gf('django.db.models.fields.BooleanField')(default=False, db_index=True)),
('spam_moderated', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal(u'discussion_forum', ['Vote'])
# Adding unique constraint on 'Vote', fields ['user', 'content']
db.create_unique(u'discussion_forum_vote', ['user_id', 'content_id'])
# Adding model 'Notification'
db.create_table(u'discussion_forum_notification', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)),
('subscription', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['util.Subscription'])),
('notif_type', self.gf('django.db.models.fields.CharField')(max_length=32)),
('info', self.gf('django.db.models.fields.TextField')()),
('is_processed', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal(u'discussion_forum', ['Notification'])
def backwards(self, orm):
# Removing unique constraint on 'Vote', fields ['user', 'content']
db.delete_unique(u'discussion_forum_vote', ['user_id', 'content_id'])
# Removing index on 'UserSetting', fields ['user', 'forum']
db.delete_index(u'discussion_forum_usersetting', ['user_id', 'forum_id'])
# Removing unique constraint on 'UserSetting', fields ['user', 'forum']
db.delete_unique(u'discussion_forum_usersetting', ['user_id', 'forum_id'])
# Removing unique constraint on 'Tag', fields ['forum', 'tag_name']
db.delete_unique(u'discussion_forum_tag', ['forum_id', 'tag_name'])
# Deleting model 'DiscussionForum'
db.delete_table(u'discussion_forum_discussionforum')
# Deleting model 'Tag'
db.delete_table(u'discussion_forum_tag')
# Deleting model 'UserSetting'
db.delete_table(u'discussion_forum_usersetting')
# Deleting model 'Activity'
db.delete_table(u'discussion_forum_activity')
# Deleting model 'Content'
db.delete_table(u'discussion_forum_content')
# Deleting model 'Thread'
db.delete_table(u'discussion_forum_thread')
# Removing M2M table for field tags on 'Thread'
db.delete_table(db.shorten_name(u'discussion_forum_thread_tags'))
# Deleting model 'Comment'
db.delete_table(u'discussion_forum_comment')
# Deleting model 'Reply'
db.delete_table(u'discussion_forum_reply')
# Deleting model 'Vote'
db.delete_table(u'discussion_forum_vote')
# Deleting model 'Notification'
db.delete_table(u'discussion_forum_notification')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('<PASSWORD>', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'discussion_forum.activity': {
'Meta': {'object_name': 'Activity'},
'actor': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_activity'", 'to': u"orm['auth.User']"}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'forum_activity'", 'to': u"orm['discussion_forum.DiscussionForum']"}),
'happened_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'object_type': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'operation': ('django.db.models.fields.CharField', [], {'max_length': '32'})
},
u'discussion_forum.comment': {
'Meta': {'object_name': 'Comment', '_ormbases': [u'discussion_forum.Content']},
u'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['discussion_forum.Content']", 'unique': 'True', 'primary_key': 'True'}),
'thread': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Comment_Thread'", 'to': u"orm['discussion_forum.Thread']"})
},
u'discussion_forum.content': {
'Meta': {'object_name': 'Content'},
'anonymous': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Content_User'", 'to': u"orm['auth.User']"}),
'author_badge': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
'children_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'content': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'disabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'downvotes': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Content_Forum'", 'to': u"orm['discussion_forum.DiscussionForum']"}),
'hit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'pinned': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'popularity': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'}),
'spam_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'upvotes': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'})
},
u'discussion_forum.discussionforum': {
'Meta': {'object_name': 'DiscussionForum'},
'abuse_threshold': ('django.db.models.fields.IntegerField', [], {'default': '5'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'review_threshold': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'thread_count': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'discussion_forum.notification': {
'Meta': {'object_name': 'Notification'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'info': ('django.db.models.fields.TextField', [], {}),
'is_processed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'notif_type': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'subscription': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['util.Subscription']"})
},
u'discussion_forum.reply': {
'Meta': {'object_name': 'Reply', '_ormbases': [u'discussion_forum.Content']},
'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Reply_Comment'", 'to': u"orm['discussion_forum.Comment']"}),
u'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['discussion_forum.Content']", 'unique': 'True', 'primary_key': 'True'}),
'thread': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Thread_Reply'", 'to': u"orm['discussion_forum.Thread']"})
},
u'discussion_forum.tag': {
'Meta': {'unique_together': "(('forum', 'tag_name'),)", 'object_name': 'Tag'},
'auto_generated': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Forum_Tag'", 'to': u"orm['discussion_forum.DiscussionForum']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'tag_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'discussion_forum.thread': {
'Meta': {'object_name': 'Thread', '_ormbases': [u'discussion_forum.Content']},
u'content_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['discussion_forum.Content']", 'unique': 'True', 'primary_key': 'True'}),
'subscription': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'thread_subscribers'", 'unique': 'True', 'to': u"orm['util.Subscription']"}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'thread_tags'", 'symmetrical': 'False', 'to': u"orm['discussion_forum.Tag']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'discussion_forum.usersetting': {
'Meta': {'unique_together': "(('user', 'forum'),)", 'object_name': 'UserSetting', 'index_together': "[['user', 'forum']]"},
'badge': ('django.db.models.fields.CharField', [], {'default': "'ST'", 'max_length': '2'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'email_digest': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'UserSetting_Forum'", 'to': u"orm['discussion_forum.DiscussionForum']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'moderator': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'super_user': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'UserSetting_User'", 'to': u"orm['auth.User']"})
},
u'discussion_forum.vote': {
'Meta': {'unique_together': "(('user', 'content'),)", 'object_name': 'Vote'},
'content': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'vote_content'", 'to': u"orm['discussion_forum.Content']"}),
'downvote': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'spam': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'spam_moderated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'upvote': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'vote_user'", 'to': u"orm['auth.User']"})
},
u'util.subscription': {
'Meta': {'object_name': 'Subscription'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'users': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'subscribers'", 'symmetrical': 'False', 'to': u"orm['auth.User']"})
}
}
complete_apps = ['discussion_forum']<file_sep>/concept/models.py
""" Models related to concept """
from django.db import models
# Create your models here.
from quiz.models import Quiz
from django.contrib.auth.models import User
from courseware.models import Document
class ConceptQuizHistory(models.Model):
"""
Class for ConceptQuizHistory
"""
quiz = models.ForeignKey(Quiz)
user = models.ForeignKey(User, db_index=True)
seen_status = models.BooleanField(default=False)
times_seen = models.IntegerField(default=0)
class ConceptDocumentHistory(models.Model):
"""
Class for ConceptDocumentHistory
"""
document = models.ForeignKey(Document)
user = models.ForeignKey(User, db_index=True)
seen_status = models.BooleanField(default=False)
times_seen = models.IntegerField(default=0)
<file_sep>/assignments/signals.py
'''
This file is not being used currently.
'''
from elearning_academy.settings import MEDIA_ROOT
from evaluate.utils.executor import CommandExecutor
import os, tarfile, shutil
rootPath = os.path.realpath(os.path.dirname(__file__))
tmpDir = os.path.join(rootPath, "tmp")
# Compile model solution
def compile_model_solution(sender, instance, **kwargs):
# If source file was not changed no need to re-compile.
if not hasattr(instance, 'source_changed'):
return
if not kwargs.get('created'):
print "Not created!"
programFilePath = instance.program_files.name
ModelSolutionPath = instance.model_solution.name
# Model Solution was not provided hence do nothing.
if os.path.isdir(ModelSolutionPath):
return
os.chdir(tmpDir)
extractFile(os.path.join(MEDIA_ROOT, ModelSolutionPath), tmpDir)
# Change directory if solution tar contains a directory.
if os.path.isdir(os.listdir('./')[0]):
os.chdir(os.listdir('./')[0])
currentDir = os.getcwd()
extractFile(os.path.join(MEDIA_ROOT, programFilePath), currentDir)
# Setting up compilation and creating CommandExecutor
executor = CommandExecutor(timeout=5)
command = get_compilation_command(instance)
compileResult = executor.executeCommand(command=command)
# Update output files on success
if compileResult.returnCode == 0:
instance.UpdateOutput()
cleanUp()
# Delete all content of testDir.
def cleanUp():
os.chdir(tmpDir)
for item in os.listdir(os.getcwd()):
if os.path.isfile(item): os.remove(item)
if os.path.isdir(item): shutil.rmtree(item)
# Extracts the compressed file.
def extractFile(src, dest):
tar = tarfile.open(src)
tar.extractall(path=dest)
tar.close()
<file_sep>/assignments/assignments_utils/meta_script_schema.py
meta_script_schema_str="{\
\"$schema\": \"http://json-schema.org/draft-04/schema#\",\
\"title\": \"Meta File - Assignment Upload\",\
\"description\": \"Meta File for assignment script upload\",\
\"type\": \"object\",\
\"properties\": {\
\"assignment_name\": {\
\"description\": \"Name of the assignment\",\
\"type\": \"string\"\
},\
\"soft_deadline\": {\
\"description\": \"Soft Deadline of the assignment\",\
\"type\": \"string\",\
\"pattern\": \"^[0-9]{4} [0-9]{2} [0-9]{2} [0-9]{2}:[0-9]{2}\"\
},\
\"hard_deadline\": {\
\"description\": \"Hard Deadline of the assignment\",\
\"type\": \"string\",\
\"pattern\": \"^[0-9]{4} [0-9]{2} [0-9]{2} [0-9]{2}:[0-9]{2}\"\
},\
\"late_submission\": {\
\"description\": \"Late submission allowed or not\",\
\"type\": \"string\",\
\"pattern\":\"^(Yes|No)\"\
},\
\"language\": {\
\"description\": \"Language of the assignment\",\
\"type\": \"string\"\
},\
\"student_files\": {\
\"description\": \"Student files to be submitted\",\
\"type\": \"string\"\
},\
\"documents\": {\
\"description\": \"Documents related to the assignment\",\
\"type\": \"string\"\
},\
\"helper_code\": {\
\"description\": \"Helper code for the assignment\",\
\"type\": \"string\"\
},\
\"solution_code\": {\
\"description\": \"Solution code for the assignment\",\
\"type\": \"string\"\
},\
\"publish_date\": {\
\"description\": \"Publish Date of the assignment\",\
\"type\": \"string\",\
\"pattern\": \"^[0-9]{4} [0-9]{2} [0-9]{2} [0-9]{2}:[0-9]{2}\"\
},\
\"asgn_description\": {\
\"description\": \"Description of the assignment\",\
\"type\": \"string\"\
},\
\"sections\": {\
\"type\": \"array\",\
\"items\": {\
\"type\": \"object\",\
\"properties\": {\
\"section_name\": {\
\"description\": \"Name of the section\",\
\"type\": \"string\"\
},\
\"section_type\": {\
\"description\": \"Type of section\",\
\"type\": \"string\",\
\"pattern\":\"^(Evaluate|Practice)\"\
},\
\"compilation_command\": {\
\"description\": \"Compilation command if any.\",\
\"type\": \"array\",\
\"items\":{\"type\":\"string\"},\
\"minItems\":3,\
\"maxItems\":3\
},\
\"execution_command\": {\
\"description\": \"Execution command if any.\",\
\"type\": \"array\",\
\"items\":{\"type\":\"string\"},\
\"minItems\":3,\
\"maxItems\":3\
},\
\"section_files\": {\
\"description\": \"Section files if any.\",\
\"type\": \"string\"\
},\
\"sec_description\": {\
\"description\": \"Description of the section\",\
\"type\": \"string\"\
},\
\"testcases\": {\
\"type\": \"array\",\
\"items\": {\
\"type\": \"object\",\
\"properties\": {\
\"testcase_name\": {\
\"description\": \"Name of the testcase\",\
\"type\": \"string\"\
},\
\"command_line_args\": {\
\"description\": \"Command line arguments of the testcase\",\
\"type\": \"string\"\
},\
\"marks\": {\
\"type\": \"integer\",\
\"minimum\": 0,\
\"exclusiveMinimum\": true\
},\
\"input_files\": {\
\"description\": \"Input file archive\",\
\"type\": \"string\"\
},\
\"output_files\": {\
\"description\": \"Output file archive\",\
\"type\": \"string\"\
},\
\"std_in_file_name\": {\
\"description\": \"Input file name\",\
\"type\": \"string\"\
},\
\"std_out_file_name\": {\
\"description\": \"Output file name\",\
\"type\": \"string\"\
},\
\"test_description\": {\
\"description\": \"Description of the section\",\
\"type\": \"string\"\
}\
},\
\"required\": [\"testcase_name\"]\
},\
\"minItems\": 1\
}\
},\
\"required\": [\"section_name\", \"section_type\"]\
},\
\"minItems\": 1\
}\
},\
\"required\": [\"assignment_name\", \"soft_deadline\", \"hard_deadline\", \"late_submission\", \"language\", \"student_files\", \"publish_date\", \"asgn_description\"]\
}"<file_sep>/download/urls.py
'''
Created on Feb 27, 2014
@author: aryaveer
'''
from django.conf.urls import patterns, url
urlpatterns = patterns('download.views',
url(r'^downloadall/(?P<assignmentID>\d+)$', 'download_all_zipped', name='download_download_all_zipped'),
url(r'^assignment/data/(?P<assignmentID>\d+)$', 'download_assignment_files', name='download_downloadassignmentfiles'),
)<file_sep>/util/methods.py
"""
Util methods
"""
def get_subclasses(classes, level=0):
"""
Return the list of all subclasses given class (or list of classes) has.
"""
# for convenience, only one class can can be accepted as argument
# converting to list if this is the case
if not isinstance(classes, list):
classes = [classes]
if level < len(classes):
classes += classes[level].__subclasses__()
return get_subclasses(classes, level + 1)
else:
return classes
def receiver_subclasses(signal, sender, dispatch_uid_prefix, **kwargs):
"""
A decorator for connecting receivers and all receiver's subclasses to
signals.
Used by passing in the signal and keyword arguments to connect::
@receiver_subclasses(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
"""
def _decorator(func):
all_senders = get_subclasses(sender)
for snd in all_senders:
signal.connect(
func,
sender=snd,
dispatch_uid=dispatch_uid_prefix + '_' + snd.__name__,
**kwargs)
return func
return _decorator
<file_sep>/scripts/create_accounts.py
#!/usr/bin/python
"""
Script to create user accounts given CSV
"""
import csv
import sys
import requests
__URL__ = "http://10.102.56.95:8080/accounts/api/register/"
def create_accounts(file_location):
reader = csv.DictReader(open(file_location, 'rb'), delimiter='\t')
for record in reader:
data = {'first_name': record['firstname'],
'last_name': record['lastname'],
'username': record['email'],
'email': record['email'],
'password': '<PASSWORD>',
'remoteid': record['remotecentername'],
'mobile': record['mobile'],
'city': record['city'],
'remotecentrename': record['remotecentername']
}
req = requests.post(__URL__, data=data)
if int(req.status_code)==201 or int(req.status_code)==200:
print "SUCCESS processing record", record
else:
print "ERROR", record, req.text
if __name__ == "__main__":
create_accounts(sys.argv[1])
<file_sep>/utils/filetypes.py
# File containing the Meta interface to add new languages.
# Please do not change any original code. To add new languages please follow the instruction given in the comments below and the documentation.
import os, pickle
'''
This is the array containing the languages supported by the system. To add a new language just add the name of the language to this array.
Once that is done, please read up the comments for each of the arrays below, add make suitable additions.
'''
LANGUAGES = [
'C++',
'C',
'Java',
'Python',
'Bash',
'NS2',
'Others',
]
'''
This is the array containing the languages the need compilation. If your language is a compiled language, then add it here. Please note that
the name should be the same as added in the LANGUAGES array.
'''
COMPILED_LANGUAGES = ['C',
'C++',
'Java',
]
'''
This is the array containing the languages that are just interpreted. If your language is an interpreted language, then add it here. Please note that
the name should be the same as added in the LANGUAGES array.
NOTE: Languages that compile to a binary file (C/C++) need not be added here.
'''
INTERPRETED_LANGUAGES = ['Python',
'Bash',
'Java',
'NS2',
]
'''
This is the array containing the non compiled and interpreted languages-Kartik
'''
NONE_LANGUAGES = ['Others']
'''
This is the dictionary that maps the languages to the compilers used to compile them. If your language is a compiled language, then add the language
name and the compiler to be used here. Please note that the name of the language should be the same as added in the LANGUAGES array.
NOTE: The compiler should be installed on the system running the server.
'''
COMPILERS = {
'C++': 'g++',
'C': 'gcc',
'Java': 'javac',
}
'''
This is the dictionary that maps the interpreted languages to the interpreters used to interpret them. If your language is an interpreted language,
then add the language name and the interpeter to be used here. Please note that the name of the language should be the same as added in the LANGUAGES
array.
NOTE: The interpreter should be installed on the system running the server.
NOTE: For compiled languages, add the interpreter used to interpret the byte/object code. If the final object code is in the form of a binary file,
the dont add anything (Ex: C/C++).
'''
INTERPRETERS = {
'Java' : 'java',
'Python': 'python',
'Bash': 'bash',
'NS2' : 'ns',
}
NONE = {'Others' : 'other'}
'''
This is the dictionary that maps the compiler names to the list of file extensions that the compilers recognizes/are valid. If your language is a
compiled language, then add the compiler name and the list of valid extensions. Please note that the name of the compiler should be the same as added
in the COMPILERS dictionary.
NOTE: When creating assignments, the solution files to be uploaded are cross checked with this list. So please ensure that you have covered all valid
extensions.
'''
VALID_EXTENSIONS_COMPILERS = {
'g++': ['.cpp', '.h', '.hpp'],
'gcc': ['.c', '.h'],
'javac': ['.java'],
}
'''
This is the dictionary that maps the interpreter names to the list of file extensions that the interpreter recognizes/are valid. If your language is a
interpreted language, then add the interpreter name and the list of valid extensions. Please note that the name of the interpreter should be the same
as added in the INTERPRETERS dictionary.
NOTE: When creating assignments, the extensions of the solution files to be uploaded are cross checked with this list. So please ensure that you have
covered all valid extensions.
'''
VALID_EXTENSIONS_INTERPRETERS = {
'java': ['.class', '.java', '.jar', ''],
'python': ['.py'],
'bash': ['.sh'],
'ns': ['.tcl'],
}
'''
For None languages
'''
VALID_EXTENSIONS_NONE = {
'other':['','.tar','.tgz','.tar.gz','.c','.h','.hpp','.cpp','.java','.jar','.class','.py','.sh','.txt','.zip','.html','.htm','.css','.tar.bz2','.jpg','.s','.gz','.rar','.7z']
}
'''
This is the dictionary that maps the language names to the list of file extensions of the intermediate file created during the
compilation/interpretation process. Add the language name and the list of valid extensions. Please note that the name of the laugnage should be the same
as added in the LANGUAGES array.
NOTE: This array is used to find the intermediate files (by their extensions) to delete them and isolate the output files. Please add all possible extensions.
'''
INTERMEDIATE_FILES_EXTENSIONS = {
'C':['.exe'],
'C++': ['.exe'],
'Java': ['.class', '.jar'],
'Python': ['.pyc'],
'Bash':[],
'NS2' : ['.nam', '.tr'],
'Others':[],
}
'''
This is the dictionary that maps the topic of the readme to be rendered to the link at which the readme html file is present.
'''
README_LINKS = {
'CHECKER':'assignments/readmeChecker.html',
'METAINTERFACE':'assignments/readmeAssignmentMetaInterface.html'
}
# Function to find if a language needs compilation or not. Checks the COMPILED_LANGUAGES array to find out the same.
# Takes as input the language name as given in the LANGUAGES array.
def compile_required(language):
if language in COMPILED_LANGUAGES:
return True
else:
return False
'''
Function to find if the execution process needs to retrieve execution command from the database or not. While adding a new language, make sure
to add the condition for the new language as needed.
'''
# Takes as input the language name as given in the LANGUAGES array.
def execution_command_required(language):
if language == 'C' or language == 'C++' or language=='Others':
return False
else:
return True
# Function to retrieve compiler used to compile the language. Make sure that every compiled language has an entry in the COMPILERS dictionary.
# Takes as input the language name as given in the LANGUAGES array.
def get_compiler_name(lang):
return COMPILERS[lang]
# Function to retrieve interpreter used to interpret the language. Make sure that every interpreted language has an entry in the INTERPRETERS
# dictionary. In case the object code is a binary file then no need to add anything to the INTERPRETERS dictionary.
# Takes as input the language name as given in the LANGUAGES array.
def get_interpreter_name(lang):
return INTERPRETERS[lang]
def get_language(software):
for a in COMPILERS.keys():
if COMPILERS[a] == software:
return a
for a in INTERPRETERS.keys():
if INTERPRETERS[a] == software:
return a
for a in NONE.keys():
if NONE[a] == software:
return a
# Function to retrieve file extensions that are recognized by the compiler and the interpreter of the language. This function is called to cross
# check the files to be uploaded as solution code with the supported extensions for the language.
# Takes as input the language name as given in the LANGUAGES array or the compiler/interpreter for the language.
def get_extension(lang):
if lang not in LANGUAGES:
lang = get_language(lang)
extensions = []
if lang in COMPILED_LANGUAGES:
extensions += VALID_EXTENSIONS_COMPILERS[get_compiler_name(lang)]
if lang in INTERPRETED_LANGUAGES:
extensions += VALID_EXTENSIONS_INTERPRETERS[get_interpreter_name(lang)]
if lang in NONE_LANGUAGES:
extensions += VALID_EXTENSIONS_NONE['other']
return extensions
# Function retrieve the language category of the language given as input. The categories are as follows.
# 0 - Languages which do not need execution command to be given by the user. The execution command is constructed according to the language
# Ex: C/C++ uses the executable name as the execution command.
# 1 - Language which needs the compilation and interpreter command to be given by the user. Languages like Java.
# 2 - Language which needs only the execution command to be given by the user. The language either does not compile or the compilation command is
# constructed implicitly.
def language_category(lang):
if lang == 'C' or lang == 'C++' or lang == 'Others':
return 0
elif lang in COMPILED_LANGUAGES:
return 1
elif lang in INTERPRETED_LANGUAGES:
return 2
# Function to check if the given filename is valid for the given compiler/interpreter. It uses the VALID_EXTENSIONS_* arrays do the same.
# NOTE: Only 2 of language, compiler and interpreter are supposed to given as arguments.
# Takes as input the filename, language of the assignment, compiler to be used and the interpreter to be used.
def is_valid(filename, lang=None, compiler=None, interpreter=None):
if lang and compiler:
raise ValueError("Provide exactly one arguments 'lang' or 'compiler'. Provided both.")
if lang and interpreter:
raise ValueError("Provide exactly one arguments 'lang' or 'interpreter'. Provided both.")
if interpreter and compiler:
raise ValueError("Provide exactly one arguments 'compiler' or 'interpreter'. Provided both.")
if lang:
extensions = get_extension(lang)
if compiler:
extensions = VALID_EXTENSIONS_COMPILERS[compiler]
if interpreter:
extensions = VALID_EXTENSIONS_INTERPRETERS[interpreter]
_, ext = os.path.splitext(filename)
return (ext in extensions) # Returns True OR False
# Function to get the compilation command of the program/section. For C/C++, the function returns the command that creates the appropriate executable.
# For the rest of the languages the function returns the compilation command as given when creating the section if the language needs to be compiled.
# Otherwise the function returns an empty string.
# Takes as input the section/program object for which the compilation command is needed.
def get_compilation_command(program):
if program.language == 'C' or program.language == 'C++':
return " ".join(pickle.loads(program.compiler_command)) + " -o " + "exe_" + str(program.id)
elif program.compiler_command:
return " ".join(pickle.loads(program.compiler_command))
else:
return ""
# Function to get the execution command of the program/section. For C/C++, the function returns the command as executing the binary file.
# For the rest of the languages the function returns the execution command as given when creating the section.
# Takes as input the section/program object for which the execution command is needed.
def get_execution_command(program):
if program.language == 'C' or program.language == 'C++':
return "./" + "exe_" + str(program.id)
elif program.language in INTERPRETED_LANGUAGES:
return " ".join(pickle.loads(program.execution_command))
else:
return ""
# Function to check if the given filename is an intermediate file w.r.t to the language.
# Takes as input the filename to be checked, the section of which the file belongs to (needed for check on binary files), and the language
# of the assignment (as given in the LANGUAGE array).
def is_intermediate_files(filename, program, language):
if program.language == 'C' or program.language == 'C++':
return (filename == "exe_"+ str(program.id))
else:
_, ext = os.path.splitext(filename)
return (ext in INTERMEDIATE_FILES_EXTENSIONS[language])
# Function to retrieve the files used in the interpreter command.
# Takes as input the section/program whose files are needed.
def get_execution_command_files(program):
if program.execution_command:
return pickle.loads(program.execution_command)[2].split()
else:
return []
# Function to retrieve the files used during the compilation process.
# Takes as input the section/program whose files are needed.
def get_compilation_command_files(program):
if program.compilation_command:
return pickle.loads(program.compilation_command)[2].split()
else:
return []
<file_sep>/elearning_academy/permissions.py
"""
Handles the mode of User and associated permissions
"""
from rest_framework import permissions
from user_profile.models import CustomUser
class InInstructorMode(permissions.BasePermission):
"""
Check if the current mode of operation is valid
and in instructor mode
"""
def has_permission(self, request, view):
if request.user.is_authenticated():
if 'mode' in request.session:
customuser = CustomUser.objects.get(user=request.user)
if request.session['mode'] == 'I' and customuser.is_instructor:
return True
else:
request.session['mode'] = 'S'
return False
class InContentDeveloperMode(permissions.BasePermission):
"""
Check if the current mode of operation is valid
and in content developer mode
"""
def has_permission(self, request, view):
if request.user.is_authenticated():
if 'mode' in request.session:
customuser = CustomUser.objects.get(user=request.user)
if (request.session['mode'] == 'C' and customuser.is_content_developer):
return True
else:
request.session['mode'] = 'S'
return False
class InInstructorOrContentDeveloperMode(permissions.BasePermission):
"""
Check if the current mode of operation is valid
and in either instructor or content developer mode
"""
def has_permission(self, request, view):
if request.user.is_authenticated():
if 'mode' in request.session:
customuser = CustomUser.objects.get(user=request.user)
if request.session['mode'] == 'C':
if customuser.is_content_developer:
return True
elif request.session['mode'] == 'I':
if customuser.is_instructor:
return True
else:
request.session['mode'] = 'S'
return False
def is_valid_mode(request):
"""
Check if the current mode is valid for this user
"""
if request.user.is_authenticated():
if 'mode' in request.session:
if request.session['mode'] == 'S':
return True
customuser = CustomUser.objects.get(user=request.user)
if request.session['mode'] == 'C':
if customuser.is_content_developer:
return True
elif request.session['mode'] == 'I':
if customuser.is_instructor:
return True
else:
request.session['mode'] = 'S'
return False
def get_mode(request):
"""
Return the mode if the mode is valid otherwise returns False
"""
if request.user.is_authenticated():
if (is_valid_mode(request)):
return request.session['mode']
return False
<file_sep>/util/urls.py
"""
URL mappings for Util
"""
<file_sep>/evaluate/utils/errorcodes.py
# Dictionary mapping codes to signal names. Used to display error codes for test cases with errors.
error_codes = {
1: 'SIGHUP',
2: 'SIGINT',
3: 'SIGQUIT',
4: 'SIGILL',
5: 'SIGTRAP',
6: 'SIGABRT',
7: 'SIGBUS',
8: 'SIGFPE',
9: 'SIGKILL',
10: 'SIGUSR1',
11: 'SIGSEGV',
12: 'SIGUSR2',
13: 'SIGPIPE',
14: 'SIGALRM',
15: 'SIGTERM',
16: 'SIGSTKFLT',
17: 'SIGCHLD',
18: 'SIGCONT',
19: 'SIGSTOP',
20: 'SIGTSTP',
21: 'SIGTTIN',
22: 'SIGTTOU',
23: 'SIGURG',
24: 'SIGXCPU',
25: 'SIGXFSZ',
26: 'SIGVTALRM',
27: 'SIGPROF',
28: 'SIGWINCH',
29: 'SIGIO',
30: 'SIGPWR',
31: 'SIGSYS',
32: 'OLE',
33: 'MLE',
34: 'TLE',
35: 'RTLE',
36: 'RF',
37: 'IE',
38: 'RETNZ',
39: 'TERM',
}
# Dictionary mapping codes to error messages. Used to display error codes for test cases with errors.
error_msg = {
1: 'SIGHUP',
2: 'SIGINT',
3: 'SIGQUIT',
4: 'SIGILL',
5: 'SIGTRAP',
6: 'SIGABRT',
7: 'SIGBUS',
8: 'SIGFPE',
9: 'SIGKILL',
10: 'SIGUSR1',
11: 'Segmentation fault. Possible reasons may be your code has segmentation fault\
or Memory limit exceeded or your program is producing more output than it is allowed.',
12: 'SIGUSR2',
13: 'SIGPIPE',
14: 'SIGALRM',
15: 'SIGTERM',
16: 'SIGSTKFLT',
17: 'SIGCHLD',
18: 'SIGCONT',
19: 'SIGSTOP',
20: 'SIGTSTP',
21: 'SIGTTIN',
22: 'SIGTTOU',
23: 'SIGURG',
24: 'SIGXCPU',
25: 'SIGXFSZ',
26: 'SIGVTALRM',
27: 'SIGPROF',
28: 'SIGWINCH',
29: 'SIGIO',
30: 'SIGPWR',
31: 'SIGSYS',
32: 'Output limit exceeded',
33: 'Memory limit exceeded',
34: 'CPU time limit exceeded',
35: 'Total time limit exceeded',
36: 'RF',
37: 'IE',
38: 'RETNZ',
39: 'TERM',
}
<file_sep>/assignments/models.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save, pre_delete, pre_save
from django.core.files import File
import os, tempfile
from decimal import Decimal
#from courses.models import Course
from courseware.models import Course
from assignments import receivers
def assignment_upload_path(instance, filename):
return os.path.join(
instance.creater.username,
instance.course.title,
tempfile.mktemp().split('/')[-1],
filename
)
class Assignment(models.Model):
course = models.ForeignKey(Course)
name = models.CharField(max_length=200)
serial_number = models.IntegerField()
program_language = models.CharField(max_length=32)
deadline = models.DateTimeField(null='true')
hard_deadline = models.DateTimeField(null='true')
publish_on = models.DateTimeField()
late_submission_allowed = models.BooleanField(default=False)
document = models.FileField(upload_to=assignment_upload_path, null='true')
helper_code = models.FileField(upload_to=assignment_upload_path, null='true')
model_solution = models.FileField(upload_to=assignment_upload_path, null='true')
student_program_files = models.CharField(max_length=1024) # files that student must submit
description = models.TextField(null='true')
creater = models.ForeignKey(User)
createdOn = models.DateTimeField(auto_now_add=True)
last_modified_on = models.DateTimeField(auto_now=True)
class Meta:
unique_together = ("course", "name")
pre_delete.connect(receivers.delete_files, sender=Assignment, dispatch_uid="delete_assignment")
post_save.connect(receivers.verify_all_programs, sender=Assignment, dispatch_uid="receivers_verify_all_programs")
class AssignmentErrors(models.Model):
assignment = models.ForeignKey(Assignment)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
''' An assignment can have multiple programs. This table stores all
parameters to compile all programs for an assignment. '''
def program_upload_path(instance, filename):
return os.path.join(
instance.assignment.creater.username,
instance.assignment.course.title,
instance.assignment.name,
'program-files',
tempfile.mktemp().split('/')[-1],
filename
)
class Program(models.Model):
assignment = models.ForeignKey(Assignment)
name = models.CharField(max_length=128)
program_type = models.CharField(max_length=10)
compiler_command = models.CharField(max_length=1024)
execution_command = models.CharField(max_length=1024,default='')
program_files = models.FileField(upload_to=program_upload_path, null='true') # source code given by instructor.
makefile = models.FileField(upload_to=program_upload_path, null='true')
description = models.TextField(null='true')
is_sane = models.BooleanField(default=True)
language = models.CharField(max_length=32)
solution_ready = models.BooleanField(default=True)
def save_error(self, message): # remember it will also save current program object.
post_save.disconnect(receivers.compile_solution, sender=Program, dispatch_uid="Compile_solution_program")
self.is_sane = False
self.save()
p_errors, created = ProgramErrors.objects.get_or_create(program=self, defaults={'error_message': message})
if not created:
p_errors.error_message = message
p_errors.save()
post_save.connect(receivers.compile_solution, sender=Program, dispatch_uid="Compile_solution_program")
ctype = ContentType.objects.get_for_model(ProgramErrors)
AssignmentErrors.objects.get_or_create(
content_type=ctype,
object_id=p_errors.id,
assignment=self.assignment
)
def set_sane(self):
post_save.disconnect(receivers.compile_solution, sender=Program, dispatch_uid="Compile_solution_program")
self.is_sane = True
self.save()
post_save.connect(receivers.compile_solution, sender=Program, dispatch_uid="Compile_solution_program")
def delete_error_message(self):
try:
program_error = ProgramErrors.objects.filter(program=self)[0:1].get()
# delete entry from assignment error.
ctype = ContentType.objects.get_for_model(ProgramErrors)
AssignmentErrors.objects.filter(content_type=ctype, object_id=program_error.id).delete()
program_error.delete()
except ProgramErrors.DoesNotExist:
pass
except AssignmentErrors.DoesNotExist:
pass
#if program_error:
# program_error[0].delete()
# Updates the output files of all testcases. Deleting older files will result in a call to model's save method
# which in turn will call pre_save method.
def UpdateOutput(self):
print "Inside UpdateOutput - Updating the outputs of all the testcases"
post_save.disconnect(receivers.compile_solution, sender=Program, dispatch_uid="Compile_solution_program")
all_tests = Testcase.objects.filter(program=self)
for a_test in all_tests:
a_test.output_files.delete()
post_save.connect(receivers.compile_solution, sender=Program, dispatch_uid="Compile_solution_program")
post_save.connect(receivers.compile_solution, sender=Program, dispatch_uid="Compile_solution_program")
pre_delete.connect(receivers.delete_files, sender=Program, dispatch_uid="delete_program")
class ProgramErrors(models.Model):
program = models.ForeignKey(Program)
error_message = models.CharField(max_length=4096)
def testcase_upload_path(instance, filename):
assignment = instance.program.assignment
return os.path.join(
assignment.creater.username,
assignment.course.title,
assignment.name,
'testcase-files',
tempfile.mktemp().split('/')[-1],
filename
)
class Testcase(models.Model):
program = models.ForeignKey(Program)
command_line_args = models.TextField(null='true')
name = models.CharField(max_length=128)
marks = models.IntegerField(null='true')
input_files = models.FileField(upload_to=testcase_upload_path)
output_files = models.FileField(upload_to=testcase_upload_path)
std_in_file_name = models.CharField(max_length=256) # stores relative(to temp directory) path of the file.
std_out_file_name = models.CharField(max_length=256) # stores relative(to temp directory) path of the file.
description = models.TextField(null='true')
def save_error(self, error_file):
filter_attrs = {'testcase': self}
with open(error_file) as f:
attrs = {'error_message': "".join(f)}
try:
obj = TestcaseErrors.objects.filter(**filter_attrs)
obj.update(**attrs)
testcase_error = obj[0:1].get()
except TestcaseErrors.DoesNotExist:
attrs.update(filter_attrs)
testcase_error = TestcaseErrors.objects.create(**attrs)
# make an entry in assignment error.
ctype = ContentType.objects.get_for_model(TestcaseErrors)
AssignmentErrors.objects.get_or_create(
content_type=ctype,
object_id=testcase_error.id,
assignment=self.program.assignment
)
def clear_error(self):
try:
testcase_error = TestcaseErrors.objects.filter(testcase=self)[0:1].get()
# delete entry from assignment error.
ctype = ContentType.objects.get_for_model(TestcaseErrors)
tmp_obj = AssignmentErrors.objects.filter(content_type=ctype, object_id=testcase_error.id)#.delete()
tmp_obj.delete()
testcase_error.delete()
except TestcaseErrors.DoesNotExist:
pass
pre_delete.connect(receivers.delete_files, sender=Testcase, dispatch_uid="delete_testcase")
pre_save.connect(receivers.create_op_files, sender=Testcase, dispatch_uid="create_output_files")
post_save.connect(receivers.testcase_cleanup, sender=Testcase, dispatch_uid="testcase_cleanup")
class TestcaseErrors(models.Model):
testcase = models.ForeignKey(Testcase, unique=True)
error_message = models.TextField(null='true')
class SafeExec(models.Model):
testcase = models.ForeignKey(Testcase, unique=True)
cpu_time = models.IntegerField()
clock_time = models.IntegerField()
memory = models.IntegerField()
stack_size = models.IntegerField()
child_processes = models.IntegerField()
open_files = models.IntegerField()
file_size = models.IntegerField()
env_vars = models.TextField(null='true')
def checker_upload_path(instance, filename):
return os.path.join(
instance.program.assignment.creater.username,
instance.program.assignment.course.title,
instance.program.assignment.name,
'checker-files',
tempfile.mktemp().split('/')[-1],
filename
)
class Checker(models.Model):
program = models.ForeignKey(Program)
name = models.CharField(max_length=128)
execution_command = models.CharField(max_length=1024)
checker_files = models.FileField(upload_to=checker_upload_path)
description = models.TextField(null='true')
def save_error(self, message): # remember it will also save current program object.
self.save()
checker_errors, created = CheckerErrors.objects.get_or_create(checker=self, defaults={'error_message': message})
if not created:
checker_errors.error_message = message
checker_errors.save()
ctype = ContentType.objects.get_for_model(CheckerErrors)
AssignmentErrors.objects.get_or_create(
content_type=ctype,
object_id=checker_errors.id,
assignment=self.program.assignment
)
def delete_error_message(self):
try:
checker_error = CheckerErrors.objects.filter(checker=self)[0:1].get()
# delete entry from assignment error.
ctype = ContentType.objects.get_for_model(CheckerErrors)
AssignmentErrors.objects.filter(content_type=ctype, object_id=checker_error.id).delete()
checker_error.delete()
except CheckerErrors.DoesNotExist:
pass
except AssignmentErrors.DoesNotExist:
pass
pre_delete.connect(receivers.delete_files, sender=Checker, dispatch_uid="delete_checker")
class CheckerErrors(models.Model):
checker = models.ForeignKey(Checker)
error_message = models.CharField(max_length=4096)
def assignmentscript_upload_path(instance, filename):
return os.path.join(
instance.creater.username,
instance.course.title,
tempfile.mktemp().split('/')[-1],
filename
)
class AssignmentScript(models.Model):
course = models.ForeignKey(Course)
meta_file = models.FileField(upload_to=assignmentscript_upload_path)
assignment_archive = models.FileField(upload_to=assignmentscript_upload_path)
creater = models.ForeignKey(User)
createdOn = models.DateTimeField(auto_now_add=True)
last_modified_on = models.DateTimeField(auto_now=True)
pre_delete.connect(receivers.delete_files, sender=AssignmentScript, dispatch_uid="delete_assignment_script")
<file_sep>/requirements.txt
mysql-python
Django==1.5.2
djangorestframework==2.4.2
django-model-utils
django-admin-utils
django-filter
markdown
gunicorn
django-dajaxice
django-dajax
django-celery
south
django-guardian
psutil
jsonschema
tornado
python-memcached
<file_sep>/chat/models.py
__author__ = 'dheerendra'
from django.db import models
from django.contrib.auth.models import User
from courseware.models import Course
class ChatRoom(models.Model):
course = models.ForeignKey(Course)
title = models.TextField()
createdOn = models.DateTimeField(auto_now_add=True, blank=True)
def __unicode__(self):
return self.title
class Chat(models.Model):
chatroom = models.ForeignKey(ChatRoom)
user = models.ForeignKey(User)
message = models.TextField()
parent = models.ForeignKey('self', null=True)
timestamp = models.DateTimeField(auto_now_add=True)
hidden = models.TextField()
offensive = models.BooleanField(default=False)
def __unicode__(self):
return self.id<file_sep>/courseware/static/courseware/js/instructor/syllabus-right-pane.jsx
/** @jsx React.DOM */
var MY_GLOBAL_VARS = {
groupid: 0,
conceptid: 0,
elementid:0
}
var SyllabusConcept = React.createClass({
mixins: [LoadMixin],
getUrl: function() {
return '/courseware/api/concept/' + this.props.concept.id + '/playlist/?format=json';
},
render: function() {
var content = '';
if (this.state.loaded)
{
number=0;
content = this.state.data.map(function (object) {
number += 1;
return <div key={number}><a>Video: {object.title}</a></div>;
}.bind(this));
}
return (
<div id={'syllabus-concept-tobecopied-'+this.props.keyid} value={this.props.concept.id} data-myvar={this.props.mykey} class='panel panel-default panel-search-area syllabus-concept-in-sortable'>
<div class='panel-heading concept-syllabus-handle' data-toggle='collapse' data-target={'#syllabus-concept-' + this.props.keyid}>
Concept: {this.props.concept.title}
</div>
<div id={'syllabus-concept-'+this.props.keyid} class='syllabus-concept-collapse-box panel-collapse collapse'>
{content}
</div>
</div>
);
}
});
var SyllabusGroup = React.createClass({
mixins: [LoadMixin],
getUrl: function() {
return '/courseware/api/group/' + this.props.group.id + '/concepts/?format=json';
},
getInitialState: function() {
return {
clientloaded: true
};
},
componentDidUpdate: function() {
$('#concepts-syllabus-area-'+this.props.keyid).droppable({
activeClass: "syllabus-right-pane-activate",
hoverClass: "syllabus-right-pane-hover",
accept: ".search-concept",
drop: function(event, ui) {
MY_GLOBAL_VARS.conceptid = MY_GLOBAL_VARS.conceptid + 1;
keyid = 'n' + MY_GLOBAL_VARS.conceptid;
myid = $(ui.draggable)[0].id.substring(26);
mydata = this.state.data;
mydata.push({'keyid': keyid, id: myid, 'title':$(ui.draggable).find('.panel-heading')[0].innerText.substring(9)});
//console.log(this.props.group.id+" drop " + myid);
this.setState({data: mydata, clientloaded: true});
}.bind(this)
}).sortable({
cursor: "move",
axis: "y",
handle: '.concept-syllabus-handle',
items: ".syllabus-concept-in-sortable",
connectWith: ".syllabus-concepts",
placeholder: "state-highlight",
forcePlaceholderSize: true,
start: function(event, ui) {
$(ui.item).addClass("being-dragged");
$(this).data('startindex', ui.item.index());
$(this).data('inside', true);
}.bind(this),
beforeStop: function(event, ui) {
},
stop: function(event, ui) {
//console.log(this.props.group.id);
$(ui.item).removeClass("being-dragged");
var inside = $(this).data('inside');
if(inside) {
startindex = parseInt($(this).data('startindex'));
endindex = parseInt(ui.item.index());
//console.log(startindex);
//console.log(endindex);
$('#concepts-syllabus-area-'+this.props.keyid).sortable("cancel");
concepts = this.state.data;
temp = concepts[startindex];
concepts.splice(startindex, 1);
concepts.splice(endindex, 0, temp);
//console.log(concepts);
this.setState({data: concepts});
//$('#concepts-syllabus-area-'+this.props.group.id).sortable("cancel");
}
else {
//event.preventDefault();
//v = $(ui.item)[0].getAttribute('value');
//$('#concepts-syllabus-area-'+this.props.group.id).sortable("cancel");
//ui.item.remove();
startindex = parseInt($(this).data('startindex'));
concepts = this.state.data;
concepts.splice(startindex, 1);
loaded = !(concepts.length == 0);
//console.log(this.props.group.id+"remove" + v);
//console.log(newconcepts);
//setTimeout(function() {
this.setState({data: concepts, clientloaded: loaded});
//}.bind(this), 200);
}
//$(ui.item).remove();
}.bind(this),
receive: function(event, ui) {
endindex = ui.item.index();
$(ui.sender).sortable("cancel");
//$('#concepts-syllabus-area-'+this.props.group.id).sortable("cancel");
//event.preventDefault();
//ui.item.remove();
//$(ui.item).addClass('extra-garbage');
//setTimeout(function() {
// $('.extra-garbage').remove();
// console.log($(".extra-garbage"));
//}, 100);
//setTimeout(function() {
myid = $(ui.item)[0].getAttribute('value');
keyid = $(ui.item)[0].getAttribute('data-myvar');
console.log(keyid);
//console.log(myid);
mydata = this.state.data;
mydata.splice(endindex, 0, {'keyid': keyid, 'id':myid, 'title':$(ui.item).find('.panel-heading')[0].innerText.substring(9)});
//console.log(this.props.group.id+" sortable receive " + myid);
this.setState({data: mydata, clientloaded: true});
//}.bind(this), 100);
}.bind(this),
remove: function(event, ui) {
$(this).data('inside', false);
}.bind(this)
});
},
handleDelete: function() {
if(this.props.keyid[0]!='n') {
url = "/courseware/api/group/" + this.props.group.id + "/?format=json";
request = ajax_json_request(url, "DELETE",{});
request.done(function(response) {
display_global_message("Successfully deleted the group", "success");
this.props.callback(this.props.keyid);
}.bind(this));
}
else {
this.props.callback(this.props.keyid);
}
return false;
},
handleEdit: function(data) {
url = "/courseware/api/group/" + this.props.group.id + "/?format=json";
request = ajax_json_request(url, "PATCH", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
display_global_message("Successfully updated the group", "success");
oldState = this.state;
oldState['title'] = response.title;
oldState['description'] = response.description;
oldState['showform'] = false;
this.setState(oldState);
}.bind(this));
},
render: function() {
// console.log("I am "+ this.props.group.id);
var content = (
<div class='panel panel-default panel-search-area'>
<div class='panel-heading'>
No content till now.
</div>
</div>
);
if (this.state.loaded && this.state.clientloaded && this.state.data.length > 0)
{
content = this.state.data.map(function (object) {
//do something to differentiate the key of 2 copies of the same copncept dragged into this
if(object.keyid) {
keyid = object.keyid;
}
else {
keyid = object.id;
}
return <SyllabusConcept key={this.props.keyid+'_'+keyid} mykey={keyid} keyid={this.props.keyid+'_'+keyid} concept={object}/>;
}.bind(this));
}
return (
<div class='panel panel-default panel-search-area'>
<div class='panel-heading group-syllabus-handle' data-toggle='collapse' data-target={'#syllabus-group-' + this.props.keyid}>
Group: {this.props.group.title}
<validateDeleteBtn label={"syllabusgroup_"+this.props.group.id+"Label"} modal={"syllabusgroup_"+this.props.group.id+"Modal"} callback={this.handleDelete} heading="group" />
<div class="pull-right">
<span class="glyphicon glyphicon-save"></span>
<span class="glyphicon glyphicon-edit"></span>
<a data-toggle="modal" href={"#syllabusgroup_"+this.props.group.id+"Modal"}>
<span class="glyphicon glyphicon-trash"></span>
</a>
</div>
</div>
<div id={'syllabus-group-'+this.props.keyid} class='syllabus-group-collapse-box panel-collapse collapse'>
<div class='panel-group syllabus-concepts' id={'concepts-syllabus-area-'+this.props.keyid}>
{content}
</div>
</div>
</div>
);
}
});
var SyllabusGroups = React.createClass({
mixins: [LoadMixin, SavedStatusMixin, BackgroundTransitionMixin],
getUrl: function() {
return '/courseware/api/course/' + this.props.id + '/groups/?format=json';
},
componentDidUpdate: function() {
$('#groups-syllabus-area').droppable({
activeClass: "syllabus-right-pane-activate",
hoverClass: "syllabus-right-pane-hover",
accept: ".search-group",
drop: function(event, ui) {
// console.log('fasfasd');
MY_GLOBAL_VARS.groupid = MY_GLOBAL_VARS.groupid + 1;
// console.log('fasfasd');
keyid = 'n' + MY_GLOBAL_VARS.groupid;
myid = $(ui.draggable)[0].id.substring(24);
mydata = this.state.data;
mydata.push({'keyid': keyid, 'id':myid, 'title':$(ui.draggable).find('.panel-heading')[0].innerText.substring(7)});
//console.log(" drop " + myid);
//console.log(" drop " + keyid);
this.setState({data: mydata});
}.bind(this)
}).sortable({
cursor: "move",
axis: "y",
handle: ".group-syllabus-handle",
placeholder: "state-highlight",
forcePlaceholderSize: true,
start: function(event, ui) {
$(ui.item).addClass("being-dragged");
},
stop: function(event, ui) {
$(ui.item).removeClass("being-dragged");
},
receive: function(event, ui) {
//console.log("sortable");
}
});
},
handleDelete: function(id) {
data = this.state.data;
newdata = data.filter(function (group) {
if (group.keyid) {
return (group.keyid != id);
}
else {
return (parseInt(group.id) != parseInt(id));
}
});
this.setState({data: newdata});
},
render: function() {
var content = '';
if (this.state.loaded)
{
content = this.state.data.map(function (object) {
if(object.keyid) {
keyid = object.keyid;
}
else {
keyid = object.id;
}
return <SyllabusGroup key={keyid} keyid={keyid} group={object} callback={this.handleDelete}/>;
}.bind(this));
}
return (
<div class='panel-group syllabus-groups' id='groups-syllabus-area'>
{content}
</div>
);
}
});
/*
*/
var Syllabus = React.createClass({
render: function() {
return (
<div>
<h3>
Syllabus
</h3>
<SyllabusGroups id={this.props.id}/>
</div>
);
}
});<file_sep>/upload/forms.py
from django import forms
from utils.archives import get_file_name_list, get_missing_files
# This form is used to upload student submissions.
# The student uploads on the details page of the assignment is collected by this form and using this form we create new instance of upload objects.
class UploadForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
error_messages={
'invalid': 'File was not a valid tar file.',
'missing_files': 'Missing files.',
},
)
def __init__(self, *args, **kwargs):
self.assignment_model_obj = kwargs.pop('assignment_model_obj', "")
super(UploadForm, self).__init__(*args, **kwargs)
# This function checks if the upload object has all the needed files.
def clean_docfile(self):
# Get all files that should be submitted by student from all programs of given AssignmentID.
data = self.cleaned_data
submitted_files = get_file_name_list(fileobj=data['docfile'])
progrm_files_name = self.assignment_model_obj.student_program_files.split()
# Check if tarfile contains all of these.
missing_files = get_missing_files(progrm_files_name, fileobj=data['docfile'])
# If there are missing files raise error and display all missing files.
if missing_files:
self.fields['docfile'].error_messages["docfile"] = "There were missing files."
if set(submitted_files) >= set(progrm_files_name):
error_msg = "Directory structure is incorrect! Put all source files in single directory only.\
Nested directories are not allowed."
else:
error_msg = 'Missing files!. Your SUBMISSION contains "{0}" and we expect you to submit "{1}"\
Please upload again with missing files "{2}"'.format(" ".join(submitted_files),\
" ".join(progrm_files_name), " ".join(missing_files))
raise forms.ValidationError(error_msg)
return data['docfile']
<file_sep>/discussion_forum/urls.py
"""
URL Mapping for Discussion Forum
This is API for accessing discussion Forum
"""
from django.conf.urls import include, patterns, url
from rest_framework import routers
from discussion_forum import views
# Configuring routers
router = routers.DefaultRouter()
router.register(r'forum', views.DiscussionForumViewSet)
router.register(r'tag', views.TagViewSet)
router.register(r'user_setting', views.UserSettingViewSet)
router.register(r'content', views.ContentViewSet)
router.register(r'thread', views.ThreadViewSet)
router.register(r'comment', views.CommentViewSet)
router.register(r'reply', views.ReplyViewSet)
urlpatterns = patterns(
'',
url(r'^$', views.forum, name='forum'),
url(r'^admin/$', views.forum_admin, name='forum_admin'),
url(r'^api/', include(router.urls)),
)
<file_sep>/courseware/viewsets/group.py
"""
Functionality Provided:
Group:
+ retrieve - IsRegisteredOrAnyInstructor
+ update, delete - IsOwner
- concepts - IsRegisteredOrAnyInstructor
- reorder_concepts - IsOwner
- add_concept - IsOwner
"""
from django.shortcuts import get_object_or_404
from courseware.models import Group, Concept
from courseware.serializers import GroupSerializer, ConceptSerializer
from courseware import playlist
from courseware.permissions import IsOwnerOrReadOnly, IsOwner
from rest_framework import mixins, status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import link, action
from document.models import Document
class GroupViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [IsOwnerOrReadOnly]
def destroy(self, request, pk=None, *args):
group = get_object_or_404(Group, pk=pk)
_course = group.course
_course.playlist = playlist.delete(_course.playlist, pk=pk)
_course.save()
return super(GroupViewSet, self).destroy(request, pk)
@link(permission_classes=((IsOwner, )))
def concepts(self, request, pk=None):
"""
Function to get all the concepts in a course
"""
group = get_object_or_404(Group, pk=pk)
self.check_object_permissions(request=request, obj=group.course)
concepts = Concept.objects.filter(group=group)
serializer = ConceptSerializer(concepts, many=True)
if len(serializer.data) == 0:
return Response([])
_playlist = playlist.to_array(group.playlist)
N = len(_playlist)
ordered_data = [""]*N
for i in range(N):
ordered_data[i] = serializer.data[_playlist[i][1]]
return Response(ordered_data)
@link(permission_classes=((IsOwnerOrReadOnly, )))
def published_concepts(self, request, pk=None):
"""
Function to get all the concepts in a course
"""
group = get_object_or_404(Group, pk=pk)
self.check_object_permissions(request=request, obj=group.course)
concepts = Concept.objects.filter(group=group)
_playlist = playlist.to_array(group.playlist)
N = len(_playlist)
serializer = ConceptSerializer(concepts, many=True)
ordered_data = []
for i in range(N):
concept = serializer.data[_playlist[i][1]]
if concept['is_published']:
# TODO: check if append does not take O(n) time
ordered_data.append(concept)
return Response(ordered_data)
@action(
methods=['PATCH'],
permission_classes=((IsOwnerOrReadOnly, )),
serializer_class=GroupSerializer)
def reorder_concepts(self, request, pk=None):
group = get_object_or_404(Group, pk=pk)
self.check_object_permissions(request=request, obj=group.course)
myplaylist = request.DATA['playlist']
newplaylist = playlist.is_valid(myplaylist, group.playlist)
if newplaylist is not False:
group.playlist = newplaylist
group.save()
return Response(group.playlist)
else:
content = "Given order data does not have the correct format"
return Response(content, status.HTTP_404_NOT_FOUND)
@action(
methods=['POST'],
permission_classes=((IsOwnerOrReadOnly, )),
serializer_class=ConceptSerializer
)
def add_concept(self, request, pk=None):
group = get_object_or_404(Group, pk=pk)
self.check_object_permissions(request, group.course)
serializer = ConceptSerializer(data=request.DATA)
if serializer.is_valid():
document = Document(
title='dummy',
description='dummy'
)
document.save()
concept = Concept(
group=group,
title_document=document,
title=serializer.data['title'],
description=serializer.data['description']
)
if request.FILES != {}:
concept.image = request.FILES['image']
concept.save()
group.playlist = playlist.append(concept.id, group.playlist)
group.save()
return Response(ConceptSerializer(concept).data)
else:
content = serializer.errors
return Response(content, status.HTTP_400_BAD_REQUEST)
<file_sep>/util/models.py
"""
This file contains abstracted functionality for more convenience
"""
from django.db import models
from django.contrib.auth.models import User
SHORT_TEXT = 255
LARGE_TEXT = 1023
class Votable(models.Model):
"""
This is Non-Abstract class which can be inherited by any class for \
getting voting functionality.
Meant to be use for elements which requires voting.
We have included this class into discussion_forum.models.Content for\
efficiency reasons.
"""
# Indexed for efficient sorting on colum
upvotes = models.IntegerField(default=0, db_index=True)
downvotes = models.IntegerField(default=0, db_index=True)
# popularity = upvotes - downvotes
popularity = models.IntegerField(default=0, db_index=True)
upvoters = models.ManyToManyField(User, related_name='_upvoters')
downvoters = models.ManyToManyField(User, related_name='_downvoters')
def vote_up(self, user):
"""
perform checks and vote up accordingly
"""
if self.upvoters.filter(upvoters_pk=user.pk).exists():
return
elif self.downvoters.filter(downvoters_pk=user.pk).exists():
self.downvotes -= 1
self.upvotes += 1
self.downvoters.remove(user)
self.upvoters.add(user)
else:
self.upvotes += 1
self.upvoters.add(user)
self.save()
def vote_down(self, user):
"""
perform checks and vote up accordingly
"""
if self.downvoters.filter(downvoters__pk=user.pk).exists():
return
elif self.upvoters.filter(upvoters__pk=user.pk).exists():
self.upvotes -= 1
self.downvotes += 1
self.upvoters.remove(user)
self.downvoters.add(user)
else:
self.downvotes += 1
self.downvoters.add(user)
self.save()
class Meta: # pylint: disable=W0232
"""This class will have its own database table"""
abstract = False
class TimeKeeper(models.Model):
"""
Abstraction for storing creation and last edit time of database object
"""
created = models.DateTimeField(auto_now_add=True, db_index=True)
modified = models.DateTimeField(auto_now=True, db_index=True)
class Meta: # pylint: disable=W0232
"""This class won't have its own database table"""
abstract = True
class HitCounter(models.Model):
"""
Abstraction for counting hits of a particular object
"""
hit_count = models.IntegerField(default=0)
def make_hit(self):
""" Increase hit_count and saves immediately """
self.hit_count += 1
self.save()
class Meta: # pylint: disable=W0232
"""This class won't have its own database table"""
abstract = True
class Subscription(models.Model):
"""
Abstracted idea of maintaining subscription list.
Any object can have OneToOne relationship with this model
"""
users = models.ManyToManyField(User, related_name='subscribers')
def subscribe(self, user):
""" Add user into subscriber list """
self.users.add(user)
def unsubscribe(self, user):
""" Remove user from subscriber list """
self.users.remove(user)
def subscribers(self):
""" Returns all the users """
return self.users.all()
def is_subscribed(self, user):
""" Return True if user is subcribed else returns False """
return Subscription.objects.filter(pk=self.pk,
users__pk=user.pk).exists()
<file_sep>/user_profile/urls.py
"""
URL mappings for User Profile
"""
from django.conf.urls import include, patterns, url
from user_profile import views
from django.conf import settings
from rest_framework.routers import DefaultRouter
from user_profile.viewsets import UserProfileViewSet
router = DefaultRouter()
router.register(r'profile', UserProfileViewSet)
urlpatterns = patterns(
'',
url(r'^api/', include(router.urls)),
url(r'^api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
url(r'^home/', views.home, name="home"),
url(r'^view-profile$', views.view_profile, name="view-profile"),
url(r'^view-profile/(?P<pk>[1-9][0-9]*)$', views.view_profile, name="view-profile"),
url(r'^all/(?P<key>college|major|company)', views.all_data, name="data"),
url(r'^settings/', views.view_settings, name="settings"),
url(r'^get-privileges/', views.get_privileges, name="get-privileges"),
url(r'^pending_approvals/', views.pending_approvals, name="pending_approvals"),
url(r'^approve/', views.approve, name="approve"),
url(r'^discard/', views.discard, name="discard"),
url(r'^switch-mode/', views.switch_mode, name="switch-mode"),
)
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns(
'',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}))
<file_sep>/quiz_template/grader.py
"""
Grader class to handle assessment of submissions
"""
from quiz_template.models import Question_Master, User_Submissions
import json
class Grader():
"""
Grader class to handle assessment of submissions
"""
question = None
submission = None
the_question = None
def __init__(self, submission, question):
""" Initialize this class """
self.submission = submission
self.question = question
if self.question is None:
self.question = self.submission.question
def update_marks(self, is_correct=True):
"""
Get and update the marks for this submission
"""
difference = 0
if is_correct:
attempts = self.submission.attempts
marks = 0
if(self.submission.hint_taken):
attempts += 1
granularity = json.loads(self.question.marks)
attempts -= 1
if(attempts < len(granularity)):
marks = granularity[attempts]
self.submission.status = User_Submissions.CORRECT
self.submission.marks = marks
else:
self.submission.status = User_Submissions.ATTEMPTED
if(self.submission.attempts >= self.question.attempts):
self.submission.status = User_Submissions.WRONG
self.submission.save()
return
def grade(self):
"""
Grade the submission or pass it appropriate grader
IMPORTANT: This method must save the submission
IMPORTANT: Ensure that update_marks() gets called
Return True if result is directly available, false otherwise
"""
if self.submission is None:
return False
else:
answer = self.submission.answer
self.the_question = Question_Master.objects.get_subclass(
pk=self.question.pk)
correct_answer = self.the_question.answer
if self.question.type == \
Question_Master.SINGLE_CHOICE_QUESTION:
self.grade_single_choice(answer, correct_answer)
return True
elif self.question.type == \
Question_Master.MULTIPLE_CHOICE_QUESTION:
self.grade_multiple_choice(answer, correct_answer)
return True
elif self.question.type == \
Question_Master.FIXED_ANSWER_QUESTION:
self.grade_fixed_answer(answer, correct_answer)
return True
elif self.question.type == \
Question_Master.DESCRIPTIVE_ANSWER_QUESTION:
self.submission.status = User_Submissions.CORRECT
self.submission.marks = 0
self.submission.save()
return True
def grade_fixed_answer(self, answer, correct_answer):
""" Grade fixed answer Question """
print answer, correct_answer
correct = False
explainations = json.loads(self.the_question.explainations)
cur_explain = ""
for ans in correct_answer:
if ans.lower() == answer.lower():
correct = True
cur_explain = explainations[correct_answer.index(ans)]
break
if(not correct):
cur_explain = self.the_question.default_explanation_wrong
self.submission.explaination = cur_explain
print "result is ", correct, "\n\n\n"
self.update_marks(correct)
def grade_single_choice(self, answer, correct_answer):
""" Grade single choice correct Question """
print answer, correct_answer
correct = False
explainations = json.loads(self.the_question.explainations)
cur_explain = ""
if(int(answer) < len(explainations)):
cur_explain = explainations[int(answer)]
if int(answer) == int(correct_answer):
correct = True
if(cur_explain == ""):
cur_explain = self.the_question.default_explanation_correct
else:
if(cur_explain == ""):
cur_explain = self.the_question.default_explanation_wrong
self.submission.explaination = cur_explain
print "result is ", correct, "\n\n\n"
self.update_marks(correct)
def grade_multiple_choice(self, answer, correct_answer):
""" Grade Multiple choice correct Question """
print "grade_multiple_choice : ", answer, correct_answer
correct = False
cur_explain = ""
explainations = json.loads(self.the_question.explainations)
answers = json.loads(answer)
for index in range(len(answers)):
print answers[index], explainations[index]
if (answers[index]):
cur_explain += explainations[index] + "\n"
if answer == correct_answer:
correct = True
if(cur_explain == ""):
cur_explain = self.the_question.default_explanation_correct
else:
if(cur_explain == ""):
cur_explain = self.the_question.default_explanation_wrong
self.submission.explaination = cur_explain
print "result is ", correct, "\n\n\n"
self.update_marks(correct)
def grade_descriptive_answer(self, answer, correct_answer, submission):
""" Grade Descriptive Question """
pass
<file_sep>/TestBed/Python/Student/Incorrect/beads.py
T=input()
for a in range(T):
N=input()
b=[int(next) for next in raw_input().split(' ')]
ans=1
for x in b:
ans*=x**(x-1)
ans+=1
ans*=sum(b)**(N-2)
print int(ans)%1000000007<file_sep>/notification/models.py
"""
Contains database schema for Email Notifications
"""
from django.db import models
from django.contrib.auth.models import User
from elearning_academy import settings
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(subject, text_msg, from_email, to_email_list, html_msg):
"""
Send email to list of reciepients using smtp
Django mail is not used because it uses only 3 authentication method
and is a smtp server propogates MD5 but does not support then it fails
work around is from http://www.harelmalka.com/?p=94
:arg subject: Email subject, preferably be not None otherwise mail
can be rendered as spam
:arg text_msg: (string) Message to be sent in plain text format
:arg from_email: email id to be displayed in From field of header
:arg to_email_list: a list of email ids to which to send the email
:arg html_msg: (String) Message to be sent in text/html format
"""
server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
server.starttls()
server.ehlo()
server.esmtp_features['auth'] = 'LOGIN PLAIN'
server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
mail = MIMEMultipart("alternative")
mail['Subject'] = subject
mail['From'] = from_email
mail.attach(MIMEText(text_msg, 'plain'))
mail.attach(MIMEText(html_msg, 'html'))
for to_email in to_email_list:
mail['To'] = to_email
server.sendmail(from_email, to_email, mail.as_string())
class NotificationEmail(models.Model):
"""
Model to store email content to be consumed by cron
worker and sent to Users
"""
user = models.ForeignKey(User, related_name='Email_Notification')
service = models.CharField(max_length=50)
email_subject = models.CharField(max_length=50)
text_email_body = models.TextField()
html_email_body = models.TextField()
def send_email(self):
'''
Sends Notification Mail using <<EMAIL>
using SMTP using global settings
'''
from_email = "<EMAIL>" % (self.service)
send_mail(subject=self.email_subject, text_msg=self.text_email_body,
from_email=from_email, to_email_list=[self.user.email],
html_msg=self.html_email_body)
<file_sep>/progress/views.py
"""
Views for Progress
"""
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from elearning_academy.permissions import get_mode
from rest_framework import status
from rest_framework.response import Response
@login_required
def view_progress(request, course):
"""
View progress page of current user
"""
mode = get_mode(request)
if mode is not False:
if mode == 'S':
return render(request, 'progress/student_progress.html', {'courseId': course})
elif mode == 'I':
return render(request, 'progress/course_progress.html', {'courseId': course})
return Response("Bad request", status.HTTP_400_BAD_REQUEST)
<file_sep>/evaluate/templates/evaluate/test_run_messages.html
{% load evaluatetags %}
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion{{ prgrm.program_result.program.id }}pro" href="#collapse{{ tst.test_case.id }}tst">
{% if tst.return_code == 0 and tst.test_passed %} {{ tst.test_case.name }} PASS
{% else %} {{ tst.test_case.name }} FAIL {% endif %} <span class="pull-right">{{ tst.marks }} Marks</span>
</a>
</div>
<div id="collapse{{ tst.test_case.id }}tst" class="accordion-body collapse">
<div style="padding-left:40px" class="accordion-inner">
{% if tst.return_code == 0 %}
<div class="row">
{% if is_due or is_moderator %}
<div class="span4" style="word-wrap: break-word;">
Input:<hr style="margin-top: 5px; margin-bottom: 10px">
{{ tst.std_input|join:"<br/>" }}
</div>
<div class="span4" style="word-wrap: break-word;">
Expected output:<hr style="margin-top: 5px; margin-bottom: 10px">
{{ tst.expected_output|join:"<br/>" }}
</div>
<div class="span4" style="word-wrap: break-word;">
Actual output:<hr style="margin-top: 5px; margin-bottom: 10px">
{{ tst.actual_output|join:"<br/>" }}
</div>
{% else %}
Output is hidden before deadline
{% endif %}
</div>
{% else %}
<div class="row">
<h5>{{ error_msg|getdictvalue:tst.return_code }}. Program exited with return code {{ tst.return_code }}.</h5>
</div>
<div class="row">
{% if is_due or is_moderator %}
<div class="span4" style="word-wrap: break-word;">
Input:<hr style="margin-top: 5px; margin-bottom: 10px">
{{ tst.std_input|join:"<br/>" }}
</div>
<div class="span4" style="word-wrap: break-word;">
Expected output:<hr style="margin-top: 5px; margin-bottom: 10px">
{{ tst.expected_output|join:"<br/>" }}
</div>
<div class="span4" style="word-wrap: break-word;">
Actual output:<hr style="margin-top: 5px; margin-bottom: 10px">
{{ tst.actual_output|join:"<br/>" }}
</div>
{% else %}
Output is hidden before deadline
{% endif %}
</div>
{% endif %}
</div>
</div>
</div>
<file_sep>/courses/models.py
from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
from datetime import date
'''
termNames = ['spring', 'winter', 'fall', 'summer']
def termChoices():
years = [date.today().year + i for i in range(-1,2)]
return [(term +" "+ str(year), term +" "+ str(year)) for year in years for term in termNames]
class Course(models.Model):
code = models.CharField(blank=False, max_length=20, help_text="Course code eg CS 101")
name = models.CharField(blank=False, max_length=150, help_text="Course name")
creater = models.ForeignKey(User)
createdOn = models.DateTimeField(auto_now_add=True)
lastModifiedOn = models.DateTimeField(auto_now=True)
isActive = models.BooleanField(default=True)
#TODO: make termChoices dynamic
term = models.CharField(max_length=50,
blank=False,
choices=termChoices()
)
courseDescription= models.TextField(default="None")
class Meta:
unique_together = ("code", "creater", "term")
class CourseForm(ModelForm):
class Meta:
model = Course
include = ('code', 'name', 'isActive', 'term', 'courseDescription')
exclude = ('creater')
widgets = {}
f = model._meta.get_field('code')
formField = f.formfield()
widgets['code'] = type(formField.widget)(attrs={'title': f.help_text})
class Role(models.Model):
user = models.ForeignKey(User)
course = models.ForeignKey(Course)
role = models.CharField(max_length=50)
'''
<file_sep>/discussion_forum/serializers.py
"""
Serializer classes for Django Rest Framework
"""
from django.contrib.auth.models import User
from rest_framework import serializers, pagination
from discussion_forum import models
class ForumTagSerializer(serializers.Serializer):
""" Serializer for parsing Tag attribtues while creating new Tag """
title = serializers.CharField(max_length=models.SHORT_TEXT)
tag_name = serializers.CharField(max_length=models.SHORT_TEXT)
class ForumThreadSerializer(serializers.Serializer):
""" Serializer class for Parsing Thread attributes while creating """
title = serializers.CharField(max_length=models.SHORT_TEXT)
content = serializers.CharField()
anonymous = serializers.BooleanField()
subscribe = serializers.BooleanField() # Post and subscribe
class BooleanSerializer(serializers.Serializer):
""" Serializer class for BooleanField """
mark = serializers.BooleanField(required=True)
class OrderSerializer(serializers.Serializer):
""" Serializer for sort order """
order = serializers.CharField()
class IntegerSerializer(serializers.Serializer):
""" Serializer class for IntegerField """
value = serializers.IntegerField(required=True)
class BadgeSerializer(serializers.Serializer):
""" Serialzer class for Badge """
badge = serializers.CharField(max_length=2)
class ForumContentSerializer(serializers.Serializer):
""" Content Serializer while creating new one """
content = serializers.CharField()
anonymous = serializers.BooleanField()
class UserSerializer(serializers.ModelSerializer):
""" Serializer for django.contrib.auth.User """
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name')
class TagSerializer(serializers.ModelSerializer):
""" serialization for Tag modal """
class Meta:
""" Meta """
model = models.Tag
def restore_object(self, attrs, instance=None):
""" Updates tag's title or discussion_models."""
if instance:
# Update existing instance
instance.title = attrs.get('title', instance.title)
instance.tag_name = attrs.get('tag_name', instance.tag_name)
return instance
else:
return None
class DiscussionForumSerializer(serializers.ModelSerializer):
""" serialization for DiscussionForum modal """
tags = TagSerializer(many=True)
class Meta:
""" Meta """
model = models.DiscussionForum
def restore_object(self, attrs, instance=None):
""" Updates DiscussionForum object """
if instance:
# Update existing instance
instance.abuse_threshold = attrs.get(
'abuse_threshold',
instance.abuse_threshold
)
instance.review_threshold = attrs.get(
'review_threshold',
instance.review_threshold
)
return instance
else:
return None
class DiscussionForumSettingSerializer(serializers.ModelSerializer):
""" serialization for DiscussionForum modal without tags """
class Meta:
""" Meta """
model = models.DiscussionForum
class UserSettingSerializer(serializers.ModelSerializer):
""" serialization for UserSetting modal """
user = UserSerializer()
class Meta:
""" Meta """
model = models.UserSetting
def restore_object(self, attrs, instance=None):
""" This can only update email_setting """
if instance:
instance.email_digest = attrs.get(
'email_digest',
instance.email_digest
)
return instance
else:
return None
class PaginatedUserSettingSerializer(pagination.PaginationSerializer):
""" Serializing UserSetting class as a list """
class Meta:
""" Meta """
object_serializer_class = UserSettingSerializer
class ActivitySerializer(serializers.ModelSerializer):
""" serialization for Activity modal """
actor = UserSerializer()
class Meta:
""" Meta """
model = models.Activity
class ContentSerializer(serializers.ModelSerializer):
""" serialization for Content modal """
author = serializers.Field(source='get_author')
class Meta:
""" Meta """
model = models.Content
# Need to exclude author if anonymous is true
exclude = ("spammers", "old_spammers", "upvoters", "downvoters")
def restore_object(self, attrs, instance=None):
""" Can only update content attribute """
if instance:
instance.content = attrs.get('content', instance.content)
return instance
else:
return None
class PaginatedContentSerializer(pagination.PaginationSerializer):
"""
Serializers page objects of Comment queryset
"""
class Meta:
""" Meta """
object_serializer_class = ContentSerializer
class ThreadListSerializer(serializers.ModelSerializer):
""" Serializing thread class leaving some attributes for efficiency """
class Meta:
model = models.Thread
exclude = ("spammers", "old_spammers",
"upvoters", "downvoters",
"subscription", "tags", "author")
class ThreadSerializer(serializers.ModelSerializer):
""" serialization for Thread modal """
tags = TagSerializer(many=True)
author = serializers.Field(source='get_author')
class Meta:
""" Meta """
model = models.Thread
exclude = ("spammers", "old_spammers",
"upvoters", "downvoters",
"subscription")
def restore_object(self, attrs, instance=None):
""" Can only update thread's title or content """
if instance:
instance.title = attrs.get('title', instance.title)
instance.content = attrs.get('content', instance.content)
return instance
else:
return None
class PaginatedThreadSerializer(pagination.PaginationSerializer):
"""
Serializers page objects of Thread queryset
"""
class Meta:
""" Meta """
object_serializer_class = ThreadSerializer
class CommentSerializer(serializers.ModelSerializer):
""" serialization for Comment modal """
author = serializers.Field(source='get_author')
class Meta:
""" Meta """
model = models.Comment
exclude = ("spammers", "old_spammers", "upvoters", "downvoters")
def restore_object(self, attrs, instance=None):
""" Can only update comment's content """
if instance:
instance.content = attrs.get('content', instance.content)
return instance
else:
return None
class PaginatedCommentSerializer(pagination.PaginationSerializer):
"""
Serializers page objects of Comment queryset
"""
class Meta:
""" Meta """
object_serializer_class = CommentSerializer
class ReplySerializer(serializers.ModelSerializer):
""" serialization for Reply modal """
author = serializers.Field(source='get_author')
class Meta:
""" Meta """
model = models.Reply
exclude = ("spammers", "old_spammers", "upvoters", "downvoters")
def restore_object(self, attrs, instance=None):
""" Can only update reply's content """
if instance:
instance.content = attrs.get('content', instance.content)
return instance
else:
return None
class PaginatedReplySerializer(pagination.PaginationSerializer):
"""
Serializers page objects of Thread queryset
"""
class Meta:
""" Meta """
object_serializer_class = ReplySerializer
class NotificationSerializer(serializers.ModelSerializer):
""" serialization for Reply modal """
class Meta:
""" Meta """
model = models.Notification
<file_sep>/user_profile/tests.py
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase, Client
from django.contrib.auth.models import User
from user_profile.models import CustomUser
from user_profile.views import *
import json
class UserModelTest(TestCase):
def setUp(self):
#instructor or content developer
user = User(username='user', is_active=True, email="<EMAIL>")
user.set_password('<PASSWORD>')
user.save()
c_user = CustomUser.objects.get(user=user)
c_user.is_instructor = True
c_user.is_content_developer = True
c_user.default_mode = 'C'
c_user.save()
#student user
user = User(username='student', is_active=True, email="<EMAIL>")
user.set_password('<PASSWORD>')
user.save()
c_user = CustomUser.objects.get(user=user)
c_user.is_instructor = False
c_user.is_content_developer = False
c_user.default_mode = 'S'
c_user.save()
College(college='college1').save()
Major(major='major1').save()
def test_user_model(self):
u = User.objects.get(pk=1)
cu = CustomUser.objects.get(user=u)
self.assertEqual(u.username, 'user')
self.assertTrue(cu.is_instructor)
def test_user_login_required(self):
c = Client()
#without login
response = c.get('/user/home/')
self.assertEqual(response.status_code, 302)
#login
response = c.post('/accounts/login/', {'username':'user','password':'<PASSWORD>'}, follow=True)
self.assertEqual(response.status_code, 200)
#trying to get a login required page
response = c.get('/user/home/')
self.assertEqual(response.status_code, 200)
def test_user_all_data(self):
c = Client()
response = c.post('/accounts/login/', {'username':'user','password':'<PASSWORD>'}, follow=True)
response = c.get('/user/all/college')
self.assertEqual(response.status_code, 200)
j = json.loads(response.content)
self.assertTrue('college1' in j)
def test_switch_mode_instructor(self):
c = Client()
response = c.post('/accounts/login/', {'username':'user','password':'<PASSWORD>'}, follow=True)
response = c.post('/user/switch-mode/', {'new_mode':'I'}, follow=True)
self.assertEqual(response.status_code, 200)
def test_switch_mode_student(self):
c = Client()
response = c.post('/accounts/login/', {'username':'student','password':'<PASSWORD>'}, follow=True)
response = c.post('/user/switch-mode/', {'new_mode':'I'}, follow=True)
self.assertEqual(response.status_code, 400)
def test_user_profile_edit(self):
c = Client()
response = c.post('/accounts/login/', {'username':'user','password':'<PASSWORD>'}, follow=True)
response = c.post('/user/view-profile/',{'form_method':'about', 'first_name':'user', 'last_name':'1', 'about':'test user'}, follow=True)
self.assertEqual(response.status_code, 200)
response = c.post('/user/view-profile/',{'form_method':'personal_info', 'gender':'F'}, follow=True)
self.assertEqual(response.status_code, 200)
response = c.post('/user/view-profile/',{'form_method':'add_education', 'college':'college1', 'major':'major1', 'degree':'BTECH', 'start_date':'10/2/2014', 'end_date':'12/2/2014'}, follow=True)
self.assertEqual(response.status_code, 200)
response = c.post('/user/view-profile/',{'form_method':'social','twitter':'user'}, follow=True)
self.assertEqual(response.status_code, 200)
user = User.objects.get(username='user')
profile = UserProfile.objects.get(user=user)
education = Education.objects.get(user=user)
self.assertEqual(profile.user.first_name, 'user')
self.assertEqual(profile.user.last_name, '1')
self.assertEqual(profile.about, 'test user')
self.assertEqual(profile.gender, 'F')
self.assertEqual(education.college.college, 'college1')
self.assertEqual(education.major.major, 'major1')
self.assertEqual(profile.website_twitter, 'user')
response = c.post('/user/view-profile/',{'form_method':'remove_education','education_id': education.pk}, follow=True)
self.assertEqual(response.status_code, 200)
with self.assertRaises(Education.DoesNotExist):
Education.objects.get(user=user)<file_sep>/grader/urls.py
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from dajaxice.core import dajaxice_config
from dajaxice.core import dajaxice_autodiscover
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
dajaxice_autodiscover()
admin.autodiscover()
urlpatterns = patterns('',
# url(r'^$', 'grader.views.home', name='home'),
# url(r'^grader/', include('grader.foo.urls')),
(r'^cribs/', include('cribs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^accounts/', include('userena.urls')),
url(r'^messages/', include('userena.contrib.umessages.urls')),
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
url(r'^upload/', include('upload.urls')),
url(r'^download/', include('download.urls')),
url(r'^courses/', include('courses.urls')),
url(r'^assignments/', include('assignments.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^evaluate/', include('evaluate.urls')),
url(r'^$', 'courses.views.index', name='courses_index'), # TODO: temporary page change it later.
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
<file_sep>/elearning_academy/urls.py
"""
Root URL resolver file
"""
from django.conf.urls import patterns, include, url
from django.contrib import admin
from dajaxice.core import dajaxice_config
from dajaxice.core import dajaxice_autodiscover
from elearning_academy import settings
import views
admin.autodiscover()
dajaxice_autodiscover()
urlpatterns = patterns( # pylint: disable=C0103
'',
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^$', views.index, name='index'),
url(r'^old/', views.old_site, name='old_site'),
url(r'^team/', views.team, name='team'),
url(r'^mission/', views.mission, name='mission'),
url(r'^contact/', views.contact, name='contact'),
url(r'^accounts/', include('registration.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# Django Static file serve
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
# Django Media file serve
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
url(r'^user/', include('user_profile.urls')),
url(r'^notification/', include('notification.urls')),
url(r'^forum/', include('discussion_forum.urls')),
url(r'^quiz/', include('quiz.urls')),
url(r'^courseware/', include('courseware.urls')),
url(r'^concept/', include('concept.urls')),
url(r'^video/', include('video.urls')),
url(r'^document/', include('document.urls')),
url(r'^progress/', include('progress.urls')),
url(r'^quiz_template/', include('quiz_template.urls')),
#grader
(r'^cribs/', include('cribs.urls')),
#url(r'^messages/', include('userena.contrib.umessages.urls')),
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
url(r'^upload/', include('upload.urls')),
url(r'^download/', include('download.urls')),
url(r'^courses/', include('courses.urls')),
url(r'^assignments/', include('assignments.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^evaluate/', include('evaluate.urls')),
#url(r'course^$', 'courses.views.index', name='courses_index'), # TODO: temporary page change it later.
# url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
#Chat
url(r'^chat/', include('chat.urls')),
)
<file_sep>/scripts/quiz_playlist.py
#!/usr/bin/python
"""
Script to fill quiz, question module playlist initially
"""
import os
import csv
import sys
sys.path.append(os.getcwd())
os.environ['DJANGO_SETTINGS_MODULE'] = 'elearning_academy.settings'
from django.conf import settings
from quiz.models import Quiz, QuestionModule, Question
from courseware import playlist
for quiz in Quiz.objects.all():
quiz.playlist = '[]'
qms = QuestionModule.objects.filter(quiz=quiz)
for qm in qms:
quiz.playlist = playlist.append(qm.id, quiz.playlist)
quiz.save()
for question_module in QuestionModule.objects.all():
question_module.playlist = '[]'
qs = Question.objects.filter(question_module=question_module)
for q in qs:
question_module.playlist = playlist.append(q.id, question_module.playlist)
question_module.save()
<file_sep>/evaluate/utils/checkOutput.py
from evaluate.utils.executor import CommandExecutor
from utils.archives import get_file_name_list, extract_or_copy
from elearning_academy.settings import PROJECT_DIR
import pickle, os, shutil, tempfile
# Class to manage custom testcases (student fed input files)
class CustomTestcase(object):
def __init__(self, inputFile, program, submission):
# Setting section of the testcase, submission to use, the input file given by the student and the command executor that runs the commands.
self.program = program
self.submission = submission
self.inputFile = inputFile
self.commandExecutor = CommandExecutor()
self.eval_dir = os.path.join(PROJECT_DIR, 'evaluate/safeexec')
def get_resource_limit(self):
# Return default values because there is no setting for custom testcase.
return {'cpu_time':10, 'clock_time':10,
'memory': 32768, 'stack_size': 8192, 'child_processes': 0,
'open_files': 512, 'file_size': 1024,
}
# Store the input file that student uploaded
def store_input_file(self, inputFile, dest):
file_path = os.path.join(dest, inputFile.name.split('/')[-1])
destination = open(file_path, 'wb+')
# Work-around to support file and InMemoeryUploadedFile objects
if hasattr(inputFile, 'chunks'):
all_file = inputFile.chunks()
else:
all_file = inputFile
# Write everything to the input file represented by destination object. Then return the full path of file name.
for chunk in all_file:
destination.write(chunk)
destination.close()
return file_path
# Function to setup the environment (input file, solution files and submission files) before running the code.
def setup(self):
# This is the directory where the student program is copied to.
self.temp_dir = tempfile.mkdtemp(prefix="grader", dir=self.eval_dir)
os.chdir(self.temp_dir)
# Copy student solution files to tmp directory.
extract_or_copy(src=self.submission.filePath.file.name, dest=self.temp_dir)
self.submission.filePath.close()
# Another temp directory for running solution program. This is the directory where the solution program is copied to.
self.solution_temp_dir = tempfile.mkdtemp(prefix="solution", dir=self.eval_dir)
directories = [a for a in os.listdir('./') if os.path.isdir(a)]
if directories:
os.chdir(directories[0])
currentDir = os.getcwd()
# Extract the program file and the input file to the student directory, and the input file to the program directory as well.
if self.program.program_files :
extract_or_copy(src=self.program.program_files.file.name, dest=currentDir)
self.program.program_files.close()
self.submittedFiles = get_file_name_list(name=self.submission.filePath.file.name)
self.submission.filePath.close()
input_file = self.store_input_file(self.inputFile, currentDir)
shutil.copy(src=input_file, dst=self.solution_temp_dir)
# Function to compile the student program.
def compile(self):
self.exe_file = str(self.program.id)
compiler_command = " ".join(pickle.loads(self.program.compiler_command)) + " -o " + self.exe_file
self.compileResult = self.commandExecutor.executeCommand(command=compiler_command)
# Function to run the student and model solution on the input file.
def run(self):
# Run student exe file.
_, self.actual_stdout = tempfile.mkstemp(dir='./')
os.chmod(self.actual_stdout, 0777)
runStudentProgram = "./" + self.exe_file + " < " + self.inputFile.name
self.actualOutput = self.commandExecutor.safe_execute(
command=runStudentProgram,
limits=self.get_resource_limit()
)
# Run solution exe file.
shutil.copy(src=self.program.exe_file_name.file.name, dst=self.solution_temp_dir)
self.program.exe_file_name.close()
os.chdir(self.solution_temp_dir)
_, self.expected_stdout = tempfile.mkstemp(dir='./')
os.chmod(self.expected_stdout, 0777)
exe = self.program.exe_file_name.name.split('/')[-1]
runSolutionProgram = "./" + exe + " < " + self.inputFile.name
self.expectedOutput = self.commandExecutor.safe_execute(
command=runSolutionProgram,
limits=self.get_resource_limit()
)
self.passed = self.testPassed()
# This function is called after run(), and checks the actual and the expected output.
def testPassed(self):
# At this point actual o/p is in self.actual_stdout and expected O/P is in self.expected_stdout.
# compare them and display result on browser.
if not (self.expectedOutput.returnCode == 0 and self.actualOutput.returnCode == 0):
return False
exp_op = iter(self.expectedOutput.get_stdout())
act_op = iter(self.actualOutput.get_stdout())
if len(self.expectedOutput.get_stdout()) > len(self.actualOutput.get_stdout()):
return False
for line1, line2 in zip(exp_op, act_op):
if line1.strip() != line2.strip():
return False
for line2 in act_op:
if line2.strip() != "":
return False
return True
# This is the function called to get the result once the input file is uploaded.
def getResult(self):
# Setup the environment.
self.setup()
# Compile the program.
self.compile()
# If compilation is successful then run the program.
if self.compileResult.returnCode == 0:
self.run()
# Clean up the temporary directories.
self.cleanUp()
return self
# Function to clean up the temporary directories.
def cleanUp(self):
shutil.rmtree(self.temp_dir, ignore_errors=True)
<file_sep>/courseware/static/courseware/js/instructor/syllabus.jsx
/** @jsx React.DOM */
var SearchConcept = React.createClass({
mixins: [LoadMixin],
componentWillReceiveProps: function(nextProps) {
state = this.state;
state.loaded = false;
state.data = undefined;
this.setState(state, this.loadData);
},
getUrl: function() {
return '/courseware/api/concept/' + this.props.concept.id + '/playlist/?format=json';
},
render: function() {
var content = '';
if (this.state.loaded)
{
content = this.state.data.map(function (object) {
return <a>Video: {object.title}</a>;
}.bind(this));
}
return (
<div id={'search-concept-tobecopied-'+this.props.concept.id} class='panel panel-default panel-search-area search-concept'>
<div class='panel-heading concept-search-handle' data-toggle='collapse' data-target={'#search-concept-' + this.props.concept.id}>
Concept: {this.props.concept.title}
</div>
<div id={'search-concept-'+this.props.concept.id} class='panel-collapse collapse'>
{content}
</div>
</div>
);
}
});
var SearchGroup = React.createClass({
mixins: [LoadMixin],
componentWillReceiveProps: function(nextProps) {
state = this.state;
state.loaded = false;
state.data = undefined;
this.setState(state, this.loadData);
},
getUrl: function() {
return '/courseware/api/group/' + this.props.group.id + '/concepts/?format=json';
},
componentDidUpdate: function() {
$('.search-concept').draggable({
cursor: "move",
cursorAt: {left: 5},
revert: "invalid",
handle: ".concept-search-handle",
zIndex: 100,
helper: function() {
return $("<div class='panel panel-default'><div class='panel-heading'>Concept.....Drag me to the right side</div></div>");
},
});
},
render: function() {
var content = '';
if (this.state.loaded)
{
content = this.state.data.map(function (object) {
return <SearchConcept key={object.id} concept={object}/>;
}.bind(this));
}
return (
<div id={'search-group-tobecopied-'+this.props.group.id} class='panel panel-default panel-search-area search-group'>
<div class='panel-heading group-search-handle' data-toggle='collapse' data-target={'#search-group-' + this.props.group.id}>
Group: {this.props.group.title}
</div>
<div id={'search-group-'+this.props.group.id} class='panel-collapse collapse'>
<div class='panel-group' id={'concepts-search-area-'+this.props.group.id}>
{content}
</div>
</div>
</div>
);
}
});
var SearchGroups = React.createClass({
mixins: [LoadMixin],
componentWillReceiveProps: function(nextProps) {
state = this.state;
state.loaded = false;
state.data = undefined;
this.setState(state, this.loadData);
},
getUrl: function() {
return '/courseware/api/course/' + this.props.id + '/groups/?format=json';
},
componentDidUpdate: function() {
$('#groups-search-area .search-group').draggable({
cursor: "move",
cursorAt: {left: 5},
revert: "invalid",
handle: ".group-search-handle",
zIndex: 100,
helper: function() {
return $("<div class='panel panel-default'><div class='panel-heading'>Group.....Drag me to the right side</div></div>");
},
});
},
render: function() {
var content = '';
if (this.state.loaded)
{
content = this.state.data.map(function (object) {
return <SearchGroup key={object.id} group={object}/>;
}.bind(this));
}
return (
<div class='panel-group' id='groups-search-area'>
{content}
</div>
);
}
});
var List = React.createClass({
mixins: [LoadMixin],
componentWillReceiveProps: function(nextProps) {
state = this.state;
state.loaded = false;
state.data = undefined;
this.setState(state, this.loadData);
},
getUrl: function() {
return '/courseware/api/' + this.props.url + 'format=json';
},
handleClick: function (event) {
value = event.target.getAttribute('value');
title = event.target.innerText;
this.props.callBack(value, title);
},
render: function() {
var content = <LoadingBar />;
if (this.state.loaded)
{
content = this.state.data.results.map(function (object) {
return (
<li key={object.id} value={this.props.childType+object.id} onClick={this.handleClick}>
{object.title}
</li>);
}.bind(this));
}
return (
<ul>
{content}
</ul>
);
}
});
var InnerSearchArea = React.createClass({
getInitialState: function() {
return {
current_link: 'H',
p: {'id':undefined, 'title':undefined},
c: {'id':undefined, 'title':undefined},
t: {'id':undefined, 'title':undefined}
};
},
handleChange: function(value, title) {
state = this.state;
state.current_link = value[0];
id = value.substring(1);
if(value[0]=='P') {
state.p.id = id;
state.p.title = title;
}
else if(value[0]=='C') {
state.c.id = id;
state.c.title = title;
}
else if(value[0]=='T') {
state.t.id = id;
state.t.title = title;
}
this.setState(state);
},
handleClick: function(event) {
value = event.target.getAttribute('value');
state = this.state;
state.current_link = value[0];
this.setState(state);
},
render: function() {
var content = '';
var home = <li onClick={this.handleClick}><a value='H' href="#">Home</a></li>;
var p = '';
var c = '';
var t = '';
if(this.state.current_link == 'H') {
content = <List childType='P' url='parent_category/?' callBack={this.handleChange}/>;
home = <li class='active'>Home</li>;
}
else if(this.state.current_link == 'P') {
content = <List childType='C' url={'category/?parent='+this.state.p.id+'&'} callBack={this.handleChange}/>;
p = <li class='active'>{this.state.p.title}</li>;
}
else if(this.state.current_link == 'C') {
content = <List childType='T' url={'course/?category='+this.state.c.id+'&'} callBack={this.handleChange}/>;
p = <li onClick={this.handleClick}><a value='P' href="#">{this.state.p.title}</a></li>;
c = <li class="active">{this.state.c.title}</li>;
}
else if(this.state.current_link == 'T') {
content = <SearchGroups id={this.state.t.id}/>;
p = <li onClick={this.handleClick} value=''><a value='P' href="#">{this.state.p.title}</a></li>;
c = <li onClick={this.handleClick}><a value='C' href="#">{this.state.c.title}</a></li>;
t = <li class='active'>{this.state.t.title}</li>;
}
return (
<div class='panel panel-default'>
<div class='panel-heading heading-inner-search-area'>
<div class='row'>
<div class='col-md-11'>
<ol class="breadcrumb bread-crumb-search-area">
{home}{p}{c}{t}
</ol>
</div>
<button class='btn btn-default btn-sm btn-inner-search-area' data-toggle='collapse' data-parent='#search-area' data-target='#searchable-area'>
<span class='glyphicon glyphicon-chevron-down' />
</button>
</div>
</div>
<div id='searchable-area' class='panel-collapse collapse'>
{content}
</div>
</div>
);
}
});
/*
This class contains the shortlisted courses from which data is to be copied
to the syllabus
*/
var Shortlisted = React.createClass({
mixins: [LoadMixin],
getUrl: function() {
return '/courseware/api/offering/' + this.props.courseid + '/get_shortlisted_courses/?format=json';
},
componentWillReceiveProps: function(nextProps) {
state = this.state;
state.loaded = false;
state.data = undefined;
this.setState(state, this.loadData);
},
render: function() {
var content = '';
if (this.state.loaded)
{
content = this.state.data.map(function (course) {
return <div>{course.title}</div>;
}.bind(this));
}
return (
<div>
{content}
</div>
);
}
});
/*
This class defines the left handside of the syllabus box.
This class handles the search area from which data will be presented to be included
in the syllabus.
Structure:
SearchArea [R]
Heading
Shortlisted Courses[R]
InnerSearchArea [R]
*/
var SearchArea = React.createClass({
render: function() {
return (
<div>
<h3 class='center'>
Search Area
</h3>
<div class='panel-group' id='search-area'>
<div class='panel panel-default'>
<div class='panel-heading' data-toggle='collapse' data-parent='#search-area' data-target='#shortlisted'>
Shortlisted Courses
</div>
<div id='shortlisted' class='panel-collapse collapse'>
<Shortlisted courseid={this.props.id}/>
</div>
</div>
<InnerSearchArea />
</div>
</div>
);
}
});
/*
This class defines the structure of the syllabus box.
Structure:
SearchArea[R] Syllabus[R]
*/
var SyllabusStructure = React.createClass({
render: function() {
return (
<div>
<div class='col-md-6'>
<SearchArea id={this.props.id}/>
</div>
<div class='col-md-6'>
<Syllabus id={this.props.id}/>
</div>
</div>
);
}
});<file_sep>/courseware/vsserializers/category.py
from rest_framework import serializers
from courseware.models import ParentCategory, Category
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
""" Serializer for django.contrib.auth.User """
class Meta:
"""Meta"""
model = User
fields = ('id', 'username', 'first_name', 'last_name')
class ParentCategorySerializer(serializers.ModelSerializer):
"""Serializer for ParentCategory Model"""
class Meta:
"""Meta"""
model = ParentCategory
class CategorySerializer(serializers.ModelSerializer):
"""serializer for the category class"""
# TODO: content_developers = UserSerializer(many=True)
class Meta:
"""Meta"""
model = Category
exclude = ('content_developers',)
<file_sep>/scripts/create_user.sh
#!/usr/bin/sh
## Example script to create single account
## TODO: Read from CSV or maybe an entire python based solution
curl -i -X POST http://10.102.56.95:8080/accounts/api/register/ -F"username=saket" \
-F "first_name=test" -F "last_name=test" -F "password=<PASSWORD>"\
-F"email=<EMAIL>" --noproxy 10.102.56.95
<file_sep>/quiz_old/tests.py
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
"""
add_fixed_answer_question:
{
"question_module": 1,
"quiz": 1,
"description": "My first question",
"hint": null,
"grader_type": "D",
"answer_description": "the answer is password",
"marks": "5",
"granularity": "5,0",
"granularity_hint":"1,0",
"type": "F",
"answer": "password"
}
Test script to populate data:
from courseware.models import *
from django.contrib.auth.models import *
from quiz.models import *
saif = User(username='saif',first_name='',last_name='',email='<EMAIL>',is_active=True)
saif.set_password('0')
saif.save()
alankar = User(username='alankar',first_name='',last_name='',email='<EMAIL>',is_active=True)
alankar.set_password('0')
alankar.save()
category = Category(title="My category")
category.save()
course = Course(title='My course', category=category)
course.save()
concept=Concept(title="My concept")
concept.save()
quiz = Quiz(title="Quiz - 1", course=course, concept=concept)
quiz.save()
saif_ch = CourseHistory(course=course, user=saif, is_instructor=True)
alankar_ch = CourseHistory(course=course, user=alankar, is_instructor=False)
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
<file_sep>/evaluate/utils/executor.py
from elearning_academy.settings import PROJECT_DIR
import subprocess
import threading, os, psutil
# Class to manage command execution.
class CommandExecutor(object):
def __init__(self):
self.process = None
self.result = None
self.sandbox = os.path.join(PROJECT_DIR, 'grader/safeexec')
# Function to run the command using the process interface of python.
# Takes as input the command to be run, and the output file to write the standard output to.
def run(self, command, outfile):
# Setup command line.
commandLine = ["/bin/bash", "-c", command]
# Setup output file if it has been passed as an argument. If the output file is valid then open the file as a file object.
# Else capture the std output separately.
if outfile and os.path.isfile(outfile):
outfile_obj = open(outfile, 'wb')
else:
outfile_obj = None
# Open a subprocess with the command line, output file object. Wait for the process to finish.
self.process = subprocess.Popen(
commandLine,
stdout=outfile_obj or subprocess.PIPE,
stderr=subprocess.PIPE
)
self.process.wait()
# Collect the std error and return code of the process.
cmdError = self.process.stderr.readlines()
returnCode = self.process.returncode
# If output file object has been created then close it and set the stdoutfile variable to outfile. This will be used to create CommandResult.
# Else collect command line output in cmd_output and set stdoutfile to none.
if outfile_obj:
outfile_obj.close()
stdoutfile = outfile
cmd_output = None
else:
cmd_output = [aLine.strip() for aLine in self.process.stdout.readlines()]
stdoutfile = None
# Set self.result to CommandResult with the command, command line output, std error, return code, and the stdoutfile as arguments.
self.result = CommandResult(command, cmd_output, cmdError, returnCode, stdoutfile)
# Function to execute command. Calls the run function.
def executeCommand(self, command, outfile=None):
# Call run function with the right arguments.
self.run(command, outfile=outfile)
# Return the self.result object, which is set in run() function.
return self.result
# Function to execute command using safe-exec environment. It uses the limits passed as arguments.
# Takes as input command, limits and the outfile for the output to be written to.
def safe_execute(self, command, limits, safe=True, outfile=None):
# For now use run() directly.
# print "Command run previously >>> ", command
if not safe:
self.run(command, outfile)
return self.result
# Solve the safeexec bug. Once the bug is solved, remove the above 2 lines and uncomment this part.
# Arguments dictionary for the safe-exec features. Maps the features to the command line options for the safe-exec executable.
# Construct the run time parameters using the limit dictionary.
args = {'cpu_time': '--cpu', 'clock_time': '--clock',
'memory': '--mem', 'stack_size': '--stack',
'child_processes': '--nproc', 'open_files': '--nfile',
'file_size': '--fsize', 'env_vars': '--env_vars'}
run_params = ' '
for a in limits.keys():
run_params = run_params + args[a] + ' ' + str(limits[a]) + ' '
# Construct new command with the actual command passed to the safe-exec executable with the limits parameters.
# Call run() function with the new command.
command = self.sandbox + run_params + ' --exec ' + command
print "Command run >> ", command
self.run(command, outfile)
return self.result
# Class to manage the results of a command run by the CommandExecutor.
# Takes as input the command, std output, std error, return code and the output file of the command execution.
class CommandResult(object):
def __init__(self, command, stdout, stderr, returnCode, outfile=None):
self.command = command
self.outfile = outfile
self.stdout = stdout
self.stderr = stderr
self.returnCode = returnCode
# Function to return the command.
def get_command(self):
return self.command
# Function to return the standard output.
# Extracts the standard output from either the outfile or the stdout variables.
def get_stdout(self):
# If self.outfile exists then extract the output from this file.
# Else return the self.stdout variable.
if self.outfile:
if os.path.isfile(self.outfile):
with open(self.outfile, 'r') as f:
return [line for line in f]
else:
raise Exception("output was written to a file. That file was not found.")
else:
return self.stdout
# Function to return the standard error.
def get_stderr(self):
return self.stderr
# Function to return the return code of the command execution.
def getReturnCode(self):
return self.returnCode
# Function to print the attributes for logging.
def printResult(self):
print "Command Executed - ",self.command
print "Return Code - ",self.returnCode
print "Standard error if any - ",self.stderr<file_sep>/grader/static/js/jquery.ba-serializeobject.min.js
/*
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" <NAME>
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,a){$.fn.serializeObject=function(){var b={};$.each(this.serializeArray(),function(d,e){var f=e.name,c=e.value;b[f]=b[f]===a?c:$.isArray(b[f])?b[f].concat(c):[b[f],c]});return b}})(jQuery);
<file_sep>/user_profile/static/user_profile/js/profile.jsx
/** @jsx React.DOM */
// Showdown converter
var converter = new Showdown.converter();
var PersonalInfo = React.createClass({
render: function() {
var user_profile = JSON.parse(this.props.user_profile);
return (
<table class="table col-md-8">
<tr>
<th>Gender</th>
<td>{user_profile.gender}</td>
</tr>
<tr>
<th>Date of Birth</th>
<td>{user_profile.dob}</td>
</tr>
<tr>
<th>City</th>
<td>{user_profile.city}</td>
</tr>
<tr>
<th>State</th>
<td>{user_profile.state}</td>
</tr>
<tr>
<th>Country</th>
<td>{user_profile.country}</td>
</tr>
</table>
);
}
});
var EditButton = React.createClass({
render: function() {
return (
<div class="row">
<a id="edit-image-btn" class="btn btn-primary pull-left" href={this.props.image_url}>
<span class="glyphicon glyphicon-pencil"></span> Edit Image
</a>
<a id="edit-pi-btn" class="btn btn-primary pull-right" href={this.props.pi_url}>
<span class="glyphicon glyphicon-pencil"></span> Edit Profile
</a>
</div>
);
}
});
var ProfileTop = React.createClass({
render: function() {
var user_profile = JSON.parse(this.props.user_profile);
if (user_profile.photo != "/media/") {
var image_url = user_profile.photo;
}
else {
var image_url = this.props.default_image;
}
return (
<div class="row">
<table class="table col-md-8">
<tr >
<td width="30%">
<img width="180px" height="180px" src={image_url} />
</td>
<td>
<h2>{this.props.user_name}</h2>
<p><i>{user_profile.about}</i></p><br/><br/>
<p><b>Interests: </b>{user_profile.interests}</p>
</td>
</tr>
</table>
</div>
);
}
});
var OtherInfo = React.createClass({
render: function() {
return (
<div id="course-list" class="row">
<p><b>Courses: </b>{this.props.courses}</p>
</div>
);
}
});
var Profile = React.createClass({
render: function() {
console.log('creating a profile div :'+this.props.user);
return (
<div class="container">
<ProfileTop user_name={this.props.user_name} user_profile={this.props.user_profile}
default_image={this.props.default_image}/>
<EditButton pi_url={this.props.pi_url} image_url={this.props.image_url}/>
<PersonalInfo user_profile={this.props.user_profile}/>
</div>
);
}
});
<file_sep>/video/static/video/js/student/concept_video_box.jsx
/** @jsx React.DOM */
/**
Concept Video Box for Student.
This will be rendered in student_concept.jsx
Provides features to :-
1. Upvote
2. DownVote
**/
/**
ConceptVideoBox [R]
- Video Navigation
- VideoTOC [R]
- VideoVote [R]
- Video [R]
**/
var ConceptVideoBox = React.createClass({
mixins: [ScrollToElementMixin],
changeCurrent: function(index) {
if (index == -2) {
if (this.state.markers.length == 0) {
index = -1;
} else {
index = 0;
}
}
start_time = 0;
if (index >= 0 && this.state.markers.length >= 0) {
start_time = this.state.markers[index]['time'];
}
state = this.state;
state.current_marker = index;
state.startTime = start_time;
this.setState(state);
},
updateVote: function(newVotes, newVote) {
if (newVote == this.state.vote) {
newVote = 'N';
}
this.setState({
votes: newVotes,
vote: newVote,
});
},
getInitialState: function() {
data = this.props.data;
cur_marker = 0;
if (data.content.markers.length == 0) {
cur_marker = -1;
}
return {
title: data.content.title,
content: data.content.content,
current_marker: cur_marker,
markers: data.content.markers,
votes: [data.content.upvotes, data.content.downvotes],
vote: data.history.vote,
startTime: 0,
};
},
render: function() {
data = this.props.data;
marker = undefined;
if (this.current_marker != -1) {
marker = this.state.markers[this.state.current_marker];
} else {
marker = undefined;
}
return (
<div class="row" class="concept-video-box">
<div class="col-md-4 panel-group video-sidebar" id="video-sidebar">
<VideoContent content={this.state.content} title={this.state.title} />
<VideoTOC markers={this.state.markers} clickCallback={this.changeCurrent} />
{this.props.data.content.other_file != '/media/' ?
<VideoSlide other_file={this.props.data.content.other_file} />
: null
}
</div>
<div class="col-md-8 video-container" id="video-container">
<VideoNavigation
nextVideo={this.props.nextCallback}
prevVideo={this.props.prevCallback}
title={this.state.title} />
<Video videoFile={data.content.video_file} videoStartTime={this.state.startTime}
markers={this.state.markers} videoId={data.content.id}/>
<VideoVote votes={this.state.votes} updateVote={this.updateVote}
vote={this.state.vote} videoId={data.content.id}/>
</div>
</div>
);
}
});
/**
VideoSlide
- slide link
**/
var VideoSlide = React.createClass({
render: function() {
return (
<div class="panel panel-default video-desc-container" id="slide-container"
ref="videoSlideDiv">
<div class="panel-heading" data-toggle="collapse"
data-parent="#video-sidebar" data-target="#slide-description">
<span class="video-sidebar-heading"> Slides </span>
</div>
<div class="video-sidebar-content panel-collapse collapse" id="slide-description">
<div class="row">
<div class="col-md-12">
<div class="video-desc">
<a href={this.props.other_file} target="_blank">Slides</a>
</div>
</div>
</div>
</div>
</div>
);
}
});
/**
VideoContent
- Content
**/
var VideoContent = React.createClass({
render: function() {
return (
<div class="panel panel-default video-desc-container" id="content-container" ref="videoContentDiv">
<div class="panel-heading" data-toggle="collapse"
data-parent="#video-sidebar" data-target="#video-description">
<span class="video-sidebar-heading"> Description </span>
</div>
<div class="video-sidebar-content panel-collapse collapse in" id="video-description">
<div class="row">
<div class="col-md-12">
<div class="video-desc">
<h4> {this.props.title} </h4>
<p> {this.props.content} </p>
</div>
</div>
</div>
</div>
</div>
);
}
});
/**
VideoTOC
- Video Title
- Video Description
- Video Markers
**/
var VideoTOC = React.createClass({
handleClick: function(index) {
this.props.clickCallback(index);
return false;
},
toTime: function(t) {
sec = t%60;
min = (t-sec)/60;
if (sec < 10) {
sec = "0"+sec;
}
if (min < 10) {
min = "0"+min;
}
return min + ":" + sec;
},
render: function() {
var markers = this.props.markers.map(
function (marker, index) {
if (marker.type == 'S') {
return <li key={index} id={"marker_"+marker.id} class="marker-item"
href="#" onClick={this.handleClick.bind(this, index)}>
<span href="#" class="marker-title">
{marker.title}
</span>
<span class="marker-time">
{this.toTime(marker.time)}
</span>
</li>;
} else {
return <li key={index} id={"marker_"+marker.id} class="marker-item"
href="#" onClick={this.handleClick.bind(this, index)}>
<span href="#" class="marker-title">
Quiz : {marker.quiz_title}
</span>
<span class="marker-time">
{this.toTime(marker.time)}
</span>
</li>;
}
}.bind(this)
);
var toc = <div />;
if (markers.length != 0) {
toc = <div class="panel panel-default video-toc-container" id="toc-container">
<div class="panel-heading" data-toggle="collapse" data-parent="#video-sidebar"
data-target="#toc">
<span class="video-sidebar-heading"> Table of Content </span>
</div>
<div class="video-sidebar-content panel-collapse collapse" id="toc">
<ul id="tocList" role="menu" class="tocList">
{markers}
</ul>
</div>
</div>;
}
return (toc);
}
});
/**
Video Navigation
- Previous Video
- Next Video
- Auto Play
**/
var VideoNavigation = React.createClass({
render: function() {
return (
<div class="row video-navigation" id="navigation-container">
<span class="video-nav-btn pull-left"> <a href="#" onClick={this.props.nextVideo}>
<span class="glyphicon glyphicon-step-backward" />
</a> </span>
<span class="video-title"> {this.props.title} </span>
<span class="video-nav-btn pull-right"> <a href="#" onClick={this.props.prevVideo}>
<span class="glyphicon glyphicon-step-forward" />
</a> </span>
</div>
);
}
});
/**
Video
- Video Element
**/
var Video = React.createClass({
seen_markers: [],
video: undefined,
componentWillReceiveProps: function(nextProps) {
all_markers = nextProps.markers;
quiz_markers = [];
this.seen_markers = [];
for (var i = 0; i < all_markers.length; i++) {
if (all_markers[i]['type'] == 'Q') {
quiz_markers.push({
id: all_markers[i].id,
time: all_markers[i].time,
quiz: all_markers[i].quiz
});
this.seen_markers.push(false);
}
}
this.setState({quiz_markers: quiz_markers});
videoStartTime = nextProps.videoStartTime;
_V_("video-player").ready(function() {
setTimeout(function(){
video.currentTime = videoStartTime;
}, 1);
});
},
componentDidUpdate: function() {
this.video = document.getElementsByTagName("video")[0];
video = this.video;
},
inEpsilon: function(value, list, delta) {
for (var i = 0; i < list.length; i++) {
if (this.seen_markers[i] == false && value > list[i] - delta && value < list[i] + delta) {
return i;
}
}
return -1;
},
openDiv: function(index, video) {
video.pause();
player = _V_("video-player", {}, function(){ console.log("Player set for exit fullscreen");});
if (player && player.isFullscreen()) {
alert("Please exit FullScreen and attempt Quiz.");
}
this.seen_markers[index] = true;
url = "/video/api/marker/"+ quiz_markers[index]['id'] + "/update_quiz_marker_status/?format=json";
request = ajax_json_request(url, "PATCH", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
}.bind(this));
this.setState({current_quiz: this.state.quiz_markers[index].quiz});
},
Paused: function() {
alert("Paused.");
},
Ended: function() {
url = "/video/api/video/"+ this.props.videoId +"/ended/?format=json";
request = ajax_json_request(url, "PATCH", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
}.bind(this));
},
componentDidMount: function() {
this.video = document.getElementsByTagName("video")[0];
video = this.video;
inEpsilon = this.inEpsilon;
openDiv = this.openDiv;
quiz_markers = this.state.quiz_markers;
Ended = this.Ended;
Paused = this.Paused;
_V_(this.video, {
plugins: {
speed: [
{text: '0.5x', rate: 0.5 },
{ text: '1x', rate: 1, selected: true },
{ text: '1.5x', rate: 1.5},
{ text: '2x', rate: 2 },
{ text: '4x', rate: 4 }
]
}
}).ready(function() {
setTimeout(function(){
all_time = quiz_markers.map(function(q_m) {return q_m.time;});
video.addEventListener("timeupdate", function() {
index = inEpsilon(video.currentTime, all_time, 0.25);
if (index >= 0){
openDiv(index, video);
}
}.bind(video, inEpsilon, all_time, openDiv));
video.addEventListener("ended", function() {
Ended();
});
/* document.addEventListener("keypress", function(e) {
var code = (e.keyCode ? e.keyCode : e.charCode)
if (code == 32) {
if (video.paused) {
video.play();
} else {
video.pause();
}
} else if (code == 27) {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
video.mozCancelFullScreen();
} else {
document.webkitCancelFullScreen();
video.mozCancelFullScreen();
}
}
});*/
}, 1);
});
},
getInitialState: function() {
all_markers = this.props.markers;
quiz_markers = [];
this.seen_markers = [];
for (var i = 0; i < all_markers.length; i++) {
if (all_markers[i]['type'] == 'Q') {
quiz_markers.push({
id: all_markers[i].id,
time: all_markers[i].time,
quiz: all_markers[i].quiz
});
this.seen_markers.push(false);
}
}
return {
quiz_markers: quiz_markers,
current_quiz: undefined
};//, seen_markers: seen_markers};
},
unsetCurrentQuiz: function(play){
this.setState({current_quiz : undefined});
if(play) this.video.play();
},
render: function() {
file = this.props.videoFile;
return (
<div>
<div class="video">
<video ref="videoPlayer" id="video-player" class="video-js vjs-default-skin"
controls autobuffer preload="auto" width="720" height="480" >
<source type='video/webm' src={file} />
<source type='video/mp4' src={file} />
<track src="/media/static/video/a.srt" srclang="en" label="English" default />
</video>
</div>
{this.state.current_quiz != undefined ?
<ConceptQuiz id={this.state.current_quiz}
closeCallback={this.unsetCurrentQuiz.bind(this,true)} />
: null
}
</div>
);
}
});
/**
VideoVote
- Upvote
- Downvote
**/
var VideoVote = React.createClass({
base_url: "/video/api/",
sendVote: function(data, method) {
url = this.base_url + "video/" + this.props.videoId + "/vote/?format=json";
request = ajax_json_request(url, "PATCH", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
if (method == this.state.vote) {
method = 'N'
}
this.setState({
vote: method,
upvotes: response['vote'][0],
downvotes: response['vote'][1],
});
//this.props.updateVote(response['vote'], method);
}.bind(this));
},
upvote: function() {
data = {'vote': 'up'};
this.sendVote(data, 'U');
},
downvote: function() {
data = {'vote': 'down'};
this.sendVote(data, 'D');
},
componentWillReceiveProps: function(nextProps) {
this.setState({
vote: nextProps.vote,
upvotes: nextProps.votes[0],
downvotes: nextProps.votes[1]
});
},
getInitialState: function() {
return {
vote: this.props.vote,
upvotes: this.props.votes[0],
downvotes: this.props.votes[1]
};
},
render: function() {
if (this.state.vote == 'U') {
Upvote = <b> Upvote </b>;
} else {
Upvote = "Upvote";
}
if (this.state.vote == 'D') {
Downvote = <b> Downvote </b>;
} else {
Downvote = "Downvote";
}
return (
<div class="row video-vote">
<span class="pull-right">
<span class="vote">
<span class="text-success" onClick={this.upvote}>
{Upvote} </span> : {this.state.upvotes}
</span>
<span class="vote">
<span class="text-danger" onClick={this.downvote}>
{Downvote} </span> : {this.state.downvotes}
</span>
</span>
</div>
);
}
});
<file_sep>/quiz_old/static/quiz/js/quiz_admin.jsx
/** @jsx React.DOM */
// TODO: Disable buttons when ajax request is sent
// Enable back when request completes
/*
* |--------------------------------------|
* | QuestionModuleEditAdmin: |
* | |-----------------------------| |
* | | QuestionCreate | |
* | | QuestionEditRow | |
* | |-----------------------------| |
* | |
* | QuizEditAdmin: |
* | |-----------------------------| |
* | | QuestionModuleCreate | |
* | | QuestionModuleEditRow | |
* | |-----------------------------| |
* | |
* | QuizAdmin: |
* | |-----------------------------| |
* | | QuizCreate | |
* | | QuizEditRow | |
* | |-----------------------------| |
* |--------------------------------------|
*/
var QuizAdminId = 'quiz-admin';
var QuizEditAdminId = 'quiz-edit-admin';
var QuestionModuleEditId = 'question-module-edit-admin';
var QUESTION_TYPES = {
SINGLE_CHOICE_QUESTION: 'S',
MULTIPLE_CHOICE_QUESTION: 'M',
FIXED_ANSWER_QUESTION: 'F',
DESCRIPTIVE_ANSWER_QUESTION: 'D',
PROGRAMMING_QUESTION: 'P'
};
function add_error_to_element(element, errors) {
element.attr('title', 'This field is required.');
element.tooltip('show');
element.focus(function() {
element.tooltip('destroy');
});
element.parent().addClass("has-warning");
}
function remove_error_from_element(element) {
element.parent().removeClass("has-warning");
}
function close_question_list() {
$("#" + QuestionModuleEditId).fadeOut(function() {
$(this).html("");
});
}
function close_question_module_list() {
$("#" + QuizEditAdminId).fadeOut(function() {
$(this).html("");
});
}
var confirmDeleteMixin = {
getInitialState: function() {
return {
delete_stage: false
};
},
resetDelete: function() {
state = this.state;
state.delete_stage = false;
this.setState(state);
},
getDeleteBar: function() {
delete_bar =
<button type="submit" class="btn btn-danger btn-sm" onClick={this.deleteObject}>
Delete
</button>;
if (this.state.delete_stage) {
delete_bar =
<div>
<button type="submit" class="btn btn-warning btn-sm quiz-right-margin" onClick={this.resetDelete}>No</button>
<button type="submit" class="btn btn-danger btn-sm" onClick={this.deleteObject}>Yes</button>
</div>;
}
return delete_bar;
},
checkDeleteStage: function() {
if (!this.state.delete_stage) {
state = this.state;
state.delete_stage = true;
this.setState(state);
return true;
}
return false;
}
};
var ListCreator = React.createClass({
getInitialState: function() {
list = [];
if (this.props.defaultValue != undefined) {
list = this.props.defaultValue;
}
max = this.maxInRow;
if (this.props.maxInRow != undefined) {
max = this.props.maxInRow;
}
return {
list: list,
maxInRow: max
};
},
onChange: function() {
if (this.props.onChange != undefined) {
this.props.onChange(this.state.list);
}
},
addItem: function() {
list = this.state.list;
item_node = this.refs.item.getDOMNode();
item = item_node.value.trim();
this.refs.item.getDOMNode().value = '';
item_node.focus();
check = this.props.check;
if (check == undefined) {
check = function(item) {return !isNaN(item);};
}
if (item != '' && check(item)) {
list.push(item);
}
state = this.state;
state.list = list;
this.setState(state);
this.onChange();
},
removeItem: function() {
this.refs.item.getDOMNode().focus();
list = this.state.list;
if (list.length != 0) {
list.pop();
}
state = this.state;
state.list = list;
this.setState(state);
this.onChange();
},
maxInRow: 6,
render: function() {
all_values = this.state.list.map(function(l) {
return <span class="input-group-addon">{l}</span>;
});
values = new Array();
rows = Math.floor(all_values.length / this.state.maxInRow);
extra = all_values.length % this.state.maxInRow;
counter = 0;
for (var i = 0; i < rows; i++) {
this_row = new Array();
for (var j = 0; j < this.state.maxInRow; j++) {
this_row.push(all_values[counter]);
counter++;
}
values.push(this_row);
}
more_values = new Array();
for (var i = 0; i < extra; i++) {
more_values.push(all_values[counter]);
counter++;
}
div_values = values.map(function(v) {
return(
<div class="input-group">
{v}
</div>);
});
id = '';
if (this.props.id != undefined) {
id = this.props.id;
}
remove_button = <div></div>;
if (this.state.list.length != 0) {
remove_button =
<span class="input-group-btn">
<button class="btn btn-default" type="button" onClick={this.removeItem}>
<span class="glyphicon glyphicon-remove"></span>
</button>
</span>;
}
return (
<div>
{div_values}
<div class="input-group">
{remove_button}
{more_values}
<input type="text" class="form-control" ref="item" id={id} />
<span class="input-group-btn">
<button class="btn btn-default" type="button" onClick={this.addItem}>
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
);
}
});
var FixedAnswerQuestionCreate = React.createClass({
setAnswer: function(answer) {
answer = answer.toString();
this.props.onChange({answer: answer});
},
getInitialState: function() {
answer = [];
if (this.props.defaults != undefined) {
if (this.props.defaults.answer != undefined) {
answer = [].concat(this.props.defaults.answer);
}
}
return {answer: answer};
},
check: function(text) {
return true;
},
render: function() {
// Important to call setAnswer here once, so that parent gets correct
// default value of answer
this.setAnswer(this.state.answer);
id = this.props.answerId;
return (
<div class="form-group">
<label class="control-label col-md-2">Correct Answer</label>
<div class="col-md-7">
<ListCreator
id={id}
check={this.check}
onChange={this.setAnswer}
defaultValue={this.state.answer} />
</div>
</div>
);
}
});
var QuestionCreate = React.createClass({
// CAUTION: This class modifies this.state directly at some places
// TODO: FETCH answers
base_url: '/quiz/api/',
answer_box_id: 'answer_box',
createQuestion: function() {
console.log(this.state);
if (this.state['answer'] == undefined || this.state['answer'] == '') {
add_error_to_element($("#" + this.answer_box_id), 'This field is required.');
return;
}
url = '';
method = '';
if (this.refs.type.getDOMNode().value == QUESTION_TYPES.FIXED_ANSWER_QUESTION) {
if (this.props.edit) {
url = this.base_url + "fixed_answer_question/" + this.props.defaults.id + "/?format=json";
method = 'PATCH';
}
else {
url = this.base_url + "question_module/" + this.props.question_module.id + '/add_fixed_answer_question/?format=json';
method = 'POST';
}
} // Add more types here
data = {};
for (var i = 0; i < this.validationFields.length; i++) {
if (this.refs[this.validationFields[i]] != undefined) {
data[this.validationFields[i]] = this.refs[this.validationFields[i]].getDOMNode().value.trim();
}
}
data["granularity"] = this.state.defaults.granularity.toString();
data["granularity_hint"] = this.state.defaults.granularity_hint.toString();
if (data["granularity"] == "") {
data["granularity"] = "undefined";
}
if (data["granularity_hint"] == "") {
data["granularity_hint"] = "undefined";
}
if (this.state.answer_props != undefined) {
for (var attrname in this.state.answer_props) {
data[attrname] = this.state[attrname];
}
}
request = ajax_json_request(url, method, data);
request.done(function(response) {
response = jQuery.parseJSON(response);
data = response;
data['answer_fields'] = {};
for (var attrname in this.state.answer_props) {
data.answer_fields[attrname] = this.state[attrname];
}
this.props.callback(data);
}.bind(this));
request.complete(function(response) {
if (response.status == 400) {
// BAD REQUEST - Data Validation failed
response = jQuery.parseJSON(response.responseText);
this.validation(response);
}
else {
this.removeValidation();
}
}.bind(this));
return false;
},
changeType: function() {
type = this.refs.type.getDOMNode().value;
state = this.state;
state.type = type;
this.setState(state);
},
setAnswer: function(obj) {
console.log("setAnswer");
console.log(obj);
state = this.state;
state["answer_props"] = obj;
for (var attrname in obj) {
state[attrname] = obj[attrname];
}
// WARNING: modifying this.state directly here
this.state = state;
},
getInitialState: function() {
state = {
description: '',
answer_description: '',
granularity: '',
granularity_hint: '',
type: QUESTION_TYPES.FIXED_ANSWER_QUESTION,
marks: 0,
grader_type: 'D',
hint: '',
attempts: 1,
answer_fields: {}
}
main_state = {'answer_props': {}};
if (this.props.defaults != undefined) {
// There may be a better way to do this
for (var i = 0; i < this.validationFields.length; i++) {
if (this.props.defaults[this.validationFields[i]] != undefined) {
state[this.validationFields[i]] = this.props.defaults[this.validationFields[i]];
}
}
if (this.props.defaults.answer_fields != undefined) {
state['answer_fields'] = this.props.defaults.answer_fields;
for (var attr in this.props.defaults.answer_fields) {
main_state[attr] = this.props.defaults.answer_fields[attr];
main_state.answer_props[attr] = this.props.defaults.answer_fields[attr];
}
}
}
if (state.granularity == '') {
state.granularity = [];
}
else {
state.granularity = state.granularity.split(",");
}
if (state.granularity_hint == '') {
state.granularity_hint = [];
}
else {
state.granularity_hint = state.granularity_hint.split(",");
}
main_state['defaults'] = state;
return main_state;
},
onGranularityChange: function(list) {
// WARNING: modifying this.state directly here
this.state.defaults.granularity = list;
},
onHintGranularityChange: function(list) {
// WARNING: modifying this.state directly here
this.state.defaults.granularity_hint = list;
},
validationFields: new Array('description', 'answer_description', 'hint', 'granularity', 'granularity_hint', 'marks', 'grader_type', 'type', 'attempts'),
removeValidation: function() {
// this may not be needed because after creation, the parent of QuestionCreate should be re-rendered and hence this module
if (this.refs == undefined) {
return;
}
for (var i = 0; i < this.validationFields.length; i++) {
if (this.refs[this.validationFields[i]] != undefined) {
input = $(this.refs[this.validationFields[i]].getDOMNode());
remove_error_from_element(input);
}
}
},
validation: function(response) {
for (var i = 0; i < this.validationFields.length; i++) {
if (response[this.validationFields[i]] != undefined) {
input = $(this.refs[this.validationFields[i]].getDOMNode());
add_error_to_element(input, response[this.validationFields[i]]);
}
}
},
checkGranularity: function(text) {
return !isNaN(text);
},
render: function() {
answer_box = <div></div>;
if (this.state.defaults.type == QUESTION_TYPES.FIXED_ANSWER_QUESTION) {
answer_box = <FixedAnswerQuestionCreate defaults={this.state.defaults.answer_fields} onChange={this.setAnswer} answerId={this.answer_box_id} />
}
return (
<form role="form" class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2">Description</label>
<div class="col-md-7">
<WmdTextarea ref="description" placeholder="Description" defaultValue={this.state.defaults.description} />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Marks</label>
<div class="col-md-4">
<input type="number" class="form-control" ref="marks" placeholder="Maximum marks" defaultValue={this.state.defaults.marks} />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Attempts</label>
<div class="col-md-4">
<input type="number" class="form-control" ref="attempts" placeholder="Maximum attempts" defaultValue={this.state.defaults.attempts} />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Granularity</label>
<div class="col-md-6">
<ListCreator check={this.checkGranularity} onChange={this.onGranularityChange} defaultValue={this.state.defaults.granularity} />
<span class="help-block">Leave blank for default value</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Type</label>
<div class="col-md-4">
<select class="form-control" ref="type" onChange={this.changeType} defaultValue={this.state.defaults.type}>
<option value='F'>Fixed Answer Question</option>
</select>
</div>
</div>
{answer_box}
<div class="form-group">
<label class="control-label col-md-2">Hint</label>
<div class="col-md-7">
<WmdTextarea ref="hint" placeholder="Hint" defaultValue={this.state.defaults.hint} />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Granularity after hint</label>
<div class="col-md-6">
<ListCreator check={this.checkGranularity} onChange={this.onHintGranularityChange} defaultValue={this.state.defaults.granularity_hint} />
<span class="help-block">Leave blank for default value</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Answer Description</label>
<div class="col-md-7">
<WmdTextarea ref="answer_description" placeholder="Answer Description" defaultValue={this.state.defaults.answer_description} />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Grading Type</label>
<div class="col-md-4">
<select class="form-control" ref="grader_type" defaultValue={this.state.defaults.grader_type}>
<option value='D'>Direct</option>
<option value='M'>Manual</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-2">
<button type="button" class="btn btn-primary" onClick={this.createQuestion}>Save Question</button>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-danger" onClick={this.props.closeCallback}>Close</button>
</div>
</div>
</form>
);
}
});
var QuestionEditRow = React.createClass({
mixins: [confirmDeleteMixin],
base_url: '/quiz/api/',
editQuestion: function() {
this.props.editCallback(this.props.data);
},
deleteObject: function() {
if (this.checkDeleteStage()) return;
url = this.base_url + "question/" + this.props.data.id + "/?format=json";
request = ajax_json_request(url, "DELETE", {});
request.done(function(response) {
this.props.deleteCallback(this.props.data);
}.bind(this));
request.complete(function(response) {
this.resetDelete();
}.bind(this));
},
render: function() {
delete_bar = this.getDeleteBar();
var _description = converter.makeHtml(this.props.data.description);
return (
<tr>
<td>
<button type="submit" class="btn btn-default btn-sm" onClick={this.editQuestion}>
Edit
</button>
</td>
<td>
<span dangerouslySetInnerHTML={{__html: _description}} />
</td>
<td>{this.props.data.marks}</td>
<td>{this.props.data.attempts}</td>
<td>
{delete_bar}
</td>
</tr>
);
}
});
var QuestionModuleEditAdmin = React.createClass({
closePanel: function() {
close_question_list();
},
base_url: "/quiz/api/",
openQuestion: null,
getInitialState: function() {
this.getQuestions();
return {
loaded: false,
create: false,
edit: false,
title_edit: false,
question_module: this.props.question_module
};
},
editQuestion: function(data) {
this.openQuestion = data.id;
state = this.state;
state.create = false;
state.edit = true;
state.defaults = data;
this.setState(state);
window.scrollTo(0, document.getElementById(QuestionModuleEditId).offsetTop-75);
},
createQuestion: function(data) {
oldState = this.state;
if (this.state.edit) {
for (var i = 0; i < oldState.questions.length; i++) {
if (oldState.questions[i]['id'] == data['id']) {
oldState.questions[i] = data;
break;
}
}
}
else if (this.state.create) { // Either one must be true
oldState.questions.push(data);
}
oldState.create = false;
oldState.edit = false;
this.setState(oldState);
window.scrollTo(0, document.getElementById(QuestionModuleEditId).offsetTop-75);
},
deleteQuestion: function(data) {
questions = this.state.questions;
index = questions.indexOf(data);
if (index > -1) {
questions.splice(index, 1);
}
oldState = this.state;
oldState.questions = questions;
if (this.openQuestion == data.id) {
oldState.create = false;
oldState.edit = false;
window.scrollTo(0, document.getElementById(QuestionModuleEditId).offsetTop-75);
}
this.setState(oldState);
},
getQuestions: function() {
url = this.base_url + "question_module/" + this.props.question_module.id + "/get_questions_admin/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.questions = response;
oldState.loaded = true;
this.setState(oldState);
}.bind(this));
},
showQuestionCreate: function() {
oldState = this.state;
oldState.create = true;
this.setState(oldState);
},
closeCreate: function() {
oldState = this.state;
oldState.create = false;
oldState.edit = false;
// Change this to suit the application of this component
window.scrollTo(0, document.getElementById(QuestionModuleEditId).offsetTop-75);
this.setState(oldState);
},
editQuestionModule: function(data) {
state = this.state;
state.question_module = data;
state.title_edit = false;
display_global_message("Successfully saved", "success");
this.setState(state);
},
showTitleEdit: function() {
state = this.state;
state.title_edit = true;
this.setState(state);
},
render: function() {
if (!this.state.loaded) {
return (
<div class="panel panel-default">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>
);
}
question_create = <button type="button" class="btn btn-primary" onClick={this.showQuestionCreate}> Add new Question </button>;
if (this.state.create) {
question_create =
<QuestionCreate
callback={this.createQuestion}
question_module={this.state.question_module}
closeCallback={this.closeCreate} />;
}
else if (this.state.edit) {
question_create =
<QuestionCreate
key={this.state.question_module.id + "/" + this.state.defaults.id}
edit={true}
callback={this.createQuestion}
defaults={this.state.defaults}
question_module={this.props.question_module}
closeCallback={this.closeCreate} />;
}
question_edit = this.state.questions.map(function(q) {
return <QuestionEditRow editCallback={this.editQuestion} deleteCallback={this.deleteQuestion} data={q} />;
}.bind(this));
title_edit = '';
if (this.state.title_edit) {
title_edit =
<ul class="list-group">
<li class="list-group-item question-module-edit">
<QuestionModuleCreate data={this.state.question_module} callback={this.editQuestionModule} />
</li>
</ul>;
}
else {
title_edit =
<ul class="list-group">
<li class="list-group-item question-module-edit">
<button type="button" class="btn btn-default" onClick={this.showTitleEdit} >Edit Description</button>
</li>
</ul>;
}
return (
<div class="panel panel-default">
<div class="panel-heading">
<span class="quiz-text-mute quiz-right-margin">Editing</span>
<strong class="quiz-right-margin">
{this.props.quiz.title}
</strong>
<span class="glyphicon glyphicon-arrow-right quiz-right-margin"></span>
<strong>
Module ID {this.state.question_module.id}
</strong>
<span class="pull-right">
<button type="button" class="close" onClick={this.closePanel}>×</button>
</span>
</div>
<div class="panel-body" ref="create">
{question_create}
</div>
{title_edit}
<table class="table table-hover quiz-table">
<tbody>
<tr>
<th width="11%"></th>
<th>Description</th>
<th>Points</th>
<th>Attempts</th>
<th class="confirm-delete"></th>
</tr>
{question_edit}
</tbody>
</table>
</div>
);
}
});
var QuestionModuleCreate = React.createClass({
base_url: "/quiz/api/",
// always return false
createQuestionModule: function() {
url = this.base_url + "quiz/" + this.props.quiz_id + "/add_question_module/?format=json";
method = "POST";
data = {
quiz: this.props.quiz_id,
title: this.refs.title.getDOMNode().value.trim()
};
if (this.props.data != undefined) {
url = this.base_url + "question_module/" + this.props.data.id + "/?format=json";
method = "PATCH";
}
request = ajax_json_request(url, method, data);
request.done(function(response) {
response = jQuery.parseJSON(response);
data = response;
this.props.callback(data);
}.bind(this));
request.complete(function(response) {
if (response.status == 400) {
// BAD REQUEST - Data Validation failed
response = jQuery.parseJSON(response.responseText);
if (response.title != undefined) {
// TODO: replace with foreach (this.refs)
title_input = $(this.refs.title.getDOMNode());
add_error_to_element(title_input, response.title);
}
}
else {
title_input = $(this.refs.title.getDOMNode());
remove_error_from_element(title_input);
}
if (this.props.data == undefined) {
this.refs.title.getDOMNode().value = '';
}
}.bind(this));
return false;
},
getInitialState: function() {
return {
errors: {
title: "",
description: ""
}
};
},
render: function() {
if (this.props.data != undefined) {
return (
<div>
<div class="col-md-4 form-group">
<button onClick={this.createQuestionModule} type="submit" class="btn btn-primary">Save Description</button>
</div>
<div class="col-md-8 form-group">
<WmdTextarea ref="title" placeholder="Question Module Description" defaultValue={this.props.data.title} />
</div>
</div>
);
}
return (
<div>
<div class="col-md-4 form-group">
<button onClick={this.createQuestionModule} type="submit" class="btn btn-primary">Add Question Module</button>
</div>
<div class="col-md-8 form-group">
<WmdTextarea ref="title" placeholder="Question Module Description" />
</div>
</div>
);
}
});
var QuestionModuleEditRow = React.createClass({
mixins: [confirmDeleteMixin],
base_url: "/quiz/api/",
editQuestionModule: function() {
this.props.editCallback(this.props.data);
},
deleteObject: function() {
if (this.checkDeleteStage()) return;
url = this.base_url + "question_module/" + this.props.data.id + "/?format=json";
request = ajax_json_request(url, "DELETE", {});
request.done(function(response) {
this.props.deleteCallback(this.props.data);
}.bind(this));
request.complete(function(response) {
this.resetDelete();
}.bind(this));
},
render: function() {
delete_bar = this.getDeleteBar();
var _title = converter.makeHtml(this.props.data.title);
return (
<tr>
<td>
<button type="submit" class="btn btn-default btn-sm" onClick={this.editQuestionModule}>
Edit
</button>
</td>
<td>{this.props.data.id}</td>
<td><span dangerouslySetInnerHTML={{__html: _title}} /></td>
<td>
{delete_bar}
</td>
</tr>
);
}
});
var QuizEditAdmin = React.createClass({
// TODO: Use a mixin to implement functionality of QuizEditAdmin and QuizAdmin
// when the course module is completed and quizzes are fetched from the
// course instead of list(quiz)
closePanel: function() {
close_question_list();
close_question_module_list();
},
base_url: "/quiz/api/",
openQuestionModule: null,
getInitialState: function() {
this.getQuestionModules();
return {
loaded: false
};
},
editQuestionModule: function(data) {
this.openQuestionModule = data.id;
$("#" + QuestionModuleEditId).html("");
React.renderComponent(
<QuestionModuleEditAdmin question_module={data} quiz={this.props.quiz}/>,
document.getElementById(QuestionModuleEditId)
);
$("#" + QuestionModuleEditId).hide().fadeIn();
},
createQuestionModule: function(data) {
oldState = this.state;
oldState.question_modules.push(data);
this.setState(oldState);
this.editQuestionModule(data);
},
deleteQuestionModule: function(data) {
if (this.openQuestionModule == data.id) {
close_question_list();
window.scrollTo(0, document.getElementById(QuizEditAdminId).offsetTop-75);
}
question_modules = this.state.question_modules;
index = question_modules.indexOf(data);
if (index > -1) {
question_modules.splice(index, 1);
}
oldState = this.state;
oldState.question_modules = question_modules;
this.setState(oldState);
},
getQuestionModules: function() {
url = this.base_url + "quiz/" + this.props.quiz.id + "/get_question_modules/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.question_modules = response;
oldState.loaded = true;
this.setState(oldState);
}.bind(this));
},
refresh: function() {
this.getQuestionModules();
},
render: function() {
if (!this.state.loaded) {
return (
<div class="panel panel-default">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>
);
}
qm_edit = this.state.question_modules.map(function(q) {
return <QuestionModuleEditRow editCallback={this.editQuestionModule} deleteCallback={this.deleteQuestionModule} data={q} />;
}.bind(this));
return (
<div class="panel panel-default">
<div class="panel-heading">
<span class="quiz-text-mute quiz-right-margin">Editing</span>
<strong>{this.props.quiz.title}</strong>
<span class="pull-right">
<button type="button" class="close" onClick={this.closePanel}>×</button>
</span>
</div>
<div class="panel-body">
<QuestionModuleCreate quiz_id={this.props.quiz.id} callback={this.createQuestionModule}/>
</div>
<table class="table table-hover quiz-table">
<tbody>
<tr>
<th width="11%"></th>
<th>ID</th>
<th>Title</th>
<th class="confirm-delete">
<span class="pull-right">
<button class="btn btn-default" title="Refresh">
<span class="glyphicon glyphicon-refresh" onClick={this.refresh}></span>
</button>
</span>
</th>
</tr>
{qm_edit}
</tbody>
</table>
</div>
);
}
});
var QuizCreate = React.createClass({
base_url: "/quiz/api/",
// always return false
createQuiz: function() {
url = this.base_url + "quiz/?format=json";
data = {
title: this.refs.title.getDOMNode().value.trim()
};
this.refs.title.getDOMNode().value = '';
request = ajax_json_request(url, "POST", data);
request.done(function(response) {
response = jQuery.parseJSON(response);
data = response;
this.props.callback(data);
}.bind(this));
request.complete(function(response) {
if (response.status == 400) {
// BAD REQUEST - Data Validation failed
response = jQuery.parseJSON(response.responseText);
if (response.title != undefined) {
// TODO: replace with foreach (this.refs)
title_input = $(this.refs.title.getDOMNode());
add_error_to_element(title_input, response.title);
}
}
else {
title_input = $(this.refs.title.getDOMNode());
remove_error_from_element(title_input);
}
}.bind(this));
return false;
},
getInitialState: function() {
return {
errors: {
title: ""
}
};
},
render: function() {
return (
<form role="form" class="form-inline" onSubmit={this.createQuiz}>
<div class="col-md-2 form-group">
<button type="submit" class="btn btn-primary">Add Quiz</button>
</div>
<div class="col-md-4 form-group">
<input type="text" class="form-control" ref="title" placeholder="Quiz Title" />
</div>
</form>
);
}
});
var QuizEditRow = React.createClass({
mixins: [confirmDeleteMixin],
base_url: "/quiz/api/",
editQuiz: function() {
this.props.editCallback(this.props.data);
},
deleteObject: function() {
if (this.checkDeleteStage()) return;
url = this.base_url + "quiz/" + this.props.data.id + "/?format=json";
request = ajax_json_request(url, "DELETE", {});
request.done(function(response) {
this.props.deleteCallback(this.props.data);
}.bind(this));
request.complete(function(response) {
this.resetDelete();
}.bind(this));
},
render: function() {
delete_bar = this.getDeleteBar();
return (
<tr>
<td>
<button type="submit" class="btn btn-default btn-sm" onClick={this.editQuiz}>
Edit
</button>
</td>
<td>{this.props.data.title}</td>
<td>{this.props.data.marks}</td>
<td>{this.props.data.question_modules}</td>
<td>{this.props.data.questions}</td>
<td>
{delete_bar}
</td>
</tr>
);
}
});
var QuizAdmin = React.createClass({
/*
* We do not update the question stats in this component using callbacks
* since we want to be able to include any component anywhere on the platform
* and doing so will make it more complex for reusablity. Hence we provide
* a REFRESH button
*/
base_url: "/quiz/api/",
openQuiz: null,
getInitialState: function() {
this.getQuizzes();
return {
loaded: false
};
},
editQuiz: function(data) {
this.openQuiz = data.id;
$("#" + QuizEditAdminId).html("");
React.renderComponent(
<QuizEditAdmin quiz={data} />,
document.getElementById(QuizEditAdminId)
);
$("#" + QuizEditAdminId).hide().fadeIn();
},
createQuiz: function(data) {
oldState = this.state;
oldState.quizzes.push(data);
this.setState(oldState);
this.editQuiz(data);
},
deleteQuiz: function(data) {
if (this.openQuiz == data.id) {
close_question_list();
close_question_module_list();
window.scrollTo(0, document.getElementById(QuizAdminId).offsetTop-75);
}
quizzes = this.state.quizzes;
index = quizzes.indexOf(data);
if (index > -1) {
quizzes.splice(index, 1);
}
oldState = this.state;
oldState.quizzes = quizzes;
this.setState(oldState);
},
getQuizzes: function() {
url = this.base_url + "quiz/?format=json";
request = ajax_json_request(url, "GET", {});
request.done(function(response) {
response = jQuery.parseJSON(response);
oldState = this.state;
oldState.quizzes = response;
oldState.loaded = true;
this.setState(oldState);
}.bind(this));
},
refresh: function() {
this.getQuizzes();
},
render: function() {
if (!this.state.loaded) {
return (
<div class="panel panel-default">
<div class="panel-heading text-center"><LoadingBar /></div>
</div>
);
}
else {
quiz_edit = this.state.quizzes.map(function(q) {
return <QuizEditRow editCallback={this.editQuiz} deleteCallback={this.deleteQuiz} data={q} />;
}.bind(this));
return (
<div class="panel panel-default">
<div class="panel-heading">
Course Quizzes
<span class="pull-right quiz-text-mute">Admin Panel</span>
</div>
<div class="panel-body">
<QuizCreate callback={this.createQuiz} />
<span class="pull-right">
<button class="btn btn-default" title="Refresh">
<span class="glyphicon glyphicon-refresh" onClick={this.refresh}></span>
</button>
</span>
</div>
<table class="table table-hover quiz-table">
<tbody>
<tr>
<th></th>
<th>Title</th>
<th>Maximum points</th>
<th>Question modules</th>
<th>Questions</th>
<th class="confirm-delete"></th>
</tr>
{quiz_edit}
</tbody>
</table>
</div>
);
}
}
});
React.renderComponent(
<QuizAdmin id="1" />,
document.getElementById(QuizAdminId)
);
$("#" + QuizAdminId).hide().fadeIn();
<file_sep>/upload/migrations/0002_auto__add_field_upload_comments.py
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Upload.comments'
db.add_column(u'upload_upload', 'comments',
self.gf('django.db.models.fields.TextField')(null=True, blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Upload.comments'
db.delete_column(u'upload_upload', 'comments')
models = {
u'assignments.assignment': {
'Meta': {'unique_together': "(('course', 'name'),)", 'object_name': 'Assignment'},
'course': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['courseware.Course']"}),
'createdOn': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'creater': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'deadline': ('django.db.models.fields.DateTimeField', [], {'null': "'true'"}),
'description': ('django.db.models.fields.TextField', [], {'null': "'true'"}),
'document': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': "'true'"}),
'hard_deadline': ('django.db.models.fields.DateTimeField', [], {'null': "'true'"}),
'helper_code': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': "'true'"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modified_on': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'late_submission_allowed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'model_solution': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': "'true'"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'program_language': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'publish_on': ('django.db.models.fields.DateTimeField', [], {}),
'serial_number': ('django.db.models.fields.IntegerField', [], {}),
'student_program_files': ('django.db.models.fields.CharField', [], {'max_length': '1024'})
},
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('<PASSWORD>', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'courseware.category': {
'Meta': {'object_name': 'Category'},
'content_developers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Category_User'", 'symmetrical': 'False', 'to': u"orm['auth.User']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Parent'", 'to': u"orm['courseware.ParentCategory']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'courseware.course': {
'Meta': {'object_name': 'Course'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Category_Course'", 'to': u"orm['courseware.Category']"}),
'course_info': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'CourseInfo_Course'", 'unique': 'True', 'null': 'True', 'to': u"orm['courseware.CourseInfo']"}),
'enrollment_type': ('django.db.models.fields.CharField', [], {'default': "'M'", 'max_length': '1'}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Course_Forum'", 'to': u"orm['discussion_forum.DiscussionForum']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'max_score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'page_playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'pages': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'Course_Document'", 'symmetrical': 'False', 'to': u"orm['document.Document']"}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'type': ('django.db.models.fields.CharField', [], {'default': "'T'", 'max_length': '1'})
},
u'courseware.courseinfo': {
'Meta': {'object_name': 'CourseInfo'},
'description': ('django.db.models.fields.TextField', [], {'default': "''"}),
'end_enrollment_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'end_time': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'start_time': ('django.db.models.fields.DateField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'})
},
u'courseware.parentcategory': {
'Meta': {'object_name': 'ParentCategory'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
u'discussion_forum.discussionforum': {
'Meta': {'object_name': 'DiscussionForum'},
'abuse_threshold': ('django.db.models.fields.IntegerField', [], {'default': '5'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'review_threshold': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'thread_count': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'document.document': {
'Meta': {'object_name': 'Document'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_heading': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_link': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'link': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}),
'playlist': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'uid': ('django.db.models.fields.CharField', [], {'max_length': '32'})
},
u'upload.upload': {
'Meta': {'object_name': 'Upload'},
'assignment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['assignments.Assignment']", 'null': 'True', 'blank': 'True'}),
'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'filePath': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_stale': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'uploaded_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
}
}
complete_apps = ['upload']<file_sep>/video/urls.py
"""
URL Mapping for Video API
This is API for view/edit/upload video
"""
from django.conf.urls import include, patterns, url
from rest_framework.routers import DefaultRouter
from video import views
# Configuring ROUTERs
router = DefaultRouter()
router.register(r'video', views.VideoViewSet)
router.register(r'marker', views.MarkerViewSet)
urlpatterns = patterns(
'',
url(r'^api/', include(router.urls)),
url(r'^api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
url(r'^play_video', views.play_video, name="play_video"),
url(r'^upload_video', views.upload_video, name="upload_video"),
url(r'^edit_video', views.edit_video, name="edit_video"),
)
<file_sep>/courses/urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('courses.views',
url(r'^$', 'index', name='courses_index'),
#url(r'^(?P<courseid>\d+)$', 'courseInfo', name='courses_courseInfo'),
#url(r'^join/(?P<courseid>\d+)$', 'joinCourse', name='courses_joincourse'), TODO:
#url(r'^join/(?P<courseid>\d+)$', 'joinCourse', name='courses_joincourse'),
#url(r'^leave/(?P<courseid>\d+)$', 'leaveCourse', name='courses_leavecourse'),
#url(r'^searchcourses/$', 'searchCourse', name='courses_searchcourse'),
#url(r'^edit/(?P<courseid>\d+)$', 'editCourse', name='courses_editCourse'),
#url(r'^all/$', 'all_courses', name='courses_allcourses'),
#url(r'^create/$', 'create_course', name='courses_createcourse'),
#url(r'^delete/(?P<courseid>\d+)$', 'delete_course', name='courses_deletecourse'),
)
<file_sep>/cribs/models.py
from django.db import models
from django.contrib.auth.models import User
from assignments.models import Assignment
class Crib(models.Model):
assignment = models.ForeignKey(Assignment)
created_by = models.ForeignKey(User)
title = models.CharField(max_length=512)
crib_detail = models.TextField()
is_resolved = models.BooleanField()
created_on = models.DateTimeField(auto_now_add=True)
last_modified_on = models.DateTimeField(auto_now=True)
class Comment(models.Model):
crib = models.ForeignKey(Crib)
posted_by = models.ForeignKey(User)
comment = models.TextField()
posted_on = models.DateTimeField(auto_now_add=True) | a8048b1c877aa4130c92f4e3ae0179f5d90bb170 | [
"HTML",
"JavaScript",
"Markdown",
"INI",
"Java",
"Python",
"Text",
"C++",
"Shell"
] | 186 | HTML | saketkc/elearning_academy1 | 84d462bd51c178c70cb3eaeb1228f6b3ef92ba7d | 1b488c1580be54bf949114dffb1e52db99379988 |
refs/heads/master | <file_sep>x=int(input("enter first number:"))
y=int(input("enter second number:"))
z=int(input("enter third number:"))
print("the max number is:")
print(max(x,y,z))
input("please press enter to exit")
| 1597c623faa25834fc410759910c656785bcd39c | [
"Python"
] | 1 | Python | Evashen-123/Python-maxNumber | 2e76e85e97895d5c40ec6a39f9c2a95496d63a75 | d27d5b825b44a9cc01523a6fbe6d6c71bad2bb17 |
refs/heads/main | <file_sep>from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from pickle import dump
import read_dataset
names = ["Nearest Neighbors", "Linear SVM", "Decision Tree", "Neural Net"]
scoring = ["accuracy", "recall", "precision", "f1"]
kncParams = {'n_neighbors': [3, 5, 10]}
svcParams = {'C': [0.025, 0.5, 1]}
dtcParams = {'max_depth': [5, 10, 15]}
mlpParams = {'alpha': [0.0001, 0.001, 1], 'max_iter': [500, 1000, 1500]}
tuneParams = [kncParams, svcParams, dtcParams, mlpParams]
classifiers = [
KNeighborsClassifier(),
SVC(kernel="linear"),
DecisionTreeClassifier(),
MLPClassifier()]
X, y = read_dataset.get_happieness_dataset()
X = StandardScaler().fit_transform(X)
y = y.astype('int')
X_train, X_test, y_train, y_test = \
train_test_split(X, y, test_size=.4, random_state=42)
wholeBestEstimator = None
wholeBestScore = 0.0
# iterate over classifiers
for name, clf, params in zip(names, classifiers, tuneParams):
gsCV = GridSearchCV(clf, params, scoring=scoring, refit='accuracy')
gsCV.fit(X_train, y_train)
if wholeBestScore < gsCV.best_score_:
wholeBestEstimator = (name, gsCV.best_estimator_)
wholeBestScore = gsCV.best_score_
y_pred = gsCV.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
print("Accuracy:{:.3f}".format(accuracy),
"| Recall:{:.3f}".format(recall),
"| Precision:{:.3f}".format(precision),
"| F1 score:{:.3f}".format(f1),
"({0}; params:{1})".format(name, gsCV.best_params_))
print(wholeBestEstimator[0] + " won the prize!")
bestFileNameEver = "happieness.dbd"
dump(wholeBestEstimator, open(bestFileNameEver, 'wb'))
print(wholeBestEstimator[0] + " was saved to " + bestFileNameEver)
print("Done")
<file_sep>FROM python:3.7
RUN pip install --upgrade pip
RUN pip install --no-cache-dir scikit-learn pandas pymongo
RUN mkdir -p /usr/src/app/
WORKDIR /usr/src/app/
COPY . /usr/src/app/
EXPOSE 27017
CMD ["python", "-u", "run.py"]<file_sep>import pandas as pd
from time import sleep
from ml_model import MlModel
from Mongo.mongodb_service import MongodbService
print("create MlModel")
model = MlModel()
storage = MongodbService.get_instance()
while 1:
print("Waiting for transaction")
transaction = None
while transaction is None:
sleep(0.5)
transaction = storage.get_input_transaction()
print("Got it - {}".format(transaction))
df = pd.DataFrame(transaction, index=[0]).drop("_id", axis=1)
result = model.predict(df)[0]
print("Result - {}".format(result))
storage.set_output_transaction(result)
<file_sep>version: '3.3'
services:
mongodb:
image : mongo
container_name: mongodb
environment:
- PUID=1000
- PGID=1000
volumes:
- /mongodb/database:/data/db
ports:
- 27017:27017
restart: unless-stopped
client:
build: ./Client
ports:
- '5000:5000'
volumes:
- '/var/run/docker.sock:/tmp/docker.sock:ro'
image: client_lab
server:
build: ./Server
volumes:
- '/var/run/docker.sock:/tmp/docker.sock:ro'
image: server_lab<file_sep>from pymongo import MongoClient
class MongodbService(object):
_instance = None
_client = None
_db = None
@classmethod
def get_instance(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls, *args, **kwargs)
cls.__init__(cls._instance, *args, **kwargs)
return cls._instance
def __init__(self):
self._client = MongoClient("192.168.1.32", 27017)
self._db = self._client.breast_cancer_db
def get_input_transaction(self):
current_transaction = self._db.transactions_input.find_one()
if current_transaction is not None:
self._db.transactions_input.delete_one({"_id": current_transaction["_id"]})
return current_transaction
def set_output_transaction(self, result):
return self._db.transactions_output.insert_one({"result": int(result)})
<file_sep>FROM python:3.7
RUN pip install --upgrade pip
RUN pip install --no-cache-dir scikit-learn pandas pymongo flask requests boto3
RUN mkdir -p /usr/src/app/
WORKDIR /usr/src/app/
COPY . /usr/src/app/
EXPOSE 27017 8000
CMD ["python", "-u", "app.py"]
<file_sep>from time import sleep
from Mongo.mongodb_service import MongodbService
#from sklearn.preprocessing import StandardScaler
#import cgi, cgitb
def predict(dto):
storage = MongodbService.get_instance()
print(dto)
storage.set_input_transaction(dto)
result = None
while result is None:
sleep(0.5)
result = storage.get_output_transaction()
return result<file_sep>from flask import Flask, render_template, request
import os
import requests
from run_client import predict
import json
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/uploader', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
input2 = request.form['input2']
input4 = request.form['input4']
input5 = request.form['input5']
input6 = request.form['input6']
input7 = request.form['input7']
input8 = request.form['input8']
input9 = request.form['input9']
result = predict({'Country or region': input2, 'GDP per capita': input4, 'Social support': input5, 'Healthy life expectancy': input6, 'Freedom to make life choices': input7, 'Generosity': input8, 'Perceptions of corruption': input9})
print(result)
if float(result) == 1:
result = "Most likely you are happy and live in a happy environment"
else:
result = "Keep strong, be happy"
else:
result = 'damn'
return render_template('result.html', result=result)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)
<file_sep>from pickle import load
best_clf_filename = "happieness.dbd"
class MlModel(object):
_model = None
def __init__(self):
loaded_model = load(open(best_clf_filename, 'rb'))
self._model = loaded_model[1]
def predict(self, x_data):
return self._model.predict(x_data)
<file_sep>import pandas as pd
def get_happieness_dataset():
df = pd.read_csv(r'2019.csv')
return df.drop('happieness', axis=1), df['happieness']
| 7ec87c0b8e09a0173a3e9b4051a117fb526fbf94 | [
"Python",
"Dockerfile",
"YAML"
] | 10 | Python | VaskaKasatka/DenisovLabPosii | e8af58edd000398123fbe537cb081b9ca6831371 | bfaaca6765baa38f59f1dea063c8c43f27133689 |
refs/heads/master | <repo_name>adiu2016/ng1<file_sep>/src/services/ajax.js
/**
* author: guorm
* description: AJAX工具
*/
angular.module('app').factory('ajax', ajax);
function ajax($http, $httpParamSerializerJQLike)
{
return {
get: function(url, paramsObj)
{
return $http({
url: url,
method: 'GET',
params: paramsObj,
paramSerializer: '$httpParamSerializerJQLike'
});
},
post: function(url, dataObj)
{
return $http({
url: url,
method: 'POST',
data: $httpParamSerializerJQLike(dataObj),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
}
};
<file_sep>/src/features/basicInfo/org/org.router.js
/**
* @author: guorm
* @desp: 组织机构 路由定义
*/
angular.module('app.basicInfo.org')
.config(function ($stateProvider) {
$stateProvider
.state('layout.org', {
url: '/org',
views:{
"main":{
templateUrl: 'features/basicInfo/org/tpls/org.html',
controller: 'OrgCtrl'
}
}
})
});<file_sep>/workflow/task/tplsCache.js
/**
* 缓存HTML模板
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
gulp.task('tplsCache', function() {
return gulp.src(common.config.src.views)
.pipe(common.plugins.ngHtml2Js({
moduleName: "app.template"
}))
.pipe(common.plugins.concat("tplsCache.js"))
.pipe(common.plugins.uglify())
.pipe(common.plugins.rev())
.pipe(gulp.dest(common.config.dist.js))
.pipe(common.plugins.rev.manifest({
base: common.config.src.rev,
merge: true
}))
.pipe(gulp.dest(common.config.src.rev))
});
}<file_sep>/src/components/ngTab/ngTab.js
/**
* author: guorm
* descriptipn: 选项卡
*
<tabs init="1" position="left" event="hover">
<pane
ng-repeat="pane in panes track by $index"
name="pane.name"
iname="pane.iname">
{{pane.text}}
</pane>
</tabs>
* @param - name:标签项名称
* @param - iname:icon图标名称
* @param - init:指定选项索引值,默认为0
* @param - event:指定触发事件,默认为单击
* @param - position:指定标签项的显示方位(left, bottom, right),默认为top
*/
angular.module('ngTab', []).directive('tabs', tabs).directive('pane', pane);
function tabs()
{
return {
restrict: 'E',
transclude: true,
scope: {
event: '@',
initIndex: '@init',
tabPosition: '@position'
},
controller: TabsCtrl,
templateUrl: 'components/ngTab/tabs.html',
replace: true
};
};
function pane()
{
return {
require: '^?tabs',
restrict: 'E',
transclude: true,
scope: {
name: '=',
iname: '='
},
/* 建立数据绑定 */
link: function(scope, element, attrs, tabsCtrl) {
tabsCtrl.addPane(scope);
},
template:
'<div class="tab-pane" ng-class="{active: selected}" ng-transclude></div>',
replace: true
};
};
function TabsCtrl($scope)
{
var vm = $scope;
var items = vm.items = [];
// 参数初始化
var initIndex = vm.initIndex ? vm.initIndex : 0,
event = (vm.event == 'hover') ? true : false;
vm.getTabPos = function()
{
if(vm.tabPosition)
{
return 'tab-' + vm.tabPosition;
};
};
// 当前状态的切换
vm.select = function(item)
{
angular.forEach(items, function(item)
{
item.selected = false;
});
item.selected = true;
};
// TAB初始化数据
this.addPane = function(item)
{
if (items.length == initIndex)
{
vm.select(item);
};
items.push(item);
};
};<file_sep>/workflow/task/rev.js
/**
* index模板文件替换为MD5后缀文件
*
* @author: guorm
* @date 2016-03-20
*/
module.exports = function(gulp, common)
{
gulp.task('rev', function() {
return gulp.src([common.config.src.revFile,common.config.dist.index])
.pipe(common.plugins.revCollector({replaceReved:true}))
.pipe(gulp.dest(common.config.dist.root))
});
}<file_sep>/workflow/task/minCtrls.js
/**
* 服务打包
*
* @author: guorm
* @date 2016-03-20
*/
module.exports = function(gulp, common)
{
gulp.task('minCtrls', function() {
return gulp.src(common.config.src.ctrls)
.pipe(common.plugins.ngAnnotate({single_quotes: true}))
.pipe(common.plugins.concat('ctrls.js'))
.pipe(common.plugins.uglify())
.pipe(common.plugins.rev())
.pipe(gulp.dest(common.config.dist.js))
.pipe(common.plugins.rev.manifest({
base: common.config.src.rev,
merge: true
}))
.pipe(gulp.dest(common.config.src.rev))
});
}<file_sep>/workflow/task/clean.js
/**
* 删除文件
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
gulp.task('clean', function() {
return gulp.src(common.config.dist.root)
.pipe(common.plugins.clean());
});
}<file_sep>/src/features/user/router/user.router.js
/**
* author: guorm
* descriptipn: 登陆模块路由
*/
angular.module('app.user').config(function($stateProvider) {
$stateProvider
.state('root.login', {
url: '/login',
views: {
'main@': {
templateUrl: 'features/user/tpls/user.login.html',
controller: 'UserLogin'
}
},
data: {
pageTitle: '登陆',
pageClass: 'login'
}
})
});<file_sep>/src/decorators/active.js
/**
* author: guorm
* descriptipn: 当前单击项高亮显示
*
<ul active>
<li ng-click="storeIndex($index)" ng-class="{'active': $index == curIndex}" ng-repeat="list in lists track by $index">
{{list.name}}
</li>
</ul>
*/
angular.module('app').directive('active', active);
function active()
{
return {
restrict: 'A',
scope: true,
link: function(scope, ele, attrs)
{
var vm = scope;
vm.storeIndex = function(index)
{
vm.curIndex = index;
};
}
}
};<file_sep>/src/components/ngSearch/ngSearch.js
/**
* author: guorm
* description: 搜索
*
<search type="search" go-state="root.datum.detail" search-conditions="conditions"></search>
* @param - type,指定搜索框的类型:文本按钮(search)、图标按钮(sicon)
* @param - go-state,搜索列表页地址
* @param - search-conditions,搜索条件设置,写在父Controller里
*/
angular.module('ngSearch', []).directive('search', search);
function search()
{
return {
restrict: 'E',
scope: {
type: '@',
goState: '@',
searchConditions: '='
},
controller: SearchCtrl,
templateUrl: 'components/ngSearch/search.html',
replace: true
}
};
function SearchCtrl($scope, $state)
{
var vm = $scope;
vm.searchForm = {};
vm.searchForm.keyword = '';
if(!angular.isUndefined(vm.searchConditions))
{
vm.searchForm.condition = vm.searchConditions[0].value;
};
vm.searchFn = function()
{
$state.go(vm.goState, vm.searchForm);
};
};<file_sep>/src/common/directives/nores.js
/**
* author: guorm
* descriptipn: 没有结果的提示
*
<nores text="暂无结果可显示" url="images/nodata.png"></nores>
*/
angular.module('app').directive('nores', nores);
function nores()
{
return {
restrict: 'EA',
scope: {
text: '@',
url: '@'
},
controller: NoresCtrl,
templateUrl: 'common/tpls/nores.html',
replace: true
}
};
function NoresCtrl($scope, $element, $attrs)
{
var vm = $scope;
if(angular.isUndefined(vm.text))
{
vm.text = '哎!我还没有结果可显示啊!';
}
if(angular.isUndefined(vm.url))
{
vm.url = 'images/nodata.png';
}
};<file_sep>/src/app.js
/**
* @author: guorm
* @desp: 应用模块的划分定义
*/
// HTML模板打包模块
angular.module('app.template', []);
angular.module('app.user', []);
// 基础信息
angular.module('app.basicInfo', [
'app.basicInfo.org',
'app.basicInfo.role',
'app.basicInfo.operator',
'app.basicInfo.setting',
'app.basicInfo.product']);
// 组织机构
angular.module('app.basicInfo.org', []);
// 岗位权限
angular.module('app.basicInfo.role', []);
// 用户管理
angular.module('app.basicInfo.operator', []);
// 密码设置
angular.module('app.basicInfo.setting', []);
// 开票项目管理
angular.module('app.basicInfo.product', []);
angular.module('app', [
'ui.router',
'angular-loading-bar',
'ngDialog',
'ngColTab',
'ngAcdion',
'ngTree',
'app.user',
'app.basicInfo',
'ngInputGroup'
]);<file_sep>/src/features/basicInfo/org/controllers/org.ctrl.js
/**
* @author: guorm
* @desp: 组织机构 Ctrl
*/
angular.module('app.basicInfo.org').controller('OrgCtrl', OrgCtrl);
function OrgCtrl($scope)
{
var vm = $scope;
};<file_sep>/src/components/ngColTab/ngColTab.js
/**
* @author: guorm
* @desp:与左侧菜单栏配合使用的布局Tab
*/
angular.module('ngColTab', []).directive('colTab', colTab);
function colTab()
{
return {
restrict: 'E',
scope: {
items: '=tabItems'
},
controller: ColTabCtrl,
templateUrl: 'components/ngColTab/colTab.html',
replace: true
}
};
function ColTabCtrl($scope)
{
var vm = $scope;
};<file_sep>/src/common/directives/paging.js
/**
* author: guorm
* descriptipn: 本地分页
*
<paging page-size='20' page-data='textPageData'>
...
<ul>
<li ng-repeat="list in $parent.pageData | filter: $parent.overFn | range:$parent.selectedPage:$parent.perPageSize">
{{ list.name }}
</li>
</ul>
</paging>
* @param - page-size,每页显示的条数
* @param - page-data,要分页的数据
*/
angular.module('app').directive('paging', paging);
function paging()
{
return {
restrict: 'E',
transclude: true,
scope: {
pageData: '=',
pageSize: '='
},
controller: PagingCtrl,
templateUrl: 'common/tpls/paging.html',
replace: true
}
};
function PagingCtrl($scope, $element, $attrs)
{
var vm = $scope;
vm.selectedPage = 1;
if(angular.isUndefined(vm.pageSize))
{
vm.perPageSize = 10;
}
else
{
vm.perPageSize = vm.pageSize;
};
vm.overFn = function ()
{
return true;
};
vm.curIndex = 0;
vm.selectPage = function (index, newPage)
{
vm.curIndex = index;
vm.selectedPage = newPage;
};
};<file_sep>/src/services/trans.js
/**
*
* @desp: 转换工具
*/
angular.module('app').factory('trans', trans);
function trans()
{
return {
listToTree: function(nodes, id, pid)
{
var id = id || 'id',
pid = pid || 'pid';
var map = {}, roots = [];
for (var i = 0; i < nodes.length; i++)
{
if(!nodes[i].isLeaf)
{
nodes[i].children = [];
map[nodes[i][id]] = i; // use map to look up the parents
}
}
for (var i = 0; i < nodes.length; i++)
{
if (nodes[i][pid] && map[nodes[i][pid]]<nodes.length)
{
nodes[map[nodes[i][pid]]].children.push(nodes[i]);
} else
{
roots.push(nodes[i]);
}
}
return roots;
}
}
};<file_sep>/src/features/app.ctrl.js
/**
* author: guorm
* descriptipn: ...
*/
angular.module('app').controller('AppCtrl', AppCtrl);
function AppCtrl($scope, $log, $state)
{
$state.go('layout.home');
var vm = $scope;
vm.exders = [{title: '基础信息', child: [
{id: 1, iname: 'img', selected: true, name: '组织机构', state: 'layout.org'},
{id: 2, iname: 'img', selected: true, name: '岗位权限', state: 'layout.role'},
{id: 3, iname: 'img', selected: true, name: '用户管理', state: 'layout.operator'},
{id: 4, iname: 'img', selected: true, name: '密码设置', state: 'layout.setting'},
{id: 5, iname: 'img', selected: true, name: '开票项目管理', state: 'layout.product'}
]},
{title: '进项管理'},
{title: '销项管理'},
{title: '实时报表'},
{title: '税金测算'},
{title: '预警监控'},
{title: '网上申报'}];
vm.tabItems = [{id: 0, iname: 'img', selected: true, name: '首页', state: 'layout.home'}];
vm.addTabItem = function(tabItem)
{
var index = vm.tabItems.indexOf(tabItem);
if( index == -1)
{
if(vm.tabItems.length == 8)
{
vm.tabItems.splice(1);
};
vm.tabItems.push(tabItem);
$state.go(tabItem.state);
}
else
{
$state.go(vm.tabItems[index].state);
};
};
vm.itemClicked = function($item)
{
vm.parentCode = $item.id;
vm.parentName = $item.name;
$log.debug(vm.parentName, vm.parentCode);
};
vm.itemCheckedChanged = function($item)
{
console.log($item,'item checked');
};
};<file_sep>/workflow/task/minCss.js
/**
* CSS压缩
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
gulp.task('minifyCss', function() {
return gulp.src(common.config.src.css)
.pipe(common.plugins.concat('main.css'))
.pipe(common.plugins.cssmin())
.pipe(common.plugins.rev())
.pipe(gulp.dest(common.config.dist.css))
.pipe(common.plugins.rev.manifest({
base: common.config.src.rev,
merge: true
}))
.pipe(gulp.dest(common.config.src.rev))
});
}<file_sep>/src/decorators/cross.js
/**
* author: guorm
* desp: 表格的某个单元格获得焦点时,其所在的行与列均高亮显示
*/
angular.module('app').directive('cross', cross);
function cross($timeout)
{
return {
restrict: 'A',
scope: {},
link: function(scope, ele, attrs)
{
$timeout(timeoutFn, 0);
function timeoutFn()
{
var tdArr = ele.find('td'),
trArr = ele.find('tr');
tdArr.on('mouseover', function(e)
{
var index = e.target.cellIndex;
angular.forEach(trArr, function(item)
{
angular.ele(item).removeClass('highlight');
angular.ele(item).find('td').removeClass('highlight').eq(index).addClass('highlight');
});
angular.element(this).parent().addClass('highlight');
});
tdArr.on('mouseout', function()
{
tdArr.removeClass('highlight');
trArr.removeClass('highlight');
});
};
}
}
};<file_sep>/src/features/user/directives/user.loginbar.js
/**
* author: guorm
* description: 用户登陆栏
*/
angular.module('app.user').directive('loginToolbar', loginToolbar);
function loginToolbar(security)
{
return {
restrict: 'E',
scope: true,
templateUrl: 'features/user/tpls/loginbar.tpl.html',
controller: function($scope, $element, $attrs)
{
var vm = $scope;
vm.isAuthenticated = security.isAuthenticated;
vm.login = security.showLogin;
vm.logout = security.logout;
vm.$watch(function() {
return security.currentUser;
}, function() {
vm.currentUser = security.currentUser;
});
},
replace: true
}
};<file_sep>/src/features/user/services/user.retryQueue.fcy.js
/**
* author: guorm
* descriptipn: 重试队列
*/
angular.module('app.user').factory('retryQueue', retryQueue);
function retryQueue($q, $log)
{
var retryQueue = [];
var s = {
onItemAddedCallbacks: [],
hasMore: function()
{
return retryQueue.length > 0;
},
push: function(retryItem)
{
retryQueue.push(retryItem);
angular.forEach(s.onItemAddedCallbacks, function(cb) {
try
{
cb(retryItem);
}
catch(e)
{
$log.error('retryQueue.push(retryItem): callback threw an error' + e);
}
})
},
pushRetryFn: function(reason, retryFn)
{
if ( arguments.length === 1)
{
retryFn = reason;
reason = undefined;
}
var deferred = $q.defer();
var retryItem = {
reason: reason,
retry: function()
{
$q.when(retryFn()).then(function(value) {
deferred.resolve(value);
}, function(value) {
deferred.reject(value);
});
},
cancel: function()
{
deferred.reject();
}
};
s.push(retryItem);
return deferred.promise;
},
retryReason: function()
{
return s.hasMore() && retryQueue[0].reason;
},
cancelAll: function()
{
while(s.hasMore()) {
retryQueue.shift().cancel();
}
},
retryAll: function()
{
while(s.hasMore()) {
retryQueue.shift().retry();
}
}
};
return s;
};<file_sep>/src/features/basicInfo/role/role.router.js
/**
* @author: guorm
* @desp: 岗位权限 路由定义
*/
angular.module('app.basicInfo.role')
.config(function ($stateProvider) {
$stateProvider
.state('layout.role', {
url: '/role',
views:{
"main":{
templateUrl: 'features/basicInfo/role/tpls/role.html',
controller: 'RoleCtrl'
}
}
})
});<file_sep>/mock/mockApi.js
/**
* 拦截请求,使其读取本地文件(模拟数据)
*
* @author: guorm
* @date 2017-2-8
*/
var path = require('path'),
fs = require('fs');
var mockBase = path.join(__dirname, 'api');
var mockApi = function(res, pathname, next)
{
switch(pathname)
{
case '/login':
var data = fs.readFileSync(path.join(mockBase, 'login.json'), 'utf-8');
res.setHeader('Content-Type', 'application/json');
res.end(data);
return;
case '/logout':
var data = fs.readFileSync(path.join(mockBase, 'logout.json'), 'utf-8');
res.setHeader('Content-Type', 'application/json');
res.end(data);
return;
}
next();
};
module.exports = mockApi;<file_sep>/src/configs/log.config.js
/**
* author: guorm
* desp: $log.debug()的开启和禁用,默认开启
*/
angular.module('app')
.config(function($logProvider)
{
$logProvider.debugEnabled(true);
});<file_sep>/src/components/ngAcdion/ngAcdion.js
/**
* author: guorm
* desp: 手风琴
*
<acdion>
<exder ng-repeat='exder in exders track by $index' exder-title='exder.title'>
{{exder.text}}
</exder>
</acdion>
*
*/
angular.module('ngAcdion', []).directive('acdion', acdion).directive('exder', exder);
function acdion()
{
return {
restrict: 'E',
transclude: true,
template: '<div class="acdion" ng-transclude></div>',
controller: AcdionCtrl,
replace: true
};
};
function exder()
{
return {
restrict: 'EA',
transclude: true,
require: '^?acdion',
scope: {
exderTitle: '=',
exderIcon: '='
},
templateUrl: 'components/ngAcdion/exder.html',
link: exderLinkFn,
replace: true
}
};
function AcdionCtrl($scope)
{
var vm = $scope;
var exders = [];
this.getOpened = function(selectedExder)
{
angular.forEach(exders, function(exder) {
if (selectedExder != exder)
{
exder.folded = false;
}
});
};
this.addexder = function(exder)
{
exders.push(exder);
};
};
function exderLinkFn(scope, ele, attrs, AcdionCtrl)
{
var vm = scope;
vm.folded = false;
AcdionCtrl.addexder(vm);
vm.toggle = function()
{
vm.folded = !vm.folded;
AcdionCtrl.getOpened(vm);
};
vm.getExderIcon = function()
{
if(vm.folded)
{
return 'icon icon-acdion-up';
}
else
{
return 'icon icon-acdion-down';
}
};
};<file_sep>/src/decorators/fixed.js
/**
* author: guorm
* desp: 固定悬浮
*
* targetTopDist:悬浮目标元素在非悬浮状态下的offsetTop值
* scrollTopDist:获取滚动条的scrollTop值
*/
angular.module('app').directive('fixed', fixed);
function fixed($window)
{
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs)
{
var targetTopDist = element[0].offsetTop,
scrollTopDist = null;
angular.element($window).on('scroll', function()
{
scrollTopDist = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
(scrollTopDist > targetTopDist) ? element.addClass('fixed') : element.removeClass('fixed');
});
}
}
};<file_sep>/src/services/dom.js
/**
* author: guorm
* description: 类名(CSS)的相关操作工具;如,添加、移除、切换
*/
angular.module('app').factory('dom', dom);
function dom()
{
var list = null;
return {
el: function(el)
{
list = angular.element(document.querySelector(el));
return this;
},
add: function(c)
{
list.addClass(c);
return this;
},
remove: function(c)
{
list.removeClass(c);
return this;
},
toggle: function(c)
{
list.toggleClass(c);
return this;
}
}
};<file_sep>/workflow/task/copySpritesImg.js
/**
* 复制Sprites合成图片
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
gulp.task('copySpriteImg', function() {
return gulp.src(common.config.src.spritesImg)
.pipe(gulp.dest(common.config.dist.css))
});
}<file_sep>/src/features/user/controllers/user.ctrl.js
/**
* author: guorm
* description: 登陆模块Ctrl
*/
angular.module('app.user').controller('UserCtrl', UserCtrl);
function UserCtrl($scope, security)
{
var vm = $scope;
vm.user = {};
vm.login = function()
{
security.login(vm.user);
};
};<file_sep>/src/decorators/toggle.js
/**
* author: guorm
* descriptipn: toggle效果
*/
angular.module('app').directive('toggle', toggle);
function toggle()
{
return {
restrict: 'A',
scope: true,
link: toggleLink
}
};
function toggleLink(scope, element, attrs)
{
var vm = scope;
if(angular.isUndefined(vm.folded))
{
vm.folded = false;
}
vm.toggle = function()
{
vm.folded = !vm.folded;
}
};<file_sep>/src/components/ngTree/ngTree.js
/**
* @author: guorm
* @desp: 树
*/
angular.module('ngTree', [])
.service('ngTree', ngTree)
.directive('treeView', function() {
return {
restrict: 'EA',
scope: {
data: '=treeData',
itemClicked: '&',
itemCheckedChanged: '&'
},
templateUrl: 'components/ngTree/treeView.html',
controller: TreeCtrl,
replace: true
}
});
function ngTree()
{
var self = this;
var defaults = self.defaults = {
textField: 'name',
idField: 'id',
pidField: 'pid',
canChecked: false,
};
self.getDefaults = function()
{
return defaults;
};
var enhanceItem = function(item, childrenName, parent)
{
if(parent)
{
item.parent = parent
};
item.$hasChildren = function()
{
var subItems = this.$children();
return angular.isArray(subItems) && subItems.length;
};
item.$children = function()
{
return this[childrenName] || [];
};
item.$getItemIcon = function()
{
if(item.isLeaf)
{
return 'icon icon-leaf';
}
return item.isExpend ? 'icon icon-minus' : 'icon icon-plus';
};
item.$foldedToggle = function()
{
this.folded = !this.folded;
};
item.$isFolded = function()
{
return this.folded;
};
var hasCheckedNode = function(node)
{
var flag = false;
angular.forEach(node.$children(), function(subNode) {
if(subNode.checked)
{
flag = true;
return;
}
});
return flag;
};
var updateAncestorsState = function(node)
{
var parent = node.parent;
while(parent)
{
parent.checked = hasCheckedNode(parent);
parent = parent.parent;
}
};
var setCheckState = function(node, checked)
{
node.checked = checked;
if(node.$children())
{
angular.forEach(node.$children(), function(subNode) {
setCheckState(subNode, checked);
});
}
updateAncestorsState(node);
};
item.$setCheckState = function(checked)
{
setCheckState(this, checked);
};
angular.forEach(item.$children(), function(subItem) {
enhanceItem(subItem, childrenName, item);
});
};
self.enhance = function(items, childrenName)
{
if(angular.isUndefined(childrenName))
{
childrenName = 'children';
}
angular.forEach(items, function(item) {
enhanceItem(item, childrenName);
});
return items;
};
};
function TreeCtrl($scope, $element, $attrs, ngTree)
{
var vm = $scope;
var defaults = ngTree.getDefaults();
vm.textField = $attrs.textField || defaults.textField;
vm.idField = $attrs.idField || defaults.idField;
vm.pidField = $attrs.pidField || defaults.pidField;
vm.canChecked = ($attrs.canChecked == 'true') ? true : false;
vm.data = ngTree.enhance(vm.data);
vm.screenCheckedCode = function(data)
{
angular.forEach(data, function(item) {
if(item.checked)
{
vm.checkedCodeList.push(item[vm.idField]);
};
if(item.$children())
{
vm.screenCheckedCode(item.children);
}
});
return vm.checkedCodeList;
};
// 通过回调,和父Ctrl进行通信
vm.dataCb = function(cbName, item, $event)
{
vm.checkedCodeList = [];
if(cbName == 'itemCheckedChanged')
{
vm.item = vm.screenCheckedCode(item);
}
else
{
vm.item = item
}
(vm[cbName] || angular.noop)({
$item: vm.item,
$event: $event
})
};
};<file_sep>/workflow/task/sass.js
/**
* SASS编译
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
gulp.task('sass', function() {
return gulp.src(common.config.src.main)
.pipe(common.plugins.sass({outputStyle: 'expanded'}).on('error', common.plugins.sass.logError))
.pipe(common.plugins.autoprefixer())
.pipe(gulp.dest(common.config.src.cssComp));
});
}<file_sep>/src/decorators/sort.js
/**
* author: guorm
* descriptipn: 表格字段排序
*
<table class="table" sort>
<thead>
<th>序号</th>
<th ng-click="sort('age')">
年龄
<i ng-class="{'icon-up': isSortUp('age'), 'icon-down': isSortDown('age')}"></i>
</th>
<th ng-click="sort('year')">
年份
<i ng-class="{'icon-up': isSortUp('year'), 'icon-down': isSortDown('year')}"></i>
</th>
</thead>
<tbody>
<tr ng-repeat="item in items | orderBy: sortField : reverse track by $index">
<td>{{$index + 1}}</td>
<td>{{item.age}}</td>
<td>{{item.year}}</td>
</tr>
</tbody>
</table>
* @param - vm.sortField,指定默认排序字段(在页面controller中设置)
* @param - vm.reverse,排序方向,控制升、降序切换
*/
angular.module('app').directive('sort', sort);
function sort()
{
return {
restrict: 'A',
scope: true,
controller: SortCtrl
}
};
function SortCtrl($scope, $element, $attrs)
{
var vm = $scope;
if(angular.isUndefined(vm.sortField))
{
vm.sortField = null;
};
vm.reverse = false;
vm.sort = function(fieldName)
{
(vm.sortField == fieldName) ? vm.reverse = !vm.reverse : vm.sortField = fieldName;
};
vm.isSortUp = function(fieldName)
{
return vm.sortField == fieldName && !vm.reverse;
};
vm.isSortDown = function(fieldName)
{
return vm.sortField == fieldName && vm.reverse;
};
};<file_sep>/src/features/basicInfo/role/controllers/role.ctrl.js
/**
* @author: guorm
* @desp: 岗位权限 Ctrl
*/
angular.module('app.basicInfo.role').controller('RoleCtrl', RoleCtrl);
function RoleCtrl($scope)
{
var vm = $scope;
};<file_sep>/src/configs/intercept.config.js
/**
* author: guorm
* description: 拦截器配置
*/
function ajaxLoadingIntercept($q, $injector)
{
return {
request: function (config)
{
return config || $q.when(config);
},
response: function (response)
{
var ngDialog = $injector.get('ngDialog');
if(angular.isObject(response.data) && response.data.code === '0000')
{
if (response.data.data == null)
{
response.data.data = {};
}
response.data.data.config = response.config;
response = response.data.data;
};
if(angular.isObject(response.data) && !angular.isUndefined(response.data.code) && (response.data.code == '9999'))
{
ngDialog.open({
plain: true,
template: response.data.msg
});
};
return response || $q.when(response);
}
}
};
function httpErrorIntercept($q, $injector)
{
return {
responseError: function (response)
{
var ngDialog = $injector.get('ngDialog');
switch (response.status)
{
case 200:
break;
case -1:
ngDialog.open({
plain: true,
template: '网络异常'
});
break;
case 404:
ngDialog.open({
plain: true,
template: '请求地址不存在(404)'
});
break;
case 500:
ngDialog.open({
plain: true,
template: '服务器开小差了,请稍后再试(500)'
});
break;
case 502:
ngDialog.open({
plain: true,
template: 'Bad GateWay(502)'
});
break;
default:
ngDialog.open({
plain: true,
template: '网络异常(' + response.status + ')'
});
}
return $q.reject(response);
}
}
};
function securityIntercept($injector, retryQueue)
{
return function(promise) {
var $http = $injector.get('$http');
return promise.then(null, function(res) {
if(res.status === 401)
{
promise = retryQueue.pushRetryFn('unauthorized-server', function() {
return $http(res.config);
});
}
return promise;
});
}
};
angular.module('app').factory('httpErrorIntercept', httpErrorIntercept);
angular.module('app').factory('ajaxLoadingIntercept', ajaxLoadingIntercept);
angular.module('app').factory('securityIntercept', securityIntercept);
angular.module('app').config(function($httpProvider, $locationProvider) {
// 去掉ng1.6.3访问路径中的'!'
$locationProvider.hashPrefix('');
$httpProvider.interceptors.push('httpErrorIntercept');
$httpProvider.interceptors.push('ajaxLoadingIntercept');
$httpProvider.interceptors.push('securityIntercept');
});<file_sep>/workflow/task/sprites.js
/**
* 拼合雪碧图
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
gulp.task('sprites', function() {
return gulp.src(common.config.src.sprites)
.pipe(common.plugins.spritesmith({
imgName: 'sprites.png',
cssName: 'sprites.css',
padding: 10,
algorithm: 'binary-tree'
}))
.pipe(gulp.dest(common.config.src.spritesComp));
});
}<file_sep>/workflow/task/ftp.js
/**
* 将打包后的文件上传服务器
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
gulp.task('ftp', function() {
gulp.src(common.config.dist.root)
.pipe(common.plugins.sftp(common.config.remoteServer))
});
}<file_sep>/README.md
## ng1 project construction<file_sep>/src/services/store.js
/**
* author: guorm
* description: 存储工具
*/
angular.module('app').factory('store', store);
function store()
{
return {
setVal: function(name, val)
{
if(name && val)
{
localStorage[name] = val;
}
},
getVal: function(name)
{
if(!name || !localStorage[name])
{
return;
}
return localStorage[name];
},
setObj: function(name, obj)
{
if(name && angular.isObject(obj))
{
localStorage[name] = JSON.stringify(obj);
}
},
getObj: function(name)
{
if(!name || !localStorage[name])
{
return;
}
return JSON.parse(localStorage[name]);
},
clearAll: function()
{
localStorage.clear();
}
}
};<file_sep>/workflow/task/replaceIndex.js
/**
* 替换index模板
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
gulp.task('indexHtml', function() {
return gulp.src(common.config.src.entryHtml)
.pipe(common.plugins.htmlmin({
collapseWhitespace: true,
removeComments: true,
}))
.pipe(common.plugins.cheerio(
function($){
var mainCssUrl = '<link rel="stylesheet" href="css/main.css">',
vendorJsUrl = '<script type="text/javascript" src="js/vendorJs.js"></script>',
commonJsUrl = '<script type="text/javascript" src="js/common.js"></script>',
tplsCacheJsUrl = '<script type="text/javascript" src="js/tplsCache.js"></script>',
bundleJsUrl = '<script type="text/javascript" src="js/bundle.js"></script>',
ctrlsJsUrl = '<script type="text/javascript" src="js/ctrls.js"></script>';
$('script').remove();
$('link').remove();
$('head').append(mainCssUrl);
$('body').append(vendorJsUrl);
$('body').append(commonJsUrl);
$('body').append(tplsCacheJsUrl);
$('body').append(bundleJsUrl);
$('body').append(ctrlsJsUrl);
}
))
.pipe(gulp.dest(common.config.dist.root))
});
}<file_sep>/workflow/task/server.js
/**
* 服务
*
* @author: guorm
* @date 2016-12-30
*/
module.exports = function(gulp, common)
{
var url = require('url');
gulp.task('server', function() {
common.browserSync.init({
open: false,
port: common.config.browserSyncPort,
server: common.config.browserSyncDefaultPath,
middleware: function(req, res, next)
{
var urlObj = url.parse(req.url, true),
method = req.method,
paramObj = urlObj.query;
// mock数据
common.mockApi(res, urlObj.pathname, next);
}
});
gulp.watch(common.config.browserSyncWatchPath.html).on('change',common.reload);
gulp.watch(common.config.browserSyncWatchPath.css).on('change',common.reload);
gulp.watch(common.config.browserSyncWatchPath.sass,{cwd: './'},['sass']);
});
}
<file_sep>/gulpfile.js
/**
* gulpfile.js Gulp 工作流
*
* @author: guorm
* @date 2016-12-30
*/
var gulp = require('gulp-help')(require('gulp'), {
description: '任务列表',
hideDepsMessage: false
}),
fs = require('fs'),
common = require('./workflow/common');
// 载入任务
var taskPath = 'workflow/task';
fs.readdirSync(taskPath).filter(function (_file) {
// 排除非 JS 文件
return _file.match(/js$/);
}).forEach(function (_file) {
require('./' + taskPath + '/' + _file)(gulp, common);
});<file_sep>/src/common/filters/paging.js
/**
* author: guorm
* descriptipn: 本地分页
*
* @param - page:当前页
* @param - pageSize:每页显示的条数
*/
angular.module('app').filter('range', range);
angular.module('app').filter('pageCount', pageCount);
function range($filter)
{
return function(data, page, pageSize)
{
if(angular.isArray(data) && angular.isNumber(page) && angular.isNumber(pageSize))
{
var startIndex = (page - 1) * pageSize;
if(data.length < startIndex)
{
return [];
}
else
{
return $filter('limitTo')(data.splice(startIndex), pageSize);
}
}
else
{
return data;
}
}
};
function pageCount()
{
return function(data, pageSize)
{
if(angular.isArray(data) && angular.isNumber(pageSize))
{
var result = [], i;
for (i = 0; i < Math.ceil(data.length / pageSize); i++)
{
result.push(i);
}
return result;
}
else
{
return data;
}
}
};<file_sep>/src/components/ngInputGroup/inputNum.js
/**
* author: guorm
* desp: 可加、减的输入框
<input-num data="money" step="1"></input-num>
*/
angular.module('ngInputGroup', []).directive('inputNum', inputNum);
function inputNum()
{
return {
restrict: 'E',
scope: {
value: '=',
step: '@'
},
templateUrl: 'components/ngInputGroup/inputNum.html',
controller: InputNumCtrl,
replace: true
}
};
function InputNumCtrl($scope, $element, $attrs)
{
var vm = $scope;
var value, step;
function typeTrans()
{
value = Number(vm.value);
step = Number(vm.step);
};
vm.plus = function()
{
typeTrans();
value += step;
vm.value = value;
};
vm.redu = function()
{
typeTrans();
value -= step;
vm.value = value;
};
}; | 77343d754095407f58f23ea91e932f670bacc803 | [
"JavaScript",
"Markdown"
] | 44 | JavaScript | adiu2016/ng1 | 54204f9a89c5955268b3bc01accd58f9d4807ab4 | 4bc48d2d315a16761ec3f9bab415fcea812184cb |
refs/heads/master | <repo_name>marquinhusgoncalves-zz/marquinhusgoncalves.github.io<file_sep>/gulpfile.js
const gulp = require('gulp');
const plumber = require('gulp-plumber');
const gutil = require('gulp-util');
const sass = require('gulp-sass');
const prefix = require('gulp-autoprefixer');
const nano = require('gulp-cssnano');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify-es').default;
const browserSync = require('browser-sync');
const cp = require('child_process');
const sourcemaps = require('gulp-sourcemaps');
const imagemin = require('gulp-imagemin');
const messages = {
jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
gulp.task('css', () => {
gulp.src('src/scss/**/*.scss')
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'compressed'
})
.on('error', sass.logError))
.pipe(concat('style.css'))
.pipe(sourcemaps.write())
.pipe(browserSync.reload({stream: true}))
.pipe(gulp.dest('assets/css'));
});
gulp.task('js', () => {
return gulp.src('src/js/**/*.js')
.pipe(plumber())
.pipe(concat('script.js'))
.pipe(uglify())
.pipe(gulp.dest('assets/js/'));
});
gulp.task('imagemin', () => {
return gulp.src('src/img/**/*')
.pipe(plumber())
.pipe(imagemin({optimizationLevel: 3, progressive: true, interlaced: true}))
.pipe(gulp.dest('assets/img/'));
});
gulp.task('fonts', function() {
return gulp.src([
'src/fonts/**'])
.pipe(gulp.dest('assets/fonts/'));
});
/**
* Monta o site do Jekyll
*/
gulp.task('jekyll-build', function(done) {
browserSync.notify(messages.jekyllBuild);
return cp.spawn('jekyll', ['build'], {stdio: 'inherit'})
.on('close', done);
});
/**
* Refaz o site e atualiza a página
*/
gulp.task('jekyll-rebuild', ['jekyll-build'], function() {
browserSync.reload();
});
/**
* Espera até que o jekyll-build seja executado e então levanta o
* servidor utilizando o _site como pasta raiz
*/
gulp.task('browser-sync', ['jekyll-build'], function() {
browserSync({
server: {
baseDir: '_site'
}
});
});
gulp.task('watch', function () {
gulp.watch('src/scss/**/*.scss', ['css', 'jekyll-rebuild']);
gulp.watch('src/js/**/*.js', ['js', 'jekyll-rebuild']);
gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin', 'jekyll-rebuild']);
gulp.watch('src/fonts/**/*.{eot,svg,ttf, woff}', ['fonts', 'jekyll-rebuild']);
gulp.watch(['*.md', '_includes/*.html', '_layouts/*.html', '_posts/*'], ['jekyll-rebuild']);
});
gulp.task('default', ['css', 'js', 'imagemin', 'fonts', 'browser-sync', 'watch']);
<file_sep>/README.md
[](https://opensource.org/licenses/MIT)
[](https://travis-ci.org/marquinhusgoncalves/marquinhusgoncalves.github.io)
# Project Marquinhus Blog
Personal Blog.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
### Prerequisites
What things you need to install the software and how to install them
```
Ruby 2.4.2
Gem 2.7.6
```
### Installing
A step by step series of examples that tell you have to get a development env running
Say what the step will be
```
gem install bundler
```
After
```
bundle install
```
End with an example of getting some data out of the system or using it for a little demo
## Main Commands Jekyll
| Command | README |
| ------ | ------ |
| build, b | Build your site |
| clean | Clean the site (removes site output and metadata file) without building. |
| doctor, hyde | Search site and print specific deprecation warnings |
| help | Show the help message |
| new | Creates a new Jekyll site scaffold in PATH |
| new-theme | Creates a new Jekyll theme scaffold |
| serve, server, s | Serve your site locally |
## Deployment
Add additional notes about how to deploy this on a live system
```
branch: (master) git push
```
## Built With
* [GitHub Pages](https://pages.github.com/) - Hosted
* [Jekyll](http://jekyllrb.com/) - Generated
## Contributing
Please read [CONTRIBUTING.md](https://github.com/marquinhusgoncalves/marquinhusgoncalves.github.io/issues) for details on our code of conduct, and the process for submitting pull requests to us.
## Versioning
We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/marquinhusgoncalves/marquinhusgoncalves.github.io/tags).
## Authors
* **<NAME>** - *Software Engineer* - [<NAME>](https://github.com/marquinhusgoncalves)
See also the list of [contributors](https://github.com/marquinhusgoncalves/marquinhusgoncalves.github.io/graphs/contributors) who participated in this project.
## License
This project is licensed under the MIT License - see the [License: MIT](https://opensource.org/licenses/MIT) file for details
## Acknowledgments
* [Jekyll Course - Willian Justen](https://www.udemy.com/criando-sites-estaticos-com-jekyll/learn/v4/overview)
<file_sep>/_projects/oceano-web.md
---
layout: post
category: project
title: Oceano Web
description: Desenvolvido com HTML5, CSS3, Javascript.
href: http://www.oceanoweb.com.br
---
<file_sep>/_projects/mundo-sa.md
---
layout: post
category: project
title: <NAME>
description: Desenvolvido na plataforma Wordpress, HTML5, CSS3, Javascript, PHP, Responsivo, Bootstrap.
href: http://www.mundosa.com.br
---
<file_sep>/_projects/papel-sa.md
---
layout: post
category: project
title: Papel S/A
description: Desenvolvido na plataforma Magento, HTML5, CSS3, Javascript, PHP, Responsivo
href: http://www.papelsa.com.br
---
<file_sep>/_projects/sistema-formulario.md
---
layout: post
category: project
title: Sistema de Formulário
description: Desenvolvido em PHP com Banco de Dados, HTML5, CSS3, Javascript/jQuery, Responsivo, Pure.
href: http://formulario.oceanoweb.com.br
---
<file_sep>/_projects/sistema-upload.md
---
layout: post
category: project
title: Sistema de Upload
description: Desenvolvido em PHP com Banco de Dados, HTML5, CSS3, Responsivo, Bootstrap
href: http://upload.oceanoweb.com.br
---
<file_sep>/_projects/sistema-crud.md
---
layout: post
category: project
title: Sistema CRUD
description: Desenvolvido em PHP com Banco de Dados, HTML5, CSS3, Responsivo, Pure.
href: http://crud.oceanoweb.com.br
---
<file_sep>/_projects/palacio-do-pao.md
---
layout: post
category: project
title: Palácio do Pão
description: Desenvolvido na plataforma Wordpress, HTML5, CSS3, Javascript, PHP, Responsivo, Bootstrap.
href: http://www.palaciodopao.com.br
---
<file_sep>/_projects/projeto-quote.md
---
layout: post
category: project
title: Projeto Quote - Frases e Cores Aleatórios
description: Desenvolvido com HTML5, CSS3, Javascript.
href: http://quote.oceanoweb.com.br
---
<file_sep>/_projects/codecademy-angular.md
---
layout: post
category: project
title: Codecademy - Angular
description: Javascript, Angular, HTML5, CSS3, Bootstrap, FontAwesome.
href: http://angular.oceanoweb.com.br
---
<file_sep>/about.md
---
layout: page
title: Sobre
---
<p class="about">
Bom meu nome é <NAME> sou nascido e criado em São Bernardo do Campo / SP sempre fui apaixonado por tecnologia, com 14 anos ganhei meu primeiro computador um 486 com o na época recente Windows 3.11 mas para utiliza-lo tinha que ter conhecimento de DOS foi onde me apaixonei mais ainda pelos computadores, a linha de comando foi amor a primeira vista ficava horas no computador, nem desligava, não existia internet existia BBS e o acesso era discado alguns meses depois me matriculei em um curso de informática na <a href="http://www.sos.com.br" target="_blank">S.O.S Computadores</a> onde tirei nota máxima em todos os cursos e ainda recebi o convite de dar aulas, a paixão só aumentou e meu conhecimento também, junto do ensino médio estudei técnico em Informática no <a href="http://www.portalanchieta.com.br" target="_blank">Colégio Anchieta</a> fui bolsista integral, onde tive bastante contato com Hardware e Programação, então nem tive dúvidas do que estudar na faculdade, de cara Ciência da Computação na <a href="http://portal.metodista.br" target="_blank">Universidade Metodista</a> passei entre os 20 primeiros e fui bolsista e ai que minha vida mudou totalmente mesmo amando o que estudava tive difuldades com algumas matérias acabei pegando DP´s perdendo a bolsa e nesse tempo já procurava emprego mas a dificuldade de conseguir emprego e os salários de estágio eram baixos e não pagavam a mensalidade, acabei indo para o comércio e trancando meus estudos. Foram 10 anos totalmente fora, trabalhei muito na <a href="http://www.tentbeach.com.br" target="_blank">Tent Beach</a> não vou comentar muito porque seria uma longa história, mas resumindo fui muito feliz tive diversas promoções, premiações, fiz muitas amizades e cresci muito como pessoa, mas chegou uma hora que eu queria crescer mais profissionalmente, foi então que resolvi voltar para área porém estava totalmente desatualizado, primeira coisa que fiz foi, matricular em uma outra faculdade dessa vez na <a href="http://www.anhembi.br" target="_blank">Anhembi Morumbi</a> no curso de Análise e Desenvolvimento de Sistemas. Hoje estou formado e atuando na área de FRONT END, estudando muito, fazendo muitos cursos e participando de vários eventos da área, inclusive esse blog é um motivo para eu estudar mais e sempre estar buscando as novas tecnologias, novos métodos, testando o que há de novo no mercado ampliando meu network e me divertindo.
Meus hobbies são (não poderia faltar porque adoro essa parte rsrs) curto música pra c... meu estilo músical é rock e blues, toco violão, guitarra e percurssão. Curto muito praticar esportes correr, nadar, pedalar, bate uma bola, academia, surf, skate, patins e sou fascinado por esportes radicais. Leitura, filmes e séries sempre que sobra um tempo.
</p><file_sep>/src/js/scrollToTop.js
function showButton() {
if (this.scrollY >= 50) {
document.querySelector('#return-to-top').classList.add('visible');
} else {
document.querySelector('#return-to-top').classList.remove('visible');
}
}
function scrollTo(element, to, duration) {
if (duration <= 0) return;
const difference = to - element.scrollTop;
const perTick = difference / duration * 10;
setTimeout(function () {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop === to) return;
scrollTo(element, to, duration - 10);
}, 10);
}
function runScroll() {
scrollTo(document.documentElement, 0, 600);
}
const scrollme = document.querySelector('#return-to-top');
scrollme.addEventListener('click', runScroll);
window.addEventListener('scroll', showButton);
<file_sep>/src/js/responsiveMenu.js
var $menuToggle = document.querySelector('.menu-toggle');
var $menuMobile = document.querySelector('.header-menu-mobile');
var $menuMobileNav = document.querySelector('.header-menu-mobile-nav');
$menuToggle.addEventListener('click', function () {
this.classList.toggle('on');
$menuMobile.classList.toggle('on');
$menuMobileNav.classList.toggle('hidden');
})<file_sep>/_projects/lorenzzato-motor.md
---
layout: post
category: project
title: Lorenzzato Motor
description: Desenvolvido com HTML5, CSS3, Javascript, PHP, Responsivo, Foundation.
href: http://www.lorenzzatomotor.com.br
---
<file_sep>/testlinks.sh
#!/usr/bin/env bash
set -e # halt script on error
echo 'Testing travis...'
bundle exec travis-lint
bundle exec jekyll build
bundle exec htmlproofer ./_site --http-status-ignore "0,999"<file_sep>/_projects/regina-alves-nutricionista.md
---
layout: post
category: project
title: <NAME>
description: Desenvolvido na plataforma Wordpress, HTML5, CSS3, Javascript, PHP, Responsivo, Bootstrap.
href: http://www.reginaalvesnutri.com.br
---
<file_sep>/index.md
---
layout: default
title: Home
---
<div class="content">
<img class="content-img" src="/assets/img/marquinhus-goncalves.jpg" alt="<NAME>">
<div class="content-box-text">
<p>Oi meu nome é <NAME> sou desenvolvedor front end, grunge, adoro estudar, viajar, praticar esportes e tocar violão.</p>
<p>Amante de tecnologia e um eterno aprendiz, gosto de solucionar problemas, ir a eventos e meetups sobre assuntos relacionados a desenvolvimento web.</p>
<p>Esse espaço uso para meus estudos e quem sabe ajudar outras pessoas.</p>
</div>
</div><file_sep>/_projects/curso-caelum-javascript.md
---
layout: post
category: project
title: Curso Caelum Javascript
description: Javascript, HTML5, CSS3.
href: http://ceep.oceanoweb.com.br
---
<file_sep>/_posts/2017-08-31-agilidade-usando-emmet.md
---
layout: post
title: Escreva HTML com mais agilidade usando Emmet #frontend
---
E ai pessoal tudo bem?
Neste post quero comentar sobre o plugin [Emmet](https://emmet.io/){:target="_blank"}.
Bom o Emmet é um plugin para HTML e CSS, que digitando menos você consegue escrever mais código, com pequenas sentenças você cria
estruturas grandes, ganhando agilidade, produtividade e evitando ter que reescrever códigos.
Bom em primeiro lugar é possível instalar o Emmet em diversos editores como [VSCode](https://code.visualstudio.com/), [Sublime](https://www.sublimetext.com/), [Atom](https://atom.io/), [Brackets](http://brackets.io/) e etc, você pode baixar e instalar [por aqui](https://emmet.io/download/){:target="_blank"} ou instalar diretamente no seu editor.
Alguns serviços online como [JSFinddle](https://jsfiddle.net/) e [Codepen](https://codepen.io/) também são possíveis de utilizar.
Depois de instalado.... vamos aos exemplos para ficar mais claro.
A sintaxe é fácil ao final de cada sentença use o TAB.
Usando apenas
{% highlight html %}
html:5 ou !
{% endhighlight html %}
{% highlight html %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
{% endhighlight html %}
{% highlight html %}
script:src
{% endhighlight html %}
{% highlight html %}
<script src=""></script>
{% endhighlight html %}
Com essa sentença
{% highlight html %}
header#header+(main.main>h1.title{Emmet}+section.container>ul>li>a{Item $}*5)+footer.footer
{% endhighlight html %}
Olha que é gerado
{% highlight html %}
<header id="header"></header>
<main class="main">
<h1 class="title">Emmet</h1>
<section class="container">
<ul>
<li>
<a href="">Item 1</a>
<a href="">Item 2</a>
<a href="">Item 3</a>
<a href="">Item 4</a>
<a href="">Item 5</a>
</li>
</ul>
</section>
</main>
<footer class="footer"></footer>
{% endhighlight html %}
Para qualquer tag HTML:
{% highlight html %}
div
{% endhighlight html %}
{% highlight html %}
<div></div>
{% endhighlight html %}
Para uma tag com id:
{% highlight html %}
div#container
{% endhighlight html %}
{% highlight html %}
<div id="name-id"></div>
{% endhighlight html %}
Para uma tag com class:
{% highlight html %}
div.class
div.class1.class2
{% endhighlight html %}
{% highlight html %}
<div class="class"></div>
<div class="class1 class2"></div>
{% endhighlight html %}
Se caso for diitado apenas .class ou #id a TAG <div> é adicionada automáticamente.
{% highlight html %}
#name-id
.name-class
{% endhighlight html %}
{% highlight html %}
<div id="name-id"></div>
<div class="name-class"></div>
{% endhighlight html %}
Para criar uma árvore de elementos você utiliza ` > ` para que o próximo elemento fique dentro da TAG anterior (filho ) e ` + ` para ficar após a TAG anterior (irmão)
Vamos aos exemplos:
{% highlight html %}
section>p
{% endhighlight html %}
{% highlight html %}
<section>
<p></p>
</section>
{% endhighlight html %}
{% highlight html %}
section+p
{% endhighlight html %}
{% highlight html %}
<section></section>
<p></p>
{% endhighlight html %}
O símbolo ` ^ ` faz com que os elementos fiquem irmãos da última sentença.
{% highlight html %}
section>p>a{link}^section
{% endhighlight html %}
{% highlight html %}
<section>
<p><a href="">Link</a></p>
<section></section>
</section>
{% endhighlight html %}
Obs.: O símbolo ` ^ ` pode ser útilizado mais de uma vez assim a cada vez usado sobe um nível na árvore
{% highlight html %}
section>p>a{link}^^section
{% endhighlight html %}
{% highlight html %}
<section>
<p><a href="">link</a></p>
</section>
<section></section>
{% endhighlight html %}
O símbolo ` * ` multiplica o elemento declarado pelo n vezes.
{% highlight html %}
ul>li*3
{% endhighlight html %}
{% highlight html %}
<ul>
<li></li>
<li></li>
<li></li>
</ul>
{% endhighlight html %}
Os parenteses ` () `servem para agrupar um conjunto de sentença.
{% highlight html %}
header.header(article>p+span)+footer>p
{% endhighlight html %}
{% highlight html %}
<header class="header"></header>
<article>
<p></p>
<span></span>
</article>
<footer>
<p></p>
</footer>
{% endhighlight html %}
E pode melhorar adicionada
{% highlight html %}
(section>ul>(li>p+a)*3)+footer>p
{% endhighlight html %}
{% highlight html %}
<section>
<ul>
<li>
<p></p>
<a href=""></a>
</li>
<li>
<p></p>
<a href=""></a>
</li>
<li>
<p></p>
<a href=""></a>
</li>
<footer></footer>
</ul>
</section>
{% endhighlight html %}
Com o ` $ ` você pode numerar elementos que oram criado com a repetição ` * `.
{% highlight html %}
ul>li.item$*3
{% endhighlight html %}
{% highlight html %}
<ul>
<li class="item1"></li>
<li class="item2"></li>
<li class="item3"></li>
</ul>
{% endhighlight html %}
Pode ser usado ` $ ` em sequência
{% highlight html %}
ul>li.item$$$*3
{% endhighlight html %}
{% highlight html %}
<ul>
<li class="item001"></li>
<li class="item002"></li>
<li class="item003"></li>
</ul>
{% endhighlight html %}
Com o uso ` @- ` voc6e muda a ordenação, podendo ser crescente (default) e decrescente.
{% highlight html %}
ul>li.item$@-*3
{% endhighlight html %}
{% highlight html %}
<ul>
<li class="item3"></li>
<li class="item2"></li>
<li class="item1"></li>
</ul>
{% endhighlight html %}
Para mudar o contador base use ` @N `
{% highlight html %}
ul>li.item$@3*3
{% endhighlight html %}
{% highlight html %}
<ul>
<li class="item3"></li>
<li class="item4"></li>
<li class="item5"></li>
</ul>
{% endhighlight html %}
E também pode inverter
{% highlight html %}
ul>li.item$@-3*3
{% endhighlight html %}
{% highlight html %}
<ul>
<li class="item5"></li>
<li class="item4"></li>
<li class="item3"></li>
</ul>
{% endhighlight html %}
Para adicionar texto use ` {} ``
{% highlight html %}
a{Clique aqui}
{% endhighlight html %}
{% highlight html %}
<a href="">Click me</a>
{% endhighlight html %}
Também pode adicionar textos que fiquem dentro do elemento anterior ou após
{% highlight html %}
a{Clique}+b{aqui}
a>{Clique}+b{aqui}
{% endhighlight html %}
{% highlight html %}
<a href="">Clique</a><b>aqui</b>
<a href="">Clique<b>aqui</b></a>
{% endhighlight html %}
Pode ser gerado um [Lorem Ipsum](http://br.lipsum.com/) por default é gerado com 30 linhas mas é possível personalizar
{% highlight html %}
p*4>lorem
{% endhighlight html %}
{% highlight html %}
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui dicta minus molestiae vel beatae natus eveniet ratione temporibus aperiam harum alias officiis assumenda officia quibusdam deleniti eos cupiditate dolore doloribus!</p>
<p>Ad dolore dignissimos asperiores dicta facere optio quod commodi nam tempore recusandae. Rerum sed nulla eum vero expedita ex delectus voluptates rem at neque quos facere sequi unde optio aliquam!</p>
<p>Tenetur quod quidem in voluptatem corporis dolorum dicta sit pariatur porro quaerat autem ipsam odit quam beatae tempora quibusdam illum! Modi velit odio nam nulla unde amet odit pariatur at!</p>
<p>Consequatur rerum amet fuga expedita sunt et tempora saepe? Iusto nihil explicabo perferendis quos provident delectus ducimus necessitatibus reiciendis optio tempora unde earum doloremque commodi laudantium ad nulla vel odio?</p>
{% endhighlight html %}
Alguns Lorem Ipsum online:
[Bacon](https://baconipsum.com/)
[Mussum](hhttp://mussumipsum.com/)
## Emmet para CSS
Bom acredito que para o CSS o Emmet não será muito útil porque os editores já oferecem um auxílio para a escrita sugerindo com o auto-complete.
{% highlight css %}
-display
{% endhighlight css %}
{% highlight css %}
-webkit-display: ;
-moz-display: ;
-ms-display: ;
-o-display: ;
display: ;
{% endhighlight css %}
Também podemos passar valores.
{% highlight css %}
-flex:10px
{% endhighlight css %}
{% highlight css %}
-webkit-flex: 10px;
-moz-flex: 10px;
-ms-flex: 10px;
-o-flex: 10px;
flex: 10px;
{% endhighlight css %}
E a referência de valores fica
- p → %
- e → em
- x → ex
Podemos usar com cores e abreviações
{% highlight css %}
bd5#0s
{% endhighlight css %}
{% highlight css %}
border: 5px #000 solid
{% endhighlight css %}
- #1 → #111111
- #e0 → #e0e0e0
- #fc0 → #ffcc00
## Recomendações finais
Para o Emmet poder parsear não pode haver espaços nas sentenças.
Esse é um overview básico porém essencial para poder usar o Emmet, a ideia é trazer praticidade e não complexividade por isso que o Emmet não é recomendado para estruturas complexas e grandes.
E por experiência própria aqui estão o que é mais usado no dia a dia porém [nessa documentação](https://docs.emmet.io/cheat-sheet/) você encotrará todas as abreviações e talvez alguma que não expliquei possa ser útil vale a pena dar uma olhada.
Espero que tenham gostado e ajudado !!!
De qualquer forma caso precisem de uma ajuda podem deixar um comentário ou me procurar nas redes sociais.
## Referências:
[Documentação Emmet](https://docs.emmet.io/abbreviations/syntax/)
[Documentação Emmet - CSS](https://docs.emmet.io/css-abbreviations/)<file_sep>/_projects/avedon.md
---
layout: post
category: project
title: Avedon
description: Desenvolvido na plataforma Wordpress, HTML5, CSS3, Javascript, PHP, Responsivo, Bootstrap.
href: http://www.avedon.com.br
---
<file_sep>/_projects/banda-forro-nupelo.md
---
layout: post
category: project
title: <NAME>
description: Javascript, HTML5, CSS3.
href: http://forronupelo.oceanoweb.com.br
---
<file_sep>/blog.md
---
layout: page
title: Blog
---
<section class="cards">
{% for post in site.posts %}
<a href="{{ post.url }}" class="card">
<article>
<header>
<h1 class="card-title">{{ post.title }}</h1>
</header>
</article>
<div class="card-plus"></div>
</a>
{% endfor %}
</section><file_sep>/projects.md
---
layout: page
title: Projetos
---
<section class="cards">
{% for project in site.projects %}
<a href="{{project.href}}" class="card" target="_blank">
<p class="card-title">{{ project.title }}</p>
<p class="card-description">{{ project.description }}</p>
<div class="card-plus"></div>
</a>
{% endfor %}
</section>
| c01f0e2b03aff50772ab9c565aa85343b72738bb | [
"JavaScript",
"Markdown",
"Shell"
] | 24 | JavaScript | marquinhusgoncalves-zz/marquinhusgoncalves.github.io | ca3ccc3291aee82e7a912a4e15d97884c88cdfc7 | 8e4587ec0d6762897b8fc13cc24f38fe44623004 |
refs/heads/main | <file_sep>import axiosInstance from './index'
const axios = axiosInstance
export const getBooks = () => {return axios.get(`http://localhost:8000/api/articles/`)}
export const postBook = (bookName, bookAuthor) => {return axios.post(`http://localhost:8000/api/articles/`,{'name':bookName,'author':bookAuthor})} | bb6732cc8b7021fe5c12759f1d2381d19574a91b | [
"JavaScript"
] | 1 | JavaScript | SQQS123/appfront | 9b2ef06dd44e78073cc234230f1cecee264a6652 | 5a82b8eb0bed3211c19f2f36333ac5c1fa08d85e |
refs/heads/master | <repo_name>guinslym/cypress-tutorial-with-react<file_sep>/cypress/integration/Page.spec.js
describe ('Second Test', () => {
it ('Visit the app', () => {
cy.visit ('http://localhost:3000/');
});
});
describe ('Sixth Tests', () => {
context ('No Todos', () => {
it ('Adds a new todo', () => {
cy.visit ('/');
cy.get ('.new').type ('New todo').type ('{enter}');
});
});
});
| 46c768455360f9f20a5f0f87653dda5200e699b0 | [
"JavaScript"
] | 1 | JavaScript | guinslym/cypress-tutorial-with-react | 46251ab799f4185446137638055d1131ccbcbafc | 0376c77476c60b0c0e3524edda45e53fc55f1140 |
refs/heads/master | <repo_name>davidoleary/express-error-handling-show-and-tell<file_sep>/server.js
// 1. show crash1 - doesnt break app
// 2. show crash2 - does break app
// 3. why does crash2 kill the app and crash1 does not
// 4. add middlewware
// 5. show crash1 handled
// 6. show crash2 unhandled
// 7. add uncaughtException
// 8. show crash1 handled in middleware
// 9. show crash2 handled in uncaughtException and UI is timing out
// 10. show next usage with crash3
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json({
limit: '10mb'
}));
app.get('/crash1', (req, res, next) => {
console.log(undefined.split('|')[1])
res.send('will crash the app!');
});
app.get('/crash2', (req, res, next) => {
process.nextTick(function () {
var j = i.someProperty;
});
})
app.get('/crash3', (req, res, next) => {
process.nextTick(function () {
try {
var j = i.someProperty;
} catch (err) {
console.log('------>>>> in catch for next');
next(err);
}
});
})
app.get('/', (req, res) => res.send('Hello World!'));
app.use(function (err, req, res, next) {
console.error('--->>>> error middleware', err.stack);
res.status(500).send('Something broke!');
})
process.on('uncaughtException', function (err) {
console.log('--->>>> uncaughtException', err.stack);
});
app.listen(9900, () => console.log('Example app listening on http://localhost:9900!'));
<file_sep>/README.md
# Express error handling show & tell
Examples of how to handle errors in node and express.
Shows:
- express error handling of sync vs async requests
- express error middleware
- handling uncaught exceptions
- what errors crash the node process and what doesn't
# Demo sequence
1. show crash1 - doesnt break app
2. show crash2 - does break app
3. why does crash2 kill the app and crash1 does not - explain
4. add middlewware
5. show crash1 handled
6. show crash2 unhandled
7. add uncaughtException
8. show crash1 handled in middleware
9. show crash2 handled in uncaughtException and UI is timing out
10. show next usage with crash3
| 53c0345dc4c3ad58747707becc7a3f65dbee1423 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | davidoleary/express-error-handling-show-and-tell | b080d2513169ea59c49fc215ac7c01ba37b3bd2b | 0c1a818d967e3bdc708a9d670a9ed2b1c8a37225 |
refs/heads/master | <repo_name>chaohstat/GHMM_nD<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_EM_terminate.h
/*
* SREM_EM_terminate.h
*
* Code generation for function 'SREM_EM_terminate'
*
*/
#ifndef __SREM_EM_TERMINATE_H__
#define __SREM_EM_TERMINATE_H__
/* Include files */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "mwmathutil.h"
#include "tmwtypes.h"
#include "mex.h"
#include "emlrt.h"
#include "blas.h"
#include "rtwtypes.h"
#include "SREM_EM_types.h"
/* Function Declarations */
extern void SREM_EM_atexit(void);
extern void SREM_EM_terminate(void);
#endif
/* End of code generation (SREM_EM_terminate.h) */
<file_sep>/subfuns/codegen/mex/SREM_EM/bSSupdate.c
/*
* bSSupdate.c
*
* Code generation for function 'bSSupdate'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "bSSupdate.h"
#include "bbarupdate.h"
#include "SREM_EM_emxutil.h"
#include "taufun.h"
#include "mldivide.h"
#include "diag.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRSInfo tb_emlrtRSI = { 4, "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m" };
static emlrtRSInfo ub_emlrtRSI = { 5, "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m" };
static emlrtRSInfo vb_emlrtRSI = { 6, "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m" };
static emlrtRTEInfo s_emlrtRTEI = { 1, 30, "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m" };
static emlrtBCInfo k_emlrtBCI = { -1, -1, 4, 12, "Y1", "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m", 0 };
static emlrtBCInfo l_emlrtBCI = { -1, -1, 4, 45, "Pb", "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m", 0 };
static emlrtECInfo i_emlrtECI = { -1, 4, 9, "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m" };
static emlrtBCInfo m_emlrtBCI = { -1, -1, 6, 34, "beta", "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m", 0 };
static emlrtECInfo j_emlrtECI = { -1, 6, 21, "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m" };
static emlrtBCInfo n_emlrtBCI = { -1, -1, 5, 13, "beta0", "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m", 0 };
static emlrtECInfo k_emlrtECI = { -1, 5, 5, "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m" };
static emlrtBCInfo o_emlrtBCI = { -1, -1, 6, 55, "beta0", "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m", 0 };
static emlrtECInfo l_emlrtECI = { -1, 6, 41, "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m" };
static emlrtBCInfo p_emlrtBCI = { -1, -1, 6, 5, "Sigma_s0", "bSSupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bSSupdate.m", 0 };
/* Function Declarations */
static void c_eml_xgemm(int32_T m, int32_T n, const real_T A_data[], int32_T lda,
const real_T B_data[], emxArray_real_T *C, int32_T ldc);
/* Function Definitions */
static void c_eml_xgemm(int32_T m, int32_T n, const real_T A_data[], int32_T lda,
const real_T B_data[], emxArray_real_T *C, int32_T ldc)
{
real_T alpha1;
real_T beta1;
char_T TRANSB;
char_T TRANSA;
ptrdiff_t m_t;
ptrdiff_t n_t;
ptrdiff_t k_t;
ptrdiff_t lda_t;
ptrdiff_t ldb_t;
ptrdiff_t ldc_t;
double * alpha1_t;
double * Aia0_t;
double * Bib0_t;
double * beta1_t;
double * Cic0_t;
if ((m < 1) || (n < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(m);
n_t = (ptrdiff_t)(n);
k_t = (ptrdiff_t)(3);
lda_t = (ptrdiff_t)(lda);
ldb_t = (ptrdiff_t)(3);
ldc_t = (ptrdiff_t)(ldc);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&A_data[0]);
Bib0_t = (double *)(&B_data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&C->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
void bSSupdate(const emlrtStack *sp, const emxArray_real_T *Y1, const
emxArray_real_T *Pb, const emxArray_real_T *W1, const
emxArray_real_T *beta, const real_T exbetabar_data[], const
int32_T exbetabar_size[2], real_T q, emxArray_real_T *beta0,
emxArray_real_T *Sigma_s0)
{
emxArray_real_T *r0;
emxArray_real_T *y;
emxArray_real_T *b_y;
emxArray_real_T *c_y;
int32_T i7;
int32_T i;
int32_T loop_ub;
int32_T ll;
emxArray_real_T *a;
emxArray_real_T *d_y;
emxArray_real_T *b_a;
emxArray_real_T *b;
emxArray_real_T *b_b;
emxArray_real_T *r1;
emxArray_real_T *r2;
real_T z_data[1200];
int32_T b_loop_ub;
int32_T c_loop_ub;
int32_T i8;
int16_T unnamed_idx_0;
real_T Pb_data[3600];
int32_T tmp_size[1];
real_T tmp_data[1200];
int32_T b_tmp_data[10];
int32_T d_loop_ub;
const mxArray *e_y;
static const int32_T iv10[2] = { 1, 45 };
const mxArray *m7;
char_T cv16[45];
static const char_T cv17[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D',
'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p',
'a', 'n', 's', 'i', 'o', 'n' };
const mxArray *f_y;
static const int32_T iv11[2] = { 1, 21 };
char_T cv18[21];
static const char_T cv19[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' };
int32_T e_loop_ub;
int16_T unnamed_idx_1;
real_T alpha1;
real_T beta1;
char_T TRANSB;
char_T TRANSA;
ptrdiff_t m_t;
ptrdiff_t n_t;
ptrdiff_t k_t;
ptrdiff_t lda_t;
ptrdiff_t ldb_t;
ptrdiff_t ldc_t;
double * alpha1_t;
double * Aia0_t;
double * Bib0_t;
double * beta1_t;
double * Cic0_t;
int32_T iv12[1];
boolean_T guard2 = false;
boolean_T guard1 = false;
real_T a_data[1200];
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
emlrtStack d_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
d_st.prev = &b_st;
d_st.tls = b_st.tls;
emlrtHeapReferenceStackEnterFcnR2012b(sp);
emxInit_real_T(sp, &r0, 2, &s_emlrtRTEI, true);
emxInit_real_T(sp, &y, 2, &s_emlrtRTEI, true);
c_emxInit_real_T(sp, &b_y, 1, &s_emlrtRTEI, true);
c_emxInit_real_T(sp, &c_y, 1, &s_emlrtRTEI, true);
i7 = beta0->size[0] * beta0->size[1];
beta0->size[0] = (int32_T)q;
emxEnsureCapacity(sp, (emxArray__common *)beta0, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
i = Y1->size[0];
i7 = beta0->size[0] * beta0->size[1];
beta0->size[1] = i;
emxEnsureCapacity(sp, (emxArray__common *)beta0, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
loop_ub = (int32_T)q * Y1->size[0];
for (i7 = 0; i7 < loop_ub; i7++) {
beta0->data[i7] = 0.0;
}
i7 = Sigma_s0->size[0] * Sigma_s0->size[1];
Sigma_s0->size[0] = 1;
emxEnsureCapacity(sp, (emxArray__common *)Sigma_s0, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
i = Y1->size[0];
i7 = Sigma_s0->size[0] * Sigma_s0->size[1];
Sigma_s0->size[1] = i;
emxEnsureCapacity(sp, (emxArray__common *)Sigma_s0, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
loop_ub = Y1->size[0];
for (i7 = 0; i7 < loop_ub; i7++) {
Sigma_s0->data[i7] = 0.0;
}
ll = 0;
emxInit_real_T(sp, &a, 2, &s_emlrtRTEI, true);
emxInit_real_T(sp, &d_y, 2, &s_emlrtRTEI, true);
emxInit_real_T(sp, &b_a, 2, &s_emlrtRTEI, true);
emxInit_real_T(sp, &b, 2, &s_emlrtRTEI, true);
c_emxInit_real_T(sp, &b_b, 1, &s_emlrtRTEI, true);
emxInit_real_T(sp, &r1, 2, &s_emlrtRTEI, true);
emxInit_real_T(sp, &r2, 2, &s_emlrtRTEI, true);
while (ll <= Y1->size[0] - 1) {
loop_ub = Y1->size[1];
i7 = Y1->size[0];
i = 1 + ll;
i7 = emlrtDynamicBoundsCheckFastR2012b(i, 1, i7, &k_emlrtBCI, sp);
for (i = 0; i < loop_ub; i++) {
z_data[i] = Y1->data[(i7 + Y1->size[0] * i) - 1];
}
st.site = &tb_emlrtRSI;
i7 = a->size[0] * a->size[1];
a->size[0] = W1->size[1];
a->size[1] = W1->size[0];
emxEnsureCapacity(&st, (emxArray__common *)a, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
b_loop_ub = W1->size[0];
for (i7 = 0; i7 < b_loop_ub; i7++) {
c_loop_ub = W1->size[1];
for (i = 0; i < c_loop_ub; i++) {
a->data[i + a->size[0] * i7] = W1->data[i7 + W1->size[0] * i];
}
}
b_st.site = &db_emlrtRSI;
b_dynamic_size_checks(&b_st, a, exbetabar_size);
if ((a->size[1] == 1) || (exbetabar_size[0] == 1)) {
i7 = y->size[0] * y->size[1];
y->size[0] = a->size[0];
y->size[1] = 3;
emxEnsureCapacity(&st, (emxArray__common *)y, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
b_loop_ub = a->size[0];
for (i7 = 0; i7 < b_loop_ub; i7++) {
for (i = 0; i < 3; i++) {
y->data[i7 + y->size[0] * i] = 0.0;
c_loop_ub = a->size[1];
for (i8 = 0; i8 < c_loop_ub; i8++) {
y->data[i7 + y->size[0] * i] += a->data[i7 + a->size[0] * i8] *
exbetabar_data[i8 + exbetabar_size[0] * i];
}
}
}
} else {
unnamed_idx_0 = (int16_T)a->size[0];
i7 = y->size[0] * y->size[1];
y->size[0] = unnamed_idx_0;
y->size[1] = 3;
emxEnsureCapacity(&st, (emxArray__common *)y, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
b_loop_ub = unnamed_idx_0 * 3;
for (i7 = 0; i7 < b_loop_ub; i7++) {
y->data[i7] = 0.0;
}
b_st.site = &cb_emlrtRSI;
b_eml_xgemm(a->size[0], a->size[1], a, a->size[0], exbetabar_data, a->
size[1], y, a->size[0]);
}
st.site = &tb_emlrtRSI;
i7 = Pb->size[2];
i = ll + 1;
emlrtDynamicBoundsCheckFastR2012b(i, 1, i7, &l_emlrtBCI, &st);
i7 = Pb->size[1];
unnamed_idx_0 = (int16_T)y->size[0];
i = r0->size[0] * r0->size[1];
r0->size[0] = unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)r0, i, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
i = r0->size[0] * r0->size[1];
r0->size[1] = (int16_T)i7;
emxEnsureCapacity(&st, (emxArray__common *)r0, i, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
b_loop_ub = unnamed_idx_0 * (int16_T)i7;
for (i7 = 0; i7 < b_loop_ub; i7++) {
r0->data[i7] = 0.0;
}
i7 = Pb->size[1];
b_loop_ub = Pb->size[1];
for (i = 0; i < b_loop_ub; i++) {
for (i8 = 0; i8 < 3; i8++) {
Pb_data[i8 + 3 * i] = Pb->data[(i8 + Pb->size[0] * i) + Pb->size[0] *
Pb->size[1] * ll];
}
}
b_st.site = &cb_emlrtRSI;
c_eml_xgemm(y->size[0], i7, y->data, y->size[0], Pb_data, r0, y->size[0]);
st.site = &tb_emlrtRSI;
diag(&st, r0, tmp_data, tmp_size);
emlrtSizeEqCheck1DFastR2012b(loop_ub, tmp_size[0], &i_emlrtECI, sp);
for (i7 = 0; i7 < loop_ub; i7++) {
z_data[i7] -= tmp_data[i7];
}
b_loop_ub = beta0->size[0];
for (i7 = 0; i7 < b_loop_ub; i7++) {
b_tmp_data[i7] = i7;
}
i7 = beta0->size[1];
i = ll + 1;
emlrtDynamicBoundsCheckFastR2012b(i, 1, i7, &n_emlrtBCI, sp);
st.site = &ub_emlrtRSI;
i7 = b_a->size[0] * b_a->size[1];
b_a->size[0] = W1->size[0];
b_a->size[1] = W1->size[1];
emxEnsureCapacity(&st, (emxArray__common *)b_a, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
c_loop_ub = W1->size[0] * W1->size[1];
for (i7 = 0; i7 < c_loop_ub; i7++) {
b_a->data[i7] = W1->data[i7];
}
i7 = b->size[0] * b->size[1];
b->size[0] = W1->size[1];
b->size[1] = W1->size[0];
emxEnsureCapacity(&st, (emxArray__common *)b, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
c_loop_ub = W1->size[0];
for (i7 = 0; i7 < c_loop_ub; i7++) {
d_loop_ub = W1->size[1];
for (i = 0; i < d_loop_ub; i++) {
b->data[i + b->size[0] * i7] = W1->data[i7 + W1->size[0] * i];
}
}
b_st.site = &db_emlrtRSI;
if (!(W1->size[1] == b->size[0])) {
if (((W1->size[0] == 1) && (W1->size[1] == 1)) || ((b->size[0] == 1) &&
(b->size[1] == 1))) {
e_y = NULL;
m7 = emlrtCreateCharArray(2, iv10);
for (i = 0; i < 45; i++) {
cv16[i] = cv17[i];
}
emlrtInitCharArrayR2013a(&b_st, 45, m7, cv16);
emlrtAssign(&e_y, m7);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, e_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
f_y = NULL;
m7 = emlrtCreateCharArray(2, iv11);
for (i = 0; i < 21; i++) {
cv18[i] = cv19[i];
}
emlrtInitCharArrayR2013a(&b_st, 21, m7, cv18);
emlrtAssign(&f_y, m7);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, f_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((W1->size[1] == 1) || (b->size[0] == 1)) {
i7 = d_y->size[0] * d_y->size[1];
d_y->size[0] = W1->size[0];
d_y->size[1] = b->size[1];
emxEnsureCapacity(&st, (emxArray__common *)d_y, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
c_loop_ub = W1->size[0];
for (i7 = 0; i7 < c_loop_ub; i7++) {
d_loop_ub = b->size[1];
for (i = 0; i < d_loop_ub; i++) {
d_y->data[i7 + d_y->size[0] * i] = 0.0;
e_loop_ub = W1->size[1];
for (i8 = 0; i8 < e_loop_ub; i8++) {
d_y->data[i7 + d_y->size[0] * i] += W1->data[i7 + W1->size[0] * i8] *
b->data[i8 + b->size[0] * i];
}
}
}
} else {
unnamed_idx_0 = (int16_T)W1->size[0];
unnamed_idx_1 = (int16_T)b->size[1];
i7 = r1->size[0] * r1->size[1];
r1->size[0] = unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)r1, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
i7 = r1->size[0] * r1->size[1];
r1->size[1] = unnamed_idx_1;
emxEnsureCapacity(&st, (emxArray__common *)r1, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
c_loop_ub = unnamed_idx_0 * unnamed_idx_1;
for (i7 = 0; i7 < c_loop_ub; i7++) {
r1->data[i7] = 0.0;
}
b_st.site = &cb_emlrtRSI;
c_st.site = &eb_emlrtRSI;
i7 = d_y->size[0] * d_y->size[1];
d_y->size[0] = unnamed_idx_0;
emxEnsureCapacity(&c_st, (emxArray__common *)d_y, i7, (int32_T)sizeof
(real_T), &s_emlrtRTEI);
i7 = d_y->size[0] * d_y->size[1];
d_y->size[1] = unnamed_idx_1;
emxEnsureCapacity(&c_st, (emxArray__common *)d_y, i7, (int32_T)sizeof
(real_T), &s_emlrtRTEI);
c_loop_ub = unnamed_idx_0 * unnamed_idx_1;
for (i7 = 0; i7 < c_loop_ub; i7++) {
d_y->data[i7] = 0.0;
}
if ((W1->size[0] < 1) || (b->size[1] < 1) || (W1->size[1] < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(W1->size[0]);
n_t = (ptrdiff_t)(b->size[1]);
k_t = (ptrdiff_t)(W1->size[1]);
lda_t = (ptrdiff_t)(W1->size[0]);
ldb_t = (ptrdiff_t)(W1->size[1]);
ldc_t = (ptrdiff_t)(W1->size[0]);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&b_a->data[0]);
Bib0_t = (double *)(&b->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&d_y->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t,
Bib0_t, &ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
st.site = &ub_emlrtRSI;
b_st.site = &ub_emlrtRSI;
mldivide(&b_st, d_y->data, d_y->size, W1, r2);
i7 = b_a->size[0] * b_a->size[1];
b_a->size[0] = r2->size[0];
b_a->size[1] = r2->size[1];
emxEnsureCapacity(&st, (emxArray__common *)b_a, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
c_loop_ub = r2->size[0] * r2->size[1];
for (i7 = 0; i7 < c_loop_ub; i7++) {
b_a->data[i7] = r2->data[i7];
}
i7 = b_b->size[0];
b_b->size[0] = loop_ub;
emxEnsureCapacity(&st, (emxArray__common *)b_b, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
for (i7 = 0; i7 < loop_ub; i7++) {
b_b->data[i7] = z_data[i7];
}
b_st.site = &db_emlrtRSI;
c_dynamic_size_checks(&b_st, b_a, b_b);
if ((b_a->size[1] == 1) || (loop_ub == 1)) {
i7 = b_y->size[0];
b_y->size[0] = b_a->size[0];
emxEnsureCapacity(&st, (emxArray__common *)b_y, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
c_loop_ub = b_a->size[0];
for (i7 = 0; i7 < c_loop_ub; i7++) {
b_y->data[i7] = 0.0;
d_loop_ub = b_a->size[1];
for (i = 0; i < d_loop_ub; i++) {
b_y->data[i7] += b_a->data[i7 + b_a->size[0] * i] * b_b->data[i];
}
}
} else {
unnamed_idx_0 = (int16_T)b_a->size[0];
i7 = b_y->size[0];
b_y->size[0] = unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)b_y, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
c_loop_ub = unnamed_idx_0;
for (i7 = 0; i7 < c_loop_ub; i7++) {
b_y->data[i7] = 0.0;
}
b_st.site = &cb_emlrtRSI;
d_eml_xgemm(b_a->size[0], b_a->size[1], b_a, b_a->size[0], b_b, b_a->size
[1], b_y, b_a->size[0]);
}
iv12[0] = b_loop_ub;
emlrtSubAssignSizeCheckR2012b(iv12, 1, *(int32_T (*)[1])b_y->size, 1,
&k_emlrtECI, sp);
b_loop_ub = b_y->size[0];
for (i7 = 0; i7 < b_loop_ub; i7++) {
beta0->data[b_tmp_data[i7] + beta0->size[0] * ll] = b_y->data[i7];
}
st.site = &vb_emlrtRSI;
i7 = b_a->size[0] * b_a->size[1];
b_a->size[0] = W1->size[1];
b_a->size[1] = W1->size[0];
emxEnsureCapacity(&st, (emxArray__common *)b_a, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
b_loop_ub = W1->size[0];
for (i7 = 0; i7 < b_loop_ub; i7++) {
c_loop_ub = W1->size[1];
for (i = 0; i < c_loop_ub; i++) {
b_a->data[i + b_a->size[0] * i7] = W1->data[i7 + W1->size[0] * i];
}
}
b_loop_ub = beta->size[0];
i7 = beta->size[1];
i = 1 + ll;
i7 = emlrtDynamicBoundsCheckFastR2012b(i, 1, i7, &m_emlrtBCI, &st);
i = b_b->size[0];
b_b->size[0] = b_loop_ub;
emxEnsureCapacity(&st, (emxArray__common *)b_b, i, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
for (i = 0; i < b_loop_ub; i++) {
b_b->data[i] = beta->data[i + beta->size[0] * (i7 - 1)];
}
b_st.site = &db_emlrtRSI;
c_dynamic_size_checks(&b_st, b_a, b_b);
guard2 = false;
if (b_a->size[1] == 1) {
guard2 = true;
} else {
i7 = beta->size[0];
if (i7 == 1) {
guard2 = true;
} else {
unnamed_idx_0 = (int16_T)b_a->size[0];
i7 = b_y->size[0];
b_y->size[0] = unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)b_y, i7, (int32_T)sizeof
(real_T), &s_emlrtRTEI);
b_loop_ub = unnamed_idx_0;
for (i7 = 0; i7 < b_loop_ub; i7++) {
b_y->data[i7] = 0.0;
}
b_st.site = &cb_emlrtRSI;
d_eml_xgemm(b_a->size[0], b_a->size[1], b_a, b_a->size[0], b_b,
b_a->size[1], b_y, b_a->size[0]);
}
}
if (guard2) {
i7 = b_y->size[0];
b_y->size[0] = b_a->size[0];
emxEnsureCapacity(&st, (emxArray__common *)b_y, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
b_loop_ub = b_a->size[0];
for (i7 = 0; i7 < b_loop_ub; i7++) {
b_y->data[i7] = 0.0;
c_loop_ub = b_a->size[1];
for (i = 0; i < c_loop_ub; i++) {
b_y->data[i7] += b_a->data[i7 + b_a->size[0] * i] * b_b->data[i];
}
}
}
i7 = b_y->size[0];
emlrtSizeEqCheck1DFastR2012b(loop_ub, i7, &j_emlrtECI, sp);
st.site = &vb_emlrtRSI;
i7 = b_a->size[0] * b_a->size[1];
b_a->size[0] = W1->size[1];
b_a->size[1] = W1->size[0];
emxEnsureCapacity(&st, (emxArray__common *)b_a, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
b_loop_ub = W1->size[0];
for (i7 = 0; i7 < b_loop_ub; i7++) {
c_loop_ub = W1->size[1];
for (i = 0; i < c_loop_ub; i++) {
b_a->data[i + b_a->size[0] * i7] = W1->data[i7 + W1->size[0] * i];
}
}
b_loop_ub = beta0->size[0];
i7 = beta0->size[1];
i = 1 + ll;
i7 = emlrtDynamicBoundsCheckFastR2012b(i, 1, i7, &o_emlrtBCI, &st);
i = b_b->size[0];
b_b->size[0] = b_loop_ub;
emxEnsureCapacity(&st, (emxArray__common *)b_b, i, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
for (i = 0; i < b_loop_ub; i++) {
b_b->data[i] = beta0->data[i + beta0->size[0] * (i7 - 1)];
}
b_st.site = &db_emlrtRSI;
c_dynamic_size_checks(&b_st, b_a, b_b);
guard1 = false;
if (b_a->size[1] == 1) {
guard1 = true;
} else {
i7 = beta0->size[0];
if (i7 == 1) {
guard1 = true;
} else {
unnamed_idx_0 = (int16_T)b_a->size[0];
i7 = c_y->size[0];
c_y->size[0] = unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)c_y, i7, (int32_T)sizeof
(real_T), &s_emlrtRTEI);
b_loop_ub = unnamed_idx_0;
for (i7 = 0; i7 < b_loop_ub; i7++) {
c_y->data[i7] = 0.0;
}
b_st.site = &cb_emlrtRSI;
d_eml_xgemm(b_a->size[0], b_a->size[1], b_a, b_a->size[0], b_b,
b_a->size[1], c_y, b_a->size[0]);
}
}
if (guard1) {
i7 = c_y->size[0];
c_y->size[0] = b_a->size[0];
emxEnsureCapacity(&st, (emxArray__common *)c_y, i7, (int32_T)sizeof(real_T),
&s_emlrtRTEI);
b_loop_ub = b_a->size[0];
for (i7 = 0; i7 < b_loop_ub; i7++) {
c_y->data[i7] = 0.0;
c_loop_ub = b_a->size[1];
for (i = 0; i < c_loop_ub; i++) {
c_y->data[i7] += b_a->data[i7 + b_a->size[0] * i] * b_b->data[i];
}
}
}
i7 = c_y->size[0];
emlrtSizeEqCheck1DFastR2012b(loop_ub, i7, &l_emlrtECI, sp);
st.site = &vb_emlrtRSI;
for (i7 = 0; i7 < loop_ub; i7++) {
a_data[i7] = z_data[i7] - b_y->data[i7];
}
for (i7 = 0; i7 < loop_ub; i7++) {
alpha1 = z_data[i7] - c_y->data[i7];
z_data[i7] = alpha1;
}
b_st.site = &db_emlrtRSI;
if (loop_ub == 1) {
alpha1 = 0.0;
i7 = 0;
while (i7 <= 0) {
alpha1 += a_data[0] * z_data[0];
i7 = 1;
}
} else {
b_st.site = &je_emlrtRSI;
c_st.site = &ke_emlrtRSI;
if (loop_ub < 1) {
alpha1 = 0.0;
} else {
n_t = (ptrdiff_t)(loop_ub);
m_t = (ptrdiff_t)(1);
k_t = (ptrdiff_t)(1);
alpha1_t = (double *)(&a_data[0]);
Aia0_t = (double *)(&z_data[0]);
alpha1 = ddot(&n_t, alpha1_t, &m_t, Aia0_t, &k_t);
}
}
i7 = Sigma_s0->size[1];
i = 1 + ll;
Sigma_s0->data[emlrtDynamicBoundsCheckFastR2012b(i, 1, i7, &p_emlrtBCI, sp)
- 1] = alpha1 / (real_T)Y1->size[1];
ll++;
emlrtBreakCheckFastR2012b(emlrtBreakCheckR2012bFlagVar, sp);
}
emxFree_real_T(&r2);
emxFree_real_T(&r1);
emxFree_real_T(&b_b);
emxFree_real_T(&b);
emxFree_real_T(&b_a);
emxFree_real_T(&d_y);
emxFree_real_T(&a);
emxFree_real_T(&c_y);
emxFree_real_T(&b_y);
emxFree_real_T(&y);
emxFree_real_T(&r0);
emlrtHeapReferenceStackLeaveFcnR2012b(sp);
}
void b_dynamic_size_checks(const emlrtStack *sp, const emxArray_real_T *a, const
int32_T b_size[2])
{
const mxArray *y;
static const int32_T iv8[2] = { 1, 45 };
const mxArray *m6;
char_T cv12[45];
int32_T i;
static const char_T cv13[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D',
'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p',
'a', 'n', 's', 'i', 'o', 'n' };
const mxArray *b_y;
static const int32_T iv9[2] = { 1, 21 };
char_T cv14[21];
static const char_T cv15[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' };
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = sp;
b_st.tls = sp->tls;
if (!(a->size[1] == b_size[0])) {
if ((a->size[0] == 1) && (a->size[1] == 1)) {
y = NULL;
m6 = emlrtCreateCharArray(2, iv8);
for (i = 0; i < 45; i++) {
cv12[i] = cv13[i];
}
emlrtInitCharArrayR2013a(sp, 45, m6, cv12);
emlrtAssign(&y, m6);
st.site = &ef_emlrtRSI;
b_st.site = &mf_emlrtRSI;
error(&st, b_message(&b_st, y, &g_emlrtMCI), &h_emlrtMCI);
} else {
b_y = NULL;
m6 = emlrtCreateCharArray(2, iv9);
for (i = 0; i < 21; i++) {
cv14[i] = cv15[i];
}
emlrtInitCharArrayR2013a(sp, 21, m6, cv14);
emlrtAssign(&b_y, m6);
st.site = &ff_emlrtRSI;
b_st.site = &nf_emlrtRSI;
error(&st, b_message(&b_st, b_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
}
void b_eml_xgemm(int32_T m, int32_T k, const emxArray_real_T *A, int32_T lda,
const real_T B_data[], int32_T ldb, emxArray_real_T *C, int32_T
ldc)
{
real_T alpha1;
real_T beta1;
char_T TRANSB;
char_T TRANSA;
ptrdiff_t m_t;
ptrdiff_t n_t;
ptrdiff_t k_t;
ptrdiff_t lda_t;
ptrdiff_t ldb_t;
ptrdiff_t ldc_t;
double * alpha1_t;
double * Aia0_t;
double * Bib0_t;
double * beta1_t;
double * Cic0_t;
if ((m < 1) || (k < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(m);
n_t = (ptrdiff_t)(3);
k_t = (ptrdiff_t)(k);
lda_t = (ptrdiff_t)(lda);
ldb_t = (ptrdiff_t)(ldb);
ldc_t = (ptrdiff_t)(ldc);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&A->data[0]);
Bib0_t = (double *)(&B_data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&C->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
/* End of code generation (bSSupdate.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_EM_types.h
/*
* SREM_EM_types.h
*
* Code generation for function 'SREM_EM'
*
*/
#ifndef __SREM_EM_TYPES_H__
#define __SREM_EM_TYPES_H__
/* Include files */
#include "rtwtypes.h"
/* Type Definitions */
#ifndef struct_emxArray__common
#define struct_emxArray__common
struct emxArray__common
{
void *data;
int32_T *size;
int32_T allocatedSize;
int32_T numDimensions;
boolean_T canFreeData;
};
#endif /*struct_emxArray__common*/
#ifndef typedef_emxArray__common
#define typedef_emxArray__common
typedef struct emxArray__common emxArray__common;
#endif /*typedef_emxArray__common*/
#ifndef struct_emxArray_boolean_T
#define struct_emxArray_boolean_T
struct emxArray_boolean_T
{
boolean_T *data;
int32_T *size;
int32_T allocatedSize;
int32_T numDimensions;
boolean_T canFreeData;
};
#endif /*struct_emxArray_boolean_T*/
#ifndef typedef_emxArray_boolean_T
#define typedef_emxArray_boolean_T
typedef struct emxArray_boolean_T emxArray_boolean_T;
#endif /*typedef_emxArray_boolean_T*/
#ifndef struct_emxArray_int32_T
#define struct_emxArray_int32_T
struct emxArray_int32_T
{
int32_T *data;
int32_T *size;
int32_T allocatedSize;
int32_T numDimensions;
boolean_T canFreeData;
};
#endif /*struct_emxArray_int32_T*/
#ifndef typedef_emxArray_int32_T
#define typedef_emxArray_int32_T
typedef struct emxArray_int32_T emxArray_int32_T;
#endif /*typedef_emxArray_int32_T*/
#ifndef struct_emxArray_int32_T_1200
#define struct_emxArray_int32_T_1200
struct emxArray_int32_T_1200
{
int32_T data[1200];
int32_T size[1];
};
#endif /*struct_emxArray_int32_T_1200*/
#ifndef typedef_emxArray_int32_T_1200
#define typedef_emxArray_int32_T_1200
typedef struct emxArray_int32_T_1200 emxArray_int32_T_1200;
#endif /*typedef_emxArray_int32_T_1200*/
#ifndef struct_emxArray_int32_T_1x10
#define struct_emxArray_int32_T_1x10
struct emxArray_int32_T_1x10
{
int32_T data[10];
int32_T size[2];
};
#endif /*struct_emxArray_int32_T_1x10*/
#ifndef typedef_emxArray_int32_T_1x10
#define typedef_emxArray_int32_T_1x10
typedef struct emxArray_int32_T_1x10 emxArray_int32_T_1x10;
#endif /*typedef_emxArray_int32_T_1x10*/
#ifndef struct_emxArray_int32_T_1x6
#define struct_emxArray_int32_T_1x6
struct emxArray_int32_T_1x6
{
int32_T data[6];
int32_T size[2];
};
#endif /*struct_emxArray_int32_T_1x6*/
#ifndef typedef_emxArray_int32_T_1x6
#define typedef_emxArray_int32_T_1x6
typedef struct emxArray_int32_T_1x6 emxArray_int32_T_1x6;
#endif /*typedef_emxArray_int32_T_1x6*/
#ifndef struct_emxArray_real_T
#define struct_emxArray_real_T
struct emxArray_real_T
{
real_T *data;
int32_T *size;
int32_T allocatedSize;
int32_T numDimensions;
boolean_T canFreeData;
};
#endif /*struct_emxArray_real_T*/
#ifndef typedef_emxArray_real_T
#define typedef_emxArray_real_T
typedef struct emxArray_real_T emxArray_real_T;
#endif /*typedef_emxArray_real_T*/
#ifndef struct_emxArray_real_T_10
#define struct_emxArray_real_T_10
struct emxArray_real_T_10
{
real_T data[10];
int32_T size[1];
};
#endif /*struct_emxArray_real_T_10*/
#ifndef typedef_emxArray_real_T_10
#define typedef_emxArray_real_T_10
typedef struct emxArray_real_T_10 emxArray_real_T_10;
#endif /*typedef_emxArray_real_T_10*/
#ifndef struct_emxArray_real_T_1200
#define struct_emxArray_real_T_1200
struct emxArray_real_T_1200
{
real_T data[1200];
int32_T size[1];
};
#endif /*struct_emxArray_real_T_1200*/
#ifndef typedef_emxArray_real_T_1200
#define typedef_emxArray_real_T_1200
typedef struct emxArray_real_T_1200 emxArray_real_T_1200;
#endif /*typedef_emxArray_real_T_1200*/
#ifndef struct_emxArray_real_T_1x10
#define struct_emxArray_real_T_1x10
struct emxArray_real_T_1x10
{
real_T data[10];
int32_T size[2];
};
#endif /*struct_emxArray_real_T_1x10*/
#ifndef typedef_emxArray_real_T_1x10
#define typedef_emxArray_real_T_1x10
typedef struct emxArray_real_T_1x10 emxArray_real_T_1x10;
#endif /*typedef_emxArray_real_T_1x10*/
#ifndef struct_emxArray_real_T_3x1200
#define struct_emxArray_real_T_3x1200
struct emxArray_real_T_3x1200
{
real_T data[3600];
int32_T size[2];
};
#endif /*struct_emxArray_real_T_3x1200*/
#ifndef typedef_emxArray_real_T_3x1200
#define typedef_emxArray_real_T_3x1200
typedef struct emxArray_real_T_3x1200 emxArray_real_T_3x1200;
#endif /*typedef_emxArray_real_T_3x1200*/
#ifndef struct_emxArray_real_T_6
#define struct_emxArray_real_T_6
struct emxArray_real_T_6
{
real_T data[6];
int32_T size[1];
};
#endif /*struct_emxArray_real_T_6*/
#ifndef typedef_emxArray_real_T_6
#define typedef_emxArray_real_T_6
typedef struct emxArray_real_T_6 emxArray_real_T_6;
#endif /*typedef_emxArray_real_T_6*/
#endif
/* End of code generation (SREM_EM_types.h) */
<file_sep>/subfuns/codegen/mex/SREM_EM/taufun.c
/*
* taufun.c
*
* Code generation for function 'taufun'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "taufun.h"
#include "SREM_EM_emxutil.h"
#include "exp.h"
#include "abs.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRSInfo we_emlrtRSI = { 6, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtRSInfo xe_emlrtRSI = { 7, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtRSInfo ye_emlrtRSI = { 8, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtRSInfo af_emlrtRSI = { 9, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtRSInfo bf_emlrtRSI = { 10, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtRTEInfo bb_emlrtRTEI = { 1, 20, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtRTEInfo cb_emlrtRTEI = { 4, 5, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtRTEInfo db_emlrtRTEI = { 4, 17, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtECInfo p_emlrtECI = { -1, 10, 25, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtECInfo q_emlrtECI = { -1, 9, 25, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtECInfo r_emlrtECI = { -1, 8, 25, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtBCInfo q_emlrtBCI = { -1, -1, 7, 34, "b0", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtECInfo s_emlrtECI = { -1, 7, 24, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtBCInfo r_emlrtBCI = { -1, -1, 6, 58, "y", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtECInfo t_emlrtECI = { -1, 6, 50, "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m" };
static emlrtBCInfo s_emlrtBCI = { -1, -1, 6, 25, "DIC", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtBCInfo t_emlrtBCI = { -1, -1, 4, 28, "Y11DIC", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtBCInfo u_emlrtBCI = { -1, -1, 4, 12, "b", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtBCInfo v_emlrtBCI = { -1, -1, 6, 25, "DICind", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtBCInfo w_emlrtBCI = { -1, -1, 6, 50, "y", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtBCInfo x_emlrtBCI = { -1, -1, 7, 24, "b0", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtBCInfo y_emlrtBCI = { -1, -1, 8, 25, "b0", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtBCInfo ab_emlrtBCI = { -1, -1, 9, 25, "b0", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
static emlrtBCInfo bb_emlrtBCI = { -1, -1, 10, 25, "b0", "taufun",
"D:\\CODE\\GHMM_V3\\subfuns\\taufun.m", 0 };
/* Function Definitions */
void taufun(const emlrtStack *sp, real_T tau, const emxArray_real_T *b, const
emxArray_real_T *Y11DIC, real_T N0, const emxArray_real_T *DIC,
const emxArray_real_T *DICind, real_T *f1, real_T *f2)
{
int32_T ii;
emxArray_real_T *b0;
emxArray_real_T *y;
int32_T loop_ub;
int32_T i13;
int32_T b_ii;
int32_T kk;
int32_T idx;
boolean_T x_data[6];
int32_T ii_data[6];
boolean_T exitg1;
boolean_T guard1 = false;
const mxArray *b_y;
const mxArray *m17;
int32_T sind_data[6];
real_T y_data[6];
real_T ub;
int32_T y_size[1];
int32_T Dis_size[1];
real_T Dis_data[6];
int32_T a_size_idx_1;
real_T a_data[1200];
real_T b_data[1200];
const mxArray *c_y;
static const int32_T iv37[2] = { 1, 45 };
char_T cv44[45];
static const char_T cv45[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D',
'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p',
'a', 'n', 's', 'i', 'o', 'n' };
const mxArray *d_y;
static const int32_T iv38[2] = { 1, 21 };
char_T cv46[21];
static const char_T cv47[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' };
ptrdiff_t n_t;
ptrdiff_t incx_t;
ptrdiff_t incy_t;
double * xix0_t;
double * yiy0_t;
const mxArray *e_y;
static const int32_T iv39[2] = { 1, 45 };
const mxArray *f_y;
static const int32_T iv40[2] = { 1, 21 };
real_T ub1;
const mxArray *g_y;
static const int32_T iv41[2] = { 1, 45 };
const mxArray *h_y;
static const int32_T iv42[2] = { 1, 21 };
real_T ub2;
const mxArray *i_y;
static const int32_T iv43[2] = { 1, 45 };
const mxArray *j_y;
static const int32_T iv44[2] = { 1, 21 };
real_T ub3;
real_T a;
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
emlrtStack d_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
d_st.prev = &b_st;
d_st.tls = b_st.tls;
emlrtHeapReferenceStackEnterFcnR2012b(sp);
*f1 = 0.0;
*f2 = 0.0;
ii = 0;
c_emxInit_real_T(sp, &b0, 1, &cb_emlrtRTEI, true);
c_emxInit_real_T(sp, &y, 1, &db_emlrtRTEI, true);
while (ii <= (int32_T)N0 - 1) {
loop_ub = b->size[0];
i13 = b->size[1];
b_ii = emlrtDynamicBoundsCheckFastR2012b(ii + 1, 1, i13, &u_emlrtBCI, sp);
i13 = b0->size[0];
b0->size[0] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)b0, i13, (int32_T)sizeof(real_T),
&bb_emlrtRTEI);
for (i13 = 0; i13 < loop_ub; i13++) {
b0->data[i13] = b->data[i13 + b->size[0] * (b_ii - 1)];
}
loop_ub = Y11DIC->size[0];
i13 = Y11DIC->size[1];
b_ii = emlrtDynamicBoundsCheckFastR2012b(ii + 1, 1, i13, &t_emlrtBCI, sp);
i13 = y->size[0];
y->size[0] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)y, i13, (int32_T)sizeof(real_T),
&bb_emlrtRTEI);
for (i13 = 0; i13 < loop_ub; i13++) {
y->data[i13] = Y11DIC->data[i13 + Y11DIC->size[0] * (b_ii - 1)];
}
kk = 0;
while (kk <= DICind->size[0] - 1) {
st.site = &we_emlrtRSI;
loop_ub = DIC->size[1];
i13 = DIC->size[0];
idx = DICind->size[0];
b_ii = 1 + kk;
idx = (int32_T)DICind->data[emlrtDynamicBoundsCheckFastR2012b(b_ii, 1, idx,
&v_emlrtBCI, &st) - 1];
idx = emlrtDynamicBoundsCheckFastR2012b(idx, 1, i13, &s_emlrtBCI, &st);
for (i13 = 0; i13 < loop_ub; i13++) {
x_data[i13] = (DIC->data[(idx + DIC->size[0] * i13) - 1] == 1.0);
}
b_st.site = &p_emlrtRSI;
idx = 0;
c_st.site = &q_emlrtRSI;
b_ii = 1;
exitg1 = false;
while ((!exitg1) && (b_ii <= loop_ub)) {
guard1 = false;
if (x_data[b_ii - 1]) {
idx++;
ii_data[idx - 1] = b_ii;
if (idx >= loop_ub) {
exitg1 = true;
} else {
guard1 = true;
}
} else {
guard1 = true;
}
if (guard1) {
b_ii++;
}
}
if (idx <= loop_ub) {
} else {
b_y = NULL;
m17 = emlrtCreateString("Assertion failed.");
emlrtAssign(&b_y, m17);
c_st.site = &gf_emlrtRSI;
error(&c_st, b_y, &d_emlrtMCI);
}
if (loop_ub == 1) {
if (idx == 0) {
loop_ub = 0;
}
} else if (1 > idx) {
loop_ub = 0;
} else {
loop_ub = idx;
}
for (i13 = 0; i13 < loop_ub; i13++) {
sind_data[i13] = ii_data[i13];
}
i13 = Y11DIC->size[0];
emlrtVectorVectorIndexCheckR2012b(i13, 1, 1, loop_ub, &t_emlrtECI, sp);
i13 = Y11DIC->size[0];
for (idx = 0; idx < loop_ub; idx++) {
b_ii = sind_data[idx];
emlrtDynamicBoundsCheckFastR2012b(b_ii, 1, i13, &w_emlrtBCI, sp);
}
i13 = Y11DIC->size[0];
idx = kk + 1;
emlrtDynamicBoundsCheckFastR2012b(idx, 1, i13, &r_emlrtBCI, sp);
ub = Y11DIC->data[kk + Y11DIC->size[0] * ii];
y_size[0] = loop_ub;
for (i13 = 0; i13 < loop_ub; i13++) {
y_data[i13] = y->data[sind_data[i13] - 1] - ub;
}
c_abs(y_data, y_size, Dis_data, Dis_size);
idx = Dis_size[0];
for (i13 = 0; i13 < idx; i13++) {
Dis_data[i13] *= -0.5;
}
d_exp(Dis_data, Dis_size);
i13 = b->size[0];
emlrtVectorVectorIndexCheckR2012b(i13, 1, 1, loop_ub, &s_emlrtECI, sp);
st.site = &xe_emlrtRSI;
a_size_idx_1 = Dis_size[0];
idx = Dis_size[0];
for (i13 = 0; i13 < idx; i13++) {
a_data[i13] = Dis_data[i13];
}
i13 = b->size[0];
idx = b->size[0];
b_ii = 1 + kk;
emlrtDynamicBoundsCheckFastR2012b(b_ii, 1, idx, &q_emlrtBCI, &st);
ub = b->data[kk + b->size[0] * ii];
for (idx = 0; idx < loop_ub; idx++) {
b_ii = sind_data[idx];
b_data[idx] = (b0->data[emlrtDynamicBoundsCheckFastR2012b(b_ii, 1, i13,
&x_emlrtBCI, &st) - 1] == ub);
}
b_st.site = &db_emlrtRSI;
if (!(Dis_size[0] == loop_ub)) {
if ((Dis_size[0] == 1) || (loop_ub == 1)) {
c_y = NULL;
m17 = emlrtCreateCharArray(2, iv37);
for (idx = 0; idx < 45; idx++) {
cv44[idx] = cv45[idx];
}
emlrtInitCharArrayR2013a(&b_st, 45, m17, cv44);
emlrtAssign(&c_y, m17);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, c_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
d_y = NULL;
m17 = emlrtCreateCharArray(2, iv38);
for (idx = 0; idx < 21; idx++) {
cv46[idx] = cv47[idx];
}
emlrtInitCharArrayR2013a(&b_st, 21, m17, cv46);
emlrtAssign(&d_y, m17);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, d_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((Dis_size[0] == 1) || (loop_ub == 1)) {
ub = 0.0;
for (i13 = 0; i13 < a_size_idx_1; i13++) {
ub += a_data[i13] * b_data[i13];
}
} else {
b_st.site = &je_emlrtRSI;
c_st.site = &ke_emlrtRSI;
if (Dis_size[0] < 1) {
ub = 0.0;
} else {
n_t = (ptrdiff_t)(Dis_size[0]);
incx_t = (ptrdiff_t)(1);
incy_t = (ptrdiff_t)(1);
xix0_t = (double *)(&a_data[0]);
yiy0_t = (double *)(&b_data[0]);
ub = ddot(&n_t, xix0_t, &incx_t, yiy0_t, &incy_t);
}
}
i13 = b->size[0];
emlrtVectorVectorIndexCheckR2012b(i13, 1, 1, loop_ub, &r_emlrtECI, sp);
st.site = &ye_emlrtRSI;
a_size_idx_1 = Dis_size[0];
idx = Dis_size[0];
for (i13 = 0; i13 < idx; i13++) {
a_data[i13] = Dis_data[i13];
}
i13 = b->size[0];
for (idx = 0; idx < loop_ub; idx++) {
b_ii = sind_data[idx];
b_data[idx] = (b0->data[emlrtDynamicBoundsCheckFastR2012b(b_ii, 1, i13,
&y_emlrtBCI, &st) - 1] == 0.0);
}
b_st.site = &db_emlrtRSI;
if (!(Dis_size[0] == loop_ub)) {
if ((Dis_size[0] == 1) || (loop_ub == 1)) {
e_y = NULL;
m17 = emlrtCreateCharArray(2, iv39);
for (idx = 0; idx < 45; idx++) {
cv44[idx] = cv45[idx];
}
emlrtInitCharArrayR2013a(&b_st, 45, m17, cv44);
emlrtAssign(&e_y, m17);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, e_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
f_y = NULL;
m17 = emlrtCreateCharArray(2, iv40);
for (idx = 0; idx < 21; idx++) {
cv46[idx] = cv47[idx];
}
emlrtInitCharArrayR2013a(&b_st, 21, m17, cv46);
emlrtAssign(&f_y, m17);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, f_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((Dis_size[0] == 1) || (loop_ub == 1)) {
ub1 = 0.0;
for (i13 = 0; i13 < a_size_idx_1; i13++) {
ub1 += a_data[i13] * b_data[i13];
}
} else {
b_st.site = &je_emlrtRSI;
c_st.site = &ke_emlrtRSI;
if (Dis_size[0] < 1) {
ub1 = 0.0;
} else {
n_t = (ptrdiff_t)(Dis_size[0]);
incx_t = (ptrdiff_t)(1);
incy_t = (ptrdiff_t)(1);
xix0_t = (double *)(&a_data[0]);
yiy0_t = (double *)(&b_data[0]);
ub1 = ddot(&n_t, xix0_t, &incx_t, yiy0_t, &incy_t);
}
}
i13 = b->size[0];
emlrtVectorVectorIndexCheckR2012b(i13, 1, 1, loop_ub, &q_emlrtECI, sp);
st.site = &af_emlrtRSI;
a_size_idx_1 = Dis_size[0];
idx = Dis_size[0];
for (i13 = 0; i13 < idx; i13++) {
a_data[i13] = Dis_data[i13];
}
i13 = b->size[0];
for (idx = 0; idx < loop_ub; idx++) {
b_ii = sind_data[idx];
b_data[idx] = (b0->data[emlrtDynamicBoundsCheckFastR2012b(b_ii, 1, i13,
&ab_emlrtBCI, &st) - 1] == 1.0);
}
b_st.site = &db_emlrtRSI;
if (!(Dis_size[0] == loop_ub)) {
if ((Dis_size[0] == 1) || (loop_ub == 1)) {
g_y = NULL;
m17 = emlrtCreateCharArray(2, iv41);
for (idx = 0; idx < 45; idx++) {
cv44[idx] = cv45[idx];
}
emlrtInitCharArrayR2013a(&b_st, 45, m17, cv44);
emlrtAssign(&g_y, m17);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, g_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
h_y = NULL;
m17 = emlrtCreateCharArray(2, iv42);
for (idx = 0; idx < 21; idx++) {
cv46[idx] = cv47[idx];
}
emlrtInitCharArrayR2013a(&b_st, 21, m17, cv46);
emlrtAssign(&h_y, m17);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, h_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((Dis_size[0] == 1) || (loop_ub == 1)) {
ub2 = 0.0;
for (i13 = 0; i13 < a_size_idx_1; i13++) {
ub2 += a_data[i13] * b_data[i13];
}
} else {
b_st.site = &je_emlrtRSI;
c_st.site = &ke_emlrtRSI;
if (Dis_size[0] < 1) {
ub2 = 0.0;
} else {
n_t = (ptrdiff_t)(Dis_size[0]);
incx_t = (ptrdiff_t)(1);
incy_t = (ptrdiff_t)(1);
xix0_t = (double *)(&a_data[0]);
yiy0_t = (double *)(&b_data[0]);
ub2 = ddot(&n_t, xix0_t, &incx_t, yiy0_t, &incy_t);
}
}
i13 = b->size[0];
emlrtVectorVectorIndexCheckR2012b(i13, 1, 1, loop_ub, &p_emlrtECI, sp);
st.site = &bf_emlrtRSI;
a_size_idx_1 = Dis_size[0];
idx = Dis_size[0];
for (i13 = 0; i13 < idx; i13++) {
a_data[i13] = Dis_data[i13];
}
i13 = b->size[0];
for (idx = 0; idx < loop_ub; idx++) {
b_ii = sind_data[idx];
b_data[idx] = (b0->data[emlrtDynamicBoundsCheckFastR2012b(b_ii, 1, i13,
&bb_emlrtBCI, &st) - 1] == 2.0);
}
b_st.site = &db_emlrtRSI;
if (!(Dis_size[0] == loop_ub)) {
if ((Dis_size[0] == 1) || (loop_ub == 1)) {
i_y = NULL;
m17 = emlrtCreateCharArray(2, iv43);
for (idx = 0; idx < 45; idx++) {
cv44[idx] = cv45[idx];
}
emlrtInitCharArrayR2013a(&b_st, 45, m17, cv44);
emlrtAssign(&i_y, m17);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, i_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
j_y = NULL;
m17 = emlrtCreateCharArray(2, iv44);
for (idx = 0; idx < 21; idx++) {
cv46[idx] = cv47[idx];
}
emlrtInitCharArrayR2013a(&b_st, 21, m17, cv46);
emlrtAssign(&j_y, m17);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, j_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((Dis_size[0] == 1) || (loop_ub == 1)) {
ub3 = 0.0;
for (i13 = 0; i13 < a_size_idx_1; i13++) {
ub3 += a_data[i13] * b_data[i13];
}
} else {
b_st.site = &je_emlrtRSI;
c_st.site = &ke_emlrtRSI;
if (Dis_size[0] < 1) {
ub3 = 0.0;
} else {
n_t = (ptrdiff_t)(Dis_size[0]);
incx_t = (ptrdiff_t)(1);
incy_t = (ptrdiff_t)(1);
xix0_t = (double *)(&a_data[0]);
yiy0_t = (double *)(&b_data[0]);
ub3 = ddot(&n_t, xix0_t, &incx_t, yiy0_t, &incy_t);
}
}
*f1 = (*f1 + ub) - ((ub1 * muDoubleScalarExp(tau * ub1) + ub2 *
muDoubleScalarExp(tau * ub2)) + ub3 *
muDoubleScalarExp(tau * ub3)) / ((muDoubleScalarExp
(tau * ub1) + muDoubleScalarExp(tau * ub2)) + muDoubleScalarExp(tau *
ub3));
ub = (ub1 * muDoubleScalarExp(tau * ub1) + ub2 * muDoubleScalarExp(tau *
ub2)) + ub3 * muDoubleScalarExp(tau * ub3);
a = (muDoubleScalarExp(tau * ub1) + muDoubleScalarExp(tau * ub2)) +
muDoubleScalarExp(tau * ub3);
*f2 = (*f2 - ((ub1 * ub1 * muDoubleScalarExp(tau * ub1) + ub2 * ub2 *
muDoubleScalarExp(tau * ub2)) + ub3 * ub3 *
muDoubleScalarExp(tau * ub3)) / ((muDoubleScalarExp(tau *
ub1) + muDoubleScalarExp(tau * ub2)) + muDoubleScalarExp(tau *
ub3))) + ub * ub / (a * a);
kk++;
emlrtBreakCheckFastR2012b(emlrtBreakCheckR2012bFlagVar, sp);
}
ii++;
emlrtBreakCheckFastR2012b(emlrtBreakCheckR2012bFlagVar, sp);
}
emxFree_real_T(&y);
emxFree_real_T(&b0);
emlrtHeapReferenceStackLeaveFcnR2012b(sp);
}
/* End of code generation (taufun.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_EM_data.c
/*
* SREM_EM_data.c
*
* Code generation for function 'SREM_EM_data'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
const volatile char_T *emlrtBreakCheckR2012bFlagVar;
emlrtRSInfo l_emlrtRSI = { 20, "eml_int_forloop_overflow_check",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_int_forloop_overflow_check.m"
};
emlrtRSInfo m_emlrtRSI = { 13, "sum",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\sum.m"
};
emlrtRSInfo n_emlrtRSI = { 46, "sumprod",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\private\\sumprod.m"
};
emlrtRSInfo p_emlrtRSI = { 41, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
emlrtRSInfo q_emlrtRSI = { 230, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
emlrtRSInfo cb_emlrtRSI = { 68, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtRSInfo db_emlrtRSI = { 21, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtRSInfo eb_emlrtRSI = { 54, "eml_xgemm",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xgemm.m"
};
emlrtRSInfo pb_emlrtRSI = { 14, "sqrt",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elfun\\sqrt.m"
};
emlrtRSInfo bc_emlrtRSI = { 90, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
emlrtRSInfo cc_emlrtRSI = { 117, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
emlrtRSInfo dc_emlrtRSI = { 120, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
emlrtRSInfo ec_emlrtRSI = { 128, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
emlrtRSInfo fc_emlrtRSI = { 130, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
emlrtRSInfo gc_emlrtRSI = { 8, "eml_xgetrf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\eml_xgetrf.m"
};
emlrtRSInfo hc_emlrtRSI = { 8, "eml_lapack_xgetrf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\internal\\eml_lapack_xgetrf.m"
};
emlrtRSInfo ic_emlrtRSI = { 30, "eml_matlab_zgetrf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgetrf.m"
};
emlrtRSInfo jc_emlrtRSI = { 36, "eml_matlab_zgetrf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgetrf.m"
};
emlrtRSInfo kc_emlrtRSI = { 44, "eml_matlab_zgetrf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgetrf.m"
};
emlrtRSInfo lc_emlrtRSI = { 50, "eml_matlab_zgetrf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgetrf.m"
};
emlrtRSInfo mc_emlrtRSI = { 58, "eml_matlab_zgetrf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgetrf.m"
};
emlrtRSInfo nc_emlrtRSI = { 20, "eml_ixamax",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_ixamax.m"
};
emlrtRSInfo oc_emlrtRSI = { 1, "ixamax",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\ixamax.p"
};
emlrtRSInfo sc_emlrtRSI = { 41, "eml_xgeru",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xgeru.m"
};
emlrtRSInfo tc_emlrtRSI = { 1, "xgeru",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xgeru.p"
};
emlrtRSInfo uc_emlrtRSI = { 1, "xger",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xger.p"
};
emlrtRSInfo wc_emlrtRSI = { 54, "eml_xtrsm",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xtrsm.m"
};
emlrtRSInfo xc_emlrtRSI = { 1, "xtrsm",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xtrsm.p"
};
emlrtRSInfo rd_emlrtRSI = { 1, "xnrm2",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xnrm2.p"
};
emlrtRSInfo yd_emlrtRSI = { 28, "eml_xscal",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xscal.m"
};
emlrtRSInfo ae_emlrtRSI = { 1, "xscal",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xscal.p"
};
emlrtRSInfo ge_emlrtRSI = { 1, "xgemv",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xgemv.p"
};
emlrtRSInfo ie_emlrtRSI = { 1, "xgerc",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xgerc.p"
};
emlrtRSInfo je_emlrtRSI = { 61, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtRSInfo ke_emlrtRSI = { 30, "eml_xdotu",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xdotu.m"
};
emlrtRSInfo le_emlrtRSI = { 1, "xdotu",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xdotu.p"
};
emlrtRSInfo me_emlrtRSI = { 1, "xdot",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xdot.p"
};
emlrtRSInfo ue_emlrtRSI = { 74, "diag",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\diag.m"
};
emlrtMCInfo d_emlrtMCI = { 239, 9, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
emlrtMCInfo g_emlrtMCI = { 99, 13, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtMCInfo h_emlrtMCI = { 98, 23, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtMCInfo i_emlrtMCI = { 104, 13, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtMCInfo j_emlrtMCI = { 103, 23, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtMCInfo k_emlrtMCI = { 14, 5, "rdivide",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\rdivide.m"
};
emlrtMCInfo l_emlrtMCI = { 13, 15, "rdivide",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\rdivide.m"
};
emlrtRTEInfo b_emlrtRTEI = { 30, 1, "combine_vector_elements",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\private\\combine_vector_elements.m"
};
emlrtRTEInfo j_emlrtRTEI = { 33, 6, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
emlrtRSInfo cf_emlrtRSI = { 13, "rdivide",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\rdivide.m"
};
emlrtRSInfo ef_emlrtRSI = { 98, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtRSInfo ff_emlrtRSI = { 103, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtRSInfo gf_emlrtRSI = { 239, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
emlrtRSInfo lf_emlrtRSI = { 14, "rdivide",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\rdivide.m"
};
emlrtRSInfo mf_emlrtRSI = { 99, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
emlrtRSInfo nf_emlrtRSI = { 104, "eml_mtimes_helper",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\eml_mtimes_helper.m"
};
/* End of code generation (SREM_EM_data.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/bSSupdate.h
/*
* bSSupdate.h
*
* Code generation for function 'bSSupdate'
*
*/
#ifndef __BSSUPDATE_H__
#define __BSSUPDATE_H__
/* Include files */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "mwmathutil.h"
#include "tmwtypes.h"
#include "mex.h"
#include "emlrt.h"
#include "blas.h"
#include "rtwtypes.h"
#include "SREM_EM_types.h"
/* Function Declarations */
extern void bSSupdate(const emlrtStack *sp, const emxArray_real_T *Y1, const
emxArray_real_T *Pb, const emxArray_real_T *W1, const
emxArray_real_T *beta, const real_T exbetabar_data[],
const int32_T exbetabar_size[2], real_T q, emxArray_real_T
*beta0, emxArray_real_T *Sigma_s0);
extern void b_dynamic_size_checks(const emlrtStack *sp, const emxArray_real_T *a,
const int32_T b_size[2]);
extern void b_eml_xgemm(int32_T m, int32_T k, const emxArray_real_T *A, int32_T
lda, const real_T B_data[], int32_T ldb, emxArray_real_T *C, int32_T ldc);
#endif
/* End of code generation (bSSupdate.h) */
<file_sep>/subfuns/codegen/mex/SREM_EM/diag.c
/*
* diag.c
*
* Code generation for function 'diag'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "diag.h"
#include "SREM_EM_emxutil.h"
#include "taufun.h"
#include "eml_int_forloop_overflow_check.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRSInfo wb_emlrtRSI = { 90, "diag",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\diag.m"
};
static emlrtMCInfo n_emlrtMCI = { 87, 9, "diag",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\diag.m"
};
static emlrtMCInfo o_emlrtMCI = { 86, 19, "diag",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\diag.m"
};
static emlrtRTEInfo t_emlrtRTEI = { 1, 14, "diag",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\diag.m"
};
static emlrtRSInfo hf_emlrtRSI = { 86, "diag",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\diag.m"
};
static emlrtRSInfo pf_emlrtRSI = { 87, "diag",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\diag.m"
};
/* Function Declarations */
static void calclen(const emxArray_real_T *v, int32_T *dlen, int32_T *firstidx,
int32_T *stride);
/* Function Definitions */
static void calclen(const emxArray_real_T *v, int32_T *dlen, int32_T *firstidx,
int32_T *stride)
{
int32_T m;
int32_T n;
m = v->size[0];
n = v->size[1];
if (0 < v->size[1]) {
*dlen = muIntScalarMin_sint32(m, n);
*firstidx = 1;
*stride = v->size[0] + 1;
} else {
*dlen = 0;
*firstidx = 1;
*stride = 0;
}
}
void b_diag(const emlrtStack *sp, const emxArray_real_T *v, emxArray_real_T *d)
{
int32_T unnamed_idx_0;
int32_T unnamed_idx_1;
int32_T i11;
unnamed_idx_0 = v->size[0];
unnamed_idx_1 = v->size[0];
i11 = d->size[0] * d->size[1];
d->size[0] = unnamed_idx_0;
emxEnsureCapacity(sp, (emxArray__common *)d, i11, (int32_T)sizeof(real_T),
&t_emlrtRTEI);
i11 = d->size[0] * d->size[1];
d->size[1] = unnamed_idx_1;
emxEnsureCapacity(sp, (emxArray__common *)d, i11, (int32_T)sizeof(real_T),
&t_emlrtRTEI);
unnamed_idx_0 *= unnamed_idx_1;
for (i11 = 0; i11 < unnamed_idx_0; i11++) {
d->data[i11] = 0.0;
}
for (unnamed_idx_0 = 0; unnamed_idx_0 + 1 <= v->size[0]; unnamed_idx_0++) {
d->data[unnamed_idx_0 + d->size[0] * unnamed_idx_0] = v->data[unnamed_idx_0];
}
}
void diag(const emlrtStack *sp, const emxArray_real_T *v, real_T d_data[],
int32_T d_size[1])
{
const mxArray *y;
static const int32_T iv13[2] = { 1, 39 };
const mxArray *m8;
char_T cv20[39];
int32_T i;
static const char_T cv21[39] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'd', 'i', 'a', 'g', '_', 'v', 'a', 'r', 's', 'i',
'z', 'e', 'd', 'M', 'a', 't', 'r', 'i', 'x', 'V', 'e', 'c', 't', 'o', 'r' };
int32_T stride;
int32_T dlen;
boolean_T b2;
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = sp;
b_st.tls = sp->tls;
c_st.prev = &st;
c_st.tls = st.tls;
if ((v->size[0] == 1) && (v->size[1] == 1)) {
d_size[0] = 1;
d_data[0] = v->data[0];
} else {
if (!((v->size[0] == 1) || (v->size[1] == 1))) {
} else {
y = NULL;
m8 = emlrtCreateCharArray(2, iv13);
for (i = 0; i < 39; i++) {
cv20[i] = cv21[i];
}
emlrtInitCharArrayR2013a(sp, 39, m8, cv20);
emlrtAssign(&y, m8);
st.site = &hf_emlrtRSI;
b_st.site = &pf_emlrtRSI;
error(&st, b_message(&b_st, y, &n_emlrtMCI), &o_emlrtMCI);
}
calclen(v, &dlen, &i, &stride);
d_size[0] = dlen;
st.site = &wb_emlrtRSI;
if (1 > dlen) {
b2 = false;
} else {
b2 = (dlen > 2147483646);
}
if (b2) {
c_st.site = &l_emlrtRSI;
check_forloop_overflow_error(&c_st);
}
for (i = 0; i + 1 <= dlen; i++) {
d_data[i] = v->data[i * stride];
}
}
}
/* End of code generation (diag.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_MAP.c
/*
* SREM_MAP.c
*
* Code generation for function 'SREM_MAP'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "SREM_MAP.h"
#include "bSSupdate.h"
#include "SREM_EM_emxutil.h"
#include "abs.h"
#include "power.h"
#include "taufun.h"
#include "sum.h"
#include "eml_int_forloop_overflow_check.h"
#include "exp.h"
#include "std.h"
#include "isequal.h"
#include "rdivide.h"
#include "find.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRSInfo o_emlrtRSI = { 47, "combine_vector_elements",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\private\\combine_vector_elements.m"
};
static emlrtRSInfo r_emlrtRSI = { 21, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo s_emlrtRSI = { 25, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo t_emlrtRSI = { 27, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo u_emlrtRSI = { 28, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo v_emlrtRSI = { 30, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo w_emlrtRSI = { 33, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo x_emlrtRSI = { 35, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo y_emlrtRSI = { 36, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo ab_emlrtRSI = { 40, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo bb_emlrtRSI = { 44, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRSInfo fb_emlrtRSI = { 1, "xgemm",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xgemm.p"
};
static emlrtRSInfo gb_emlrtRSI = { 18, "min",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\min.m"
};
static emlrtRSInfo hb_emlrtRSI = { 15, "eml_min_or_max",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_min_or_max.m"
};
static emlrtRSInfo ib_emlrtRSI = { 106, "eml_min_or_max",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_min_or_max.m"
};
static emlrtRSInfo jb_emlrtRSI = { 108, "eml_min_or_max",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_min_or_max.m"
};
static emlrtRSInfo kb_emlrtRSI = { 229, "eml_min_or_max",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_min_or_max.m"
};
static emlrtRSInfo lb_emlrtRSI = { 202, "eml_min_or_max",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_min_or_max.m"
};
static emlrtRSInfo mb_emlrtRSI = { 19, "sumprod",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\private\\sumprod.m"
};
static emlrtRSInfo nb_emlrtRSI = { 38, "sumprod",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\private\\sumprod.m"
};
static emlrtRSInfo qb_emlrtRSI = { 16, "mean",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\mean.m"
};
static emlrtRSInfo rb_emlrtRSI = { 19, "mean",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\mean.m"
};
static emlrtRSInfo sb_emlrtRSI = { 28, "mean",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\mean.m"
};
static emlrtMCInfo m_emlrtMCI = { 28, 19, "assert",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\shared\\coder\\coder\\+coder\\+internal\\assert.m"
};
static emlrtRTEInfo n_emlrtRTEI = { 1, 28, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo fb_emlrtRTEI = { 91, 1, "eml_min_or_max",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_min_or_max.m"
};
static emlrtRTEInfo gb_emlrtRTEI = { 19, 19, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo hb_emlrtRTEI = { 20, 1, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo ib_emlrtRTEI = { 20, 21, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo jb_emlrtRTEI = { 20, 41, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo kb_emlrtRTEI = { 21, 1, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo lb_emlrtRTEI = { 21, 22, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo mb_emlrtRTEI = { 21, 45, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo nb_emlrtRTEI = { 22, 1, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo ob_emlrtRTEI = { 24, 5, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo pb_emlrtRTEI = { 24, 49, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtRTEInfo qb_emlrtRTEI = { 30, 13, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtECInfo u_emlrtECI = { -1, 40, 6, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo cb_emlrtBCI = { -1, -1, 40, 11, "Pb", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo db_emlrtBCI = { -1, -1, 40, 53, "U", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo eb_emlrtBCI = { -1, -1, 40, 31, "U", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo v_emlrtECI = { -1, 34, 28, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtECInfo w_emlrtECI = { -1, 34, 41, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtECInfo x_emlrtECI = { -1, 34, 9, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo fb_emlrtBCI = { -1, -1, 34, 13, "b", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo gb_emlrtBCI = { -1, -1, 33, 33, "U", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo y_emlrtECI = { -1, 32, 9, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo hb_emlrtBCI = { -1, -1, 32, 15, "U", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo ab_emlrtECI = { 2, 32, 19, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo ib_emlrtBCI = { -1, -1, 32, 37, "U1", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo bb_emlrtECI = { -1, 30, 37, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo jb_emlrtBCI = { -1, -1, 30, 45, "U1", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo kb_emlrtBCI = { -1, -1, 32, 26, "U0", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo cb_emlrtECI = { -1, 27, 9, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo lb_emlrtBCI = { -1, -1, 27, 16, "U0", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo db_emlrtECI = { 2, 30, 56, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtECInfo eb_emlrtECI = { 2, 27, 22, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo mb_emlrtBCI = { -1, -1, 28, 43, "W0", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo nb_emlrtBCI = { -1, -1, 27, 78, "W0", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtRTEInfo vb_emlrtRTEI = { 26, 5, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtECInfo fb_emlrtECI = { -1, 25, 12, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo ob_emlrtBCI = { -1, -1, 25, 22, "W0", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo gb_emlrtECI = { 2, 24, 66, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo pb_emlrtBCI = { -1, -1, 24, 93, "DIC", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo hb_emlrtECI = { -1, 24, 20, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtBCInfo qb_emlrtBCI = { -1, -1, 24, 15, "Y", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtECInfo ib_emlrtECI = { -1, 21, 34, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m" };
static emlrtDCInfo d_emlrtDCI = { 19, 39, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 1 };
static emlrtDCInfo e_emlrtDCI = { 19, 39, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 4 };
static emlrtBCInfo rb_emlrtBCI = { -1, -1, 21, 34, "DIC", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo sb_emlrtBCI = { -1, -1, 24, 20, "Ymat", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo tb_emlrtBCI = { -1, -1, 24, 33, "Yii", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtDCInfo f_emlrtDCI = { 24, 33, "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 1 };
static emlrtBCInfo ub_emlrtBCI = { -1, -1, 34, 28, "bmat", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo vb_emlrtBCI = { -1, -1, 34, 41, "b", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo wb_emlrtBCI = { -1, -1, 35, 9, "sum_U_MAP", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo xb_emlrtBCI = { -1, -1, 35, 37, "cri", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo yb_emlrtBCI = { -1, -1, 35, 47, "sum_U_MAP", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtBCInfo ac_emlrtBCI = { -1, -1, 36, 25, "sum_U_MAP", "SREM_MAP",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_MAP.m", 0 };
static emlrtRSInfo df_emlrtRSI = { 28, "assert",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\shared\\coder\\coder\\+coder\\+internal\\assert.m"
};
/* Function Declarations */
static int32_T div_nzp_s32_floor(int32_T numerator, int32_T denominator);
static void dynamic_size_checks(const emlrtStack *sp, const int32_T a_size[2],
const emxArray_real_T *b);
static void eml_xgemm(int32_T n, int32_T k, const real_T A_data[], const
emxArray_real_T *B, int32_T ldb, emxArray_real_T *C);
/* Function Definitions */
static int32_T div_nzp_s32_floor(int32_T numerator, int32_T denominator)
{
int32_T quotient;
uint32_T absNumerator;
uint32_T absDenominator;
boolean_T quotientNeedsNegation;
uint32_T tempAbsQuotient;
if (numerator >= 0) {
absNumerator = (uint32_T)numerator;
} else {
absNumerator = (uint32_T)-numerator;
}
if (denominator >= 0) {
absDenominator = (uint32_T)denominator;
} else {
absDenominator = (uint32_T)-denominator;
}
quotientNeedsNegation = ((numerator < 0) != (denominator < 0));
tempAbsQuotient = absNumerator / absDenominator;
if (quotientNeedsNegation) {
absNumerator %= absDenominator;
if (absNumerator > 0U) {
tempAbsQuotient++;
}
}
if (quotientNeedsNegation) {
quotient = -(int32_T)tempAbsQuotient;
} else {
quotient = (int32_T)tempAbsQuotient;
}
return quotient;
}
static void dynamic_size_checks(const emlrtStack *sp, const int32_T a_size[2],
const emxArray_real_T *b)
{
const mxArray *y;
static const int32_T iv5[2] = { 1, 45 };
const mxArray *m4;
char_T cv6[45];
int32_T i;
static const char_T cv7[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D',
'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p',
'a', 'n', 's', 'i', 'o', 'n' };
const mxArray *b_y;
static const int32_T iv6[2] = { 1, 21 };
char_T cv8[21];
static const char_T cv9[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' };
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = sp;
b_st.tls = sp->tls;
if (!(a_size[1] == b->size[0])) {
if ((a_size[1] == 1) || ((b->size[0] == 1) && (b->size[1] == 1))) {
y = NULL;
m4 = emlrtCreateCharArray(2, iv5);
for (i = 0; i < 45; i++) {
cv6[i] = cv7[i];
}
emlrtInitCharArrayR2013a(sp, 45, m4, cv6);
emlrtAssign(&y, m4);
st.site = &ef_emlrtRSI;
b_st.site = &mf_emlrtRSI;
error(&st, b_message(&b_st, y, &g_emlrtMCI), &h_emlrtMCI);
} else {
b_y = NULL;
m4 = emlrtCreateCharArray(2, iv6);
for (i = 0; i < 21; i++) {
cv8[i] = cv9[i];
}
emlrtInitCharArrayR2013a(sp, 21, m4, cv8);
emlrtAssign(&b_y, m4);
st.site = &ff_emlrtRSI;
b_st.site = &nf_emlrtRSI;
error(&st, b_message(&b_st, b_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
}
static void eml_xgemm(int32_T n, int32_T k, const real_T A_data[], const
emxArray_real_T *B, int32_T ldb, emxArray_real_T *C)
{
real_T alpha1;
real_T beta1;
char_T TRANSB;
char_T TRANSA;
ptrdiff_t m_t;
ptrdiff_t n_t;
ptrdiff_t k_t;
ptrdiff_t lda_t;
ptrdiff_t ldb_t;
ptrdiff_t ldc_t;
double * alpha1_t;
double * Aia0_t;
double * Bib0_t;
double * beta1_t;
double * Cic0_t;
if ((n < 1) || (k < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(1);
n_t = (ptrdiff_t)(n);
k_t = (ptrdiff_t)(k);
lda_t = (ptrdiff_t)(1);
ldb_t = (ptrdiff_t)(ldb);
ldc_t = (ptrdiff_t)(1);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&A_data[0]);
Bib0_t = (double *)(&B->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&C->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
void SREM_MAP(const emlrtStack *sp, emxArray_real_T *b, const emxArray_real_T *Y,
const emxArray_real_T *DIC, const emxArray_real_T *W0, const
emxArray_real_T *beta, const real_T exbetabar_data[], const
int32_T exbetabar_size[2], const emxArray_real_T *Sigma_s, real_T
tau, real_T MAP_iter, emxArray_real_T *Pb, real_T *sum_U)
{
emxArray_real_T *sum_U_MAP;
emxArray_real_T *x;
emxArray_real_T *y;
int32_T i20;
real_T s;
int32_T loop_ub;
int32_T cri_size[1];
real_T cri_data[1200];
emxArray_real_T *U0;
int32_T i;
emxArray_real_T *U1;
emxArray_real_T *U;
emxArray_boolean_T *b_DIC;
emxArray_real_T *indd;
emxArray_int32_T *ii;
emxArray_real_T *nozeroind;
int32_T i21;
int32_T i22;
int32_T sz[2];
emxArray_real_T *Ymat;
emxArray_real_T *bmat;
int32_T b_ii;
emxArray_real_T *Yii;
emxArray_real_T *W;
emxArray_real_T *bindd;
emxArray_real_T *r4;
emxArray_real_T *r5;
emxArray_real_T *b_x;
emxArray_real_T *b_y;
emxArray_real_T *a;
emxArray_real_T *indx;
emxArray_int32_T *iindx;
emxArray_real_T *b_Sigma_s;
emxArray_real_T *r6;
emxArray_real_T *c_Sigma_s;
emxArray_real_T *b_Ymat;
emxArray_real_T *b_bindd;
emxArray_real_T *r7;
emxArray_real_T *b_U0;
emxArray_real_T *b_U1;
emxArray_real_T *c_U0;
emxArray_real_T *b_U;
int32_T n;
int32_T outsz[2];
int32_T c_y[2];
int32_T a_size[2];
real_T a_data[10];
int32_T ll;
boolean_T exitg2;
real_T W0_data[10];
const mxArray *d_y;
static const int32_T iv63[2] = { 1, 45 };
const mxArray *m29;
char_T cv48[45];
static const char_T cv49[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D',
'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p',
'a', 'n', 's', 'i', 'o', 'n' };
const mxArray *e_y;
static const int32_T iv64[2] = { 1, 21 };
char_T cv50[21];
static const char_T cv51[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' };
real_T f_y[3];
real_T beta1;
char_T TRANSB;
char_T TRANSA;
ptrdiff_t m_t;
ptrdiff_t n_t;
ptrdiff_t k_t;
ptrdiff_t lda_t;
ptrdiff_t ldb_t;
ptrdiff_t ldc_t;
double * alpha1_t;
double * Aia0_t;
double * Bib0_t;
double * beta1_t;
double * Cic0_t;
real_T b_sum_U_MAP[3];
int32_T b_iindx[2];
int32_T c_iindx[1];
int32_T d_iindx[2];
int32_T ix;
int32_T iy;
int32_T j;
int32_T ixstart;
int32_T cindx;
int32_T b_a;
boolean_T c_a;
boolean_T exitg4;
boolean_T d_a;
int32_T e_iindx[1];
boolean_T guard1 = false;
boolean_T cond;
const mxArray *g_y;
static const int32_T iv65[2] = { 1, 36 };
char_T cv52[36];
static const char_T cv53[36] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'a', 'u', 't', 'o', 'D', 'i', 'm', 'I', 'n', 'c',
'o', 'm', 'p', 'a', 't', 'i', 'b', 'i', 'l', 'i', 't', 'y' };
int32_T e_a[1];
emxArray_real_T f_a;
const mxArray *h_y;
static const int32_T iv66[2] = { 1, 37 };
char_T cv54[37];
static const char_T cv55[37] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'U', 'n', 's', 'u', 'p', 'p', 'o', 'r', 't', 'e',
'd', 'S', 'p', 'e', 'c', 'i', 'a', 'l', 'E', 'm', 'p', 't', 'y' };
int32_T exitg3;
boolean_T b_guard1 = false;
boolean_T p;
boolean_T exitg1;
const mxArray *i_y;
static const int32_T iv67[2] = { 1, 15 };
char_T cv56[15];
static const char_T cv57[15] = { 'M', 'A', 'T', 'L', 'A', 'B', ':', 'd', 'i',
'm', 'a', 'g', 'r', 'e', 'e' };
int32_T iv68[3];
const mxArray *j_y;
static const int32_T iv69[2] = { 1, 36 };
emxArray_real_T b_cri_data;
const mxArray *k_y;
static const int32_T iv70[2] = { 1, 37 };
emxArray_real_T c_cri_data;
const mxArray *l_y;
static const int32_T iv71[2] = { 1, 37 };
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
emlrtStack d_st;
emlrtStack e_st;
emlrtStack f_st;
emlrtStack g_st;
emlrtStack h_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
d_st.prev = &c_st;
d_st.tls = c_st.tls;
e_st.prev = &st;
e_st.tls = st.tls;
f_st.prev = &b_st;
f_st.tls = b_st.tls;
g_st.prev = &d_st;
g_st.tls = d_st.tls;
h_st.prev = &g_st;
h_st.tls = g_st.tls;
emlrtHeapReferenceStackEnterFcnR2012b(sp);
emxInit_real_T(sp, &sum_U_MAP, 2, &gb_emlrtRTEI, true);
emxInit_real_T(sp, &x, 2, &n_emlrtRTEI, true);
emxInit_real_T(sp, &y, 2, &n_emlrtRTEI, true);
/* % The EM algorithm */
/* ---input--------------------------------------------------------- */
/* b: initial 2D or 3D labels p*n */
/* Y1: image intensity matrix p*m */
/* DIC: dictionary of spatial relationship */
/* subind: subject information m*3 */
/* beta: initial value of beta q*p */
/* betabar: initial value of betabar q*2 */
/* Sigma_s: initial value of variance matrix in epsilon 1*p */
/* tau: initial value of tau in Gibbs distribution 1 */
/* MAP_iter: maximum number of iterations of the MAP algorithm */
/* ---output-------------------------------------------------------- */
/* b0: final 2D or 3D labels */
/* Copyright by Chao Huang, 2015/01/25 */
/* % */
i20 = sum_U_MAP->size[0] * sum_U_MAP->size[1];
sum_U_MAP->size[0] = 1;
s = emlrtNonNegativeCheckFastR2012b(MAP_iter, &e_emlrtDCI, sp);
sum_U_MAP->size[1] = (int32_T)emlrtIntegerCheckFastR2012b(s, &d_emlrtDCI, sp);
emxEnsureCapacity(sp, (emxArray__common *)sum_U_MAP, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
s = emlrtNonNegativeCheckFastR2012b(MAP_iter, &e_emlrtDCI, sp);
loop_ub = (int32_T)emlrtIntegerCheckFastR2012b(s, &d_emlrtDCI, sp);
for (i20 = 0; i20 < loop_ub; i20++) {
sum_U_MAP->data[i20] = 0.0;
}
cri_size[0] = Y->size[1];
loop_ub = Y->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
cri_data[i20] = 0.0;
}
b_emxInit_real_T(sp, &U0, 3, &hb_emlrtRTEI, true);
i = Y->size[0];
i20 = U0->size[0] * U0->size[1] * U0->size[2];
U0->size[0] = i;
U0->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)U0, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = Y->size[1];
i20 = U0->size[0] * U0->size[1] * U0->size[2];
U0->size[2] = i;
emxEnsureCapacity(sp, (emxArray__common *)U0, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = Y->size[0] * 3 * Y->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
U0->data[i20] = 0.0;
}
b_emxInit_real_T(sp, &U1, 3, &ib_emlrtRTEI, true);
i = Y->size[0];
i20 = U1->size[0] * U1->size[1] * U1->size[2];
U1->size[0] = i;
U1->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)U1, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = Y->size[1];
i20 = U1->size[0] * U1->size[1] * U1->size[2];
U1->size[2] = i;
emxEnsureCapacity(sp, (emxArray__common *)U1, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = Y->size[0] * 3 * Y->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
U1->data[i20] = 0.0;
}
b_emxInit_real_T(sp, &U, 3, &jb_emlrtRTEI, true);
i = Y->size[0];
i20 = U->size[0] * U->size[1] * U->size[2];
U->size[0] = i;
U->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)U, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = Y->size[1];
i20 = U->size[0] * U->size[1] * U->size[2];
U->size[2] = i;
emxEnsureCapacity(sp, (emxArray__common *)U, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = Y->size[0] * 3 * Y->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
U->data[i20] = 0.0;
}
i20 = Pb->size[0] * Pb->size[1] * Pb->size[2];
Pb->size[0] = 3;
emxEnsureCapacity(sp, (emxArray__common *)Pb, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = Y->size[1];
i20 = Pb->size[0] * Pb->size[1] * Pb->size[2];
Pb->size[1] = i;
emxEnsureCapacity(sp, (emxArray__common *)Pb, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = Y->size[0];
i20 = Pb->size[0] * Pb->size[1] * Pb->size[2];
Pb->size[2] = i;
emxEnsureCapacity(sp, (emxArray__common *)Pb, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = 3 * Y->size[1] * Y->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
Pb->data[i20] = 0.0;
}
emxInit_boolean_T(sp, &b_DIC, 2, &n_emlrtRTEI, true);
st.site = &r_emlrtRSI;
i20 = b_DIC->size[0] * b_DIC->size[1];
b_DIC->size[0] = DIC->size[0];
b_DIC->size[1] = DIC->size[1];
emxEnsureCapacity(&st, (emxArray__common *)b_DIC, i20, (int32_T)sizeof
(boolean_T), &n_emlrtRTEI);
loop_ub = DIC->size[0] * DIC->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
b_DIC->data[i20] = (DIC->data[i20] != 0.0);
}
c_emxInit_real_T(&st, &indd, 1, &kb_emlrtRTEI, true);
emxInit_int32_T(&st, &ii, 1, &j_emlrtRTEI, true);
b_st.site = &p_emlrtRSI;
b_eml_find(&b_st, b_DIC, ii);
i20 = indd->size[0];
indd->size[0] = ii->size[0];
emxEnsureCapacity(&st, (emxArray__common *)indd, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = ii->size[0];
emxFree_boolean_T(&b_DIC);
for (i20 = 0; i20 < loop_ub; i20++) {
indd->data[i20] = ii->data[i20];
}
c_emxInit_real_T(&st, &nozeroind, 1, &lb_emlrtRTEI, true);
emlrtMatrixMatrixIndexCheckR2012b(*(int32_T (*)[2])DIC->size, 2, *(int32_T (*)
[1])indd->size, 1, &ib_emlrtECI, sp);
i20 = nozeroind->size[0];
nozeroind->size[0] = indd->size[0];
emxEnsureCapacity(sp, (emxArray__common *)nozeroind, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = indd->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
i21 = DIC->size[0] * DIC->size[1];
i22 = (int32_T)indd->data[i20];
nozeroind->data[i20] = DIC->data[emlrtDynamicBoundsCheckFastR2012b(i22, 1,
i21, &rb_emlrtBCI, sp) - 1];
}
for (i20 = 0; i20 < 2; i20++) {
sz[i20] = DIC->size[i20];
}
emxInit_real_T(sp, &Ymat, 2, &mb_emlrtRTEI, true);
i20 = Ymat->size[0] * Ymat->size[1];
Ymat->size[0] = sz[0];
emxEnsureCapacity(sp, (emxArray__common *)Ymat, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i20 = Ymat->size[0] * Ymat->size[1];
Ymat->size[1] = sz[1];
emxEnsureCapacity(sp, (emxArray__common *)Ymat, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = sz[0] * sz[1];
for (i20 = 0; i20 < loop_ub; i20++) {
Ymat->data[i20] = 0.0;
}
for (i20 = 0; i20 < 2; i20++) {
sz[i20] = DIC->size[i20];
}
emxInit_real_T(sp, &bmat, 2, &nb_emlrtRTEI, true);
i20 = bmat->size[0] * bmat->size[1];
bmat->size[0] = sz[0];
emxEnsureCapacity(sp, (emxArray__common *)bmat, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i20 = bmat->size[0] * bmat->size[1];
bmat->size[1] = sz[1];
emxEnsureCapacity(sp, (emxArray__common *)bmat, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = sz[0] * sz[1];
for (i20 = 0; i20 < loop_ub; i20++) {
bmat->data[i20] = 0.0;
}
b_ii = 0;
c_emxInit_real_T(sp, &Yii, 1, &ob_emlrtRTEI, true);
emxInit_real_T(sp, &W, 2, &pb_emlrtRTEI, true);
emxInit_real_T(sp, &bindd, 2, &qb_emlrtRTEI, true);
emxInit_real_T(sp, &r4, 2, &n_emlrtRTEI, true);
emxInit_real_T(sp, &r5, 2, &n_emlrtRTEI, true);
emxInit_real_T(sp, &b_x, 2, &n_emlrtRTEI, true);
emxInit_real_T(sp, &b_y, 2, &n_emlrtRTEI, true);
c_emxInit_real_T(sp, &a, 1, &n_emlrtRTEI, true);
c_emxInit_real_T(sp, &indx, 1, &n_emlrtRTEI, true);
emxInit_int32_T(sp, &iindx, 1, &n_emlrtRTEI, true);
c_emxInit_real_T(sp, &b_Sigma_s, 1, &n_emlrtRTEI, true);
c_emxInit_real_T(sp, &r6, 1, &n_emlrtRTEI, true);
c_emxInit_real_T(sp, &c_Sigma_s, 1, &n_emlrtRTEI, true);
emxInit_real_T(sp, &b_Ymat, 2, &n_emlrtRTEI, true);
emxInit_real_T(sp, &b_bindd, 2, &n_emlrtRTEI, true);
c_emxInit_real_T(sp, &r7, 1, &n_emlrtRTEI, true);
emxInit_real_T(sp, &b_U0, 2, &n_emlrtRTEI, true);
emxInit_real_T(sp, &b_U1, 2, &n_emlrtRTEI, true);
emxInit_real_T(sp, &c_U0, 2, &n_emlrtRTEI, true);
emxInit_real_T(sp, &b_U, 2, &n_emlrtRTEI, true);
while (b_ii <= Y->size[1] - 1) {
loop_ub = Y->size[0];
i20 = Y->size[1];
i21 = 1 + b_ii;
i20 = emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &qb_emlrtBCI, sp);
i21 = Yii->size[0];
Yii->size[0] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)Yii, i21, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
for (i21 = 0; i21 < loop_ub; i21++) {
Yii->data[i21] = Y->data[i21 + Y->size[0] * (i20 - 1)];
}
i20 = ii->size[0];
ii->size[0] = indd->size[0];
emxEnsureCapacity(sp, (emxArray__common *)ii, i20, (int32_T)sizeof(int32_T),
&n_emlrtRTEI);
loop_ub = indd->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
i21 = Ymat->size[0] * Ymat->size[1];
i22 = (int32_T)indd->data[i20];
ii->data[i20] = emlrtDynamicBoundsCheckFastR2012b(i22, 1, i21,
&sb_emlrtBCI, sp);
}
i20 = Y->size[0];
loop_ub = nozeroind->size[0];
for (i21 = 0; i21 < loop_ub; i21++) {
s = nozeroind->data[i21];
i22 = (int32_T)emlrtIntegerCheckFastR2012b(s, &f_emlrtDCI, sp);
emlrtDynamicBoundsCheckFastR2012b(i22, 1, i20, &tb_emlrtBCI, sp);
}
i20 = ii->size[0];
i21 = indd->size[0];
emlrtSizeEqCheck1DFastR2012b(i20, i21, &hb_emlrtECI, sp);
loop_ub = nozeroind->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
Ymat->data[ii->data[i20] - 1] = Yii->data[(int32_T)nozeroind->data[i20] -
1];
}
i20 = DIC->size[0];
emlrtDynamicBoundsCheckFastR2012b(1, 1, i20, &pb_emlrtBCI, sp);
n = DIC->size[1];
i20 = b_y->size[0] * b_y->size[1];
b_y->size[0] = Yii->size[0];
b_y->size[1] = n;
emxEnsureCapacity(sp, (emxArray__common *)b_y, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = Yii->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
for (i21 = 0; i21 < n; i21++) {
b_y->data[i20 + b_y->size[0] * i21] = Yii->data[i20];
}
}
for (i20 = 0; i20 < 2; i20++) {
outsz[i20] = Ymat->size[i20];
}
for (i20 = 0; i20 < 2; i20++) {
c_y[i20] = b_y->size[i20];
}
emlrtSizeEqCheck2DFastR2012b(outsz, c_y, &gb_emlrtECI, sp);
i20 = b_Ymat->size[0] * b_Ymat->size[1];
b_Ymat->size[0] = Ymat->size[0];
b_Ymat->size[1] = Ymat->size[1];
emxEnsureCapacity(sp, (emxArray__common *)b_Ymat, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = Ymat->size[0] * Ymat->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
b_Ymat->data[i20] = Ymat->data[i20] - b_y->data[i20];
}
b_abs(sp, b_Ymat, W);
i20 = W->size[0] * W->size[1];
emxEnsureCapacity(sp, (emxArray__common *)W, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = W->size[0];
n = W->size[1];
loop_ub = i * n;
for (i20 = 0; i20 < loop_ub; i20++) {
W->data[i20] *= -0.5;
}
b_exp(W);
st.site = &s_emlrtRSI;
loop_ub = W0->size[0];
i20 = W0->size[1];
i21 = 1 + b_ii;
i20 = emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &ob_emlrtBCI, &st);
a_size[0] = 1;
a_size[1] = loop_ub;
for (i21 = 0; i21 < loop_ub; i21++) {
a_data[i21] = W0->data[i21 + W0->size[0] * (i20 - 1)];
}
b_st.site = &db_emlrtRSI;
dynamic_size_checks(&b_st, a_size, beta);
if ((loop_ub == 1) || (beta->size[0] == 1)) {
i20 = y->size[0] * y->size[1];
y->size[0] = 1;
y->size[1] = beta->size[1];
emxEnsureCapacity(&st, (emxArray__common *)y, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = beta->size[1];
for (i20 = 0; i20 < i; i20++) {
y->data[y->size[0] * i20] = 0.0;
for (i21 = 0; i21 < loop_ub; i21++) {
y->data[y->size[0] * i20] += a_data[i21] * beta->data[i21 + beta->
size[0] * i20];
}
}
} else {
sz[1] = beta->size[1];
i20 = y->size[0] * y->size[1];
y->size[0] = 1;
emxEnsureCapacity(&st, (emxArray__common *)y, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i20 = y->size[0] * y->size[1];
y->size[1] = sz[1];
emxEnsureCapacity(&st, (emxArray__common *)y, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = sz[1];
for (i20 = 0; i20 < i; i20++) {
y->data[i20] = 0.0;
}
b_st.site = &cb_emlrtRSI;
eml_xgemm(beta->size[1], loop_ub, a_data, beta, loop_ub, y);
}
i20 = a->size[0];
a->size[0] = y->size[1];
emxEnsureCapacity(sp, (emxArray__common *)a, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = y->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
a->data[i20] = y->data[y->size[0] * i20];
}
i20 = Y->size[0];
i21 = a->size[0];
emlrtSizeEqCheck1DFastR2012b(i20, i21, &fb_emlrtECI, sp);
i20 = Yii->size[0];
emxEnsureCapacity(sp, (emxArray__common *)Yii, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = Yii->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
Yii->data[i20] -= a->data[i20];
}
emlrtForLoopVectorCheckR2012b(1.0, 1.0, MAP_iter, mxDOUBLE_CLASS, (int32_T)
MAP_iter, &vb_emlrtRTEI, sp);
ll = 0;
exitg2 = false;
while ((!exitg2) && (ll <= (int32_T)MAP_iter - 1)) {
power(sp, Yii, a);
i20 = r6->size[0];
r6->size[0] = a->size[0];
emxEnsureCapacity(sp, (emxArray__common *)r6, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = a->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
r6->data[i20] = 0.5 * a->data[i20];
}
i20 = c_Sigma_s->size[0];
c_Sigma_s->size[0] = Sigma_s->size[1];
emxEnsureCapacity(sp, (emxArray__common *)c_Sigma_s, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = Sigma_s->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
c_Sigma_s->data[i20] = Sigma_s->data[Sigma_s->size[0] * i20];
}
st.site = &t_emlrtRSI;
rdivide(&st, r6, c_Sigma_s, a);
i20 = b_x->size[0] * b_x->size[1];
b_x->size[0] = a->size[0];
b_x->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)b_x, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = a->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
for (i21 = 0; i21 < 3; i21++) {
b_x->data[i20 + b_x->size[0] * i21] = a->data[i20];
}
}
i20 = b_Sigma_s->size[0];
b_Sigma_s->size[0] = Sigma_s->size[1];
emxEnsureCapacity(sp, (emxArray__common *)b_Sigma_s, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = Sigma_s->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
b_Sigma_s->data[i20] = Sigma_s->data[Sigma_s->size[0] * i20];
}
st.site = &t_emlrtRSI;
rdivide(&st, Yii, b_Sigma_s, a);
i20 = W0->size[1];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &nb_emlrtBCI, sp);
loop_ub = W0->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
W0_data[i20] = W0->data[i20 + W0->size[0] * b_ii];
}
i20 = b_y->size[0] * b_y->size[1];
b_y->size[0] = a->size[0];
b_y->size[1] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)b_y, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
i = a->size[0];
for (i20 = 0; i20 < i; i20++) {
for (i21 = 0; i21 < loop_ub; i21++) {
b_y->data[i20 + b_y->size[0] * i21] = a->data[i20] * W0_data[i21];
}
}
st.site = &t_emlrtRSI;
b_st.site = &db_emlrtRSI;
b_dynamic_size_checks(&b_st, b_y, exbetabar_size);
if ((b_y->size[1] == 1) || (exbetabar_size[0] == 1)) {
i20 = x->size[0] * x->size[1];
x->size[0] = b_y->size[0];
x->size[1] = 3;
emxEnsureCapacity(&st, (emxArray__common *)x, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = b_y->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
for (i21 = 0; i21 < 3; i21++) {
x->data[i20 + x->size[0] * i21] = 0.0;
i = b_y->size[1];
for (i22 = 0; i22 < i; i22++) {
x->data[i20 + x->size[0] * i21] += b_y->data[i20 + b_y->size[0] *
i22] * exbetabar_data[i22 + exbetabar_size[0] * i21];
}
}
}
} else {
sz[0] = b_y->size[0];
i20 = x->size[0] * x->size[1];
x->size[0] = sz[0];
x->size[1] = 3;
emxEnsureCapacity(&st, (emxArray__common *)x, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = sz[0] * 3;
for (i20 = 0; i20 < loop_ub; i20++) {
x->data[i20] = 0.0;
}
b_st.site = &cb_emlrtRSI;
b_eml_xgemm(b_y->size[0], b_y->size[1], b_y, b_y->size[0],
exbetabar_data, b_y->size[1], x, b_y->size[0]);
}
for (i20 = 0; i20 < 2; i20++) {
c_y[i20] = b_x->size[i20];
}
for (i20 = 0; i20 < 2; i20++) {
outsz[i20] = x->size[i20];
}
emlrtSizeEqCheck2DFastR2012b(c_y, outsz, &eb_emlrtECI, sp);
st.site = &u_emlrtRSI;
loop_ub = W0->size[0];
i20 = W0->size[1];
i21 = 1 + b_ii;
i20 = emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &mb_emlrtBCI, &st);
for (i21 = 0; i21 < loop_ub; i21++) {
a_data[i21] = W0->data[i21 + W0->size[0] * (i20 - 1)];
}
b_st.site = &db_emlrtRSI;
if (!(loop_ub == exbetabar_size[0])) {
if (loop_ub == 1) {
d_y = NULL;
m29 = emlrtCreateCharArray(2, iv63);
for (i = 0; i < 45; i++) {
cv48[i] = cv49[i];
}
emlrtInitCharArrayR2013a(&b_st, 45, m29, cv48);
emlrtAssign(&d_y, m29);
c_st.site = &ef_emlrtRSI;
f_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&f_st, d_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
e_y = NULL;
m29 = emlrtCreateCharArray(2, iv64);
for (i = 0; i < 21; i++) {
cv50[i] = cv51[i];
}
emlrtInitCharArrayR2013a(&b_st, 21, m29, cv50);
emlrtAssign(&e_y, m29);
c_st.site = &ff_emlrtRSI;
f_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&f_st, e_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((loop_ub == 1) || (exbetabar_size[0] == 1)) {
for (i20 = 0; i20 < 3; i20++) {
f_y[i20] = 0.0;
for (i21 = 0; i21 < loop_ub; i21++) {
f_y[i20] += a_data[i21] * exbetabar_data[i21 + exbetabar_size[0] *
i20];
}
}
} else {
b_st.site = &cb_emlrtRSI;
c_st.site = &eb_emlrtRSI;
for (i20 = 0; i20 < 3; i20++) {
f_y[i20] = 0.0;
}
if (loop_ub < 1) {
} else {
d_st.site = &fb_emlrtRSI;
s = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
g_st.site = &fb_emlrtRSI;
m_t = (ptrdiff_t)(1);
g_st.site = &fb_emlrtRSI;
n_t = (ptrdiff_t)(3);
g_st.site = &fb_emlrtRSI;
k_t = (ptrdiff_t)(loop_ub);
g_st.site = &fb_emlrtRSI;
lda_t = (ptrdiff_t)(1);
g_st.site = &fb_emlrtRSI;
ldb_t = (ptrdiff_t)(loop_ub);
g_st.site = &fb_emlrtRSI;
ldc_t = (ptrdiff_t)(1);
alpha1_t = (double *)(&s);
Aia0_t = (double *)(&a_data[0]);
Bib0_t = (double *)(&exbetabar_data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&f_y[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t,
Bib0_t, &ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
b_power(f_y, b_sum_U_MAP);
i20 = r7->size[0];
r7->size[0] = Sigma_s->size[1];
emxEnsureCapacity(sp, (emxArray__common *)r7, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = Sigma_s->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
r7->data[i20] = 0.5 / Sigma_s->data[Sigma_s->size[0] * i20];
}
i20 = r4->size[0] * r4->size[1];
r4->size[0] = r7->size[0];
r4->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)r4, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = r7->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
for (i21 = 0; i21 < 3; i21++) {
r4->data[i20 + r4->size[0] * i21] = r7->data[i20] * b_sum_U_MAP[i21];
}
}
for (i20 = 0; i20 < 2; i20++) {
c_y[i20] = b_x->size[i20];
}
for (i20 = 0; i20 < 2; i20++) {
outsz[i20] = r4->size[i20];
}
emlrtSizeEqCheck2DFastR2012b(c_y, outsz, &eb_emlrtECI, sp);
loop_ub = U0->size[0];
i20 = iindx->size[0];
iindx->size[0] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)iindx, i20, (int32_T)sizeof
(int32_T), &n_emlrtRTEI);
for (i20 = 0; i20 < loop_ub; i20++) {
iindx->data[i20] = i20;
}
i20 = U0->size[2];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &lb_emlrtBCI, sp);
b_iindx[0] = iindx->size[0];
b_iindx[1] = 3;
emlrtSubAssignSizeCheckR2012b(b_iindx, 2, *(int32_T (*)[2])b_x->size, 2,
&cb_emlrtECI, sp);
for (i20 = 0; i20 < 3; i20++) {
loop_ub = b_x->size[0];
for (i21 = 0; i21 < loop_ub; i21++) {
U0->data[(iindx->data[i21] + U0->size[0] * i20) + U0->size[0] *
U0->size[1] * b_ii] = (b_x->data[i21 + b_x->size[0] * i20] - x->
data[i21 + x->size[0] * i20]) + r4->data[i21 + r4->size[0] * i20];
}
}
for (i = 0; i < 3; i++) {
i20 = bindd->size[0] * bindd->size[1];
bindd->size[0] = bmat->size[0];
bindd->size[1] = bmat->size[1];
emxEnsureCapacity(sp, (emxArray__common *)bindd, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = bmat->size[0] * bmat->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
bindd->data[i20] = (bmat->data[i20] == 1.0 + (real_T)i);
}
for (i20 = 0; i20 < 2; i20++) {
outsz[i20] = bindd->size[i20];
}
for (i20 = 0; i20 < 2; i20++) {
c_y[i20] = W->size[i20];
}
emlrtSizeEqCheck2DFastR2012b(outsz, c_y, &db_emlrtECI, sp);
loop_ub = U1->size[0];
i20 = iindx->size[0];
iindx->size[0] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)iindx, i20, (int32_T)sizeof
(int32_T), &n_emlrtRTEI);
for (i20 = 0; i20 < loop_ub; i20++) {
iindx->data[i20] = i20;
}
i20 = U1->size[2];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &jb_emlrtBCI, sp);
i20 = b_bindd->size[0] * b_bindd->size[1];
b_bindd->size[0] = bindd->size[0];
b_bindd->size[1] = bindd->size[1];
emxEnsureCapacity(sp, (emxArray__common *)b_bindd, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = bindd->size[0] * bindd->size[1];
for (i20 = 0; i20 < loop_ub; i20++) {
b_bindd->data[i20] = bindd->data[i20] * W->data[i20];
}
st.site = &v_emlrtRSI;
sum(&st, b_bindd, a);
i20 = a->size[0];
emxEnsureCapacity(sp, (emxArray__common *)a, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = a->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
a->data[i20] = -a->data[i20];
}
i20 = a->size[0];
emxEnsureCapacity(sp, (emxArray__common *)a, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = a->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
a->data[i20] *= tau;
}
c_iindx[0] = iindx->size[0];
emlrtSubAssignSizeCheckR2012b(c_iindx, 1, *(int32_T (*)[1])a->size, 1,
&bb_emlrtECI, sp);
loop_ub = a->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
U1->data[(iindx->data[i20] + U1->size[0] * i) + U1->size[0] * U1->
size[1] * b_ii] = a->data[i20];
}
emlrtBreakCheckFastR2012b(emlrtBreakCheckR2012bFlagVar, sp);
}
i20 = U0->size[2];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &kb_emlrtBCI, sp);
i20 = U1->size[2];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &ib_emlrtBCI, sp);
loop_ub = U0->size[0];
i20 = b_U0->size[0] * b_U0->size[1];
b_U0->size[0] = loop_ub;
b_U0->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)b_U0, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
for (i20 = 0; i20 < 3; i20++) {
for (i21 = 0; i21 < loop_ub; i21++) {
b_U0->data[i21 + b_U0->size[0] * i20] = U0->data[(i21 + U0->size[0] *
i20) + U0->size[0] * U0->size[1] * b_ii];
}
}
for (i20 = 0; i20 < 2; i20++) {
outsz[i20] = b_U0->size[i20];
}
loop_ub = U1->size[0];
i20 = b_U1->size[0] * b_U1->size[1];
b_U1->size[0] = loop_ub;
b_U1->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)b_U1, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
for (i20 = 0; i20 < 3; i20++) {
for (i21 = 0; i21 < loop_ub; i21++) {
b_U1->data[i21 + b_U1->size[0] * i20] = U1->data[(i21 + U1->size[0] *
i20) + U1->size[0] * U1->size[1] * b_ii];
}
}
for (i20 = 0; i20 < 2; i20++) {
c_y[i20] = b_U1->size[i20];
}
emlrtSizeEqCheck2DFastR2012b(outsz, c_y, &ab_emlrtECI, sp);
loop_ub = U->size[0];
i20 = iindx->size[0];
iindx->size[0] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)iindx, i20, (int32_T)sizeof
(int32_T), &n_emlrtRTEI);
for (i20 = 0; i20 < loop_ub; i20++) {
iindx->data[i20] = i20;
}
i20 = U->size[2];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &hb_emlrtBCI, sp);
d_iindx[0] = iindx->size[0];
d_iindx[1] = 3;
loop_ub = U0->size[0];
i20 = c_U0->size[0] * c_U0->size[1];
c_U0->size[0] = loop_ub;
c_U0->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)c_U0, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
for (i20 = 0; i20 < 3; i20++) {
for (i21 = 0; i21 < loop_ub; i21++) {
c_U0->data[i21 + c_U0->size[0] * i20] = U0->data[(i21 + U0->size[0] *
i20) + U0->size[0] * U0->size[1] * b_ii];
}
}
for (i20 = 0; i20 < 2; i20++) {
outsz[i20] = c_U0->size[i20];
}
emlrtSubAssignSizeCheckR2012b(d_iindx, 2, outsz, 2, &y_emlrtECI, sp);
loop_ub = U0->size[0] - 1;
for (i20 = 0; i20 < 3; i20++) {
for (i21 = 0; i21 <= loop_ub; i21++) {
U->data[(iindx->data[i21] + U->size[0] * i20) + U->size[0] * U->size[1]
* b_ii] = U0->data[(i21 + U0->size[0] * i20) + U0->size[0] *
U0->size[1] * b_ii] + U1->data[(i21 + U1->size[0] * i20) + U1->size
[0] * U1->size[1] * b_ii];
}
}
st.site = &w_emlrtRSI;
i20 = U->size[2];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &gb_emlrtBCI, &st);
b_st.site = &gb_emlrtRSI;
c_st.site = &hb_emlrtRSI;
loop_ub = U->size[0];
i20 = b_U->size[0] * b_U->size[1];
b_U->size[0] = loop_ub;
b_U->size[1] = 3;
emxEnsureCapacity(&c_st, (emxArray__common *)b_U, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
for (i20 = 0; i20 < 3; i20++) {
for (i21 = 0; i21 < loop_ub; i21++) {
b_U->data[i21 + b_U->size[0] * i20] = U->data[(i21 + U->size[0] * i20)
+ U->size[0] * U->size[1] * b_ii];
}
}
for (i20 = 0; i20 < 2; i20++) {
outsz[i20] = b_U->size[i20];
}
i20 = a->size[0];
a->size[0] = outsz[0];
emxEnsureCapacity(&c_st, (emxArray__common *)a, i20, (int32_T)sizeof
(real_T), &fb_emlrtRTEI);
i20 = iindx->size[0];
iindx->size[0] = outsz[0];
emxEnsureCapacity(&c_st, (emxArray__common *)iindx, i20, (int32_T)sizeof
(int32_T), &n_emlrtRTEI);
loop_ub = outsz[0];
for (i20 = 0; i20 < loop_ub; i20++) {
iindx->data[i20] = 1;
}
i20 = U->size[0];
ix = 0;
iy = -1;
d_st.site = &ib_emlrtRSI;
for (j = 1; j <= i20; j++) {
ix++;
d_st.site = &jb_emlrtRSI;
ixstart = ix;
i = ix + (i20 << 1);
loop_ub = U->size[0];
i21 = b_x->size[0] * b_x->size[1];
b_x->size[0] = loop_ub;
b_x->size[1] = 3;
emxEnsureCapacity(&d_st, (emxArray__common *)b_x, i21, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
for (i21 = 0; i21 < 3; i21++) {
for (i22 = 0; i22 < loop_ub; i22++) {
b_x->data[i22 + b_x->size[0] * i21] = U->data[(i22 + U->size[0] *
i21) + U->size[0] * U->size[1] * b_ii];
}
}
i21 = b_x->size[0];
s = b_x->data[(ix - 1) % b_x->size[0] + b_x->size[0] * div_nzp_s32_floor
(ix - 1, i21)];
n = 1;
cindx = 1;
if (muDoubleScalarIsNaN(s)) {
b_a = ix + i20;
g_st.site = &lb_emlrtRSI;
if (b_a > i) {
c_a = false;
} else {
c_a = (i > MAX_int32_T - i20);
}
if (c_a) {
h_st.site = &l_emlrtRSI;
check_forloop_overflow_error(&h_st);
}
exitg4 = false;
while ((!exitg4) && (b_a <= i)) {
cindx++;
ixstart = b_a;
loop_ub = U->size[0];
i21 = b_x->size[0] * b_x->size[1];
b_x->size[0] = loop_ub;
b_x->size[1] = 3;
emxEnsureCapacity(&d_st, (emxArray__common *)b_x, i21, (int32_T)
sizeof(real_T), &n_emlrtRTEI);
for (i21 = 0; i21 < 3; i21++) {
for (i22 = 0; i22 < loop_ub; i22++) {
b_x->data[i22 + b_x->size[0] * i21] = U->data[(i22 + U->size[0] *
i21) + U->size[0] * U->size[1] * b_ii];
}
}
i21 = b_x->size[0];
if (!muDoubleScalarIsNaN(b_x->data[(b_a - 1) % b_x->size[0] +
b_x->size[0] * div_nzp_s32_floor(b_a - 1, i21)])) {
loop_ub = U->size[0];
i21 = b_x->size[0] * b_x->size[1];
b_x->size[0] = loop_ub;
b_x->size[1] = 3;
emxEnsureCapacity(&d_st, (emxArray__common *)b_x, i21, (int32_T)
sizeof(real_T), &n_emlrtRTEI);
for (i21 = 0; i21 < 3; i21++) {
for (i22 = 0; i22 < loop_ub; i22++) {
b_x->data[i22 + b_x->size[0] * i21] = U->data[(i22 + U->size[0]
* i21) + U->size[0] * U->size[1] * b_ii];
}
}
i21 = b_x->size[0];
s = b_x->data[(b_a - 1) % b_x->size[0] + b_x->size[0] *
div_nzp_s32_floor(b_a - 1, i21)];
n = cindx;
exitg4 = true;
} else {
b_a += i20;
}
}
}
if (ixstart < i) {
b_a = ixstart + i20;
g_st.site = &kb_emlrtRSI;
if (b_a > i) {
d_a = false;
} else {
d_a = (i > MAX_int32_T - i20);
}
if (d_a) {
h_st.site = &l_emlrtRSI;
check_forloop_overflow_error(&h_st);
}
while (b_a <= i) {
cindx++;
loop_ub = U->size[0];
i21 = b_x->size[0] * b_x->size[1];
b_x->size[0] = loop_ub;
b_x->size[1] = 3;
emxEnsureCapacity(&d_st, (emxArray__common *)b_x, i21, (int32_T)
sizeof(real_T), &n_emlrtRTEI);
for (i21 = 0; i21 < 3; i21++) {
for (i22 = 0; i22 < loop_ub; i22++) {
b_x->data[i22 + b_x->size[0] * i21] = U->data[(i22 + U->size[0] *
i21) + U->size[0] * U->size[1] * b_ii];
}
}
i21 = b_x->size[0];
if (b_x->data[(b_a - 1) % b_x->size[0] + b_x->size[0] *
div_nzp_s32_floor(b_a - 1, i21)] < s) {
loop_ub = U->size[0];
i21 = b_x->size[0] * b_x->size[1];
b_x->size[0] = loop_ub;
b_x->size[1] = 3;
emxEnsureCapacity(&d_st, (emxArray__common *)b_x, i21, (int32_T)
sizeof(real_T), &n_emlrtRTEI);
for (i21 = 0; i21 < 3; i21++) {
for (i22 = 0; i22 < loop_ub; i22++) {
b_x->data[i22 + b_x->size[0] * i21] = U->data[(i22 + U->size[0]
* i21) + U->size[0] * U->size[1] * b_ii];
}
}
i21 = b_x->size[0];
s = b_x->data[(b_a - 1) % b_x->size[0] + b_x->size[0] *
div_nzp_s32_floor(b_a - 1, i21)];
n = cindx;
}
b_a += i20;
}
}
iy++;
a->data[iy] = s;
iindx->data[iy] = n;
}
i20 = indx->size[0];
indx->size[0] = iindx->size[0];
emxEnsureCapacity(&b_st, (emxArray__common *)indx, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = iindx->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
indx->data[i20] = iindx->data[i20];
}
loop_ub = b->size[0];
i20 = iindx->size[0];
iindx->size[0] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)iindx, i20, (int32_T)sizeof
(int32_T), &n_emlrtRTEI);
for (i20 = 0; i20 < loop_ub; i20++) {
iindx->data[i20] = i20;
}
i20 = b->size[1];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &fb_emlrtBCI, sp);
e_iindx[0] = iindx->size[0];
emlrtSubAssignSizeCheckR2012b(e_iindx, 1, *(int32_T (*)[1])indx->size, 1,
&x_emlrtECI, sp);
loop_ub = indx->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
b->data[iindx->data[i20] + b->size[0] * b_ii] = indx->data[i20] - 1.0;
}
emlrtMatrixMatrixIndexCheckR2012b(*(int32_T (*)[2])b->size, 2, *(int32_T (*)
[1])indd->size, 1, &w_emlrtECI, sp);
i20 = ii->size[0];
ii->size[0] = indd->size[0];
emxEnsureCapacity(sp, (emxArray__common *)ii, i20, (int32_T)sizeof(int32_T),
&n_emlrtRTEI);
loop_ub = indd->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
i21 = bmat->size[0] * bmat->size[1];
i22 = (int32_T)indd->data[i20];
ii->data[i20] = emlrtDynamicBoundsCheckFastR2012b(i22, 1, i21,
&ub_emlrtBCI, sp);
}
loop_ub = nozeroind->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
i21 = b->size[0] * b->size[1];
i22 = (int32_T)nozeroind->data[i20];
emlrtDynamicBoundsCheckFastR2012b(i22, 1, i21, &vb_emlrtBCI, sp);
}
i20 = ii->size[0];
i21 = indd->size[0];
emlrtSizeEqCheck1DFastR2012b(i20, i21, &v_emlrtECI, sp);
loop_ub = nozeroind->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
bmat->data[ii->data[i20] - 1] = b->data[(int32_T)nozeroind->data[i20] -
1] + 1.0;
}
st.site = &x_emlrtRSI;
b_st.site = &m_emlrtRSI;
n = a->size[0];
guard1 = false;
if (n == 1) {
guard1 = true;
} else {
n = a->size[0];
if (n != 1) {
guard1 = true;
} else {
cond = false;
}
}
if (guard1) {
cond = true;
}
c_st.site = &mb_emlrtRSI;
if (cond) {
} else {
g_y = NULL;
m29 = emlrtCreateCharArray(2, iv65);
for (i = 0; i < 36; i++) {
cv52[i] = cv53[i];
}
emlrtInitCharArrayR2013a(&c_st, 36, m29, cv52);
emlrtAssign(&g_y, m29);
d_st.site = &df_emlrtRSI;
error(&d_st, b_message(&d_st, g_y, &m_emlrtMCI), &m_emlrtMCI);
}
e_a[0] = a->size[0];
f_a = *a;
f_a.size = (int32_T *)&e_a;
f_a.numDimensions = 1;
cond = !isequal(&f_a);
c_st.site = &nb_emlrtRSI;
if (cond) {
} else {
h_y = NULL;
m29 = emlrtCreateCharArray(2, iv66);
for (i = 0; i < 37; i++) {
cv54[i] = cv55[i];
}
emlrtInitCharArrayR2013a(&c_st, 37, m29, cv54);
emlrtAssign(&h_y, m29);
d_st.site = &df_emlrtRSI;
error(&d_st, b_message(&d_st, h_y, &m_emlrtMCI), &m_emlrtMCI);
}
n = a->size[0];
if (n == 0) {
s = 0.0;
} else {
s = a->data[0];
cindx = 2;
do {
exitg3 = 0;
n = a->size[0];
if (cindx <= n) {
s += a->data[cindx - 1];
cindx++;
} else {
exitg3 = 1;
}
} while (exitg3 == 0);
}
i20 = sum_U_MAP->size[1];
sum_U_MAP->data[emlrtDynamicBoundsCheckFastR2012b(ll + 1, 1, i20,
&wb_emlrtBCI, sp) - 1] = s;
i20 = 1 + b_ii;
i21 = sum_U_MAP->size[1];
cri_data[emlrtDynamicBoundsCheckFastR2012b(i20, 1, cri_size[0],
&xb_emlrtBCI, sp) - 1] = sum_U_MAP->
data[emlrtDynamicBoundsCheckFastR2012b(ll + 1, 1, i21, &yb_emlrtBCI, sp)
- 1];
b_guard1 = false;
if (1.0 + (real_T)ll >= 3.0) {
for (i20 = 0; i20 < 3; i20++) {
i21 = sum_U_MAP->size[1];
i22 = (int32_T)((1.0 + (real_T)ll) + (-2.0 + (real_T)i20));
b_sum_U_MAP[i20] = sum_U_MAP->data[emlrtDynamicBoundsCheckFastR2012b
(i22, 1, i21, &ac_emlrtBCI, sp) - 1];
}
st.site = &y_emlrtRSI;
if (b_std(&st, b_sum_U_MAP) < 0.01) {
exitg2 = true;
} else {
b_guard1 = true;
}
} else {
b_guard1 = true;
}
if (b_guard1) {
ll++;
emlrtBreakCheckFastR2012b(emlrtBreakCheckR2012bFlagVar, sp);
}
}
i20 = Pb->size[1];
i21 = b_ii + 1;
emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &cb_emlrtBCI, sp);
loop_ub = Pb->size[2];
i20 = iindx->size[0];
iindx->size[0] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)iindx, i20, (int32_T)sizeof
(int32_T), &n_emlrtRTEI);
for (i20 = 0; i20 < loop_ub; i20++) {
iindx->data[i20] = i20;
}
loop_ub = U->size[0];
i20 = U->size[2];
i21 = 1 + b_ii;
i20 = emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &db_emlrtBCI, sp);
i21 = b_x->size[0] * b_x->size[1];
b_x->size[0] = loop_ub;
b_x->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)b_x, i21, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
for (i21 = 0; i21 < 3; i21++) {
for (i22 = 0; i22 < loop_ub; i22++) {
b_x->data[i22 + b_x->size[0] * i21] = -U->data[(i22 + U->size[0] * i21)
+ U->size[0] * U->size[1] * (i20 - 1)];
}
}
c_exp(b_x);
loop_ub = U->size[0];
i20 = U->size[2];
i21 = 1 + b_ii;
i20 = emlrtDynamicBoundsCheckFastR2012b(i21, 1, i20, &eb_emlrtBCI, sp);
i21 = x->size[0] * x->size[1];
x->size[0] = loop_ub;
x->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)x, i21, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
for (i21 = 0; i21 < 3; i21++) {
for (i22 = 0; i22 < loop_ub; i22++) {
x->data[i22 + x->size[0] * i21] = -U->data[(i22 + U->size[0] * i21) +
U->size[0] * U->size[1] * (i20 - 1)];
}
}
c_exp(x);
st.site = &ab_emlrtRSI;
b_st.site = &m_emlrtRSI;
c_st.site = &n_emlrtRSI;
for (i20 = 0; i20 < 2; i20++) {
sz[i20] = b_x->size[i20];
}
i20 = a->size[0];
a->size[0] = sz[0];
emxEnsureCapacity(&c_st, (emxArray__common *)a, i20, (int32_T)sizeof(real_T),
&b_emlrtRTEI);
if (b_x->size[0] == 0) {
i20 = a->size[0];
a->size[0] = sz[0];
emxEnsureCapacity(&c_st, (emxArray__common *)a, i20, (int32_T)sizeof
(real_T), &n_emlrtRTEI);
loop_ub = sz[0];
for (i20 = 0; i20 < loop_ub; i20++) {
a->data[i20] = 0.0;
}
} else {
i = b_x->size[0];
iy = -1;
ixstart = -1;
d_st.site = &o_emlrtRSI;
for (j = 1; j <= i; j++) {
ixstart++;
ix = ixstart;
s = b_x->data[ixstart];
for (cindx = 0; cindx < 2; cindx++) {
ix += i;
s += b_x->data[ix];
}
iy++;
a->data[iy] = s;
}
}
i20 = b_x->size[0] * b_x->size[1];
b_x->size[0] = a->size[0];
b_x->size[1] = 3;
emxEnsureCapacity(sp, (emxArray__common *)b_x, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = a->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
for (i21 = 0; i21 < 3; i21++) {
b_x->data[i20 + b_x->size[0] * i21] = a->data[i20];
}
}
st.site = &ab_emlrtRSI;
for (i20 = 0; i20 < 2; i20++) {
sz[i20] = x->size[i20];
}
for (i20 = 0; i20 < 2; i20++) {
outsz[i20] = b_x->size[i20];
}
cond = false;
p = true;
cindx = 0;
exitg1 = false;
while ((!exitg1) && (cindx < 2)) {
if (!(sz[cindx] == outsz[cindx])) {
p = false;
exitg1 = true;
} else {
cindx++;
}
}
if (!p) {
} else {
cond = true;
}
if (cond) {
} else {
i_y = NULL;
m29 = emlrtCreateCharArray(2, iv67);
for (i = 0; i < 15; i++) {
cv56[i] = cv57[i];
}
emlrtInitCharArrayR2013a(&st, 15, m29, cv56);
emlrtAssign(&i_y, m29);
b_st.site = &cf_emlrtRSI;
e_st.site = &lf_emlrtRSI;
error(&b_st, b_message(&e_st, i_y, &k_emlrtMCI), &l_emlrtMCI);
}
i20 = r5->size[0] * r5->size[1];
r5->size[0] = 3;
r5->size[1] = x->size[0];
emxEnsureCapacity(sp, (emxArray__common *)r5, i20, (int32_T)sizeof(real_T),
&n_emlrtRTEI);
loop_ub = x->size[0];
for (i20 = 0; i20 < loop_ub; i20++) {
for (i21 = 0; i21 < 3; i21++) {
r5->data[i21 + r5->size[0] * i20] = x->data[i20 + x->size[0] * i21] /
b_x->data[i20 + b_x->size[0] * i21];
}
}
iv68[0] = 3;
iv68[1] = 1;
iv68[2] = iindx->size[0];
emlrtSubAssignSizeCheckR2012b(iv68, 3, *(int32_T (*)[2])r5->size, 2,
&u_emlrtECI, sp);
i = iindx->size[0];
for (i20 = 0; i20 < i; i20++) {
for (i21 = 0; i21 < 3; i21++) {
Pb->data[(i21 + Pb->size[0] * b_ii) + Pb->size[0] * Pb->size[1] *
iindx->data[i20]] = r5->data[i21 + 3 * i20];
}
}
b_ii++;
emlrtBreakCheckFastR2012b(emlrtBreakCheckR2012bFlagVar, sp);
}
emxFree_real_T(&b_U);
emxFree_real_T(&c_U0);
emxFree_real_T(&b_U1);
emxFree_real_T(&b_U0);
emxFree_real_T(&r7);
emxFree_real_T(&b_bindd);
emxFree_real_T(&b_Ymat);
emxFree_real_T(&c_Sigma_s);
emxFree_real_T(&r6);
emxFree_real_T(&b_Sigma_s);
emxFree_int32_T(&iindx);
emxFree_real_T(&indx);
emxFree_int32_T(&ii);
emxFree_real_T(&a);
emxFree_real_T(&b_y);
emxFree_real_T(&b_x);
emxFree_real_T(&r5);
emxFree_real_T(&r4);
emxFree_real_T(&bindd);
emxFree_real_T(&W);
emxFree_real_T(&Yii);
emxFree_real_T(&bmat);
emxFree_real_T(&Ymat);
emxFree_real_T(&nozeroind);
emxFree_real_T(&indd);
emxFree_real_T(&U);
emxFree_real_T(&U1);
emxFree_real_T(&U0);
emxFree_real_T(&sum_U_MAP);
st.site = &bb_emlrtRSI;
if ((cri_size[0] == 1) || (cri_size[0] != 1)) {
cond = true;
} else {
cond = false;
}
b_st.site = &qb_emlrtRSI;
if (cond) {
} else {
j_y = NULL;
m29 = emlrtCreateCharArray(2, iv69);
for (i = 0; i < 36; i++) {
cv52[i] = cv53[i];
}
emlrtInitCharArrayR2013a(&b_st, 36, m29, cv52);
emlrtAssign(&j_y, m29);
c_st.site = &df_emlrtRSI;
error(&c_st, b_message(&c_st, j_y, &m_emlrtMCI), &m_emlrtMCI);
}
b_cri_data.data = (real_T *)&cri_data;
b_cri_data.size = (int32_T *)&cri_size;
b_cri_data.allocatedSize = 1200;
b_cri_data.numDimensions = 1;
b_cri_data.canFreeData = false;
cond = !isequal(&b_cri_data);
b_st.site = &rb_emlrtRSI;
if (cond) {
} else {
k_y = NULL;
m29 = emlrtCreateCharArray(2, iv70);
for (i = 0; i < 37; i++) {
cv54[i] = cv55[i];
}
emlrtInitCharArrayR2013a(&b_st, 37, m29, cv54);
emlrtAssign(&k_y, m29);
c_st.site = &df_emlrtRSI;
error(&c_st, b_message(&c_st, k_y, &m_emlrtMCI), &m_emlrtMCI);
}
c_cri_data.data = (real_T *)&cri_data;
c_cri_data.size = (int32_T *)&cri_size;
c_cri_data.allocatedSize = 1200;
c_cri_data.numDimensions = 1;
c_cri_data.canFreeData = false;
cond = !isequal(&c_cri_data);
b_st.site = &sb_emlrtRSI;
if (cond) {
} else {
l_y = NULL;
m29 = emlrtCreateCharArray(2, iv71);
for (i = 0; i < 37; i++) {
cv54[i] = cv55[i];
}
emlrtInitCharArrayR2013a(&b_st, 37, m29, cv54);
emlrtAssign(&l_y, m29);
c_st.site = &df_emlrtRSI;
error(&c_st, b_message(&c_st, l_y, &m_emlrtMCI), &m_emlrtMCI);
}
if (cri_size[0] == 0) {
s = 0.0;
} else {
s = cri_data[0];
for (cindx = 2; cindx <= cri_size[0]; cindx++) {
s += cri_data[cindx - 1];
}
}
*sum_U = s / (real_T)cri_size[0];
emxFree_real_T(&y);
emxFree_real_T(&x);
emlrtHeapReferenceStackLeaveFcnR2012b(sp);
}
/* End of code generation (SREM_MAP.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/bbarupdate.c
/*
* bbarupdate.c
*
* Code generation for function 'bbarupdate'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "bbarupdate.h"
#include "SREM_EM_emxutil.h"
#include "taufun.h"
#include "mldivide.h"
#include "diag.h"
#include "squeeze.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRSInfo ne_emlrtRSI = { 3, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
static emlrtRSInfo oe_emlrtRSI = { 4, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
static emlrtRSInfo pe_emlrtRSI = { 5, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
static emlrtRSInfo qe_emlrtRSI = { 6, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
static emlrtRSInfo re_emlrtRSI = { 7, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
static emlrtRTEInfo x_emlrtRTEI = { 1, 23, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
static emlrtECInfo m_emlrtECI = { 2, 5, 16, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
static emlrtECInfo n_emlrtECI = { -1, 6, 1, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
static emlrtECInfo o_emlrtECI = { -1, 7, 1, "bbarupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\bbarupdate.m" };
/* Function Definitions */
void bbarupdate(const emlrtStack *sp, const emxArray_real_T *Y1, const
emxArray_real_T *Pb1, const emxArray_real_T *W1, const
emxArray_real_T *beta, const emxArray_real_T *Sigma_s, real_T q,
real_T betabar0_data[], int32_T betabar0_size[2])
{
emxArray_real_T *y;
int32_T i;
int32_T b;
emxArray_real_T *b_Pb1;
int32_T loop_ub;
int32_T i9;
emxArray_real_T *a;
emxArray_real_T *b_b;
uint32_T unnamed_idx_0;
emxArray_real_T *c_b;
const mxArray *b_y;
static const int32_T iv21[2] = { 1, 45 };
const mxArray *m14;
char_T cv35[45];
static const char_T cv36[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D',
'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p',
'a', 'n', 's', 'i', 'o', 'n' };
const mxArray *c_y;
static const int32_T iv22[2] = { 1, 21 };
char_T cv37[21];
static const char_T cv38[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' };
emxArray_real_T *C;
emxArray_real_T *r3;
int32_T b_loop_ub;
int32_T i10;
uint32_T unnamed_idx_1;
real_T alpha1;
real_T beta1;
char_T TRANSB;
char_T TRANSA;
ptrdiff_t m_t;
ptrdiff_t n_t;
ptrdiff_t k_t;
ptrdiff_t lda_t;
ptrdiff_t ldb_t;
ptrdiff_t ldc_t;
double * alpha1_t;
double * Aia0_t;
double * Bib0_t;
double * beta1_t;
double * Cic0_t;
const mxArray *d_y;
static const int32_T iv23[2] = { 1, 45 };
const mxArray *e_y;
static const int32_T iv24[2] = { 1, 21 };
emxArray_real_T *f_y;
emxArray_real_T *c_Pb1;
const mxArray *g_y;
static const int32_T iv25[2] = { 1, 45 };
const mxArray *h_y;
static const int32_T iv26[2] = { 1, 21 };
const mxArray *i_y;
static const int32_T iv27[2] = { 1, 45 };
const mxArray *j_y;
static const int32_T iv28[2] = { 1, 21 };
emxArray_real_T *k_y;
emxArray_real_T *d_b;
const mxArray *l_y;
static const int32_T iv29[2] = { 1, 45 };
const mxArray *m_y;
static const int32_T iv30[2] = { 1, 21 };
int32_T e_b[2];
int32_T b_C[2];
const mxArray *n_y;
static const int32_T iv31[2] = { 1, 45 };
const mxArray *o_y;
static const int32_T iv32[2] = { 1, 21 };
int32_T tmp_data[10];
int32_T tmp_size[1];
real_T b_tmp_data[10];
int32_T iv33[1];
int32_T iv34[1];
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
emlrtStack d_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
d_st.prev = &b_st;
d_st.tls = b_st.tls;
emlrtHeapReferenceStackEnterFcnR2012b(sp);
c_emxInit_real_T(sp, &y, 1, &x_emlrtRTEI, true);
betabar0_size[0] = (int32_T)q;
betabar0_size[1] = 2;
i = (int32_T)q << 1;
for (b = 0; b < i; b++) {
betabar0_data[b] = 0.0;
}
b_emxInit_real_T(sp, &b_Pb1, 3, &x_emlrtRTEI, true);
i = Pb1->size[1];
loop_ub = Pb1->size[2];
b = b_Pb1->size[0] * b_Pb1->size[1] * b_Pb1->size[2];
b_Pb1->size[0] = 1;
b_Pb1->size[1] = i;
b_Pb1->size[2] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)b_Pb1, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
for (b = 0; b < loop_ub; b++) {
for (i9 = 0; i9 < i; i9++) {
b_Pb1->data[b_Pb1->size[0] * i9 + b_Pb1->size[0] * b_Pb1->size[1] * b] =
Pb1->data[(Pb1->size[0] * i9 + Pb1->size[0] * Pb1->size[1] * b) + 1];
}
}
emxInit_real_T(sp, &a, 2, &x_emlrtRTEI, true);
c_emxInit_real_T(sp, &b_b, 1, &x_emlrtRTEI, true);
st.site = &ne_emlrtRSI;
squeeze(&st, b_Pb1, a);
st.site = &ne_emlrtRSI;
b = b_b->size[0];
b_b->size[0] = Sigma_s->size[1];
emxEnsureCapacity(&st, (emxArray__common *)b_b, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = Sigma_s->size[1];
emxFree_real_T(&b_Pb1);
for (b = 0; b < i; b++) {
b_b->data[b] = 1.0 / Sigma_s->data[Sigma_s->size[0] * b];
}
b_st.site = &db_emlrtRSI;
c_dynamic_size_checks(&b_st, a, b_b);
if ((a->size[1] == 1) || (b_b->size[0] == 1)) {
b = y->size[0];
y->size[0] = a->size[0];
emxEnsureCapacity(&st, (emxArray__common *)y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = a->size[0];
for (b = 0; b < i; b++) {
y->data[b] = 0.0;
loop_ub = a->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
y->data[b] += a->data[b + a->size[0] * i9] * b_b->data[i9];
}
}
} else {
unnamed_idx_0 = (uint32_T)a->size[0];
b = y->size[0];
y->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0;
for (b = 0; b < i; b++) {
y->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
d_eml_xgemm(a->size[0], a->size[1], a, a->size[0], b_b, a->size[1], y,
a->size[0]);
}
emxInit_real_T(&st, &c_b, 2, &x_emlrtRTEI, true);
st.site = &ne_emlrtRSI;
b_diag(&st, y, c_b);
st.site = &ne_emlrtRSI;
b = a->size[0] * a->size[1];
a->size[0] = W1->size[0];
a->size[1] = W1->size[1];
emxEnsureCapacity(&st, (emxArray__common *)a, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0] * W1->size[1];
for (b = 0; b < i; b++) {
a->data[b] = W1->data[b];
}
b_st.site = &db_emlrtRSI;
if (!(W1->size[1] == c_b->size[0])) {
if (((W1->size[0] == 1) && (W1->size[1] == 1)) || ((c_b->size[0] == 1) &&
(c_b->size[1] == 1))) {
b_y = NULL;
m14 = emlrtCreateCharArray(2, iv21);
for (i = 0; i < 45; i++) {
cv35[i] = cv36[i];
}
emlrtInitCharArrayR2013a(&b_st, 45, m14, cv35);
emlrtAssign(&b_y, m14);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, b_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
c_y = NULL;
m14 = emlrtCreateCharArray(2, iv22);
for (i = 0; i < 21; i++) {
cv37[i] = cv38[i];
}
emlrtInitCharArrayR2013a(&b_st, 21, m14, cv37);
emlrtAssign(&c_y, m14);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, c_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
emxInit_real_T(&st, &C, 2, &x_emlrtRTEI, true);
emxInit_real_T(&st, &r3, 2, &x_emlrtRTEI, true);
if ((W1->size[1] == 1) || (c_b->size[0] == 1)) {
b = C->size[0] * C->size[1];
C->size[0] = W1->size[0];
C->size[1] = c_b->size[1];
emxEnsureCapacity(&st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0];
for (b = 0; b < i; b++) {
loop_ub = c_b->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
C->data[b + C->size[0] * i9] = 0.0;
b_loop_ub = W1->size[1];
for (i10 = 0; i10 < b_loop_ub; i10++) {
C->data[b + C->size[0] * i9] += W1->data[b + W1->size[0] * i10] *
c_b->data[i10 + c_b->size[0] * i9];
}
}
}
} else {
unnamed_idx_0 = (uint32_T)W1->size[0];
unnamed_idx_1 = (uint32_T)c_b->size[1];
b = r3->size[0] * r3->size[1];
r3->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = r3->size[0] * r3->size[1];
r3->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
r3->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
c_st.site = &eb_emlrtRSI;
b = C->size[0] * C->size[1];
C->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&c_st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = C->size[0] * C->size[1];
C->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&c_st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
C->data[b] = 0.0;
}
if ((W1->size[0] < 1) || (c_b->size[1] < 1) || (W1->size[1] < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(W1->size[0]);
n_t = (ptrdiff_t)(c_b->size[1]);
k_t = (ptrdiff_t)(W1->size[1]);
lda_t = (ptrdiff_t)(W1->size[0]);
ldb_t = (ptrdiff_t)(W1->size[1]);
ldc_t = (ptrdiff_t)(W1->size[0]);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&a->data[0]);
Bib0_t = (double *)(&c_b->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&C->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
st.site = &ne_emlrtRSI;
b = c_b->size[0] * c_b->size[1];
c_b->size[0] = W1->size[1];
c_b->size[1] = W1->size[0];
emxEnsureCapacity(&st, (emxArray__common *)c_b, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0];
for (b = 0; b < i; b++) {
loop_ub = W1->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
c_b->data[i9 + c_b->size[0] * b] = W1->data[b + W1->size[0] * i9];
}
}
b_st.site = &db_emlrtRSI;
if (!(C->size[1] == c_b->size[0])) {
if (((C->size[0] == 1) && (C->size[1] == 1)) || ((c_b->size[0] == 1) &&
(c_b->size[1] == 1))) {
d_y = NULL;
m14 = emlrtCreateCharArray(2, iv23);
for (i = 0; i < 45; i++) {
cv35[i] = cv36[i];
}
emlrtInitCharArrayR2013a(&b_st, 45, m14, cv35);
emlrtAssign(&d_y, m14);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, d_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
e_y = NULL;
m14 = emlrtCreateCharArray(2, iv24);
for (i = 0; i < 21; i++) {
cv37[i] = cv38[i];
}
emlrtInitCharArrayR2013a(&b_st, 21, m14, cv37);
emlrtAssign(&e_y, m14);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, e_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
emxInit_real_T(&st, &f_y, 2, &x_emlrtRTEI, true);
if ((C->size[1] == 1) || (c_b->size[0] == 1)) {
b = f_y->size[0] * f_y->size[1];
f_y->size[0] = C->size[0];
f_y->size[1] = c_b->size[1];
emxEnsureCapacity(&st, (emxArray__common *)f_y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = C->size[0];
for (b = 0; b < i; b++) {
loop_ub = c_b->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
f_y->data[b + f_y->size[0] * i9] = 0.0;
b_loop_ub = C->size[1];
for (i10 = 0; i10 < b_loop_ub; i10++) {
f_y->data[b + f_y->size[0] * i9] += C->data[b + C->size[0] * i10] *
c_b->data[i10 + c_b->size[0] * i9];
}
}
}
} else {
unnamed_idx_0 = (uint32_T)C->size[0];
unnamed_idx_1 = (uint32_T)c_b->size[1];
b = r3->size[0] * r3->size[1];
r3->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = r3->size[0] * r3->size[1];
r3->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
r3->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
c_st.site = &eb_emlrtRSI;
b = f_y->size[0] * f_y->size[1];
f_y->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&c_st, (emxArray__common *)f_y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = f_y->size[0] * f_y->size[1];
f_y->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&c_st, (emxArray__common *)f_y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
f_y->data[b] = 0.0;
}
if ((C->size[0] < 1) || (c_b->size[1] < 1) || (C->size[1] < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(C->size[0]);
n_t = (ptrdiff_t)(c_b->size[1]);
k_t = (ptrdiff_t)(C->size[1]);
lda_t = (ptrdiff_t)(C->size[0]);
ldb_t = (ptrdiff_t)(C->size[1]);
ldc_t = (ptrdiff_t)(C->size[0]);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&C->data[0]);
Bib0_t = (double *)(&c_b->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&f_y->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
b_emxInit_real_T(&st, &c_Pb1, 3, &x_emlrtRTEI, true);
i = Pb1->size[1];
loop_ub = Pb1->size[2];
b = c_Pb1->size[0] * c_Pb1->size[1] * c_Pb1->size[2];
c_Pb1->size[0] = 1;
c_Pb1->size[1] = i;
c_Pb1->size[2] = loop_ub;
emxEnsureCapacity(sp, (emxArray__common *)c_Pb1, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
for (b = 0; b < loop_ub; b++) {
for (i9 = 0; i9 < i; i9++) {
c_Pb1->data[c_Pb1->size[0] * i9 + c_Pb1->size[0] * c_Pb1->size[1] * b] =
Pb1->data[(Pb1->size[0] * i9 + Pb1->size[0] * Pb1->size[1] * b) + 2];
}
}
st.site = &oe_emlrtRSI;
squeeze(&st, c_Pb1, a);
st.site = &oe_emlrtRSI;
b = b_b->size[0];
b_b->size[0] = Sigma_s->size[1];
emxEnsureCapacity(&st, (emxArray__common *)b_b, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = Sigma_s->size[1];
emxFree_real_T(&c_Pb1);
for (b = 0; b < i; b++) {
b_b->data[b] = 1.0 / Sigma_s->data[Sigma_s->size[0] * b];
}
b_st.site = &db_emlrtRSI;
c_dynamic_size_checks(&b_st, a, b_b);
if ((a->size[1] == 1) || (b_b->size[0] == 1)) {
b = y->size[0];
y->size[0] = a->size[0];
emxEnsureCapacity(&st, (emxArray__common *)y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = a->size[0];
for (b = 0; b < i; b++) {
y->data[b] = 0.0;
loop_ub = a->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
y->data[b] += a->data[b + a->size[0] * i9] * b_b->data[i9];
}
}
} else {
unnamed_idx_0 = (uint32_T)a->size[0];
b = y->size[0];
y->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0;
for (b = 0; b < i; b++) {
y->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
d_eml_xgemm(a->size[0], a->size[1], a, a->size[0], b_b, a->size[1], y,
a->size[0]);
}
st.site = &oe_emlrtRSI;
b_diag(&st, y, c_b);
st.site = &oe_emlrtRSI;
b = a->size[0] * a->size[1];
a->size[0] = W1->size[0];
a->size[1] = W1->size[1];
emxEnsureCapacity(&st, (emxArray__common *)a, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0] * W1->size[1];
for (b = 0; b < i; b++) {
a->data[b] = W1->data[b];
}
b_st.site = &db_emlrtRSI;
if (!(W1->size[1] == c_b->size[0])) {
if (((W1->size[0] == 1) && (W1->size[1] == 1)) || ((c_b->size[0] == 1) &&
(c_b->size[1] == 1))) {
g_y = NULL;
m14 = emlrtCreateCharArray(2, iv25);
for (i = 0; i < 45; i++) {
cv35[i] = cv36[i];
}
emlrtInitCharArrayR2013a(&b_st, 45, m14, cv35);
emlrtAssign(&g_y, m14);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, g_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
h_y = NULL;
m14 = emlrtCreateCharArray(2, iv26);
for (i = 0; i < 21; i++) {
cv37[i] = cv38[i];
}
emlrtInitCharArrayR2013a(&b_st, 21, m14, cv37);
emlrtAssign(&h_y, m14);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, h_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((W1->size[1] == 1) || (c_b->size[0] == 1)) {
b = C->size[0] * C->size[1];
C->size[0] = W1->size[0];
C->size[1] = c_b->size[1];
emxEnsureCapacity(&st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0];
for (b = 0; b < i; b++) {
loop_ub = c_b->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
C->data[b + C->size[0] * i9] = 0.0;
b_loop_ub = W1->size[1];
for (i10 = 0; i10 < b_loop_ub; i10++) {
C->data[b + C->size[0] * i9] += W1->data[b + W1->size[0] * i10] *
c_b->data[i10 + c_b->size[0] * i9];
}
}
}
} else {
unnamed_idx_0 = (uint32_T)W1->size[0];
unnamed_idx_1 = (uint32_T)c_b->size[1];
b = r3->size[0] * r3->size[1];
r3->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = r3->size[0] * r3->size[1];
r3->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
r3->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
c_st.site = &eb_emlrtRSI;
b = C->size[0] * C->size[1];
C->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&c_st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = C->size[0] * C->size[1];
C->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&c_st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
C->data[b] = 0.0;
}
if ((W1->size[0] < 1) || (c_b->size[1] < 1) || (W1->size[1] < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(W1->size[0]);
n_t = (ptrdiff_t)(c_b->size[1]);
k_t = (ptrdiff_t)(W1->size[1]);
lda_t = (ptrdiff_t)(W1->size[0]);
ldb_t = (ptrdiff_t)(W1->size[1]);
ldc_t = (ptrdiff_t)(W1->size[0]);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&a->data[0]);
Bib0_t = (double *)(&c_b->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&C->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
st.site = &oe_emlrtRSI;
b = c_b->size[0] * c_b->size[1];
c_b->size[0] = W1->size[1];
c_b->size[1] = W1->size[0];
emxEnsureCapacity(&st, (emxArray__common *)c_b, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0];
for (b = 0; b < i; b++) {
loop_ub = W1->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
c_b->data[i9 + c_b->size[0] * b] = W1->data[b + W1->size[0] * i9];
}
}
b_st.site = &db_emlrtRSI;
if (!(C->size[1] == c_b->size[0])) {
if (((C->size[0] == 1) && (C->size[1] == 1)) || ((c_b->size[0] == 1) &&
(c_b->size[1] == 1))) {
i_y = NULL;
m14 = emlrtCreateCharArray(2, iv27);
for (i = 0; i < 45; i++) {
cv35[i] = cv36[i];
}
emlrtInitCharArrayR2013a(&b_st, 45, m14, cv35);
emlrtAssign(&i_y, m14);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, i_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
j_y = NULL;
m14 = emlrtCreateCharArray(2, iv28);
for (i = 0; i < 21; i++) {
cv37[i] = cv38[i];
}
emlrtInitCharArrayR2013a(&b_st, 21, m14, cv37);
emlrtAssign(&j_y, m14);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, j_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
emxInit_real_T(&st, &k_y, 2, &x_emlrtRTEI, true);
if ((C->size[1] == 1) || (c_b->size[0] == 1)) {
b = k_y->size[0] * k_y->size[1];
k_y->size[0] = C->size[0];
k_y->size[1] = c_b->size[1];
emxEnsureCapacity(&st, (emxArray__common *)k_y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = C->size[0];
for (b = 0; b < i; b++) {
loop_ub = c_b->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
k_y->data[b + k_y->size[0] * i9] = 0.0;
b_loop_ub = C->size[1];
for (i10 = 0; i10 < b_loop_ub; i10++) {
k_y->data[b + k_y->size[0] * i9] += C->data[b + C->size[0] * i10] *
c_b->data[i10 + c_b->size[0] * i9];
}
}
}
} else {
unnamed_idx_0 = (uint32_T)C->size[0];
unnamed_idx_1 = (uint32_T)c_b->size[1];
b = r3->size[0] * r3->size[1];
r3->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = r3->size[0] * r3->size[1];
r3->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
r3->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
c_st.site = &eb_emlrtRSI;
b = k_y->size[0] * k_y->size[1];
k_y->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&c_st, (emxArray__common *)k_y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = k_y->size[0] * k_y->size[1];
k_y->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&c_st, (emxArray__common *)k_y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
k_y->data[b] = 0.0;
}
if ((C->size[0] < 1) || (c_b->size[1] < 1) || (C->size[1] < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(C->size[0]);
n_t = (ptrdiff_t)(c_b->size[1]);
k_t = (ptrdiff_t)(C->size[1]);
lda_t = (ptrdiff_t)(C->size[0]);
ldb_t = (ptrdiff_t)(C->size[1]);
ldc_t = (ptrdiff_t)(C->size[0]);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&C->data[0]);
Bib0_t = (double *)(&c_b->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&k_y->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
emxInit_real_T(&st, &d_b, 2, &x_emlrtRTEI, true);
b = d_b->size[0] * d_b->size[1];
d_b->size[0] = Y1->size[1];
d_b->size[1] = Y1->size[0];
emxEnsureCapacity(sp, (emxArray__common *)d_b, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = Y1->size[0];
for (b = 0; b < i; b++) {
loop_ub = Y1->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
d_b->data[i9 + d_b->size[0] * b] = Y1->data[b + Y1->size[0] * i9];
}
}
st.site = &pe_emlrtRSI;
b = a->size[0] * a->size[1];
a->size[0] = W1->size[1];
a->size[1] = W1->size[0];
emxEnsureCapacity(&st, (emxArray__common *)a, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0];
for (b = 0; b < i; b++) {
loop_ub = W1->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
a->data[i9 + a->size[0] * b] = W1->data[b + W1->size[0] * i9];
}
}
b = c_b->size[0] * c_b->size[1];
c_b->size[0] = beta->size[0];
c_b->size[1] = beta->size[1];
emxEnsureCapacity(&st, (emxArray__common *)c_b, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = beta->size[0] * beta->size[1];
for (b = 0; b < i; b++) {
c_b->data[b] = beta->data[b];
}
b_st.site = &db_emlrtRSI;
if (!(a->size[1] == beta->size[0])) {
if (((a->size[0] == 1) && (a->size[1] == 1)) || ((beta->size[0] == 1) &&
(beta->size[1] == 1))) {
l_y = NULL;
m14 = emlrtCreateCharArray(2, iv29);
for (i = 0; i < 45; i++) {
cv35[i] = cv36[i];
}
emlrtInitCharArrayR2013a(&b_st, 45, m14, cv35);
emlrtAssign(&l_y, m14);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, l_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
m_y = NULL;
m14 = emlrtCreateCharArray(2, iv30);
for (i = 0; i < 21; i++) {
cv37[i] = cv38[i];
}
emlrtInitCharArrayR2013a(&b_st, 21, m14, cv37);
emlrtAssign(&m_y, m14);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, m_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((a->size[1] == 1) || (beta->size[0] == 1)) {
b = C->size[0] * C->size[1];
C->size[0] = a->size[0];
C->size[1] = beta->size[1];
emxEnsureCapacity(&st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = a->size[0];
for (b = 0; b < i; b++) {
loop_ub = beta->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
C->data[b + C->size[0] * i9] = 0.0;
b_loop_ub = a->size[1];
for (i10 = 0; i10 < b_loop_ub; i10++) {
C->data[b + C->size[0] * i9] += a->data[b + a->size[0] * i10] *
beta->data[i10 + beta->size[0] * i9];
}
}
}
} else {
unnamed_idx_0 = (uint32_T)a->size[0];
unnamed_idx_1 = (uint32_T)beta->size[1];
b = r3->size[0] * r3->size[1];
r3->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = r3->size[0] * r3->size[1];
r3->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
r3->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
c_st.site = &eb_emlrtRSI;
b = C->size[0] * C->size[1];
C->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&c_st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = C->size[0] * C->size[1];
C->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&c_st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
C->data[b] = 0.0;
}
if ((a->size[0] < 1) || (beta->size[1] < 1) || (a->size[1] < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(a->size[0]);
n_t = (ptrdiff_t)(beta->size[1]);
k_t = (ptrdiff_t)(a->size[1]);
lda_t = (ptrdiff_t)(a->size[0]);
ldb_t = (ptrdiff_t)(a->size[1]);
ldc_t = (ptrdiff_t)(a->size[0]);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&a->data[0]);
Bib0_t = (double *)(&c_b->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&C->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
emxFree_real_T(&c_b);
for (b = 0; b < 2; b++) {
e_b[b] = d_b->size[b];
}
for (b = 0; b < 2; b++) {
b_C[b] = C->size[b];
}
emlrtSizeEqCheck2DFastR2012b(e_b, b_C, &m_emlrtECI, sp);
st.site = &pe_emlrtRSI;
b = a->size[0] * a->size[1];
a->size[0] = W1->size[0];
a->size[1] = W1->size[1];
emxEnsureCapacity(&st, (emxArray__common *)a, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0] * W1->size[1];
for (b = 0; b < i; b++) {
a->data[b] = W1->data[b];
}
b = d_b->size[0] * d_b->size[1];
emxEnsureCapacity(&st, (emxArray__common *)d_b, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = d_b->size[0];
b = d_b->size[1];
i *= b;
for (b = 0; b < i; b++) {
d_b->data[b] -= C->data[b];
}
b_st.site = &db_emlrtRSI;
if (!(W1->size[1] == d_b->size[0])) {
if (((W1->size[0] == 1) && (W1->size[1] == 1)) || ((d_b->size[0] == 1) &&
(d_b->size[1] == 1))) {
n_y = NULL;
m14 = emlrtCreateCharArray(2, iv31);
for (i = 0; i < 45; i++) {
cv35[i] = cv36[i];
}
emlrtInitCharArrayR2013a(&b_st, 45, m14, cv35);
emlrtAssign(&n_y, m14);
c_st.site = &ef_emlrtRSI;
d_st.site = &mf_emlrtRSI;
error(&c_st, b_message(&d_st, n_y, &g_emlrtMCI), &h_emlrtMCI);
} else {
o_y = NULL;
m14 = emlrtCreateCharArray(2, iv32);
for (i = 0; i < 21; i++) {
cv37[i] = cv38[i];
}
emlrtInitCharArrayR2013a(&b_st, 21, m14, cv37);
emlrtAssign(&o_y, m14);
c_st.site = &ff_emlrtRSI;
d_st.site = &nf_emlrtRSI;
error(&c_st, b_message(&d_st, o_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
if ((W1->size[1] == 1) || (d_b->size[0] == 1)) {
b = C->size[0] * C->size[1];
C->size[0] = W1->size[0];
C->size[1] = d_b->size[1];
emxEnsureCapacity(&st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = W1->size[0];
for (b = 0; b < i; b++) {
loop_ub = d_b->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
C->data[b + C->size[0] * i9] = 0.0;
b_loop_ub = W1->size[1];
for (i10 = 0; i10 < b_loop_ub; i10++) {
C->data[b + C->size[0] * i9] += W1->data[b + W1->size[0] * i10] *
d_b->data[i10 + d_b->size[0] * i9];
}
}
}
} else {
unnamed_idx_0 = (uint32_T)W1->size[0];
unnamed_idx_1 = (uint32_T)d_b->size[1];
b = r3->size[0] * r3->size[1];
r3->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = r3->size[0] * r3->size[1];
r3->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&st, (emxArray__common *)r3, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
r3->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
c_st.site = &eb_emlrtRSI;
b = C->size[0] * C->size[1];
C->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&c_st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
b = C->size[0] * C->size[1];
C->size[1] = (int32_T)unnamed_idx_1;
emxEnsureCapacity(&c_st, (emxArray__common *)C, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0 * (int32_T)unnamed_idx_1;
for (b = 0; b < i; b++) {
C->data[b] = 0.0;
}
if ((W1->size[0] < 1) || (d_b->size[1] < 1) || (W1->size[1] < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(W1->size[0]);
n_t = (ptrdiff_t)(d_b->size[1]);
k_t = (ptrdiff_t)(W1->size[1]);
lda_t = (ptrdiff_t)(W1->size[0]);
ldb_t = (ptrdiff_t)(W1->size[1]);
ldc_t = (ptrdiff_t)(W1->size[0]);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&a->data[0]);
Bib0_t = (double *)(&d_b->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&C->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
emxFree_real_T(&r3);
emxFree_real_T(&d_b);
emxFree_real_T(&a);
st.site = &pe_emlrtRSI;
b = b_b->size[0];
b_b->size[0] = Sigma_s->size[1];
emxEnsureCapacity(&st, (emxArray__common *)b_b, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = Sigma_s->size[1];
for (b = 0; b < i; b++) {
b_b->data[b] = Sigma_s->data[Sigma_s->size[0] * b];
}
b_st.site = &db_emlrtRSI;
c_dynamic_size_checks(&b_st, C, b_b);
if ((C->size[1] == 1) || (b_b->size[0] == 1)) {
b = y->size[0];
y->size[0] = C->size[0];
emxEnsureCapacity(&st, (emxArray__common *)y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = C->size[0];
for (b = 0; b < i; b++) {
y->data[b] = 0.0;
loop_ub = C->size[1];
for (i9 = 0; i9 < loop_ub; i9++) {
y->data[b] += C->data[b + C->size[0] * i9] * b_b->data[i9];
}
}
} else {
unnamed_idx_0 = (uint32_T)C->size[0];
b = y->size[0];
y->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity(&st, (emxArray__common *)y, b, (int32_T)sizeof(real_T),
&x_emlrtRTEI);
i = (int32_T)unnamed_idx_0;
for (b = 0; b < i; b++) {
y->data[b] = 0.0;
}
b_st.site = &cb_emlrtRSI;
d_eml_xgemm(C->size[0], C->size[1], C, C->size[0], b_b, C->size[1], y,
C->size[0]);
}
emxFree_real_T(&b_b);
emxFree_real_T(&C);
i = (int32_T)q;
for (b = 0; b < i; b++) {
tmp_data[b] = b;
}
st.site = &qe_emlrtRSI;
b_mldivide(&st, f_y->data, f_y->size, y->data, y->size, b_tmp_data, tmp_size);
iv33[0] = (int32_T)q;
emlrtSubAssignSizeCheckR2012b(iv33, 1, tmp_size, 1, &n_emlrtECI, sp);
i = tmp_size[0];
emxFree_real_T(&f_y);
for (b = 0; b < i; b++) {
betabar0_data[tmp_data[b]] = b_tmp_data[b];
}
i = (int32_T)q;
for (b = 0; b < i; b++) {
tmp_data[b] = b;
}
st.site = &re_emlrtRSI;
b_mldivide(&st, k_y->data, k_y->size, y->data, y->size, b_tmp_data, tmp_size);
iv34[0] = (int32_T)q;
emlrtSubAssignSizeCheckR2012b(iv34, 1, tmp_size, 1, &o_emlrtECI, sp);
i = tmp_size[0];
emxFree_real_T(&k_y);
for (b = 0; b < i; b++) {
betabar0_data[tmp_data[b] + (int32_T)q] = b_tmp_data[b];
}
emxFree_real_T(&y);
emlrtHeapReferenceStackLeaveFcnR2012b(sp);
}
void c_dynamic_size_checks(const emlrtStack *sp, const emxArray_real_T *a, const
emxArray_real_T *b)
{
const mxArray *y;
static const int32_T iv19[2] = { 1, 45 };
const mxArray *m13;
char_T cv31[45];
int32_T i;
static const char_T cv32[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D',
'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p',
'a', 'n', 's', 'i', 'o', 'n' };
const mxArray *b_y;
static const int32_T iv20[2] = { 1, 21 };
char_T cv33[21];
static const char_T cv34[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' };
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = sp;
b_st.tls = sp->tls;
if (!(a->size[1] == b->size[0])) {
if (((a->size[0] == 1) && (a->size[1] == 1)) || (b->size[0] == 1)) {
y = NULL;
m13 = emlrtCreateCharArray(2, iv19);
for (i = 0; i < 45; i++) {
cv31[i] = cv32[i];
}
emlrtInitCharArrayR2013a(sp, 45, m13, cv31);
emlrtAssign(&y, m13);
st.site = &ef_emlrtRSI;
b_st.site = &mf_emlrtRSI;
error(&st, b_message(&b_st, y, &g_emlrtMCI), &h_emlrtMCI);
} else {
b_y = NULL;
m13 = emlrtCreateCharArray(2, iv20);
for (i = 0; i < 21; i++) {
cv33[i] = cv34[i];
}
emlrtInitCharArrayR2013a(sp, 21, m13, cv33);
emlrtAssign(&b_y, m13);
st.site = &ff_emlrtRSI;
b_st.site = &nf_emlrtRSI;
error(&st, b_message(&b_st, b_y, &i_emlrtMCI), &j_emlrtMCI);
}
}
}
void d_eml_xgemm(int32_T m, int32_T k, const emxArray_real_T *A, int32_T lda,
const emxArray_real_T *B, int32_T ldb, emxArray_real_T *C,
int32_T ldc)
{
real_T alpha1;
real_T beta1;
char_T TRANSB;
char_T TRANSA;
ptrdiff_t m_t;
ptrdiff_t n_t;
ptrdiff_t k_t;
ptrdiff_t lda_t;
ptrdiff_t ldb_t;
ptrdiff_t ldc_t;
double * alpha1_t;
double * Aia0_t;
double * Bib0_t;
double * beta1_t;
double * Cic0_t;
if ((m < 1) || (k < 1)) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSB = 'N';
TRANSA = 'N';
m_t = (ptrdiff_t)(m);
n_t = (ptrdiff_t)(1);
k_t = (ptrdiff_t)(k);
lda_t = (ptrdiff_t)(lda);
ldb_t = (ptrdiff_t)(ldb);
ldc_t = (ptrdiff_t)(ldc);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&A->data[0]);
Bib0_t = (double *)(&B->data[0]);
beta1_t = (double *)(&beta1);
Cic0_t = (double *)(&C->data[0]);
dgemm(&TRANSA, &TRANSB, &m_t, &n_t, &k_t, alpha1_t, Aia0_t, &lda_t, Bib0_t,
&ldb_t, beta1_t, Cic0_t, &ldc_t);
}
}
/* End of code generation (bbarupdate.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/power.c
/*
* power.c
*
* Code generation for function 'power'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "power.h"
#include "SREM_EM_emxutil.h"
/* Variable Definitions */
static emlrtRTEInfo p_emlrtRTEI = { 1, 1, "scalexpAlloc",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\scalexpAlloc.p"
};
/* Function Declarations */
static void eml_scalexp_alloc(const emlrtStack *sp, const emxArray_real_T
*varargin_1, emxArray_real_T *z);
/* Function Definitions */
static void eml_scalexp_alloc(const emlrtStack *sp, const emxArray_real_T
*varargin_1, emxArray_real_T *z)
{
int32_T unnamed_idx_0;
int32_T i5;
unnamed_idx_0 = varargin_1->size[0];
i5 = z->size[0];
z->size[0] = unnamed_idx_0;
emxEnsureCapacity(sp, (emxArray__common *)z, i5, (int32_T)sizeof(real_T),
&p_emlrtRTEI);
}
void b_power(const real_T a[3], real_T y[3])
{
int32_T k;
for (k = 0; k < 3; k++) {
y[k] = a[k] * a[k];
}
}
void power(const emlrtStack *sp, const emxArray_real_T *a, emxArray_real_T *y)
{
int32_T i4;
int32_T k;
eml_scalexp_alloc(sp, a, y);
i4 = y->size[0];
for (k = 0; k < i4; k++) {
y->data[k] = a->data[k] * a->data[k];
}
}
/* End of code generation (power.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/eml_int_forloop_overflow_check.c
/*
* eml_int_forloop_overflow_check.c
*
* Code generation for function 'eml_int_forloop_overflow_check'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "eml_int_forloop_overflow_check.h"
#include "taufun.h"
#include "SREM_EM_mexutil.h"
/* Variable Definitions */
static emlrtMCInfo b_emlrtMCI = { 87, 9, "eml_int_forloop_overflow_check",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_int_forloop_overflow_check.m"
};
static emlrtMCInfo c_emlrtMCI = { 86, 15, "eml_int_forloop_overflow_check",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_int_forloop_overflow_check.m"
};
static emlrtRSInfo jf_emlrtRSI = { 86, "eml_int_forloop_overflow_check",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_int_forloop_overflow_check.m"
};
static emlrtRSInfo sf_emlrtRSI = { 87, "eml_int_forloop_overflow_check",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_int_forloop_overflow_check.m"
};
/* Function Declarations */
static const mxArray *message(const emlrtStack *sp, const mxArray *b, const
mxArray *c, emlrtMCInfo *location);
/* Function Definitions */
static const mxArray *message(const emlrtStack *sp, const mxArray *b, const
mxArray *c, emlrtMCInfo *location)
{
const mxArray *pArrays[2];
const mxArray *m24;
pArrays[0] = b;
pArrays[1] = c;
return emlrtCallMATLABR2012b(sp, 1, &m24, 2, pArrays, "message", true,
location);
}
void check_forloop_overflow_error(const emlrtStack *sp)
{
const mxArray *y;
static const int32_T iv1[2] = { 1, 34 };
const mxArray *m1;
char_T cv0[34];
int32_T i;
static const char_T cv1[34] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'i', 'n', 't', '_', 'f', 'o', 'r', 'l', 'o', 'o',
'p', '_', 'o', 'v', 'e', 'r', 'f', 'l', 'o', 'w' };
const mxArray *b_y;
static const int32_T iv2[2] = { 1, 5 };
char_T cv2[5];
static const char_T cv3[5] = { 'i', 'n', 't', '3', '2' };
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = sp;
b_st.tls = sp->tls;
y = NULL;
m1 = emlrtCreateCharArray(2, iv1);
for (i = 0; i < 34; i++) {
cv0[i] = cv1[i];
}
emlrtInitCharArrayR2013a(sp, 34, m1, cv0);
emlrtAssign(&y, m1);
b_y = NULL;
m1 = emlrtCreateCharArray(2, iv2);
for (i = 0; i < 5; i++) {
cv2[i] = cv3[i];
}
emlrtInitCharArrayR2013a(sp, 5, m1, cv2);
emlrtAssign(&b_y, m1);
st.site = &jf_emlrtRSI;
b_st.site = &sf_emlrtRSI;
error(&st, message(&b_st, y, b_y, &b_emlrtMCI), &c_emlrtMCI);
}
/* End of code generation (eml_int_forloop_overflow_check.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/eml_warning.c
/*
* eml_warning.c
*
* Code generation for function 'eml_warning'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "eml_warning.h"
#include "taufun.h"
#include "SREM_EM_mexutil.h"
/* Variable Definitions */
static emlrtMCInfo q_emlrtMCI = { 16, 13, "eml_warning",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_warning.m"
};
static emlrtMCInfo r_emlrtMCI = { 16, 5, "eml_warning",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_warning.m"
};
static emlrtRSInfo of_emlrtRSI = { 16, "eml_warning",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_warning.m"
};
/* Function Declarations */
static const mxArray *c_message(const emlrtStack *sp, const mxArray *b, const
mxArray *c, const mxArray *d, emlrtMCInfo *location);
static void warning(const emlrtStack *sp, const mxArray *b, emlrtMCInfo
*location);
/* Function Definitions */
static const mxArray *c_message(const emlrtStack *sp, const mxArray *b, const
mxArray *c, const mxArray *d, emlrtMCInfo *location)
{
const mxArray *pArrays[3];
const mxArray *m28;
pArrays[0] = b;
pArrays[1] = c;
pArrays[2] = d;
return emlrtCallMATLABR2012b(sp, 1, &m28, 3, pArrays, "message", true,
location);
}
static void warning(const emlrtStack *sp, const mxArray *b, emlrtMCInfo
*location)
{
const mxArray *pArray;
pArray = b;
emlrtCallMATLABR2012b(sp, 0, NULL, 1, &pArray, "warning", true, location);
}
void b_eml_warning(const emlrtStack *sp, real_T varargin_2, const char_T
varargin_3[14])
{
const mxArray *y;
static const int32_T iv17[2] = { 1, 32 };
const mxArray *m12;
char_T cv29[32];
int32_T i;
static const char_T cv30[32] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'r', 'a', 'n', 'k', 'D', 'e', 'f', 'i', 'c', 'i', 'e',
'n', 't', 'M', 'a', 't', 'r', 'i', 'x' };
const mxArray *b_y;
static const int32_T iv18[2] = { 1, 14 };
char_T b_varargin_3[14];
emlrtStack st;
st.prev = sp;
st.tls = sp->tls;
y = NULL;
m12 = emlrtCreateCharArray(2, iv17);
for (i = 0; i < 32; i++) {
cv29[i] = cv30[i];
}
emlrtInitCharArrayR2013a(sp, 32, m12, cv29);
emlrtAssign(&y, m12);
b_y = NULL;
m12 = emlrtCreateCharArray(2, iv18);
for (i = 0; i < 14; i++) {
b_varargin_3[i] = varargin_3[i];
}
emlrtInitCharArrayR2013a(sp, 14, m12, b_varargin_3);
emlrtAssign(&b_y, m12);
st.site = &of_emlrtRSI;
warning(&st, c_message(&st, y, emlrt_marshallOut(varargin_2), b_y, &q_emlrtMCI),
&r_emlrtMCI);
}
void eml_warning(const emlrtStack *sp)
{
const mxArray *y;
static const int32_T iv15[2] = { 1, 27 };
const mxArray *m10;
char_T cv24[27];
int32_T i;
static const char_T cv25[27] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 's', 'i', 'n', 'g', 'u', 'l', 'a', 'r', 'M', 'a', 't',
'r', 'i', 'x' };
emlrtStack st;
st.prev = sp;
st.tls = sp->tls;
y = NULL;
m10 = emlrtCreateCharArray(2, iv15);
for (i = 0; i < 27; i++) {
cv24[i] = cv25[i];
}
emlrtInitCharArrayR2013a(sp, 27, m10, cv24);
emlrtAssign(&y, m10);
st.site = &of_emlrtRSI;
warning(&st, b_message(&st, y, &q_emlrtMCI), &r_emlrtMCI);
}
/* End of code generation (eml_warning.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_MAP.h
/*
* SREM_MAP.h
*
* Code generation for function 'SREM_MAP'
*
*/
#ifndef __SREM_MAP_H__
#define __SREM_MAP_H__
/* Include files */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "mwmathutil.h"
#include "tmwtypes.h"
#include "mex.h"
#include "emlrt.h"
#include "blas.h"
#include "rtwtypes.h"
#include "SREM_EM_types.h"
/* Function Declarations */
extern void SREM_MAP(const emlrtStack *sp, emxArray_real_T *b, const
emxArray_real_T *Y, const emxArray_real_T *DIC, const
emxArray_real_T *W0, const emxArray_real_T *beta, const
real_T exbetabar_data[], const int32_T exbetabar_size[2],
const emxArray_real_T *Sigma_s, real_T tau, real_T MAP_iter,
emxArray_real_T *Pb, real_T *sum_U);
#endif
/* End of code generation (SREM_MAP.h) */
<file_sep>/subfuns/codegen/mex/SREM_EM/mldivide.c
/*
* mldivide.c
*
* Code generation for function 'mldivide'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "mldivide.h"
#include "taufun.h"
#include "eml_warning.h"
#include "colon.h"
#include "eml_int_forloop_overflow_check.h"
#include "sqrt.h"
#include "SREM_EM_emxutil.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRSInfo xb_emlrtRSI = { 1, "mldivide",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\mldivide.p"
};
static emlrtRSInfo yb_emlrtRSI = { 42, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
static emlrtRSInfo ac_emlrtRSI = { 92, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
static emlrtRSInfo pc_emlrtRSI = { 26, "eml_xswap",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xswap.m"
};
static emlrtRSInfo qc_emlrtRSI = { 1, "xswap",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+blas\\xswap.p"
};
static emlrtRSInfo rc_emlrtRSI = { 1, "xswap",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\coder\\coder\\+coder\\+internal\\+refblas\\xswap.p"
};
static emlrtRSInfo vc_emlrtRSI = { 76, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
static emlrtRSInfo yc_emlrtRSI = { 29, "eml_qrsolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_qrsolve.m"
};
static emlrtRSInfo ad_emlrtRSI = { 38, "eml_qrsolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_qrsolve.m"
};
static emlrtRSInfo bd_emlrtRSI = { 37, "eml_qrsolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_qrsolve.m"
};
static emlrtRSInfo cd_emlrtRSI = { 8, "eml_xgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\eml_xgeqp3.m"
};
static emlrtRSInfo dd_emlrtRSI = { 8, "eml_lapack_xgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\internal\\eml_lapack_xgeqp3.m"
};
static emlrtRSInfo ed_emlrtRSI = { 25, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo fd_emlrtRSI = { 31, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo gd_emlrtRSI = { 32, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo hd_emlrtRSI = { 37, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo id_emlrtRSI = { 47, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo jd_emlrtRSI = { 51, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo kd_emlrtRSI = { 64, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo ld_emlrtRSI = { 66, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo md_emlrtRSI = { 74, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo nd_emlrtRSI = { 79, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo od_emlrtRSI = { 93, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo pd_emlrtRSI = { 100, "eml_matlab_zgeqp3",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zgeqp3.m"
};
static emlrtRSInfo qd_emlrtRSI = { 19, "eml_xnrm2",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xnrm2.m"
};
static emlrtRSInfo sd_emlrtRSI = { 20, "eml_matlab_zlarfg",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarfg.m"
};
static emlrtRSInfo td_emlrtRSI = { 41, "eml_matlab_zlarfg",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarfg.m"
};
static emlrtRSInfo ud_emlrtRSI = { 53, "eml_matlab_zlarfg",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarfg.m"
};
static emlrtRSInfo vd_emlrtRSI = { 68, "eml_matlab_zlarfg",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarfg.m"
};
static emlrtRSInfo wd_emlrtRSI = { 71, "eml_matlab_zlarfg",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarfg.m"
};
static emlrtRSInfo xd_emlrtRSI = { 81, "eml_matlab_zlarfg",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarfg.m"
};
static emlrtRSInfo be_emlrtRSI = { 75, "eml_matlab_zlarf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarf.m"
};
static emlrtRSInfo ce_emlrtRSI = { 68, "eml_matlab_zlarf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarf.m"
};
static emlrtRSInfo de_emlrtRSI = { 50, "eml_matlab_zlarf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarf.m"
};
static emlrtRSInfo ee_emlrtRSI = { 103, "eml_matlab_zlarf",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\lapack\\matlab\\eml_matlab_zlarf.m"
};
static emlrtRSInfo fe_emlrtRSI = { 52, "eml_xgemv",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xgemv.m"
};
static emlrtRSInfo he_emlrtRSI = { 41, "eml_xgerc",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\blas\\eml_xgerc.m"
};
static emlrtMCInfo p_emlrtMCI = { 1, 1, "mldivide",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\mldivide.p"
};
static emlrtMCInfo s_emlrtMCI = { 29, 23, "eml_flt2str",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_flt2str.m"
};
static emlrtMCInfo t_emlrtMCI = { 29, 15, "eml_flt2str",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_flt2str.m"
};
static emlrtRTEInfo u_emlrtRTEI = { 1, 2, "mldivide",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\mldivide.p"
};
static emlrtRTEInfo v_emlrtRTEI = { 1, 19, "eml_lusolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_lusolve.m"
};
static emlrtRTEInfo w_emlrtRTEI = { 1, 24, "eml_qrsolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_qrsolve.m"
};
static emlrtRTEInfo tb_emlrtRTEI = { 106, 5, "eml_qrsolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_qrsolve.m"
};
static emlrtRTEInfo ub_emlrtRTEI = { 99, 5, "eml_qrsolve",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_qrsolve.m"
};
static emlrtRSInfo rf_emlrtRSI = { 29, "eml_flt2str",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_flt2str.m"
};
/* Function Declarations */
static void b_eml_lusolve(const emlrtStack *sp, const real_T A_data[], const
int32_T A_size[2], real_T B_data[]);
static void b_eml_qrsolve(const emlrtStack *sp, const real_T A_data[], const
int32_T A_size[2], real_T B_data[], real_T Y_data[], int32_T Y_size[1]);
static real_T b_eml_xnrm2(int32_T n, const real_T x_data[], int32_T ix0);
static void b_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, char_T y[14]);
static const mxArray *b_sprintf(const emlrtStack *sp, const mxArray *b, const
mxArray *c, const mxArray *d, emlrtMCInfo *location);
static const mxArray *c_sprintf(const emlrtStack *sp, const mxArray *b, const
mxArray *c, emlrtMCInfo *location);
static int32_T eml_ixamax(int32_T n, const real_T x_data[], int32_T ix0);
static void eml_lusolve(const emlrtStack *sp, const real_T A_data[], const
int32_T A_size[2], const emxArray_real_T *B, emxArray_real_T *X);
static void eml_matlab_zlarf(const emlrtStack *sp, int32_T m, int32_T n, int32_T
iv0, real_T tau, real_T C_data[], int32_T ic0, int32_T ldc, real_T work_data[]);
static void eml_qrsolve(const emlrtStack *sp, const real_T A_data[], const
int32_T A_size[2], emxArray_real_T *B, emxArray_real_T *Y);
static real_T eml_xnrm2(int32_T n, const real_T x_data[], int32_T ix0);
static void eml_xscal(int32_T n, real_T a, real_T x_data[], int32_T ix0);
static void eml_xswap(const emlrtStack *sp, int32_T n, real_T x_data[], int32_T
ix0, int32_T iy0);
static void emlrt_marshallIn(const emlrtStack *sp, const mxArray *d_sprintf,
const char_T *identifier, char_T y[14]);
static void q_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, char_T ret[14]);
static void warn_singular(const emlrtStack *sp);
/* Function Definitions */
static void b_eml_lusolve(const emlrtStack *sp, const real_T A_data[], const
int32_T A_size[2], real_T B_data[])
{
int32_T n;
int32_T iy;
int32_T k;
real_T b_A_data[100];
int32_T ipiv_size[2];
int32_T ipiv_data[10];
int32_T info;
int32_T b;
int32_T j;
int32_T mmj;
int32_T c;
ptrdiff_t n_t;
ptrdiff_t incx_t;
double * xix0_t;
int32_T ix;
real_T temp;
ptrdiff_t m_t;
ptrdiff_t incy_t;
ptrdiff_t lda_t;
double * alpha1_t;
double * Aia0_t;
double * Aiy0_t;
char_T DIAGA;
char_T TRANSA;
char_T UPLO;
char_T SIDE;
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
st.site = &yb_emlrtRSI;
b_st.prev = &st;
b_st.tls = st.tls;
n = A_size[1];
iy = A_size[0] * A_size[1];
for (k = 0; k < iy; k++) {
b_A_data[k] = A_data[k];
}
eml_signed_integer_colon(muIntScalarMin_sint32(A_size[1], A_size[1]),
ipiv_data, ipiv_size);
info = 0;
if (A_size[1] < 1) {
} else {
iy = A_size[1] - 1;
b = muIntScalarMin_sint32(iy, A_size[1]);
for (j = 1; j <= b; j++) {
mmj = n - j;
c = (j - 1) * (n + 1);
if (mmj + 1 < 1) {
iy = -1;
} else {
n_t = (ptrdiff_t)(mmj + 1);
incx_t = (ptrdiff_t)(1);
xix0_t = (double *)(&b_A_data[c]);
incx_t = idamax(&n_t, xix0_t, &incx_t);
iy = (int32_T)incx_t - 1;
}
if (b_A_data[c + iy] != 0.0) {
if (iy != 0) {
ipiv_data[j - 1] = j + iy;
ix = j - 1;
iy = (j + iy) - 1;
for (k = 1; k <= n; k++) {
temp = b_A_data[ix];
b_A_data[ix] = b_A_data[iy];
b_A_data[iy] = temp;
ix += n;
iy += n;
}
}
iy = (c + mmj) + 1;
for (k = c + 1; k + 1 <= iy; k++) {
b_A_data[k] /= b_A_data[c];
}
} else {
info = j;
}
iy = n - j;
if ((mmj < 1) || (iy < 1)) {
} else {
temp = -1.0;
m_t = (ptrdiff_t)(mmj);
n_t = (ptrdiff_t)(iy);
incx_t = (ptrdiff_t)(1);
incy_t = (ptrdiff_t)(n);
lda_t = (ptrdiff_t)(n);
alpha1_t = (double *)(&temp);
Aia0_t = (double *)(&b_A_data[(c + n) + 1]);
xix0_t = (double *)(&b_A_data[c + 1]);
Aiy0_t = (double *)(&b_A_data[c + n]);
dger(&m_t, &n_t, alpha1_t, xix0_t, &incx_t, Aiy0_t, &incy_t, Aia0_t,
&lda_t);
}
}
if ((info == 0) && (!(b_A_data[(A_size[1] + A_size[0] * (A_size[1] - 1)) - 1]
!= 0.0))) {
info = A_size[1];
}
}
if (info > 0) {
b_st.site = &ac_emlrtRSI;
warn_singular(&b_st);
}
for (iy = 0; iy + 1 < n; iy++) {
if (ipiv_data[iy] != iy + 1) {
temp = B_data[iy];
B_data[iy] = B_data[ipiv_data[iy] - 1];
B_data[ipiv_data[iy] - 1] = temp;
}
}
if (A_size[1] < 1) {
} else {
temp = 1.0;
DIAGA = 'U';
TRANSA = 'N';
UPLO = 'L';
SIDE = 'L';
m_t = (ptrdiff_t)(A_size[1]);
n_t = (ptrdiff_t)(1);
lda_t = (ptrdiff_t)(A_size[1]);
incx_t = (ptrdiff_t)(A_size[1]);
Aia0_t = (double *)(&b_A_data[0]);
xix0_t = (double *)(&B_data[0]);
alpha1_t = (double *)(&temp);
dtrsm(&SIDE, &UPLO, &TRANSA, &DIAGA, &m_t, &n_t, alpha1_t, Aia0_t, &lda_t,
xix0_t, &incx_t);
}
if (A_size[1] < 1) {
} else {
temp = 1.0;
DIAGA = 'N';
TRANSA = 'N';
UPLO = 'U';
SIDE = 'L';
m_t = (ptrdiff_t)(A_size[1]);
n_t = (ptrdiff_t)(1);
lda_t = (ptrdiff_t)(A_size[1]);
incx_t = (ptrdiff_t)(A_size[1]);
Aia0_t = (double *)(&b_A_data[0]);
xix0_t = (double *)(&B_data[0]);
alpha1_t = (double *)(&temp);
dtrsm(&SIDE, &UPLO, &TRANSA, &DIAGA, &m_t, &n_t, alpha1_t, Aia0_t, &lda_t,
xix0_t, &incx_t);
}
}
static void b_eml_qrsolve(const emlrtStack *sp, const real_T A_data[], const
int32_T A_size[2], real_T B_data[], real_T Y_data[], int32_T Y_size[1])
{
int32_T m;
int32_T mn;
int32_T A_size_idx_0;
int32_T k;
int32_T itemp;
real_T b_A_data[100];
int32_T b_m;
int32_T n;
int32_T b_mn;
real_T tau_data[10];
int32_T jpvt_size[2];
int32_T jpvt_data[10];
real_T work_data[10];
real_T TOL3Z;
real_T vn1_data[10];
real_T vn2_data[10];
int32_T knt;
int32_T i;
int32_T i_i;
int32_T nmi;
int32_T mmi;
real_T atmp;
real_T d1;
real_T xnorm;
real_T beta1;
boolean_T b6;
ptrdiff_t n_t;
ptrdiff_t incx_t;
double * xix0_t;
boolean_T exitg1;
const mxArray *y;
static const int32_T iv36[2] = { 1, 8 };
const mxArray *m16;
char_T cv41[8];
static const char_T cv42[8] = { '%', '%', '%', 'd', '.', '%', 'd', 'e' };
char_T cv43[14];
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
emlrtStack d_st;
emlrtStack e_st;
emlrtStack f_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
d_st.prev = &c_st;
d_st.tls = c_st.tls;
e_st.prev = &d_st;
e_st.tls = d_st.tls;
f_st.prev = &e_st;
f_st.tls = e_st.tls;
m = A_size[0] - 2;
mn = (int32_T)muDoubleScalarMin(A_size[0], A_size[1]);
st.site = &yc_emlrtRSI;
b_st.site = &cd_emlrtRSI;
c_st.site = &dd_emlrtRSI;
A_size_idx_0 = A_size[0];
k = A_size[0] * A_size[1];
for (itemp = 0; itemp < k; itemp++) {
b_A_data[itemp] = A_data[itemp];
}
b_m = A_size[0];
n = A_size[1];
b_mn = muIntScalarMin_sint32(A_size[0], A_size[1]);
eml_signed_integer_colon(A_size[1], jpvt_data, jpvt_size);
if ((A_size[0] == 0) || (A_size[1] == 0)) {
} else {
k = (int8_T)A_size[1];
for (itemp = 0; itemp < k; itemp++) {
work_data[itemp] = 0.0;
}
TOL3Z = 2.2204460492503131E-16;
d_st.site = &ed_emlrtRSI;
b_sqrt(&d_st, &TOL3Z);
k = 1;
d_st.site = &fd_emlrtRSI;
for (knt = 0; knt + 1 <= n; knt++) {
d_st.site = &gd_emlrtRSI;
vn1_data[knt] = eml_xnrm2(b_m, A_data, k);
vn2_data[knt] = vn1_data[knt];
k += b_m;
}
d_st.site = &hd_emlrtRSI;
for (i = 1; i <= b_mn; i++) {
i_i = (i + (i - 1) * b_m) - 1;
nmi = n - i;
mmi = b_m - i;
d_st.site = &id_emlrtRSI;
k = eml_ixamax(1 + nmi, vn1_data, i);
k = (i + k) - 2;
if (k + 1 != i) {
d_st.site = &jd_emlrtRSI;
eml_xswap(&d_st, b_m, b_A_data, 1 + b_m * k, 1 + b_m * (i - 1));
itemp = jpvt_data[k];
jpvt_data[k] = jpvt_data[i - 1];
jpvt_data[i - 1] = itemp;
vn1_data[k] = vn1_data[i - 1];
vn2_data[k] = vn2_data[i - 1];
}
if (i < b_m) {
d_st.site = &kd_emlrtRSI;
atmp = b_A_data[i_i];
d1 = 0.0;
if (1 + mmi <= 0) {
} else {
e_st.site = &sd_emlrtRSI;
xnorm = b_eml_xnrm2(mmi, b_A_data, i_i + 2);
if (xnorm != 0.0) {
beta1 = muDoubleScalarHypot(b_A_data[i_i], xnorm);
if (b_A_data[i_i] >= 0.0) {
beta1 = -beta1;
}
if (muDoubleScalarAbs(beta1) < 1.0020841800044864E-292) {
knt = 0;
do {
knt++;
e_st.site = &td_emlrtRSI;
eml_xscal(mmi, 9.9792015476736E+291, b_A_data, i_i + 2);
beta1 *= 9.9792015476736E+291;
atmp *= 9.9792015476736E+291;
} while (!(muDoubleScalarAbs(beta1) >= 1.0020841800044864E-292));
e_st.site = &ud_emlrtRSI;
xnorm = b_eml_xnrm2(mmi, b_A_data, i_i + 2);
beta1 = muDoubleScalarHypot(atmp, xnorm);
if (atmp >= 0.0) {
beta1 = -beta1;
}
d1 = (beta1 - atmp) / beta1;
e_st.site = &vd_emlrtRSI;
eml_xscal(mmi, 1.0 / (atmp - beta1), b_A_data, i_i + 2);
e_st.site = &wd_emlrtRSI;
if (1 > knt) {
b6 = false;
} else {
b6 = (knt > 2147483646);
}
if (b6) {
f_st.site = &l_emlrtRSI;
check_forloop_overflow_error(&f_st);
}
for (k = 1; k <= knt; k++) {
beta1 *= 1.0020841800044864E-292;
}
atmp = beta1;
} else {
d1 = (beta1 - b_A_data[i_i]) / beta1;
e_st.site = &xd_emlrtRSI;
eml_xscal(mmi, 1.0 / (b_A_data[i_i] - beta1), b_A_data, i_i + 2);
atmp = beta1;
}
}
}
tau_data[i - 1] = d1;
} else {
d_st.site = &ld_emlrtRSI;
xnorm = b_A_data[i_i];
atmp = b_A_data[i_i];
b_A_data[i_i] = xnorm;
tau_data[i - 1] = 0.0;
}
b_A_data[i_i] = atmp;
if (i < n) {
atmp = b_A_data[i_i];
b_A_data[i_i] = 1.0;
d_st.site = &md_emlrtRSI;
eml_matlab_zlarf(&d_st, 1 + mmi, nmi, i_i + 1, tau_data[i - 1], b_A_data,
i + i * b_m, b_m, work_data);
b_A_data[i_i] = atmp;
}
d_st.site = &nd_emlrtRSI;
for (knt = i; knt + 1 <= n; knt++) {
if (vn1_data[knt] != 0.0) {
xnorm = muDoubleScalarAbs(b_A_data[(i + A_size_idx_0 * knt) - 1]) /
vn1_data[knt];
xnorm = 1.0 - xnorm * xnorm;
if (xnorm < 0.0) {
xnorm = 0.0;
}
beta1 = vn1_data[knt] / vn2_data[knt];
beta1 = xnorm * (beta1 * beta1);
if (beta1 <= TOL3Z) {
if (i < b_m) {
d_st.site = &od_emlrtRSI;
e_st.site = &qd_emlrtRSI;
if (mmi < 1) {
xnorm = 0.0;
} else {
n_t = (ptrdiff_t)(mmi);
incx_t = (ptrdiff_t)(1);
xix0_t = (double *)(&b_A_data[i + b_m * knt]);
xnorm = dnrm2(&n_t, xix0_t, &incx_t);
}
vn1_data[knt] = xnorm;
vn2_data[knt] = vn1_data[knt];
} else {
vn1_data[knt] = 0.0;
vn2_data[knt] = 0.0;
}
} else {
d_st.site = &pd_emlrtRSI;
vn1_data[knt] *= muDoubleScalarSqrt(xnorm);
}
}
}
}
}
beta1 = 0.0;
if (mn > 0) {
xnorm = muDoubleScalarMax(A_size[0], A_size[1]) * muDoubleScalarAbs
(b_A_data[0]) * 2.2204460492503131E-16;
k = 0;
exitg1 = false;
while ((!exitg1) && (k <= mn - 1)) {
if (muDoubleScalarAbs(b_A_data[k + A_size_idx_0 * k]) <= xnorm) {
st.site = &ad_emlrtRSI;
y = NULL;
m16 = emlrtCreateCharArray(2, iv36);
for (i = 0; i < 8; i++) {
cv41[i] = cv42[i];
}
emlrtInitCharArrayR2013a(&st, 8, m16, cv41);
emlrtAssign(&y, m16);
b_st.site = &rf_emlrtRSI;
emlrt_marshallIn(&b_st, c_sprintf(&b_st, b_sprintf(&b_st, y,
emlrt_marshallOut(14.0), emlrt_marshallOut(6.0), &s_emlrtMCI),
emlrt_marshallOut(xnorm), &t_emlrtMCI), "sprintf", cv43);
st.site = &bd_emlrtRSI;
b_eml_warning(&st, beta1, cv43);
exitg1 = true;
} else {
beta1++;
k++;
}
}
}
Y_size[0] = (int8_T)A_size[1];
k = (int8_T)A_size[1];
for (itemp = 0; itemp < k; itemp++) {
Y_data[itemp] = 0.0;
}
for (knt = 0; knt < mn; knt++) {
if (tau_data[knt] != 0.0) {
xnorm = B_data[knt];
itemp = m - knt;
for (i = 0; i <= itemp; i++) {
k = (knt + i) + 1;
xnorm += b_A_data[k + A_size_idx_0 * knt] * B_data[k];
}
xnorm *= tau_data[knt];
if (xnorm != 0.0) {
B_data[knt] -= xnorm;
itemp = m - knt;
for (i = 0; i <= itemp; i++) {
k = (knt + i) + 1;
B_data[k] -= b_A_data[k + A_size_idx_0 * knt] * xnorm;
}
}
}
}
emlrtForLoopVectorCheckR2012b(1.0, 1.0, beta1, mxDOUBLE_CLASS, (int32_T)beta1,
&ub_emlrtRTEI, sp);
for (i = 0; i < (int32_T)beta1; i++) {
Y_data[jpvt_data[i] - 1] = B_data[i];
}
emlrtForLoopVectorCheckR2012b(beta1, -1.0, 1.0, mxDOUBLE_CLASS, (int32_T)-(1.0
+ (-1.0 - beta1)), &tb_emlrtRTEI, sp);
for (knt = 0; knt < (int32_T)-(1.0 + (-1.0 - beta1)); knt++) {
xnorm = beta1 + -(real_T)knt;
Y_data[jpvt_data[(int32_T)xnorm - 1] - 1] /= b_A_data[((int32_T)xnorm +
A_size_idx_0 * ((int32_T)xnorm - 1)) - 1];
for (i = 0; i < (int32_T)(xnorm - 1.0); i++) {
Y_data[jpvt_data[i] - 1] -= Y_data[jpvt_data[(int32_T)xnorm - 1] - 1] *
b_A_data[i + A_size_idx_0 * ((int32_T)xnorm - 1)];
}
}
}
static real_T b_eml_xnrm2(int32_T n, const real_T x_data[], int32_T ix0)
{
real_T y;
ptrdiff_t n_t;
ptrdiff_t incx_t;
double * xix0_t;
if (n < 1) {
y = 0.0;
} else {
n_t = (ptrdiff_t)(n);
incx_t = (ptrdiff_t)(1);
xix0_t = (double *)(&x_data[ix0 - 1]);
y = dnrm2(&n_t, xix0_t, &incx_t);
}
return y;
}
static void b_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, char_T y[14])
{
q_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y);
emlrtDestroyArray(&u);
}
static const mxArray *b_sprintf(const emlrtStack *sp, const mxArray *b, const
mxArray *c, const mxArray *d, emlrtMCInfo *location)
{
const mxArray *pArrays[3];
const mxArray *m26;
pArrays[0] = b;
pArrays[1] = c;
pArrays[2] = d;
return emlrtCallMATLABR2012b(sp, 1, &m26, 3, pArrays, "sprintf", true,
location);
}
static const mxArray *c_sprintf(const emlrtStack *sp, const mxArray *b, const
mxArray *c, emlrtMCInfo *location)
{
const mxArray *pArrays[2];
const mxArray *m27;
pArrays[0] = b;
pArrays[1] = c;
return emlrtCallMATLABR2012b(sp, 1, &m27, 2, pArrays, "sprintf", true,
location);
}
static int32_T eml_ixamax(int32_T n, const real_T x_data[], int32_T ix0)
{
int32_T idxmax;
ptrdiff_t n_t;
ptrdiff_t incx_t;
double * xix0_t;
if (n < 1) {
idxmax = 0;
} else {
n_t = (ptrdiff_t)(n);
incx_t = (ptrdiff_t)(1);
xix0_t = (double *)(&x_data[ix0 - 1]);
n_t = idamax(&n_t, xix0_t, &incx_t);
idxmax = (int32_T)n_t;
}
return idxmax;
}
static void eml_lusolve(const emlrtStack *sp, const real_T A_data[], const
int32_T A_size[2], const emxArray_real_T *B, emxArray_real_T *X)
{
int32_T n;
int32_T iy;
int32_T i;
real_T b_A_data[100];
int32_T ipiv_size[2];
int32_T ipiv_data[10];
int32_T info;
int32_T b;
int32_T j;
int32_T mmj;
int32_T c;
ptrdiff_t n_t;
ptrdiff_t incx_t;
double * xix0_t;
int32_T ix;
int32_T ip;
real_T temp;
ptrdiff_t m_t;
ptrdiff_t incy_t;
ptrdiff_t lda_t;
double * alpha1_t;
double * Aia0_t;
double * Aiy0_t;
char_T DIAGA;
char_T TRANSA;
char_T UPLO;
char_T SIDE;
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
st.site = &yb_emlrtRSI;
b_st.prev = &st;
b_st.tls = st.tls;
n = A_size[1];
iy = A_size[0] * A_size[1];
for (i = 0; i < iy; i++) {
b_A_data[i] = A_data[i];
}
eml_signed_integer_colon(muIntScalarMin_sint32(A_size[1], A_size[1]),
ipiv_data, ipiv_size);
info = 0;
if (A_size[1] < 1) {
} else {
iy = A_size[1] - 1;
b = muIntScalarMin_sint32(iy, A_size[1]);
for (j = 1; j <= b; j++) {
mmj = n - j;
c = (j - 1) * (n + 1);
if (mmj + 1 < 1) {
iy = -1;
} else {
n_t = (ptrdiff_t)(mmj + 1);
incx_t = (ptrdiff_t)(1);
xix0_t = (double *)(&b_A_data[c]);
incx_t = idamax(&n_t, xix0_t, &incx_t);
iy = (int32_T)incx_t - 1;
}
if (b_A_data[c + iy] != 0.0) {
if (iy != 0) {
ipiv_data[j - 1] = j + iy;
ix = j - 1;
iy = (j + iy) - 1;
for (ip = 1; ip <= n; ip++) {
temp = b_A_data[ix];
b_A_data[ix] = b_A_data[iy];
b_A_data[iy] = temp;
ix += n;
iy += n;
}
}
iy = (c + mmj) + 1;
for (i = c + 1; i + 1 <= iy; i++) {
b_A_data[i] /= b_A_data[c];
}
} else {
info = j;
}
iy = n - j;
if ((mmj < 1) || (iy < 1)) {
} else {
temp = -1.0;
m_t = (ptrdiff_t)(mmj);
n_t = (ptrdiff_t)(iy);
incx_t = (ptrdiff_t)(1);
incy_t = (ptrdiff_t)(n);
lda_t = (ptrdiff_t)(n);
alpha1_t = (double *)(&temp);
Aia0_t = (double *)(&b_A_data[(c + n) + 1]);
xix0_t = (double *)(&b_A_data[c + 1]);
Aiy0_t = (double *)(&b_A_data[c + n]);
dger(&m_t, &n_t, alpha1_t, xix0_t, &incx_t, Aiy0_t, &incy_t, Aia0_t,
&lda_t);
}
}
if ((info == 0) && (!(b_A_data[(A_size[1] + A_size[0] * (A_size[1] - 1)) - 1]
!= 0.0))) {
info = A_size[1];
}
}
if (info > 0) {
b_st.site = &ac_emlrtRSI;
warn_singular(&b_st);
}
i = X->size[0] * X->size[1];
X->size[0] = B->size[0];
X->size[1] = B->size[1];
emxEnsureCapacity(&st, (emxArray__common *)X, i, (int32_T)sizeof(real_T),
&v_emlrtRTEI);
iy = B->size[0] * B->size[1];
for (i = 0; i < iy; i++) {
X->data[i] = B->data[i];
}
iy = B->size[1];
for (i = 0; i + 1 < n; i++) {
if (ipiv_data[i] != i + 1) {
ip = ipiv_data[i] - 1;
for (ix = 0; ix + 1 <= iy; ix++) {
temp = X->data[i + X->size[0] * ix];
X->data[i + X->size[0] * ix] = X->data[ip + X->size[0] * ix];
X->data[ip + X->size[0] * ix] = temp;
}
}
}
if ((A_size[1] < 1) || (B->size[1] < 1)) {
} else {
temp = 1.0;
DIAGA = 'U';
TRANSA = 'N';
UPLO = 'L';
SIDE = 'L';
m_t = (ptrdiff_t)(A_size[1]);
n_t = (ptrdiff_t)(B->size[1]);
lda_t = (ptrdiff_t)(A_size[1]);
incx_t = (ptrdiff_t)(A_size[1]);
Aia0_t = (double *)(&b_A_data[0]);
xix0_t = (double *)(&X->data[0]);
alpha1_t = (double *)(&temp);
dtrsm(&SIDE, &UPLO, &TRANSA, &DIAGA, &m_t, &n_t, alpha1_t, Aia0_t, &lda_t,
xix0_t, &incx_t);
}
if ((A_size[1] < 1) || (B->size[1] < 1)) {
} else {
temp = 1.0;
DIAGA = 'N';
TRANSA = 'N';
UPLO = 'U';
SIDE = 'L';
m_t = (ptrdiff_t)(A_size[1]);
n_t = (ptrdiff_t)(B->size[1]);
lda_t = (ptrdiff_t)(A_size[1]);
incx_t = (ptrdiff_t)(A_size[1]);
Aia0_t = (double *)(&b_A_data[0]);
xix0_t = (double *)(&X->data[0]);
alpha1_t = (double *)(&temp);
dtrsm(&SIDE, &UPLO, &TRANSA, &DIAGA, &m_t, &n_t, alpha1_t, Aia0_t, &lda_t,
xix0_t, &incx_t);
}
}
static void eml_matlab_zlarf(const emlrtStack *sp, int32_T m, int32_T n, int32_T
iv0, real_T tau, real_T C_data[], int32_T ic0, int32_T ldc, real_T work_data[])
{
int32_T lastv;
int32_T lastc;
boolean_T exitg2;
int32_T coltop;
int32_T colbottom;
boolean_T b_coltop;
int32_T exitg1;
real_T alpha1;
real_T beta1;
char_T TRANSA;
ptrdiff_t m_t;
ptrdiff_t n_t;
ptrdiff_t lda_t;
ptrdiff_t incx_t;
ptrdiff_t incy_t;
double * alpha1_t;
double * beta1_t;
double * yiy0_t;
double * Aia0_t;
double * xix0_t;
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
if (tau != 0.0) {
lastv = m;
lastc = iv0 + m;
while ((lastv > 0) && (C_data[lastc - 2] == 0.0)) {
lastv--;
lastc--;
}
st.site = &de_emlrtRSI;
lastc = n;
exitg2 = false;
while ((!exitg2) && (lastc > 0)) {
coltop = ic0 + (lastc - 1) * ldc;
colbottom = (coltop + lastv) - 1;
b_st.site = &ee_emlrtRSI;
if (coltop > colbottom) {
b_coltop = false;
} else {
b_coltop = (colbottom > 2147483646);
}
if (b_coltop) {
c_st.site = &l_emlrtRSI;
check_forloop_overflow_error(&c_st);
}
do {
exitg1 = 0;
if (coltop <= colbottom) {
if (C_data[coltop - 1] != 0.0) {
exitg1 = 1;
} else {
coltop++;
}
} else {
lastc--;
exitg1 = 2;
}
} while (exitg1 == 0);
if (exitg1 == 1) {
exitg2 = true;
}
}
} else {
lastv = 0;
lastc = 0;
}
if (lastv > 0) {
st.site = &ce_emlrtRSI;
b_st.site = &fe_emlrtRSI;
if (lastc < 1) {
} else {
alpha1 = 1.0;
beta1 = 0.0;
TRANSA = 'C';
m_t = (ptrdiff_t)(lastv);
n_t = (ptrdiff_t)(lastc);
lda_t = (ptrdiff_t)(ldc);
incx_t = (ptrdiff_t)(1);
incy_t = (ptrdiff_t)(1);
alpha1_t = (double *)(&alpha1);
beta1_t = (double *)(&beta1);
yiy0_t = (double *)(&work_data[0]);
Aia0_t = (double *)(&C_data[ic0 - 1]);
xix0_t = (double *)(&C_data[iv0 - 1]);
dgemv(&TRANSA, &m_t, &n_t, alpha1_t, Aia0_t, &lda_t, xix0_t, &incx_t,
beta1_t, yiy0_t, &incy_t);
}
st.site = &be_emlrtRSI;
alpha1 = -tau;
b_st.site = &he_emlrtRSI;
if (lastc < 1) {
} else {
m_t = (ptrdiff_t)(lastv);
n_t = (ptrdiff_t)(lastc);
incx_t = (ptrdiff_t)(1);
incy_t = (ptrdiff_t)(1);
lda_t = (ptrdiff_t)(ldc);
alpha1_t = (double *)(&alpha1);
Aia0_t = (double *)(&C_data[ic0 - 1]);
beta1_t = (double *)(&C_data[iv0 - 1]);
yiy0_t = (double *)(&work_data[0]);
dger(&m_t, &n_t, alpha1_t, beta1_t, &incx_t, yiy0_t, &incy_t, Aia0_t,
&lda_t);
}
}
}
static void eml_qrsolve(const emlrtStack *sp, const real_T A_data[], const
int32_T A_size[2], emxArray_real_T *B, emxArray_real_T *Y)
{
int32_T m;
int32_T nb;
int32_T mn;
int32_T A_size_idx_0;
int32_T pvt;
int32_T itemp;
real_T b_A_data[100];
int32_T b_m;
int32_T n;
int32_T b_mn;
real_T tau_data[10];
int32_T jpvt_size[2];
int32_T jpvt_data[10];
real_T work_data[10];
real_T TOL3Z;
real_T vn1_data[10];
real_T vn2_data[10];
int32_T k;
int32_T knt;
int32_T i;
int32_T i_i;
int32_T nmi;
int32_T mmi;
real_T atmp;
real_T d0;
real_T xnorm;
real_T beta1;
boolean_T b3;
ptrdiff_t n_t;
ptrdiff_t incx_t;
double * xix0_t;
boolean_T exitg1;
const mxArray *y;
static const int32_T iv16[2] = { 1, 8 };
const mxArray *m11;
char_T cv26[8];
static const char_T cv27[8] = { '%', '%', '%', 'd', '.', '%', 'd', 'e' };
char_T cv28[14];
int16_T unnamed_idx_1;
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
emlrtStack d_st;
emlrtStack e_st;
emlrtStack f_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
d_st.prev = &c_st;
d_st.tls = c_st.tls;
e_st.prev = &d_st;
e_st.tls = d_st.tls;
f_st.prev = &e_st;
f_st.tls = e_st.tls;
m = A_size[0] - 2;
nb = B->size[1] - 1;
mn = (int32_T)muDoubleScalarMin(A_size[0], A_size[1]);
st.site = &yc_emlrtRSI;
b_st.site = &cd_emlrtRSI;
c_st.site = &dd_emlrtRSI;
A_size_idx_0 = A_size[0];
pvt = A_size[0] * A_size[1];
for (itemp = 0; itemp < pvt; itemp++) {
b_A_data[itemp] = A_data[itemp];
}
b_m = A_size[0];
n = A_size[1];
b_mn = muIntScalarMin_sint32(A_size[0], A_size[1]);
eml_signed_integer_colon(A_size[1], jpvt_data, jpvt_size);
if ((A_size[0] == 0) || (A_size[1] == 0)) {
} else {
pvt = (int8_T)A_size[1];
for (itemp = 0; itemp < pvt; itemp++) {
work_data[itemp] = 0.0;
}
TOL3Z = 2.2204460492503131E-16;
d_st.site = &ed_emlrtRSI;
b_sqrt(&d_st, &TOL3Z);
k = 1;
d_st.site = &fd_emlrtRSI;
for (knt = 0; knt + 1 <= n; knt++) {
d_st.site = &gd_emlrtRSI;
vn1_data[knt] = eml_xnrm2(b_m, A_data, k);
vn2_data[knt] = vn1_data[knt];
k += b_m;
}
d_st.site = &hd_emlrtRSI;
for (i = 1; i <= b_mn; i++) {
i_i = (i + (i - 1) * b_m) - 1;
nmi = n - i;
mmi = b_m - i;
d_st.site = &id_emlrtRSI;
pvt = eml_ixamax(1 + nmi, vn1_data, i);
pvt = (i + pvt) - 2;
if (pvt + 1 != i) {
d_st.site = &jd_emlrtRSI;
eml_xswap(&d_st, b_m, b_A_data, 1 + b_m * pvt, 1 + b_m * (i - 1));
itemp = jpvt_data[pvt];
jpvt_data[pvt] = jpvt_data[i - 1];
jpvt_data[i - 1] = itemp;
vn1_data[pvt] = vn1_data[i - 1];
vn2_data[pvt] = vn2_data[i - 1];
}
if (i < b_m) {
d_st.site = &kd_emlrtRSI;
atmp = b_A_data[i_i];
d0 = 0.0;
if (1 + mmi <= 0) {
} else {
e_st.site = &sd_emlrtRSI;
xnorm = b_eml_xnrm2(mmi, b_A_data, i_i + 2);
if (xnorm != 0.0) {
beta1 = muDoubleScalarHypot(b_A_data[i_i], xnorm);
if (b_A_data[i_i] >= 0.0) {
beta1 = -beta1;
}
if (muDoubleScalarAbs(beta1) < 1.0020841800044864E-292) {
knt = 0;
do {
knt++;
e_st.site = &td_emlrtRSI;
eml_xscal(mmi, 9.9792015476736E+291, b_A_data, i_i + 2);
beta1 *= 9.9792015476736E+291;
atmp *= 9.9792015476736E+291;
} while (!(muDoubleScalarAbs(beta1) >= 1.0020841800044864E-292));
e_st.site = &ud_emlrtRSI;
xnorm = b_eml_xnrm2(mmi, b_A_data, i_i + 2);
beta1 = muDoubleScalarHypot(atmp, xnorm);
if (atmp >= 0.0) {
beta1 = -beta1;
}
d0 = (beta1 - atmp) / beta1;
e_st.site = &vd_emlrtRSI;
eml_xscal(mmi, 1.0 / (atmp - beta1), b_A_data, i_i + 2);
e_st.site = &wd_emlrtRSI;
if (1 > knt) {
b3 = false;
} else {
b3 = (knt > 2147483646);
}
if (b3) {
f_st.site = &l_emlrtRSI;
check_forloop_overflow_error(&f_st);
}
for (k = 1; k <= knt; k++) {
beta1 *= 1.0020841800044864E-292;
}
atmp = beta1;
} else {
d0 = (beta1 - b_A_data[i_i]) / beta1;
e_st.site = &xd_emlrtRSI;
eml_xscal(mmi, 1.0 / (b_A_data[i_i] - beta1), b_A_data, i_i + 2);
atmp = beta1;
}
}
}
tau_data[i - 1] = d0;
} else {
d_st.site = &ld_emlrtRSI;
xnorm = b_A_data[i_i];
atmp = b_A_data[i_i];
b_A_data[i_i] = xnorm;
tau_data[i - 1] = 0.0;
}
b_A_data[i_i] = atmp;
if (i < n) {
atmp = b_A_data[i_i];
b_A_data[i_i] = 1.0;
d_st.site = &md_emlrtRSI;
eml_matlab_zlarf(&d_st, 1 + mmi, nmi, i_i + 1, tau_data[i - 1], b_A_data,
i + i * b_m, b_m, work_data);
b_A_data[i_i] = atmp;
}
d_st.site = &nd_emlrtRSI;
for (knt = i; knt + 1 <= n; knt++) {
if (vn1_data[knt] != 0.0) {
xnorm = muDoubleScalarAbs(b_A_data[(i + A_size_idx_0 * knt) - 1]) /
vn1_data[knt];
xnorm = 1.0 - xnorm * xnorm;
if (xnorm < 0.0) {
xnorm = 0.0;
}
beta1 = vn1_data[knt] / vn2_data[knt];
beta1 = xnorm * (beta1 * beta1);
if (beta1 <= TOL3Z) {
if (i < b_m) {
d_st.site = &od_emlrtRSI;
e_st.site = &qd_emlrtRSI;
if (mmi < 1) {
xnorm = 0.0;
} else {
n_t = (ptrdiff_t)(mmi);
incx_t = (ptrdiff_t)(1);
xix0_t = (double *)(&b_A_data[i + b_m * knt]);
xnorm = dnrm2(&n_t, xix0_t, &incx_t);
}
vn1_data[knt] = xnorm;
vn2_data[knt] = vn1_data[knt];
} else {
vn1_data[knt] = 0.0;
vn2_data[knt] = 0.0;
}
} else {
d_st.site = &pd_emlrtRSI;
vn1_data[knt] *= muDoubleScalarSqrt(xnorm);
}
}
}
}
}
beta1 = 0.0;
if (mn > 0) {
xnorm = muDoubleScalarMax(A_size[0], A_size[1]) * muDoubleScalarAbs
(b_A_data[0]) * 2.2204460492503131E-16;
k = 0;
exitg1 = false;
while ((!exitg1) && (k <= mn - 1)) {
if (muDoubleScalarAbs(b_A_data[k + A_size_idx_0 * k]) <= xnorm) {
st.site = &ad_emlrtRSI;
y = NULL;
m11 = emlrtCreateCharArray(2, iv16);
for (i = 0; i < 8; i++) {
cv26[i] = cv27[i];
}
emlrtInitCharArrayR2013a(&st, 8, m11, cv26);
emlrtAssign(&y, m11);
b_st.site = &rf_emlrtRSI;
emlrt_marshallIn(&b_st, c_sprintf(&b_st, b_sprintf(&b_st, y,
emlrt_marshallOut(14.0), emlrt_marshallOut(6.0), &s_emlrtMCI),
emlrt_marshallOut(xnorm), &t_emlrtMCI), "sprintf", cv28);
st.site = &bd_emlrtRSI;
b_eml_warning(&st, beta1, cv28);
exitg1 = true;
} else {
beta1++;
k++;
}
}
}
unnamed_idx_1 = (int16_T)B->size[1];
itemp = Y->size[0] * Y->size[1];
Y->size[0] = (int16_T)A_size[1];
emxEnsureCapacity(sp, (emxArray__common *)Y, itemp, (int32_T)sizeof(real_T),
&w_emlrtRTEI);
itemp = Y->size[0] * Y->size[1];
Y->size[1] = unnamed_idx_1;
emxEnsureCapacity(sp, (emxArray__common *)Y, itemp, (int32_T)sizeof(real_T),
&w_emlrtRTEI);
pvt = (int16_T)A_size[1] * unnamed_idx_1;
for (itemp = 0; itemp < pvt; itemp++) {
Y->data[itemp] = 0.0;
}
for (knt = 0; knt < mn; knt++) {
if (tau_data[knt] != 0.0) {
for (k = 0; k <= nb; k++) {
xnorm = B->data[knt + B->size[0] * k];
itemp = m - knt;
for (i = 0; i <= itemp; i++) {
pvt = (knt + i) + 1;
xnorm += b_A_data[pvt + A_size_idx_0 * knt] * B->data[pvt + B->size[0]
* k];
}
xnorm *= tau_data[knt];
if (xnorm != 0.0) {
B->data[knt + B->size[0] * k] -= xnorm;
itemp = m - knt;
for (i = 0; i <= itemp; i++) {
pvt = (knt + i) + 1;
B->data[pvt + B->size[0] * k] -= b_A_data[pvt + A_size_idx_0 * knt] *
xnorm;
}
}
}
}
}
for (k = 0; k <= nb; k++) {
emlrtForLoopVectorCheckR2012b(1.0, 1.0, beta1, mxDOUBLE_CLASS, (int32_T)
beta1, &ub_emlrtRTEI, sp);
for (i = 0; i < (int32_T)beta1; i++) {
Y->data[(jpvt_data[i] + Y->size[0] * k) - 1] = B->data[i + B->size[0] * k];
}
emlrtForLoopVectorCheckR2012b(beta1, -1.0, 1.0, mxDOUBLE_CLASS, (int32_T)
-(1.0 + (-1.0 - beta1)), &tb_emlrtRTEI, sp);
for (knt = 0; knt < (int32_T)-(1.0 + (-1.0 - beta1)); knt++) {
xnorm = beta1 + -(real_T)knt;
Y->data[(jpvt_data[(int32_T)xnorm - 1] + Y->size[0] * k) - 1] /= b_A_data
[((int32_T)xnorm + A_size_idx_0 * ((int32_T)xnorm - 1)) - 1];
for (i = 0; i < (int32_T)(xnorm - 1.0); i++) {
Y->data[(jpvt_data[i] + Y->size[0] * k) - 1] -= Y->data[(jpvt_data
[(int32_T)xnorm - 1] + Y->size[0] * k) - 1] * b_A_data[i +
A_size_idx_0 * ((int32_T)xnorm - 1)];
}
}
}
}
static real_T eml_xnrm2(int32_T n, const real_T x_data[], int32_T ix0)
{
real_T y;
ptrdiff_t n_t;
ptrdiff_t incx_t;
double * xix0_t;
if (n < 1) {
y = 0.0;
} else {
n_t = (ptrdiff_t)(n);
incx_t = (ptrdiff_t)(1);
xix0_t = (double *)(&x_data[ix0 - 1]);
y = dnrm2(&n_t, xix0_t, &incx_t);
}
return y;
}
static void eml_xscal(int32_T n, real_T a, real_T x_data[], int32_T ix0)
{
ptrdiff_t n_t;
ptrdiff_t incx_t;
double * xix0_t;
double * a_t;
if (n < 1) {
} else {
n_t = (ptrdiff_t)(n);
incx_t = (ptrdiff_t)(1);
xix0_t = (double *)(&x_data[ix0 - 1]);
a_t = (double *)(&a);
dscal(&n_t, a_t, xix0_t, &incx_t);
}
}
static void eml_xswap(const emlrtStack *sp, int32_T n, real_T x_data[], int32_T
ix0, int32_T iy0)
{
int32_T ix;
int32_T iy;
boolean_T b7;
int32_T k;
real_T temp;
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
emlrtStack d_st;
st.prev = sp;
st.tls = sp->tls;
st.site = &pc_emlrtRSI;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
d_st.prev = &c_st;
d_st.tls = c_st.tls;
b_st.site = &qc_emlrtRSI;
ix = ix0 - 1;
iy = iy0 - 1;
c_st.site = &rc_emlrtRSI;
if (1 > n) {
b7 = false;
} else {
b7 = (n > 2147483646);
}
if (b7) {
d_st.site = &l_emlrtRSI;
check_forloop_overflow_error(&d_st);
}
for (k = 1; k <= n; k++) {
temp = x_data[ix];
x_data[ix] = x_data[iy];
x_data[iy] = temp;
ix++;
iy++;
}
}
static void emlrt_marshallIn(const emlrtStack *sp, const mxArray *d_sprintf,
const char_T *identifier, char_T y[14])
{
emlrtMsgIdentifier thisId;
thisId.fIdentifier = identifier;
thisId.fParent = NULL;
b_emlrt_marshallIn(sp, emlrtAlias(d_sprintf), &thisId, y);
emlrtDestroyArray(&d_sprintf);
}
static void q_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, char_T ret[14])
{
int32_T iv50[2];
int32_T i14;
for (i14 = 0; i14 < 2; i14++) {
iv50[i14] = 1 + 13 * i14;
}
emlrtCheckBuiltInR2012b(sp, msgId, src, "char", false, 2U, iv50);
emlrtImportCharArrayR2014b(sp, src, ret, 14);
emlrtDestroyArray(&src);
}
static void warn_singular(const emlrtStack *sp)
{
emlrtStack st;
st.prev = sp;
st.tls = sp->tls;
st.site = &vc_emlrtRSI;
eml_warning(&st);
}
void b_mldivide(const emlrtStack *sp, const real_T A_data[], const int32_T
A_size[2], const real_T B_data[], const int32_T B_size[1],
real_T Y_data[], int32_T Y_size[1])
{
const mxArray *y;
static const int32_T iv35[2] = { 1, 21 };
const mxArray *m15;
char_T cv39[21];
int32_T i;
static const char_T cv40[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'd', 'i', 'm', 'a', 'g', 'r', 'e', 'e' };
int32_T i12;
real_T b_B_data[1200];
int32_T tmp_size[1];
real_T tmp_data[10];
emlrtStack st;
st.prev = sp;
st.tls = sp->tls;
if (B_size[0] == A_size[0]) {
} else {
y = NULL;
m15 = emlrtCreateCharArray(2, iv35);
for (i = 0; i < 21; i++) {
cv39[i] = cv40[i];
}
emlrtInitCharArrayR2013a(sp, 21, m15, cv39);
emlrtAssign(&y, m15);
st.site = &xb_emlrtRSI;
error(&st, b_message(&st, y, &p_emlrtMCI), &p_emlrtMCI);
}
if ((A_size[0] == 0) || (A_size[1] == 0) || (B_size[0] == 0)) {
Y_size[0] = (int8_T)A_size[1];
i = (int8_T)A_size[1];
for (i12 = 0; i12 < i; i12++) {
Y_data[i12] = 0.0;
}
} else if (A_size[0] == A_size[1]) {
Y_size[0] = B_size[0];
i = B_size[0];
for (i12 = 0; i12 < i; i12++) {
Y_data[i12] = B_data[i12];
}
st.site = &xb_emlrtRSI;
b_eml_lusolve(&st, A_data, A_size, Y_data);
} else {
i = B_size[0];
for (i12 = 0; i12 < i; i12++) {
b_B_data[i12] = B_data[i12];
}
st.site = &xb_emlrtRSI;
b_eml_qrsolve(&st, A_data, A_size, b_B_data, tmp_data, tmp_size);
Y_size[0] = tmp_size[0];
i = tmp_size[0];
for (i12 = 0; i12 < i; i12++) {
Y_data[i12] = tmp_data[i12];
}
}
}
void mldivide(const emlrtStack *sp, const real_T A_data[], const int32_T A_size
[2], const emxArray_real_T *B, emxArray_real_T *Y)
{
const mxArray *y;
static const int32_T iv14[2] = { 1, 21 };
const mxArray *m9;
char_T cv22[21];
int32_T i;
static const char_T cv23[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
'L', 'A', 'B', ':', 'd', 'i', 'm', 'a', 'g', 'r', 'e', 'e' };
emxArray_real_T *b_B;
int16_T unnamed_idx_1;
int32_T loop_ub;
emlrtStack st;
st.prev = sp;
st.tls = sp->tls;
emlrtHeapReferenceStackEnterFcnR2012b(sp);
if (B->size[0] == A_size[0]) {
} else {
y = NULL;
m9 = emlrtCreateCharArray(2, iv14);
for (i = 0; i < 21; i++) {
cv22[i] = cv23[i];
}
emlrtInitCharArrayR2013a(sp, 21, m9, cv22);
emlrtAssign(&y, m9);
st.site = &xb_emlrtRSI;
error(&st, b_message(&st, y, &p_emlrtMCI), &p_emlrtMCI);
}
emxInit_real_T(sp, &b_B, 2, &u_emlrtRTEI, true);
if ((A_size[0] == 0) || (A_size[1] == 0) || ((B->size[0] == 0) || (B->size[1] ==
0))) {
unnamed_idx_1 = (int16_T)B->size[1];
i = Y->size[0] * Y->size[1];
Y->size[0] = (int16_T)A_size[1];
emxEnsureCapacity(sp, (emxArray__common *)Y, i, (int32_T)sizeof(real_T),
&u_emlrtRTEI);
i = Y->size[0] * Y->size[1];
Y->size[1] = unnamed_idx_1;
emxEnsureCapacity(sp, (emxArray__common *)Y, i, (int32_T)sizeof(real_T),
&u_emlrtRTEI);
loop_ub = (int16_T)A_size[1] * unnamed_idx_1;
for (i = 0; i < loop_ub; i++) {
Y->data[i] = 0.0;
}
} else if (A_size[0] == A_size[1]) {
st.site = &xb_emlrtRSI;
eml_lusolve(&st, A_data, A_size, B, Y);
} else {
i = b_B->size[0] * b_B->size[1];
b_B->size[0] = B->size[0];
b_B->size[1] = B->size[1];
emxEnsureCapacity(sp, (emxArray__common *)b_B, i, (int32_T)sizeof(real_T),
&u_emlrtRTEI);
loop_ub = B->size[0] * B->size[1];
for (i = 0; i < loop_ub; i++) {
b_B->data[i] = B->data[i];
}
st.site = &xb_emlrtRSI;
eml_qrsolve(&st, A_data, A_size, b_B, Y);
}
emxFree_real_T(&b_B);
emlrtHeapReferenceStackLeaveFcnR2012b(sp);
}
/* End of code generation (mldivide.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_EM_terminate.c
/*
* SREM_EM_terminate.c
*
* Code generation for function 'SREM_EM_terminate'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "SREM_EM_terminate.h"
/* Function Definitions */
void SREM_EM_atexit(void)
{
emlrtStack st = { NULL, NULL, NULL };
emlrtCreateRootTLS(&emlrtRootTLSGlobal, &emlrtContextGlobal, NULL, 1);
st.tls = emlrtRootTLSGlobal;
emlrtEnterRtStackR2012b(&st);
emlrtLeaveRtStackR2012b(&st);
emlrtDestroyRootTLS(&emlrtRootTLSGlobal);
}
void SREM_EM_terminate(void)
{
emlrtStack st = { NULL, NULL, NULL };
st.tls = emlrtRootTLSGlobal;
emlrtLeaveRtStackR2012b(&st);
emlrtDestroyRootTLS(&emlrtRootTLSGlobal);
}
/* End of code generation (SREM_EM_terminate.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_EM.c
/*
* SREM_EM.c
*
* Code generation for function 'SREM_EM'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "SREM_EM_emxutil.h"
#include "std.h"
#include "taufun.h"
#include "bbarupdate.h"
#include "bSSupdate.h"
#include "eml_int_forloop_overflow_check.h"
#include "SREM_MAP.h"
#include "find.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRSInfo emlrtRSI = { 26, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRSInfo b_emlrtRSI = { 32, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRSInfo c_emlrtRSI = { 40, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRSInfo d_emlrtRSI = { 42, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRSInfo e_emlrtRSI = { 47, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRSInfo f_emlrtRSI = { 51, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRSInfo g_emlrtRSI = { 54, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRSInfo h_emlrtRSI = { 58, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRSInfo i_emlrtRSI = { 11, "eml_li_find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_li_find.m"
};
static emlrtRSInfo j_emlrtRSI = { 26, "eml_li_find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_li_find.m"
};
static emlrtRSInfo k_emlrtRSI = { 39, "eml_li_find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_li_find.m"
};
static emlrtRSInfo ve_emlrtRSI = { 3, "tauupdate",
"D:\\CODE\\GHMM_V3\\subfuns\\tauupdate.m" };
static emlrtMCInfo emlrtMCI = { 14, 5, "eml_li_find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_li_find.m"
};
static emlrtRTEInfo emlrtRTEI = { 1, 55, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRTEInfo c_emlrtRTEI = { 26, 20, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRTEInfo d_emlrtRTEI = { 26, 68, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRTEInfo e_emlrtRTEI = { 26, 86, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRTEInfo f_emlrtRTEI = { 28, 1, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRTEInfo g_emlrtRTEI = { 32, 1, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRTEInfo h_emlrtRTEI = { 32, 19, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRTEInfo i_emlrtRTEI = { 32, 80, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtBCInfo emlrtBCI = { -1, -1, 26, 35, "subind1", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtBCInfo b_emlrtBCI = { -1, -1, 26, 61, "subind1", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtBCInfo c_emlrtBCI = { -1, -1, 28, 38, "Y11", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtBCInfo d_emlrtBCI = { -1, -1, 30, 17, "beta", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtECInfo emlrtECI = { 1, 30, 34, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtRTEInfo rb_emlrtRTEI = { 35, 1, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtECInfo b_emlrtECI = { -1, 42, 5, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtECInfo c_emlrtECI = { 1, 47, 6, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtECInfo d_emlrtECI = { 2, 47, 6, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtECInfo e_emlrtECI = { 2, 47, 12, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtECInfo f_emlrtECI = { 1, 51, 5, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtECInfo g_emlrtECI = { 1, 56, 5, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtECInfo h_emlrtECI = { 2, 56, 5, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m" };
static emlrtDCInfo emlrtDCI = { 24, 17, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 1 };
static emlrtDCInfo b_emlrtDCI = { 24, 17, "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 4 };
static emlrtBCInfo e_emlrtBCI = { -1, -1, 26, 79, "Y1", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtBCInfo f_emlrtBCI = { -1, -1, 26, 97, "W1", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtBCInfo g_emlrtBCI = { -1, -1, 32, 91, "Y11", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtBCInfo h_emlrtBCI = { -1, -1, 40, 18, "sum_U", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtBCInfo i_emlrtBCI = { -1, -1, 42, 10, "Pb", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtBCInfo j_emlrtBCI = { -1, -1, 58, 21, "sum_U", "SREM_EM",
"D:\\CODE\\GHMM_V3\\subfuns\\SREM_EM.m", 0 };
static emlrtDCInfo c_emlrtDCI = { 20, 34, "eml_li_find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_li_find.m",
4 };
static emlrtRSInfo kf_emlrtRSI = { 14, "eml_li_find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\eml\\eml_li_find.m"
};
/* Function Declarations */
static int32_T compute_nones(const emlrtStack *sp, const boolean_T x_data[],
int32_T n);
static void eml_li_find(const emlrtStack *sp, const boolean_T x_data[], const
int32_T x_size[1], int32_T y_data[], int32_T y_size[1]);
/* Function Definitions */
static int32_T compute_nones(const emlrtStack *sp, const boolean_T x_data[],
int32_T n)
{
int32_T k;
boolean_T b0;
int32_T i;
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
k = 0;
st.site = &k_emlrtRSI;
if (1 > n) {
b0 = false;
} else {
b0 = (n > 2147483646);
}
if (b0) {
b_st.site = &l_emlrtRSI;
check_forloop_overflow_error(&b_st);
}
for (i = 1; i <= n; i++) {
if (x_data[i - 1]) {
k++;
}
}
return k;
}
static void eml_li_find(const emlrtStack *sp, const boolean_T x_data[], const
int32_T x_size[1], int32_T y_data[], int32_T y_size[1])
{
int32_T k;
const mxArray *y;
const mxArray *m0;
int32_T i;
emlrtStack st;
st.prev = sp;
st.tls = sp->tls;
st.site = &i_emlrtRSI;
k = compute_nones(&st, x_data, x_size[0]);
if (k <= x_size[0]) {
} else {
y = NULL;
m0 = emlrtCreateString("Assertion failed.");
emlrtAssign(&y, m0);
st.site = &kf_emlrtRSI;
error(&st, y, &emlrtMCI);
}
emlrtNonNegativeCheckFastR2012b(k, &c_emlrtDCI, sp);
y_size[0] = k;
k = 0;
st.site = &j_emlrtRSI;
for (i = 1; i <= x_size[0]; i++) {
if (x_data[i - 1]) {
y_data[k] = i;
k++;
}
}
}
void SREM_EM(const emlrtStack *sp, emxArray_real_T *b, const emxArray_real_T *Y1,
const emxArray_real_T *DIC, const emxArray_real_T *subind1,
emxArray_real_T *beta, real_T betabar_data[], int32_T betabar_size
[2], emxArray_real_T *Sigma_s, real_T tau, real_T EM_iter, real_T
MAP_iter, emxArray_real_T *b0, emxArray_real_T *beta0, real_T
betabar0_data[], int32_T betabar0_size[2], emxArray_real_T
*Sigma_s0, real_T *tau0, emxArray_real_T *sum_U)
{
int32_T i0;
real_T s;
int32_T iy;
int32_T i1;
int32_T ixstart;
emxArray_real_T *W1;
int32_T loop_ub;
int32_T k;
int32_T inx1_size[1];
boolean_T inx1_data[1200];
emxArray_real_T *Y11;
int32_T tmp_size[1];
int32_T tmp_data[1200];
emxArray_real_T *W11;
emxArray_real_T *Pb;
int32_T vstride;
int32_T exbetabar_size[2];
real_T exbetabar_data[30];
emxArray_boolean_T *unzeroDIC;
int32_T sz[2];
emxArray_real_T *sumDIC;
int32_T ix;
emxArray_boolean_T *b_sumDIC;
emxArray_int32_T *ii;
emxArray_real_T *Y11DIC;
int32_T i2;
emxArray_real_T *Pb1;
emxArray_real_T *b_beta;
boolean_T exitg1;
int32_T b_tmp_data[1200];
int32_T iv0[3];
boolean_T exitg2;
real_T B;
boolean_T guard1 = false;
real_T b_sum_U[3];
emlrtStack st;
emlrtStack b_st;
emlrtStack c_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
c_st.prev = &b_st;
c_st.tls = b_st.tls;
emlrtHeapReferenceStackEnterFcnR2012b(sp);
/* % The EM algorithm */
/* ---input--------------------------------------------------------- */
/* b: initial 2D or 3D labels p*n1, n1: number of pateint */
/* Y1: image intensity matrix p*m */
/* DIC: dictionary of spatial relationship */
/* subind1: subject information m*(2+q) */
/* beta: initial value of beta q*p */
/* betabar: initial value of betabar q*2 */
/* Sigma_s: initial value of variance matrix in epsilon 1*p */
/* tau: initial value of tau in Gibbs distribution 1 */
/* EM_iter: maximum number of iterations of the EM algorithm */
/* MAP_iter: maximum number of iterations of the MAP algorithm */
/* ---output-------------------------------------------------------- */
/* b0: final 2D or 3D labels */
/* beta0: final vector of beta q*p */
/* betabar0: final vector of betabar q*2 */
/* Sigma_s0: final value of variance matrix in epsilon 1*p */
/* tau0: final value of tau in Gibbs distribution 1 */
/* sum_U: energy function */
/* Copyright by <NAME>, 2015/01/23 */
i0 = sum_U->size[0] * sum_U->size[1];
sum_U->size[0] = 1;
s = emlrtNonNegativeCheckFastR2012b(EM_iter, &b_emlrtDCI, sp);
sum_U->size[1] = (int32_T)emlrtIntegerCheckFastR2012b(s, &emlrtDCI, sp);
emxEnsureCapacity(sp, (emxArray__common *)sum_U, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
s = emlrtNonNegativeCheckFastR2012b(EM_iter, &b_emlrtDCI, sp);
iy = (int32_T)emlrtIntegerCheckFastR2012b(s, &emlrtDCI, sp);
for (i0 = 0; i0 < iy; i0++) {
sum_U->data[i0] = 0.0;
}
if (3 > subind1->size[1]) {
i0 = 0;
i1 = 0;
} else {
i0 = 2;
i1 = subind1->size[1];
ixstart = subind1->size[1];
i1 = emlrtDynamicBoundsCheckFastR2012b(ixstart, 1, i1, &emlrtBCI, sp);
}
emxInit_real_T(sp, &W1, 2, &c_emlrtRTEI, true);
iy = subind1->size[0];
ixstart = W1->size[0] * W1->size[1];
W1->size[0] = i1 - i0;
W1->size[1] = iy;
emxEnsureCapacity(sp, (emxArray__common *)W1, ixstart, (int32_T)sizeof(real_T),
&emlrtRTEI);
for (ixstart = 0; ixstart < iy; ixstart++) {
loop_ub = i1 - i0;
for (k = 0; k < loop_ub; k++) {
W1->data[k + W1->size[0] * ixstart] = subind1->data[ixstart +
subind1->size[0] * (i0 + k)];
}
}
i0 = subind1->size[1];
emlrtDynamicBoundsCheckFastR2012b(2, 1, i0, &b_emlrtBCI, sp);
iy = subind1->size[0];
inx1_size[0] = iy;
for (i0 = 0; i0 < iy; i0++) {
inx1_data[i0] = (subind1->data[i0 + subind1->size[0]] != 0.0);
}
emxInit_real_T(sp, &Y11, 2, &d_emlrtRTEI, true);
st.site = &emlrtRSI;
eml_li_find(&st, inx1_data, inx1_size, tmp_data, tmp_size);
iy = Y1->size[0];
i0 = Y11->size[0] * Y11->size[1];
Y11->size[0] = iy;
Y11->size[1] = tmp_size[0];
emxEnsureCapacity(sp, (emxArray__common *)Y11, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
loop_ub = tmp_size[0];
for (i0 = 0; i0 < loop_ub; i0++) {
for (i1 = 0; i1 < iy; i1++) {
ixstart = Y1->size[1];
Y11->data[i1 + Y11->size[0] * i0] = Y1->data[i1 + Y1->size[0] *
(emlrtDynamicBoundsCheckFastR2012b(tmp_data[i0], 1, ixstart, &e_emlrtBCI,
sp) - 1)];
}
}
emxInit_real_T(sp, &W11, 2, &e_emlrtRTEI, true);
st.site = &emlrtRSI;
eml_li_find(&st, inx1_data, inx1_size, tmp_data, tmp_size);
iy = W1->size[0];
i0 = W11->size[0] * W11->size[1];
W11->size[0] = iy;
W11->size[1] = tmp_size[0];
emxEnsureCapacity(sp, (emxArray__common *)W11, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
loop_ub = tmp_size[0];
for (i0 = 0; i0 < loop_ub; i0++) {
for (i1 = 0; i1 < iy; i1++) {
ixstart = W1->size[1];
W11->data[i1 + W11->size[0] * i0] = W1->data[i1 + W1->size[0] *
(emlrtDynamicBoundsCheckFastR2012b(tmp_data[i0], 1, ixstart, &f_emlrtBCI,
sp) - 1)];
}
}
b_emxInit_real_T(sp, &Pb, 3, &f_emlrtRTEI, true);
i0 = Pb->size[0] * Pb->size[1] * Pb->size[2];
Pb->size[0] = 3;
emxEnsureCapacity(sp, (emxArray__common *)Pb, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
vstride = Y1->size[1];
i0 = Pb->size[0] * Pb->size[1] * Pb->size[2];
Pb->size[1] = vstride;
emxEnsureCapacity(sp, (emxArray__common *)Pb, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
vstride = Y1->size[0];
i0 = Pb->size[0] * Pb->size[1] * Pb->size[2];
Pb->size[2] = vstride;
emxEnsureCapacity(sp, (emxArray__common *)Pb, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
iy = 3 * Y1->size[1] * Y1->size[0];
for (i0 = 0; i0 < iy; i0++) {
Pb->data[i0] = 0.0;
}
i0 = Y11->size[0];
emlrtDynamicBoundsCheckFastR2012b(1, 1, i0, &c_emlrtBCI, sp);
i0 = Y11->size[1];
i1 = beta->size[1];
emlrtDynamicBoundsCheckFastR2012b(1, 1, i1, &d_emlrtBCI, sp);
i1 = beta->size[0];
ixstart = beta->size[0];
emlrtDimSizeEqCheckFastR2012b(ixstart, betabar_size[0], &emlrtECI, sp);
iy = beta->size[0];
exbetabar_size[0] = iy;
exbetabar_size[1] = 3;
for (ixstart = 0; ixstart < iy; ixstart++) {
exbetabar_data[ixstart] = 0.0;
}
for (ixstart = 0; ixstart < 2; ixstart++) {
loop_ub = betabar_size[0];
for (k = 0; k < loop_ub; k++) {
exbetabar_data[k + iy * (ixstart + 1)] = betabar_data[k + betabar_size[0] *
ixstart];
}
}
emxInit_boolean_T(sp, &unzeroDIC, 2, &g_emlrtRTEI, true);
ixstart = unzeroDIC->size[0] * unzeroDIC->size[1];
unzeroDIC->size[0] = DIC->size[0];
unzeroDIC->size[1] = DIC->size[1];
emxEnsureCapacity(sp, (emxArray__common *)unzeroDIC, ixstart, (int32_T)sizeof
(boolean_T), &emlrtRTEI);
iy = DIC->size[0] * DIC->size[1];
for (ixstart = 0; ixstart < iy; ixstart++) {
unzeroDIC->data[ixstart] = (DIC->data[ixstart] != 0.0);
}
st.site = &b_emlrtRSI;
b_st.site = &m_emlrtRSI;
c_st.site = &n_emlrtRSI;
for (ixstart = 0; ixstart < 2; ixstart++) {
sz[ixstart] = unzeroDIC->size[ixstart];
}
c_emxInit_real_T(&c_st, &sumDIC, 1, &h_emlrtRTEI, true);
ixstart = sumDIC->size[0];
sumDIC->size[0] = sz[0];
emxEnsureCapacity(&c_st, (emxArray__common *)sumDIC, ixstart, (int32_T)sizeof
(real_T), &b_emlrtRTEI);
if ((unzeroDIC->size[0] == 0) || (unzeroDIC->size[1] == 0)) {
ixstart = sumDIC->size[0];
sumDIC->size[0] = sz[0];
emxEnsureCapacity(&c_st, (emxArray__common *)sumDIC, ixstart, (int32_T)
sizeof(real_T), &emlrtRTEI);
iy = sz[0];
for (ixstart = 0; ixstart < iy; ixstart++) {
sumDIC->data[ixstart] = 0.0;
}
} else {
vstride = unzeroDIC->size[0];
iy = -1;
ixstart = -1;
for (loop_ub = 1; loop_ub <= vstride; loop_ub++) {
ixstart++;
ix = ixstart;
s = unzeroDIC->data[ixstart];
for (k = 2; k <= unzeroDIC->size[1]; k++) {
ix += vstride;
s += (real_T)unzeroDIC->data[ix];
}
iy++;
sumDIC->data[iy] = s;
}
}
emxFree_boolean_T(&unzeroDIC);
b_emxInit_boolean_T(&c_st, &b_sumDIC, 1, &emlrtRTEI, true);
st.site = &b_emlrtRSI;
ixstart = b_sumDIC->size[0];
b_sumDIC->size[0] = sumDIC->size[0];
emxEnsureCapacity(&st, (emxArray__common *)b_sumDIC, ixstart, (int32_T)sizeof
(boolean_T), &emlrtRTEI);
iy = sumDIC->size[0];
for (ixstart = 0; ixstart < iy; ixstart++) {
b_sumDIC->data[ixstart] = (sumDIC->data[ixstart] == 6.0);
}
emxInit_int32_T(&st, &ii, 1, &j_emlrtRTEI, true);
b_st.site = &p_emlrtRSI;
eml_find(&b_st, b_sumDIC, ii);
ixstart = sumDIC->size[0];
sumDIC->size[0] = ii->size[0];
emxEnsureCapacity(&st, (emxArray__common *)sumDIC, ixstart, (int32_T)sizeof
(real_T), &emlrtRTEI);
iy = ii->size[0];
emxFree_boolean_T(&b_sumDIC);
for (ixstart = 0; ixstart < iy; ixstart++) {
sumDIC->data[ixstart] = ii->data[ixstart];
}
emxInit_real_T(&st, &Y11DIC, 2, &i_emlrtRTEI, true);
iy = Y11->size[1];
ixstart = Y11DIC->size[0] * Y11DIC->size[1];
Y11DIC->size[0] = sumDIC->size[0];
Y11DIC->size[1] = iy;
emxEnsureCapacity(sp, (emxArray__common *)Y11DIC, ixstart, (int32_T)sizeof
(real_T), &emlrtRTEI);
for (ixstart = 0; ixstart < iy; ixstart++) {
loop_ub = sumDIC->size[0];
for (k = 0; k < loop_ub; k++) {
i2 = Y11->size[0];
vstride = (int32_T)sumDIC->data[k];
Y11DIC->data[k + Y11DIC->size[0] * ixstart] = Y11->data
[(emlrtDynamicBoundsCheckFastR2012b(vstride, 1, i2, &g_emlrtBCI, sp) +
Y11->size[0] * ixstart) - 1];
}
}
emlrtForLoopVectorCheckR2012b(1.0, 1.0, EM_iter, mxDOUBLE_CLASS, (int32_T)
EM_iter, &rb_emlrtRTEI, sp);
ix = 0;
b_emxInit_real_T(sp, &Pb1, 3, &emlrtRTEI, true);
emxInit_real_T(sp, &b_beta, 2, &emlrtRTEI, true);
exitg1 = false;
while ((!exitg1) && (ix <= (int32_T)EM_iter - 1)) {
/* %% E step: calculating expectations */
/* %% update b */
ixstart = sum_U->size[1];
st.site = &c_emlrtRSI;
SREM_MAP(&st, b, Y11, DIC, W11, beta, exbetabar_data, exbetabar_size,
Sigma_s, tau, MAP_iter, Pb1, &sum_U->
data[emlrtDynamicBoundsCheckFastR2012b(ix + 1, 1, ixstart,
&h_emlrtBCI, sp) - 1]);
st.site = &d_emlrtRSI;
eml_li_find(&st, inx1_data, inx1_size, tmp_data, tmp_size);
iy = tmp_size[0];
for (ixstart = 0; ixstart < iy; ixstart++) {
k = Pb->size[1];
b_tmp_data[ixstart] = emlrtDynamicBoundsCheckFastR2012b(tmp_data[ixstart],
1, k, &i_emlrtBCI, sp) - 1;
}
iy = Pb->size[2];
ixstart = ii->size[0];
ii->size[0] = iy;
emxEnsureCapacity(sp, (emxArray__common *)ii, ixstart, (int32_T)sizeof
(int32_T), &emlrtRTEI);
for (ixstart = 0; ixstart < iy; ixstart++) {
ii->data[ixstart] = ixstart;
}
iv0[0] = 3;
iv0[1] = tmp_size[0];
iv0[2] = ii->size[0];
emlrtSubAssignSizeCheckR2012b(iv0, 3, *(int32_T (*)[3])Pb1->size, 3,
&b_emlrtECI, sp);
iy = Pb1->size[2];
for (ixstart = 0; ixstart < iy; ixstart++) {
loop_ub = Pb1->size[1];
for (k = 0; k < loop_ub; k++) {
for (i2 = 0; i2 < 3; i2++) {
Pb->data[(i2 + Pb->size[0] * b_tmp_data[k]) + Pb->size[0] * Pb->size[1]
* ii->data[ixstart]] = Pb1->data[(i2 + Pb1->size[0] * k) + Pb1->
size[0] * Pb1->size[1] * ixstart];
}
}
}
/* %% M step: update beta, betabar, Sigma_v, Sigma_s and tau */
st.site = &e_emlrtRSI;
bSSupdate(&st, Y1, Pb, W1, beta, exbetabar_data, exbetabar_size, i1, b_beta,
Sigma_s);
ixstart = b_beta->size[0];
emlrtDimSizeGeqCheckFastR2012b(10, ixstart, &c_emlrtECI, sp);
ixstart = b_beta->size[1];
emlrtDimSizeGeqCheckFastR2012b(1000000, ixstart, &d_emlrtECI, sp);
ixstart = beta->size[0] * beta->size[1];
beta->size[0] = b_beta->size[0];
beta->size[1] = b_beta->size[1];
emxEnsureCapacity(sp, (emxArray__common *)beta, ixstart, (int32_T)sizeof
(real_T), &emlrtRTEI);
iy = b_beta->size[0] * b_beta->size[1];
for (ixstart = 0; ixstart < iy; ixstart++) {
beta->data[ixstart] = b_beta->data[ixstart];
}
ixstart = Sigma_s->size[1];
emlrtDimSizeGeqCheckFastR2012b(1000000, ixstart, &e_emlrtECI, sp);
/* update betabar */
st.site = &f_emlrtRSI;
bbarupdate(&st, Y11, Pb1, W11, b_beta, Sigma_s, i1, betabar_data,
betabar_size);
emlrtDimSizeGeqCheckFastR2012b(10, betabar_size[0], &f_emlrtECI, sp);
/* update tau */
st.site = &g_emlrtRSI;
vstride = 0;
exitg2 = false;
while ((!exitg2) && (vstride < 50)) {
b_st.site = &ve_emlrtRSI;
taufun(&b_st, tau, b, Y11DIC, i0, DIC, sumDIC, &s, &B);
tau -= s / B;
if ((vstride + 1 >= 3) && (muDoubleScalarAbs(tau - tau) < 0.01)) {
exitg2 = true;
} else {
vstride++;
emlrtBreakCheckFastR2012b(emlrtBreakCheckR2012bFlagVar, &st);
}
}
ixstart = b->size[0];
emlrtDimSizeGeqCheckFastR2012b(1000000, ixstart, &g_emlrtECI, sp);
ixstart = b->size[1];
emlrtDimSizeGeqCheckFastR2012b(1200, ixstart, &h_emlrtECI, sp);
guard1 = false;
if (1.0 + (real_T)ix >= 3.0) {
for (ixstart = 0; ixstart < 3; ixstart++) {
k = sum_U->size[1];
i2 = (int32_T)((1.0 + (real_T)ix) + (-2.0 + (real_T)ixstart));
b_sum_U[ixstart] = sum_U->data[emlrtDynamicBoundsCheckFastR2012b(i2, 1,
k, &j_emlrtBCI, sp) - 1];
}
st.site = &h_emlrtRSI;
if (b_std(&st, b_sum_U) < 0.01) {
exitg1 = true;
} else {
guard1 = true;
}
} else {
guard1 = true;
}
if (guard1) {
ix++;
emlrtBreakCheckFastR2012b(emlrtBreakCheckR2012bFlagVar, sp);
}
}
emxFree_int32_T(&ii);
emxFree_real_T(&b_beta);
emxFree_real_T(&Pb1);
emxFree_real_T(&Y11DIC);
emxFree_real_T(&sumDIC);
emxFree_real_T(&Pb);
emxFree_real_T(&W11);
emxFree_real_T(&Y11);
emxFree_real_T(&W1);
i0 = b0->size[0] * b0->size[1];
b0->size[0] = b->size[0];
b0->size[1] = b->size[1];
emxEnsureCapacity(sp, (emxArray__common *)b0, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
iy = b->size[0] * b->size[1];
for (i0 = 0; i0 < iy; i0++) {
b0->data[i0] = b->data[i0];
}
i0 = beta0->size[0] * beta0->size[1];
beta0->size[0] = beta->size[0];
beta0->size[1] = beta->size[1];
emxEnsureCapacity(sp, (emxArray__common *)beta0, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
iy = beta->size[0] * beta->size[1];
for (i0 = 0; i0 < iy; i0++) {
beta0->data[i0] = beta->data[i0];
}
betabar0_size[0] = betabar_size[0];
betabar0_size[1] = 2;
iy = betabar_size[0] * betabar_size[1];
for (i0 = 0; i0 < iy; i0++) {
betabar0_data[i0] = betabar_data[i0];
}
i0 = Sigma_s0->size[0] * Sigma_s0->size[1];
Sigma_s0->size[0] = 1;
Sigma_s0->size[1] = Sigma_s->size[1];
emxEnsureCapacity(sp, (emxArray__common *)Sigma_s0, i0, (int32_T)sizeof(real_T),
&emlrtRTEI);
iy = Sigma_s->size[0] * Sigma_s->size[1];
for (i0 = 0; i0 < iy; i0++) {
Sigma_s0->data[i0] = Sigma_s->data[i0];
}
*tau0 = tau;
emlrtHeapReferenceStackLeaveFcnR2012b(sp);
}
/* End of code generation (SREM_EM.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/find.c
/*
* find.c
*
* Code generation for function 'find'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "find.h"
#include "taufun.h"
#include "SREM_EM_emxutil.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtMCInfo e_emlrtMCI = { 123, 9, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
static emlrtMCInfo f_emlrtMCI = { 122, 19, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
static emlrtRTEInfo k_emlrtRTEI = { 127, 5, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
static emlrtRTEInfo l_emlrtRTEI = { 47, 20, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
static emlrtRTEInfo m_emlrtRTEI = { 249, 13, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
static emlrtRSInfo if_emlrtRSI = { 122, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
static emlrtRSInfo qf_emlrtRSI = { 123, "find",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elmat\\find.m"
};
/* Function Definitions */
void b_eml_find(const emlrtStack *sp, const emxArray_boolean_T *x,
emxArray_int32_T *i)
{
int32_T nx;
int32_T idx;
boolean_T b1;
const mxArray *y;
static const int32_T iv3[2] = { 1, 36 };
const mxArray *m3;
char_T cv4[36];
int32_T b_i;
static const char_T cv5[36] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
'l', 'b', 'o', 'x', ':', 'f', 'i', 'n', 'd', '_', 'i', 'n', 'c', 'o', 'm',
'p', 'a', 't', 'i', 'b', 'l', 'e', 'S', 'h', 'a', 'p', 'e' };
boolean_T exitg1;
boolean_T guard1 = false;
const mxArray *b_y;
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = sp;
b_st.tls = sp->tls;
nx = x->size[0] * x->size[1];
idx = 0;
if ((!((x->size[0] == 1) || (x->size[1] == 1))) || (x->size[0] != 1) ||
(x->size[1] <= 1)) {
b1 = true;
} else {
b1 = false;
}
if (b1) {
} else {
y = NULL;
m3 = emlrtCreateCharArray(2, iv3);
for (b_i = 0; b_i < 36; b_i++) {
cv4[b_i] = cv5[b_i];
}
emlrtInitCharArrayR2013a(sp, 36, m3, cv4);
emlrtAssign(&y, m3);
st.site = &if_emlrtRSI;
b_st.site = &qf_emlrtRSI;
error(&st, b_message(&b_st, y, &e_emlrtMCI), &f_emlrtMCI);
}
b_i = i->size[0];
i->size[0] = nx;
emxEnsureCapacity(sp, (emxArray__common *)i, b_i, (int32_T)sizeof(int32_T),
&k_emlrtRTEI);
st.site = &q_emlrtRSI;
b_i = 1;
exitg1 = false;
while ((!exitg1) && (b_i <= nx)) {
guard1 = false;
if (x->data[b_i - 1]) {
idx++;
i->data[idx - 1] = b_i;
if (idx >= nx) {
exitg1 = true;
} else {
guard1 = true;
}
} else {
guard1 = true;
}
if (guard1) {
b_i++;
}
}
if (idx <= nx) {
} else {
b_y = NULL;
m3 = emlrtCreateString("Assertion failed.");
emlrtAssign(&b_y, m3);
st.site = &gf_emlrtRSI;
error(&st, b_y, &d_emlrtMCI);
}
if (nx == 1) {
if (idx == 0) {
b_i = i->size[0];
i->size[0] = 0;
emxEnsureCapacity(sp, (emxArray__common *)i, b_i, (int32_T)sizeof(int32_T),
&l_emlrtRTEI);
}
} else {
b_i = i->size[0];
if (1 > idx) {
i->size[0] = 0;
} else {
i->size[0] = idx;
}
emxEnsureCapacity(sp, (emxArray__common *)i, b_i, (int32_T)sizeof(int32_T),
&m_emlrtRTEI);
}
}
void eml_find(const emlrtStack *sp, const emxArray_boolean_T *x,
emxArray_int32_T *i)
{
int32_T nx;
int32_T idx;
int32_T ii;
boolean_T exitg1;
boolean_T guard1 = false;
const mxArray *y;
const mxArray *m2;
emlrtStack st;
st.prev = sp;
st.tls = sp->tls;
nx = x->size[0];
idx = 0;
ii = i->size[0];
i->size[0] = x->size[0];
emxEnsureCapacity(sp, (emxArray__common *)i, ii, (int32_T)sizeof(int32_T),
&k_emlrtRTEI);
st.site = &q_emlrtRSI;
ii = 1;
exitg1 = false;
while ((!exitg1) && (ii <= nx)) {
guard1 = false;
if (x->data[ii - 1]) {
idx++;
i->data[idx - 1] = ii;
if (idx >= nx) {
exitg1 = true;
} else {
guard1 = true;
}
} else {
guard1 = true;
}
if (guard1) {
ii++;
}
}
if (idx <= x->size[0]) {
} else {
y = NULL;
m2 = emlrtCreateString("Assertion failed.");
emlrtAssign(&y, m2);
st.site = &gf_emlrtRSI;
error(&st, y, &d_emlrtMCI);
}
if (x->size[0] == 1) {
if (idx == 0) {
ii = i->size[0];
i->size[0] = 0;
emxEnsureCapacity(sp, (emxArray__common *)i, ii, (int32_T)sizeof(int32_T),
&l_emlrtRTEI);
}
} else {
ii = i->size[0];
if (1 > idx) {
i->size[0] = 0;
} else {
i->size[0] = idx;
}
emxEnsureCapacity(sp, (emxArray__common *)i, ii, (int32_T)sizeof(int32_T),
&m_emlrtRTEI);
}
}
/* End of code generation (find.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_EM.h
/*
* SREM_EM.h
*
* Code generation for function 'SREM_EM'
*
*/
#ifndef __SREM_EM_H__
#define __SREM_EM_H__
/* Include files */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "mwmathutil.h"
#include "tmwtypes.h"
#include "mex.h"
#include "emlrt.h"
#include "blas.h"
#include "rtwtypes.h"
#include "SREM_EM_types.h"
/* Function Declarations */
extern void SREM_EM(const emlrtStack *sp, emxArray_real_T *b, const
emxArray_real_T *Y1, const emxArray_real_T *DIC, const
emxArray_real_T *subind1, emxArray_real_T *beta, real_T
betabar_data[], int32_T betabar_size[2], emxArray_real_T
*Sigma_s, real_T tau, real_T EM_iter, real_T MAP_iter,
emxArray_real_T *b0, emxArray_real_T *beta0, real_T
betabar0_data[], int32_T betabar0_size[2], emxArray_real_T
*Sigma_s0, real_T *tau0, emxArray_real_T *sum_U);
#endif
/* End of code generation (SREM_EM.h) */
<file_sep>/subfuns/codegen/mex/SREM_EM/rdivide.c
/*
* rdivide.c
*
* Code generation for function 'rdivide'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "rdivide.h"
#include "taufun.h"
#include "SREM_EM_emxutil.h"
#include "SREM_EM_mexutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRTEInfo q_emlrtRTEI = { 1, 14, "rdivide",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\ops\\rdivide.m"
};
/* Function Definitions */
void rdivide(const emlrtStack *sp, const emxArray_real_T *x, const
emxArray_real_T *y, emxArray_real_T *z)
{
int32_T varargin_1[2];
int32_T varargin_2[2];
boolean_T p;
boolean_T b_p;
int32_T i;
boolean_T exitg1;
const mxArray *b_y;
static const int32_T iv7[2] = { 1, 15 };
const mxArray *m5;
char_T cv10[15];
static const char_T cv11[15] = { 'M', 'A', 'T', 'L', 'A', 'B', ':', 'd', 'i',
'm', 'a', 'g', 'r', 'e', 'e' };
int32_T loop_ub;
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = sp;
b_st.tls = sp->tls;
varargin_1[0] = x->size[0];
varargin_1[1] = 1;
varargin_2[0] = y->size[0];
varargin_2[1] = 1;
p = false;
b_p = true;
i = 0;
exitg1 = false;
while ((!exitg1) && (i < 2)) {
if (!(varargin_1[i] == varargin_2[i])) {
b_p = false;
exitg1 = true;
} else {
i++;
}
}
if (!b_p) {
} else {
p = true;
}
if (p) {
} else {
b_y = NULL;
m5 = emlrtCreateCharArray(2, iv7);
for (i = 0; i < 15; i++) {
cv10[i] = cv11[i];
}
emlrtInitCharArrayR2013a(sp, 15, m5, cv10);
emlrtAssign(&b_y, m5);
st.site = &cf_emlrtRSI;
b_st.site = &lf_emlrtRSI;
error(&st, b_message(&b_st, b_y, &k_emlrtMCI), &l_emlrtMCI);
}
i = z->size[0];
z->size[0] = x->size[0];
emxEnsureCapacity(sp, (emxArray__common *)z, i, (int32_T)sizeof(real_T),
&q_emlrtRTEI);
loop_ub = x->size[0];
for (i = 0; i < loop_ub; i++) {
z->data[i] = x->data[i] / y->data[i];
}
}
/* End of code generation (rdivide.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/bbarupdate.h
/*
* bbarupdate.h
*
* Code generation for function 'bbarupdate'
*
*/
#ifndef __BBARUPDATE_H__
#define __BBARUPDATE_H__
/* Include files */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "mwmathutil.h"
#include "tmwtypes.h"
#include "mex.h"
#include "emlrt.h"
#include "blas.h"
#include "rtwtypes.h"
#include "SREM_EM_types.h"
/* Function Declarations */
extern void bbarupdate(const emlrtStack *sp, const emxArray_real_T *Y1, const
emxArray_real_T *Pb1, const emxArray_real_T *W1, const emxArray_real_T *beta,
const emxArray_real_T *Sigma_s, real_T q, real_T betabar0_data[], int32_T
betabar0_size[2]);
extern void c_dynamic_size_checks(const emlrtStack *sp, const emxArray_real_T *a,
const emxArray_real_T *b);
extern void d_eml_xgemm(int32_T m, int32_T k, const emxArray_real_T *A, int32_T
lda, const emxArray_real_T *B, int32_T ldb, emxArray_real_T *C, int32_T ldc);
#endif
/* End of code generation (bbarupdate.h) */
<file_sep>/subfuns/codegen/mex/SREM_EM/abs.c
/*
* abs.c
*
* Code generation for function 'abs'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "abs.h"
#include "SREM_EM_emxutil.h"
/* Variable Definitions */
static emlrtRTEInfo o_emlrtRTEI = { 16, 5, "abs",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\elfun\\abs.m" };
/* Function Definitions */
void b_abs(const emlrtStack *sp, const emxArray_real_T *x, emxArray_real_T *y)
{
int32_T iv4[2];
int32_T i3;
int32_T k;
for (i3 = 0; i3 < 2; i3++) {
iv4[i3] = x->size[i3];
}
i3 = y->size[0] * y->size[1];
y->size[0] = iv4[0];
y->size[1] = iv4[1];
emxEnsureCapacity(sp, (emxArray__common *)y, i3, (int32_T)sizeof(real_T),
&o_emlrtRTEI);
i3 = x->size[0] * x->size[1];
for (k = 0; k < i3; k++) {
y->data[k] = muDoubleScalarAbs(x->data[k]);
}
}
void c_abs(const real_T x_data[], const int32_T x_size[1], real_T y_data[],
int32_T y_size[1])
{
int32_T k;
y_size[0] = (int8_T)x_size[0];
for (k = 0; k < x_size[0]; k++) {
y_data[k] = muDoubleScalarAbs(x_data[k]);
}
}
/* End of code generation (abs.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/interface/_coder_SREM_EM_api.c
/*
* _coder_SREM_EM_api.c
*
* Code generation for function '_coder_SREM_EM_api'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "_coder_SREM_EM_api.h"
#include "SREM_EM_emxutil.h"
#include "eml_warning.h"
#include "SREM_EM_mexutil.h"
/* Variable Definitions */
static emlrtRTEInfo eb_emlrtRTEI = { 1, 1, "_coder_SREM_EM_api", "" };
/* Function Declarations */
static const mxArray *b_emlrt_marshallOut(const emxArray_real_T *u);
static void c_emlrt_marshallIn(const emlrtStack *sp, const mxArray *b, const
char_T *identifier, emxArray_real_T *y);
static const mxArray *c_emlrt_marshallOut(const emxArray_real_T *u);
static void d_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y);
static const mxArray *d_emlrt_marshallOut(const real_T u_data[], const int32_T
u_size[2]);
static void e_emlrt_marshallIn(const emlrtStack *sp, const mxArray *DIC, const
char_T *identifier, emxArray_real_T *y);
static const mxArray *e_emlrt_marshallOut(const emxArray_real_T *u);
static void f_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y);
static const mxArray *f_emlrt_marshallOut(const emxArray_real_T *u);
static void g_emlrt_marshallIn(const emlrtStack *sp, const mxArray *subind1,
const char_T *identifier, emxArray_real_T *y);
static void h_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y);
static void i_emlrt_marshallIn(const emlrtStack *sp, const mxArray *beta, const
char_T *identifier, emxArray_real_T *y);
static void j_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y);
static void k_emlrt_marshallIn(const emlrtStack *sp, const mxArray *betabar,
const char_T *identifier, real_T **y_data, int32_T y_size[2]);
static void l_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, real_T **y_data, int32_T y_size[2]);
static void m_emlrt_marshallIn(const emlrtStack *sp, const mxArray *Sigma_s,
const char_T *identifier, emxArray_real_T *y);
static void n_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y);
static real_T o_emlrt_marshallIn(const emlrtStack *sp, const mxArray *tau, const
char_T *identifier);
static real_T p_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId);
static void r_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret);
static void s_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret);
static void t_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret);
static void u_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret);
static void v_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, real_T **ret_data, int32_T ret_size[2]);
static void w_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret);
static real_T x_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId);
/* Function Definitions */
static const mxArray *b_emlrt_marshallOut(const emxArray_real_T *u)
{
const mxArray *y;
static const int32_T iv45[2] = { 0, 0 };
const mxArray *m19;
y = NULL;
m19 = emlrtCreateNumericArray(2, iv45, mxDOUBLE_CLASS, mxREAL);
mxSetData((mxArray *)m19, (void *)u->data);
emlrtSetDimensions((mxArray *)m19, u->size, 2);
emlrtAssign(&y, m19);
return y;
}
static void c_emlrt_marshallIn(const emlrtStack *sp, const mxArray *b, const
char_T *identifier, emxArray_real_T *y)
{
emlrtMsgIdentifier thisId;
thisId.fIdentifier = identifier;
thisId.fParent = NULL;
d_emlrt_marshallIn(sp, emlrtAlias(b), &thisId, y);
emlrtDestroyArray(&b);
}
static const mxArray *c_emlrt_marshallOut(const emxArray_real_T *u)
{
const mxArray *y;
static const int32_T iv46[2] = { 0, 0 };
const mxArray *m20;
y = NULL;
m20 = emlrtCreateNumericArray(2, iv46, mxDOUBLE_CLASS, mxREAL);
mxSetData((mxArray *)m20, (void *)u->data);
emlrtSetDimensions((mxArray *)m20, u->size, 2);
emlrtAssign(&y, m20);
return y;
}
static void d_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y)
{
r_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y);
emlrtDestroyArray(&u);
}
static const mxArray *d_emlrt_marshallOut(const real_T u_data[], const int32_T
u_size[2])
{
const mxArray *y;
static const int32_T iv47[2] = { 0, 0 };
const mxArray *m21;
y = NULL;
m21 = emlrtCreateNumericArray(2, iv47, mxDOUBLE_CLASS, mxREAL);
mxSetData((mxArray *)m21, (void *)u_data);
emlrtSetDimensions((mxArray *)m21, u_size, 2);
emlrtAssign(&y, m21);
return y;
}
static void e_emlrt_marshallIn(const emlrtStack *sp, const mxArray *DIC, const
char_T *identifier, emxArray_real_T *y)
{
emlrtMsgIdentifier thisId;
thisId.fIdentifier = identifier;
thisId.fParent = NULL;
f_emlrt_marshallIn(sp, emlrtAlias(DIC), &thisId, y);
emlrtDestroyArray(&DIC);
}
static const mxArray *e_emlrt_marshallOut(const emxArray_real_T *u)
{
const mxArray *y;
static const int32_T iv48[2] = { 0, 0 };
const mxArray *m22;
y = NULL;
m22 = emlrtCreateNumericArray(2, iv48, mxDOUBLE_CLASS, mxREAL);
mxSetData((mxArray *)m22, (void *)u->data);
emlrtSetDimensions((mxArray *)m22, u->size, 2);
emlrtAssign(&y, m22);
return y;
}
static void f_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y)
{
s_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y);
emlrtDestroyArray(&u);
}
static const mxArray *f_emlrt_marshallOut(const emxArray_real_T *u)
{
const mxArray *y;
static const int32_T iv49[2] = { 0, 0 };
const mxArray *m23;
y = NULL;
m23 = emlrtCreateNumericArray(2, iv49, mxDOUBLE_CLASS, mxREAL);
mxSetData((mxArray *)m23, (void *)u->data);
emlrtSetDimensions((mxArray *)m23, u->size, 2);
emlrtAssign(&y, m23);
return y;
}
static void g_emlrt_marshallIn(const emlrtStack *sp, const mxArray *subind1,
const char_T *identifier, emxArray_real_T *y)
{
emlrtMsgIdentifier thisId;
thisId.fIdentifier = identifier;
thisId.fParent = NULL;
h_emlrt_marshallIn(sp, emlrtAlias(subind1), &thisId, y);
emlrtDestroyArray(&subind1);
}
static void h_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y)
{
t_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y);
emlrtDestroyArray(&u);
}
static void i_emlrt_marshallIn(const emlrtStack *sp, const mxArray *beta, const
char_T *identifier, emxArray_real_T *y)
{
emlrtMsgIdentifier thisId;
thisId.fIdentifier = identifier;
thisId.fParent = NULL;
j_emlrt_marshallIn(sp, emlrtAlias(beta), &thisId, y);
emlrtDestroyArray(&beta);
}
static void j_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y)
{
u_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y);
emlrtDestroyArray(&u);
}
static void k_emlrt_marshallIn(const emlrtStack *sp, const mxArray *betabar,
const char_T *identifier, real_T **y_data, int32_T y_size[2])
{
emlrtMsgIdentifier thisId;
thisId.fIdentifier = identifier;
thisId.fParent = NULL;
l_emlrt_marshallIn(sp, emlrtAlias(betabar), &thisId, y_data, y_size);
emlrtDestroyArray(&betabar);
}
static void l_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, real_T **y_data, int32_T y_size[2])
{
v_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y_data, y_size);
emlrtDestroyArray(&u);
}
static void m_emlrt_marshallIn(const emlrtStack *sp, const mxArray *Sigma_s,
const char_T *identifier, emxArray_real_T *y)
{
emlrtMsgIdentifier thisId;
thisId.fIdentifier = identifier;
thisId.fParent = NULL;
n_emlrt_marshallIn(sp, emlrtAlias(Sigma_s), &thisId, y);
emlrtDestroyArray(&Sigma_s);
}
static void n_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId, emxArray_real_T *y)
{
w_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y);
emlrtDestroyArray(&u);
}
static real_T o_emlrt_marshallIn(const emlrtStack *sp, const mxArray *tau, const
char_T *identifier)
{
real_T y;
emlrtMsgIdentifier thisId;
thisId.fIdentifier = identifier;
thisId.fParent = NULL;
y = p_emlrt_marshallIn(sp, emlrtAlias(tau), &thisId);
emlrtDestroyArray(&tau);
return y;
}
static real_T p_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, const
emlrtMsgIdentifier *parentId)
{
real_T y;
y = x_emlrt_marshallIn(sp, emlrtAlias(u), parentId);
emlrtDestroyArray(&u);
return y;
}
static void r_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret)
{
int32_T iv51[2];
boolean_T bv0[2];
int32_T i;
int32_T iv52[2];
for (i = 0; i < 2; i++) {
iv51[i] = -1;
bv0[i] = true;
}
emlrtCheckVsBuiltInR2012b(sp, msgId, src, "double", false, 2U, iv51, bv0, iv52);
ret->size[0] = iv52[0];
ret->size[1] = iv52[1];
ret->allocatedSize = ret->size[0] * ret->size[1];
ret->data = (real_T *)mxGetData(src);
ret->canFreeData = false;
emlrtDestroyArray(&src);
}
static void s_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret)
{
int32_T iv53[2];
boolean_T bv1[2];
int32_T i15;
int32_T iv54[2];
for (i15 = 0; i15 < 2; i15++) {
iv53[i15] = 1000000 + -999994 * i15;
bv1[i15] = true;
}
emlrtCheckVsBuiltInR2012b(sp, msgId, src, "double", false, 2U, iv53, bv1, iv54);
ret->size[0] = iv54[0];
ret->size[1] = iv54[1];
ret->allocatedSize = ret->size[0] * ret->size[1];
ret->data = (real_T *)mxGetData(src);
ret->canFreeData = false;
emlrtDestroyArray(&src);
}
static void t_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret)
{
int32_T iv55[2];
boolean_T bv2[2];
int32_T i16;
int32_T iv56[2];
for (i16 = 0; i16 < 2; i16++) {
iv55[i16] = 1200 + -1190 * i16;
bv2[i16] = true;
}
emlrtCheckVsBuiltInR2012b(sp, msgId, src, "double", false, 2U, iv55, bv2, iv56);
ret->size[0] = iv56[0];
ret->size[1] = iv56[1];
ret->allocatedSize = ret->size[0] * ret->size[1];
ret->data = (real_T *)mxGetData(src);
ret->canFreeData = false;
emlrtDestroyArray(&src);
}
static void u_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret)
{
int32_T iv57[2];
boolean_T bv3[2];
int32_T i17;
int32_T iv58[2];
for (i17 = 0; i17 < 2; i17++) {
iv57[i17] = 10 + 999990 * i17;
bv3[i17] = true;
}
emlrtCheckVsBuiltInR2012b(sp, msgId, src, "double", false, 2U, iv57, bv3, iv58);
ret->size[0] = iv58[0];
ret->size[1] = iv58[1];
ret->allocatedSize = ret->size[0] * ret->size[1];
ret->data = (real_T *)mxGetData(src);
ret->canFreeData = false;
emlrtDestroyArray(&src);
}
static void v_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, real_T **ret_data, int32_T ret_size[2])
{
int32_T iv59[2];
boolean_T bv4[2];
int32_T i18;
static const boolean_T bv5[2] = { true, false };
int32_T iv60[2];
for (i18 = 0; i18 < 2; i18++) {
iv59[i18] = 10 + -8 * i18;
bv4[i18] = bv5[i18];
}
emlrtCheckVsBuiltInR2012b(sp, msgId, src, "double", false, 2U, iv59, bv4, iv60);
ret_size[0] = iv60[0];
ret_size[1] = iv60[1];
*ret_data = (real_T *)mxGetData(src);
emlrtDestroyArray(&src);
}
static void w_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId, emxArray_real_T *ret)
{
int32_T iv61[2];
boolean_T bv6[2];
int32_T i19;
static const boolean_T bv7[2] = { false, true };
int32_T iv62[2];
for (i19 = 0; i19 < 2; i19++) {
iv61[i19] = 1 + 999999 * i19;
bv6[i19] = bv7[i19];
}
emlrtCheckVsBuiltInR2012b(sp, msgId, src, "double", false, 2U, iv61, bv6, iv62);
ret->size[0] = iv62[0];
ret->size[1] = iv62[1];
ret->allocatedSize = ret->size[0] * ret->size[1];
ret->data = (real_T *)mxGetData(src);
ret->canFreeData = false;
emlrtDestroyArray(&src);
}
static real_T x_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, const
emlrtMsgIdentifier *msgId)
{
real_T ret;
emlrtCheckBuiltInR2012b(sp, msgId, src, "double", false, 0U, 0);
ret = *(real_T *)mxGetData(src);
emlrtDestroyArray(&src);
return ret;
}
void SREM_EM_api(const mxArray *prhs[10], const mxArray *plhs[6])
{
real_T (*betabar0_data)[20];
emxArray_real_T *b;
emxArray_real_T *Y1;
emxArray_real_T *DIC;
emxArray_real_T *subind1;
emxArray_real_T *beta;
emxArray_real_T *Sigma_s;
emxArray_real_T *b0;
emxArray_real_T *beta0;
emxArray_real_T *Sigma_s0;
emxArray_real_T *sum_U;
int32_T betabar_size[2];
real_T (*betabar_data)[20];
real_T tau;
real_T EM_iter;
real_T MAP_iter;
real_T tau0;
int32_T betabar0_size[2];
emlrtStack st = { NULL, NULL, NULL };
st.tls = emlrtRootTLSGlobal;
betabar0_data = (real_T (*)[20])mxMalloc(sizeof(real_T [20]));
emlrtHeapReferenceStackEnterFcnR2012b(&st);
emxInit_real_T(&st, &b, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &Y1, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &DIC, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &subind1, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &beta, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &Sigma_s, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &b0, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &beta0, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &Sigma_s0, 2, &eb_emlrtRTEI, true);
emxInit_real_T(&st, &sum_U, 2, &eb_emlrtRTEI, true);
prhs[0] = emlrtProtectR2012b(prhs[0], 0, false, -1);
prhs[4] = emlrtProtectR2012b(prhs[4], 4, false, -1);
prhs[5] = emlrtProtectR2012b(prhs[5], 5, false, 20);
prhs[6] = emlrtProtectR2012b(prhs[6], 6, false, -1);
/* Marshall function inputs */
c_emlrt_marshallIn(&st, emlrtAlias(prhs[0]), "b", b);
c_emlrt_marshallIn(&st, emlrtAlias(prhs[1]), "Y1", Y1);
e_emlrt_marshallIn(&st, emlrtAlias(prhs[2]), "DIC", DIC);
g_emlrt_marshallIn(&st, emlrtAlias(prhs[3]), "subind1", subind1);
i_emlrt_marshallIn(&st, emlrtAlias(prhs[4]), "beta", beta);
k_emlrt_marshallIn(&st, emlrtAlias(prhs[5]), "betabar", (real_T **)
&betabar_data, betabar_size);
m_emlrt_marshallIn(&st, emlrtAlias(prhs[6]), "Sigma_s", Sigma_s);
tau = o_emlrt_marshallIn(&st, emlrtAliasP(prhs[7]), "tau");
EM_iter = o_emlrt_marshallIn(&st, emlrtAliasP(prhs[8]), "EM_iter");
MAP_iter = o_emlrt_marshallIn(&st, emlrtAliasP(prhs[9]), "MAP_iter");
/* Invoke the target function */
SREM_EM(&st, b, Y1, DIC, subind1, beta, *betabar_data, betabar_size, Sigma_s,
tau, EM_iter, MAP_iter, b0, beta0, *betabar0_data, betabar0_size,
Sigma_s0, &tau0, sum_U);
/* Marshall function outputs */
plhs[0] = b_emlrt_marshallOut(b0);
plhs[1] = c_emlrt_marshallOut(beta0);
plhs[2] = d_emlrt_marshallOut(*betabar0_data, betabar0_size);
plhs[3] = e_emlrt_marshallOut(Sigma_s0);
plhs[4] = emlrt_marshallOut(tau0);
plhs[5] = f_emlrt_marshallOut(sum_U);
sum_U->canFreeData = false;
emxFree_real_T(&sum_U);
Sigma_s0->canFreeData = false;
emxFree_real_T(&Sigma_s0);
beta0->canFreeData = false;
emxFree_real_T(&beta0);
b0->canFreeData = false;
emxFree_real_T(&b0);
Sigma_s->canFreeData = false;
emxFree_real_T(&Sigma_s);
beta->canFreeData = false;
emxFree_real_T(&beta);
subind1->canFreeData = false;
emxFree_real_T(&subind1);
DIC->canFreeData = false;
emxFree_real_T(&DIC);
Y1->canFreeData = false;
emxFree_real_T(&Y1);
b->canFreeData = false;
emxFree_real_T(&b);
emlrtHeapReferenceStackLeaveFcnR2012b(&st);
}
/* End of code generation (_coder_SREM_EM_api.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/sum.c
/*
* sum.c
*
* Code generation for function 'sum'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "sum.h"
#include "SREM_EM_emxutil.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRTEInfo r_emlrtRTEI = { 1, 14, "sum",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\sum.m"
};
/* Function Definitions */
void sum(const emlrtStack *sp, const emxArray_real_T *x, emxArray_real_T *y)
{
int32_T sz[2];
int32_T vstride;
int32_T iy;
int32_T ixstart;
int32_T j;
int32_T ix;
real_T s;
int32_T k;
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
st.site = &m_emlrtRSI;
b_st.prev = &st;
b_st.tls = st.tls;
b_st.site = &n_emlrtRSI;
for (vstride = 0; vstride < 2; vstride++) {
sz[vstride] = x->size[vstride];
}
vstride = y->size[0];
y->size[0] = sz[0];
emxEnsureCapacity(&b_st, (emxArray__common *)y, vstride, (int32_T)sizeof
(real_T), &b_emlrtRTEI);
if ((x->size[0] == 0) || (x->size[1] == 0)) {
vstride = y->size[0];
y->size[0] = sz[0];
emxEnsureCapacity(&b_st, (emxArray__common *)y, vstride, (int32_T)sizeof
(real_T), &r_emlrtRTEI);
iy = sz[0];
for (vstride = 0; vstride < iy; vstride++) {
y->data[vstride] = 0.0;
}
} else {
vstride = x->size[0];
iy = -1;
ixstart = -1;
for (j = 1; j <= vstride; j++) {
ixstart++;
ix = ixstart;
s = x->data[ixstart];
for (k = 2; k <= x->size[1]; k++) {
ix += vstride;
s += x->data[ix];
}
iy++;
y->data[iy] = s;
}
}
}
/* End of code generation (sum.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/exp.c
/*
* exp.c
*
* Code generation for function 'exp'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "exp.h"
/* Function Definitions */
void b_exp(emxArray_real_T *x)
{
int32_T i23;
int32_T k;
i23 = x->size[0] * x->size[1];
for (k = 0; k < i23; k++) {
x->data[k] = muDoubleScalarExp(x->data[k]);
}
}
void c_exp(emxArray_real_T *x)
{
int32_T i24;
int32_T k;
i24 = x->size[0] * 3;
for (k = 0; k < i24; k++) {
x->data[k] = muDoubleScalarExp(x->data[k]);
}
}
void d_exp(real_T x_data[], int32_T x_size[1])
{
int32_T i25;
int32_T k;
i25 = x_size[0];
for (k = 0; k < i25; k++) {
x_data[k] = muDoubleScalarExp(x_data[k]);
}
}
/* End of code generation (exp.c) */
<file_sep>/subfuns/codegen/mex/SREM_EM/SREM_EM_data.h
/*
* SREM_EM_data.h
*
* Code generation for function 'SREM_EM_data'
*
*/
#ifndef __SREM_EM_DATA_H__
#define __SREM_EM_DATA_H__
/* Include files */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "mwmathutil.h"
#include "tmwtypes.h"
#include "mex.h"
#include "emlrt.h"
#include "blas.h"
#include "rtwtypes.h"
#include "SREM_EM_types.h"
/* Variable Declarations */
extern const volatile char_T *emlrtBreakCheckR2012bFlagVar;
extern emlrtRSInfo l_emlrtRSI;
extern emlrtRSInfo m_emlrtRSI;
extern emlrtRSInfo n_emlrtRSI;
extern emlrtRSInfo p_emlrtRSI;
extern emlrtRSInfo q_emlrtRSI;
extern emlrtRSInfo cb_emlrtRSI;
extern emlrtRSInfo db_emlrtRSI;
extern emlrtRSInfo eb_emlrtRSI;
extern emlrtRSInfo pb_emlrtRSI;
extern emlrtRSInfo bc_emlrtRSI;
extern emlrtRSInfo cc_emlrtRSI;
extern emlrtRSInfo dc_emlrtRSI;
extern emlrtRSInfo ec_emlrtRSI;
extern emlrtRSInfo fc_emlrtRSI;
extern emlrtRSInfo gc_emlrtRSI;
extern emlrtRSInfo hc_emlrtRSI;
extern emlrtRSInfo ic_emlrtRSI;
extern emlrtRSInfo jc_emlrtRSI;
extern emlrtRSInfo kc_emlrtRSI;
extern emlrtRSInfo lc_emlrtRSI;
extern emlrtRSInfo mc_emlrtRSI;
extern emlrtRSInfo nc_emlrtRSI;
extern emlrtRSInfo oc_emlrtRSI;
extern emlrtRSInfo sc_emlrtRSI;
extern emlrtRSInfo tc_emlrtRSI;
extern emlrtRSInfo uc_emlrtRSI;
extern emlrtRSInfo wc_emlrtRSI;
extern emlrtRSInfo xc_emlrtRSI;
extern emlrtRSInfo rd_emlrtRSI;
extern emlrtRSInfo yd_emlrtRSI;
extern emlrtRSInfo ae_emlrtRSI;
extern emlrtRSInfo ge_emlrtRSI;
extern emlrtRSInfo ie_emlrtRSI;
extern emlrtRSInfo je_emlrtRSI;
extern emlrtRSInfo ke_emlrtRSI;
extern emlrtRSInfo le_emlrtRSI;
extern emlrtRSInfo me_emlrtRSI;
extern emlrtRSInfo ue_emlrtRSI;
extern emlrtMCInfo d_emlrtMCI;
extern emlrtMCInfo g_emlrtMCI;
extern emlrtMCInfo h_emlrtMCI;
extern emlrtMCInfo i_emlrtMCI;
extern emlrtMCInfo j_emlrtMCI;
extern emlrtMCInfo k_emlrtMCI;
extern emlrtMCInfo l_emlrtMCI;
extern emlrtRTEInfo b_emlrtRTEI;
extern emlrtRTEInfo j_emlrtRTEI;
extern emlrtRSInfo cf_emlrtRSI;
extern emlrtRSInfo ef_emlrtRSI;
extern emlrtRSInfo ff_emlrtRSI;
extern emlrtRSInfo gf_emlrtRSI;
extern emlrtRSInfo lf_emlrtRSI;
extern emlrtRSInfo mf_emlrtRSI;
extern emlrtRSInfo nf_emlrtRSI;
#endif
/* End of code generation (SREM_EM_data.h) */
<file_sep>/subfuns/codegen/mex/SREM_EM/std.c
/*
* std.c
*
* Code generation for function 'std'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "SREM_EM.h"
#include "std.h"
#include "eml_error.h"
#include "SREM_EM_data.h"
/* Variable Definitions */
static emlrtRSInfo ob_emlrtRSI = { 12, "std",
"D:\\Program Files\\MATLAB\\R2014b\\toolbox\\eml\\lib\\matlab\\datafun\\std.m"
};
/* Function Definitions */
real_T b_std(const emlrtStack *sp, const real_T varargin_1[3])
{
int32_T ix;
real_T xbar;
int32_T k;
real_T r;
real_T x;
emlrtStack st;
emlrtStack b_st;
st.prev = sp;
st.tls = sp->tls;
b_st.prev = &st;
b_st.tls = st.tls;
ix = 0;
xbar = varargin_1[0];
for (k = 0; k < 2; k++) {
ix++;
xbar += varargin_1[ix];
}
xbar /= 3.0;
ix = 0;
r = varargin_1[0] - xbar;
x = r * r;
for (k = 0; k < 2; k++) {
ix++;
r = varargin_1[ix] - xbar;
x += r * r;
}
x /= 2.0;
st.site = &ob_emlrtRSI;
if (x < 0.0) {
b_st.site = &pb_emlrtRSI;
eml_error(&b_st);
}
return muDoubleScalarSqrt(x);
}
/* End of code generation (std.c) */
<file_sep>/README.md
# GHMM_nD
This GHMM_nD package is developed by <NAME> and <NAME> from the [BIG-S2 lab](http://odin.mdacc.tmc.edu/bigs2/) and <NAME> from the [uncbiag lab](https://github.com/uncbiag/).
Gaussian hidden Markov model (nD) is a Matlab based package for statistical nD (n=2,3) imaging spatial heterogeneity analysis. A Gaussian hidden Markov model is introduced to build the spatial heterogeneity of imaging intensity across different patients. The statistical inference results are used in diseased region detection in both personal level and populational level.
# Command Script
We provide a command script (GHMM_nD_scp.m) to run the data analysis with GHMM_nD. Please see the file GHMM_nD_scp.m for usage. We also provide some simulated 3D imaging dataset for testing the package.
# GUI Interface
This toolbox is written in a user-friendly GUI interface. Here are some explainations of the interface:
1. Load raw data
In this panel, you need to select (a). the folder where mask data (mask file, mat format) is stored; (b). the file containing the covariate matrix (could be either txt format or mat format); (c). the folder where imaging dataset (mat format) is stored
2. Clear & Run
In this panel, you need to select the folder where to save all the output files. The 'Clear' button help you to clear all the preselcted input information, and the 'Run' button is clicked when all the input information is selected and the analysis is ready to go.
3. Export Results
In this panel, you can plot the results you are interested in.
| ac11f47415ddd35c97e0dcc0fb5e470569c83402 | [
"Markdown",
"C"
] | 27 | C | chaohstat/GHMM_nD | 00feb3c1ccf7e75e6efe1ebd05d5f5249014ae2c | 5a10b8bec7abf7fe42d564ff65fb695fdec8df14 |
refs/heads/master | <file_sep>export default class FreePokemon {
constructor(data) {
this.name = data.name;
this.url = data.url;
}
get FreePokemonTemplate() {
return /*html*/ `
<button onclick="app.pokemonController.viewPokemonAsync('${this.url}')" class="btn mb-1">${this.name}</button>`;
}
}
<file_sep>export default class Pokemon {
constructor(data) {
this._id = data.id;
this.name = data.name;
this.img = data.img || data.sprites.front_default;
this.weight = data.weight;
this.height = data.height;
this.types = data.types;
}
get Template() {
return /*html*/ `
<img id="pokemon-img" src="${this.img}" alt="" />
<h3>${this.name}</h3>
<p>${this.height} m, ${this.weight} kg</p>
<button onclick="app.pokemonController.catchPokemon(${this._id})" class="btn btn-success">Catch!</button>
`;
}
}
<file_sep>import store from "../store.js";
import FreePokemon from "../Models/FreePokemon.js";
import Pokemon from "../Models/Pokemon.js";
let _pokemonApi = axios.create({
baseURL: "https://pokeapi.co/api/v2",
timeout: 3000
});
let _pokemonDetailApi = axios.create({
baseURL: "",
timeout: 3000
});
let _sandBox = axios.create({
baseURL: "https://bcw-sandbox.herokuapp.com/api/Jenny/pokemon",
timeout: 3000
});
class PokemonService {
constructor() {}
async findPokemonAsync() {
let res = await _pokemonApi.get("pokemon?limit=20");
let freePokemon = res.data.results.map(p => new FreePokemon(p));
store.commit("freePokemon", freePokemon);
}
async viewPokemonAsync(url) {
let res = await _pokemonDetailApi.get(url);
console.log(res);
let selectedPokemon = [res.data].map(p => new Pokemon(p));
store.commit("pokemon", selectedPokemon);
}
catchPokemon(id) {
console.log(id);
let desiredPokemon = store.State.pokemon.find(p => p._id == id);
console.log("one to catch:", desiredPokemon);
_sandBox
.post("", desiredPokemon)
.then(res => {
let pokemon = [...store.State.pokemon, desiredPokemon];
store.commit("pokemon", pokemon);
})
.catch(e => {
throw e;
});
}
}
const service = new PokemonService();
export default service;
<file_sep>import PokemonService from "../Services/PokemonService.js";
import store from "../store.js";
//Private
function _drawFreePokemon() {
let template = "";
let pokemon = store.State.freePokemon;
console.log("free pokemon:", pokemon);
pokemon.forEach(p => (template += p.FreePokemonTemplate));
document.getElementById("free-pokemon").innerHTML = template;
}
function _drawSelectedPokemon() {
let template = "";
let pokemon = store.State.pokemon;
pokemon.forEach(p => (template = p.Template));
document.getElementById("selected-pokemon").innerHTML = template;
}
//Public
export default class PokemonController {
constructor() {
store.subscribe("freePokemon", _drawFreePokemon);
store.subscribe("pokemon", _drawSelectedPokemon);
}
async findPokemonAsync() {
event.preventDefault();
try {
await PokemonService.findPokemonAsync();
} catch (e) {
console.error(e);
}
}
async viewPokemonAsync(url) {
event.preventDefault();
console.log(url);
try {
await PokemonService.viewPokemonAsync(url);
} catch (e) {
console.error(e);
}
}
catchPokemon(id) {
event.preventDefault();
PokemonService.catchPokemon(id);
}
}
| b33a061fe3b1c2dfe55096710d5fcf094ff85700 | [
"JavaScript"
] | 4 | JavaScript | ricejl/pokedex | a205708e20120a330930f21606f1e2bf8bcf1876 | 2cddde9981375360555727fd12f4d540d1b232fb |
refs/heads/master | <repo_name>StephenOrJames/python-http-client<file_sep>/setup.py
import sys
import os
from setuptools import setup
long_description = 'Please see our GitHub README'
if os.path.exists('README.txt'):
long_description = open('README.txt').read()
def getRequires():
deps = []
if (2, 6) <= sys.version_info < (2, 7):
deps.append('unittest2')
return deps
base_url = 'https://github.com/sendgrid/'
version = '3.0.0'
setup(
name='python_http_client',
version=version,
author='<NAME>',
author_email='<EMAIL>',
url='{0}python-http-client'.format(base_url),
download_url='{0}python-http-client/tarball/{1}'.format(base_url, version),
packages=['python_http_client'],
license='MIT',
description='HTTP REST client, simplified for Python',
long_description=long_description,
install_requires=getRequires(),
keywords=[
'REST',
'HTTP',
'API'],
classifiers=[
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
]
)
<file_sep>/register.py
import pypandoc
import os
output = pypandoc.convert('README.md', 'rst')
f = open('README.txt','w+')
f.write(output)
f.close()
readme_rst = open('./README.txt').read()
replace = '[SendGrid Logo]\n(https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png)'
replacement = '|SendGrid Logo|\n\n.. |SendGrid Logo| image:: https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png\n :target: https://www.sendgrid.com'
final_text = readme_rst.replace(replace,replacement)
with open('./README.txt', 'w') as f:
f.write(final_text)<file_sep>/CHANGELOG.md
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [3.0.0] - 2017-08-11
### BREAKING CHANGE
- The breaking change actually happened in [version 2.3.0](https://github.com/sendgrid/python-http-client/releases/tag/v2.3.0), which I mistakenly applied a minor version bump.
- This version replaces error handling via HTTPError from urllib in favor of custom error handling via the [HTTPError class](https://github.com/sendgrid/python-http-client/blob/master/python_http_client/exceptions.py).
## [2.4.0] - 2017-07-03
### Added
- #19 Added support for slash. Created "to_dict" property in response object and exception class.
- Thanks [<NAME>](https://github.com/MrLucasCardoso)!
## [2.3.0] - 2017-06-20
### Added
- #17 Added support for error handling
- Thanks [<NAME>](https://github.com/dibyadas)!
## [2.2.1] - 2016-08-10
### Fixed
- When Content-Type is not application/json, do not JSON encode the request body
## [2.2.0] - 2016-08-10
### Added
- Ability to set the Content-Type header
## [2.1.1] - 2016-07-08
### Fixed
- [Allow multiple values for a parameter](https://github.com/sendgrid/python-http-client/pull/11)
- Thanks [<NAME>](https://github.com/chrishenry)!
## [2.1.0] - 2016-06-03
### Added
- Automatically add Content-Type: application/json when there is a request body
## [2.0.0] - 2016-06-03
### Changed
- Made the Response variables non-redundant. e.g. response.response_body becomes response.body
## [1.2.4] - 2016-03-02
### Fixed
- Getting README to display in PyPi
## [1.2.3] - 2016-03-01
### Added
- Can now reuse part of the chaining construction for multiple urls/requests
- Thanks to [<NAME>](https://github.com/extemporalgenome)!
- Update of request headers simplified
- Thanks to [<NAME>](https://github.com/mbernier)
## [1.1.3] - 2016-02-29
### Fixed
- Various standardizations for commenting, syntax, pylint
- Thanks to [<NAME>](https://github.com/iandouglas)!
## [1.1.2] - 2016-02-29
### Fixed
- Fixed TypeError in Python 3+ for data encoding
## [1.1.1] - 2016-02-25
### Updated
- Tests no longer require a mock server [#5](https://github.com/sendgrid/python-http-client/pull/5)
## [1.1.0] - 2016-02-25
### Fixed
- Config paths
## [1.0.2] - 2016-02-25
### Fixed
- Config paths
## [1.0.1] - 2016-02-25
### Fixed
- Imports
## [1.0.0] - 2016-02-25
### Added
- We are live! | c27624835f000d23b27fcfe3b074610a9061c20d | [
"Markdown",
"Python"
] | 3 | Python | StephenOrJames/python-http-client | f4cfe2a9bcb1b326bbd3ae8b8c5bc5a3385e380e | 835741ae60fd3caa022adaf93b3c070bf89442cf |
refs/heads/main | <file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 11 September 2020 */
/*********************************************************************************/
#ifndef CAN_INTERFACE_H
#define CAN_INTERFACE_H
typedef enum{
CAN0 = 0,
CAN1
}CAN_channel ;
typedef enum{
NormalMode,
LoopbackMode,
SilentMode,
LoopbackWithSilentMode
}CAN_Mode ;
typedef struct
{
u8 BaudRatePrescaler_BRP ;
u8 TimeSegmentBeforeSamplePoint_TSEG1 ;
u8 TimeSegmentAfterSamplePoint_TSEG2 ;
u8 SynchronizationJumpWidth_SJW ;
}BitTiming_Parameter ;
typedef enum
{
/* status interrupt has the highest priority */
Status_Interrupt = 0,
Error_Interrupt,
All_Interrupts
}Interrupt_Type ;
typedef enum
{
Enable_FIFO,
Disable_FIFO
}FIFO_Mode ;
typedef struct
{
// The CAN message identifier used for 11 or 29 bit identifiers.
u32 copy_u32MsgID ;
// The message identifier mask used when identifier filtering is enabled.
u32 copy_u32MsgIDMask ;
// This value holds 1 for Extended Frame and 0 for standard frame.
u8 copy_u8ExtendedFrameFlag ;
// filter on the extended ID bit : This value holds 1 for Filter Extended Frame and 0 no effect on the acceptance filtering
u8 copy_u8FilterExtendedIdentifierFlag ;
//0 no effect of acceptance filtering on Msg direction, 1 acceptance filtering effected on Msg direction
u8 copy_u8FilterMsgDirectionFlag ;
// This value is the number of bytes of data in the message object.
u32 copy_u32MsgLength ;
// This is a pointer to the message object's data.
u8 *pointer_MsgData ;
}CAN_MassegeObject ;
/* PUBLIC FUNCTIONS */
void CAN_voidInit(CAN_channel channelNumber,CAN_Mode WorkingMode,BitTiming_Parameter *BitRateParameter);
void CAN_voidInterruptEnable(CAN_channel channelNumber , Interrupt_Type copy_IntType) ;
void CAN_voidInterruptDisable(CAN_channel channelNumber , Interrupt_Type copy_IntType) ;
u8 CAN_u8TransmitMessageObjectSync(CAN_channel channelNumber,u32 copy_u32ObjID , CAN_MassegeObject *psMsgObject , FIFO_Mode copy_FIFOStatues);
u8 CAN_u8TransmitMessageObjectAsync(CAN_channel channelNumber,u32 copy_u32ObjID , CAN_MassegeObject *psMsgObject , FIFO_Mode copy_FIFOStatues,void(*callBack)(void));
u8 CAN_u8RecieveMessageObjectAsync(CAN_channel channelNumber,u32 copy_u32ObjID , CAN_MassegeObject *psMsgObject , FIFO_Mode copy_FIFOStatues,void(*callBack)(void));
u8 CAN_u8RecieveMessageObjectSync(CAN_channel channelNumber,u32 copy_u32ObjID , CAN_MassegeObject *psMsgObject , FIFO_Mode copy_FIFOStatues);
u8 CAN_u8ErrorCounterGet (CAN_channel channelNumber , u8 *p_u8TX_Count, u8 *p_u8RX_Count);
#endif
<file_sep>/**********************************************************************/
/* Author : <NAME> */
/* Date : 15 Aug 2021 */
/* Version : V01 */
/********************************************************************/
#include "BIT_MATH.h"
#include "STD_TYPES.h"
#include "uart_interface.h"
#include "uart_private.h"
#include "uart_config.h"
#define WAIT_TO_TRANSMIT (GET_BIT(UART0FR,5) == 0)
#define WAIT_TO_RECEIVE (GET_BIT(UART0FR,4) == 0)
static void (*Callback_RX_UART0) (u8) = NULL ;
static void (*Callback_TX_UART0) (void) = NULL ;
static volatile u8 Global_u8Data ;
void UART_voidInit(UART_CHANNEL channel,u16 copy_u16BaudRate,UART_PARITY Parity,UART_STOPBIT stopBitType,UART_FIFO FIFO_mode, u8 copy_u8FrameLength)
{
float global_floatBaudDivisor ;
u16 global_u16IntBaudDivisor ;
if(channel == UART1)
{
// Enable the UART module
SET_BIT(UARTx_RCGCUART, UART1) ;
// Enable the clock to the appropriate GPIO
// FOR UART1 PA0 RX , PA1 TX
SET_BIT(UARTx_RCGCGPIO,PORTA);
/* UART0 TX0 and RX0 use PA0 and PA1. Set them up. */
// Make PA0 and PA1 as digital
SET_BIT(GPIOADEN,0);
SET_BIT(GPIOADEN,1);
// Use PA0,PA1 alternate function
SET_BIT(GPIOAFSEL,0);
SET_BIT(GPIOAFSEL,1);
// configure PA0 and PA1 for UART
SET_BIT(GPIOPCTL,0);
SET_BIT(GPIOPCTL,4);
/* Baud Rate Configuration. */
global_floatBaudDivisor = ((F_CPU*1.0)/(copy_u16BaudRate*1.0))*16.0 ;
global_u16IntBaudDivisor = (u16)global_floatBaudDivisor ;
UART0IBRD = global_u16IntBaudDivisor ;
global_u16IntBaudDivisor =((global_floatBaudDivisor-global_u16IntBaudDivisor)*64)+0.5;
UART0FBRD = global_u16IntBaudDivisor ;
/* ENABLE UART0,TX and RX0 */
SET_BIT(UART0CTL,0); //Enable Clear To Send
SET_BIT(UART0CTL,8);
SET_BIT(UART0CTL,9);
/* Parity */
switch(Parity)
{
case EVEN_PARITY :
SET_BIT(UART0LCRH,1);
SET_BIT(UART0LCRH,2);
break ;
case ODD_PARITY:
SET_BIT(UART0LCRH,1);
CLR_BIT(UART0LCRH,2);
break ;
case DISABLE_PARITY:
CLR_BIT(UART0LCRH,1);
break ;
default:
break;
}
/* STOP BIT */
switch(stopBitType)
{
case ONE_STOP_BIT :
CLR_BIT(UART0LCRH,3);
break ;
case TWO_STOP_BIT :
SET_BIT(UART0LCRH,3);
break ;
default:
break;
}
/* FIFO_mode */
switch(FIFO_mode)
{
case ENABLE_FIFO : SET_BIT(UART0LCRH,4); break;
case DISABLE_FIFO: CLR_BIT(UART0LCRH,4);break;
default:
break;
}
/* Frame Length */
switch(copy_u8FrameLength)
{
case FRAME_LENGTH_5_BIT :
CLR_BIT(UART0LCRH,5);
CLR_BIT(UART0LCRH,6);
break ;
case FRAME_LENGTH_6_BIT :
SET_BIT(UART0LCRH,5);
CLR_BIT(UART0LCRH,6);
break ;
case FRAME_LENGTH_7_BIT :
CLR_BIT(UART0LCRH,5);
SET_BIT(UART0LCRH,6);
break ;
case FRAME_LENGTH_8_BIT :
SET_BIT(UART0LCRH,5);
SET_BIT(UART0LCRH,6);
break ;
default:
break;
}
}
else if (channel == UART2)
{
}
else if (channel == UART3){}
else if (channel == UART4){}
else if (channel == UART5){}
else if (channel == UART6){}
else if (channel == UART7){}
else
{
//<!TODO ERROR> Wrong Channel Selection
}
}
void UART_voidControl(UART_CHANNEL channel,u8 copy_u8State)
{
switch (channel)
{
case UART1 :
switch(copy_u8State)
{
case ENABLE : SET_BIT(UART0CTL,0); break ;
case DISABLE :CLR_BIT(UART0CTL,0); break ;
default : break ;
}
break ;
case UART2 : break ;
case UART3 : break ;
case UART4 : break ;
case UART5 : break ;
case UART6 : break ;
case UART7 : break ;
default : break;
}
}
u8 UARTx_charReceiverSynch(UART_CHANNEL channel)
{
u8 data = 0;
switch (channel)
{
case UART1 :
/* wait until Rx buffer is not empty */
while(WAIT_TO_RECEIVE);
data = UART0DR ;
data = data & 0xFF;
break ;
case UART2 : break ;
case UART3 : break ;
case UART4 : break ;
case UART5 : break ;
case UART6 : break ;
case UART7 : break ;
}
return data ;
}
void UARTx_charReceiverAsynch(UART_CHANNEL channel,void(*callBack)(u8))
{
// Store the call back function address.
Callback_RX_UART0 = callBack ;
// Enable receiver interrupt.
SET_BIT(UART0IM,4);
}
void UARTx_voidTransmitterSynch(UART_CHANNEL channel,char TransmittedData)
{
/* wait until Rx buffer is not full */
while(WAIT_TO_TRANSMIT);
UART0DR = TransmittedData ;
}
void UARTx_voidTransmitterAsynch(UART_CHANNEL channel,char TransmittedData,void(*callBack)(void))
{
// Store the call back function address.
Callback_TX_UART0 = callBack ;
// Enable receiver interrupt.
SET_BIT(UART0IM,5);
Global_u8Data = TransmittedData ;
}
void __vector_5(void)
{
//know whats making interrupt
if((GET_BIT(UART0RIS,4))) // INTRRUPT FROM RECIVING
{
//Writing a 1 to this bit clears the RXRIS bit in the UARTRIS register
SET_BIT(UART0ICR,4);
Callback_RX_UART0((0xFF)& UART0DR);
}
else if((GET_BIT(UART0RIS,5)))// INTRRUPT FROM TRANSIMTTED
{
//Writing a 1 to this bit clears the RXRIS bit in the UARTRIS register
SET_BIT(UART0ICR,5);
UART0DR = Global_u8Data ;
Callback_TX_UART0();
}
}
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 27 August 2020 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "SCB_interface.h"
#include "SCB_private.h"
#include "SCB_config.h"
u32 SCB_u32PriorityInit()
{
u32 LOC_u32RegisterValue = 0;
LOC_u32RegisterValue = SCB_AIRCR_VECT_KEY +0x0+ SCB_GROUP_SUB_SELECTION + 0x00 ;
SCB_AIRCR = LOC_u32RegisterValue ;
return LOC_u32RegisterValue ;
}
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 2 September 2020 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "SSI_interface.h"
#include "SSI_private.h"
#include "SSI_config.h"
#define TX_FIFO_NOT_FULL(SSIx) while((GET_BIT(SSIx,SSI_SR_TNF)) == 0){}
#define RX_FIFO_NOT_FULL(SSIx) while((GET_BIT(SSIx,SSI_SR_RFF)) == 1){}
#define BUS_BUSY(SSIx) while((GET_BIT(SSIx,SSI_SR_BSY)) == 1){}
static void (*Callback_RX_SSI0) (u16) = NULL ;
static void (*Callback_TX_SSI0) (void) = NULL ;
static void (*Callback_TX_SSI1) (void) = NULL ;
static void (*Callback_TX_SSI2) (void) = NULL ;
static void (*Callback_TX_SSI3) (void) = NULL ;
u8 global_u8TX_RX_State = 0 ;
void SSI_voidInit(SSI_Channel copy_SSIChennal,SSI_Mode copy_workingMode,SSI_CLK_Mode copy_CLKSelection,u8 copy_u8BaudRate,SSI_Protocol_Mode copy_protocolMode,u8 copy_u8DataSize)
{
u8 global_u8SerialCLKRate ;
switch(copy_SSIChennal)
{
case SSI0:
/* SSE bit in the SSICR1 register is clear before making any configuration changes. */
CLR_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
/* Select whether the SSI is a master or slave */
switch(copy_workingMode)
{
case Slave : SET_BIT(SSI0_module->SSICR1,SSI_CR1_MS); break;
case Master : CLR_BIT(SSI0_module->SSICR1,SSI_CR1_MS); break;
}
/* Configure the SSI clock source by writing to the SSICC register */
switch(copy_CLKSelection)
{
case SysCLK :
SSI0_module->SSICC = SYSTEM_CLK ;
break ;
case PIOSC :
SSI0_module->SSICC = PIOS_CLK ;
break ;
}
/* Configure the clock prescale divisor by writing the SSICPSR register */
if(SSI0_CLK_PRESCALER%2==0 && SSI0_CLK_PRESCALER>=2 && SSI0_CLK_PRESCALER <= 254)
{
SSI0_module->SSICPSR = (0xFF&SSI0_CLK_PRESCALER);
}
else
{
//<!TODO ERROR>
}
/* Write the SSICR0 register with the following configuration */
global_u8SerialCLKRate = (SYS_CLK/(copy_u8BaudRate*SSI0_CLK_PRESCALER))-1 ;
if(global_u8SerialCLKRate>=0 && global_u8SerialCLKRate <=255)
{
SSI0_module->SSICR0 = global_u8SerialCLKRate << 8 ;
}else
{
//<!TODO ERROR>
}
#if SSI0_IDLE_STATE == IDLE_HIGH
SET_BIT(SSI0_module->SSICR0,SSI_CR0_SPO);
#elif SSI0_IDLE_STATE == IDLE_LOW
CLR_BIT(SSI0_module->SSICR0,SSI_CR0_SPO);
#else
#error ("Wrong SSI_CR0_SPO Selection")
#endif
// Set Phase
#if SSI0_DATA_CAPTURING == CAPTURE_AT_FIRST_CLK_EDGE
CLR_BIT(SSI0_module->SSICR0,SSI_CR0_SPH);
#elif SSI0_DATA_CAPTURING == CAPTURE_AT_SECOND_CLK_EDGE
SET_BIT(SSI0_module->SSICR0,SSI_CR0_SPH);
#endif
// set Protocol Mode
switch(copy_protocolMode)
{
case SPI :
CLR_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_4);
CLR_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_5);
break ;
case TI_SSF :
CLR_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_5);
break;
case MICROWIRE:
SET_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_5);
break;
}
if(copy_u8DataSize>=4 && copy_u8DataSize<=16)
{
SSI0_module->SSICR0 |= (0xFF & copy_u8DataSize) ;
}
else
{
//<!TODO ERROR>
}
/* Enable the SSI by setting the SSE bit in the SSICR1 register. */
SET_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
break;
case SSI1: break;
case SSI2: break;
case SSI3: break;
}
}
void SSI_voidDisable(SSI_Channel copy_SSIChennal)
{
switch(copy_SSIChennal)
{
case SSI0:
CLR_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI1:
CLR_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI2:
CLR_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI3:
CLR_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
break ;
}
}
void SSI_voidEnable(SSI_Channel copy_SSIChennal)
{
switch(copy_SSIChennal)
{
case SSI0:
SET_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI1:
SET_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI2:
SET_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI3:
SET_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
break ;
}
}
void SSI_voidChangeSSIMode(SSI_Channel copy_SSIChennal,SSI_Mode copy_workingMode)
{
u8 global_u8SerialCLKRate ;
switch(copy_SSIChennal)
{
case SSI0:
CLR_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
switch(copy_workingMode)
{
case Slave : SET_BIT(SSI0_module->SSICR1,SSI_CR1_MS); break;
case Master : CLR_BIT(SSI0_module->SSICR1,SSI_CR1_MS); break;
}
SET_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI1:
CLR_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
switch(copy_workingMode)
{
case Slave : SET_BIT(SSI1_module->SSICR1,SSI_CR1_MS); break;
case Master : CLR_BIT(SSI1_module->SSICR1,SSI_CR1_MS); break;
}
SET_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI2:
CLR_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
switch(copy_workingMode)
{
case Slave : SET_BIT(SSI2_module->SSICR1,SSI_CR1_MS); break;
case Master : CLR_BIT(SSI2_module->SSICR1,SSI_CR1_MS); break;
}
SET_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI3:
CLR_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
switch(copy_workingMode)
{
case Slave : SET_BIT(SSI3_module->SSICR1,SSI_CR1_MS); break;
case Master : CLR_BIT(SSI3_module->SSICR1,SSI_CR1_MS); break;
}
SET_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
break ;
}
}
void SSI_voidChangeBuadRate(SSI_Channel copy_SSIChennal,u8 copy_u8BaudRate)
{
u8 global_u8SerialCLKRate ;
switch(copy_SSIChennal)
{
case SSI0:
CLR_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
/* Write the SSICR0 register with the following configuration */
global_u8SerialCLKRate = (SYS_CLK/(copy_u8BaudRate*SSI0_CLK_PRESCALER))-1 ;
if(global_u8SerialCLKRate>=0 && global_u8SerialCLKRate <=255)
{
SSI0_module->SSICR0 = global_u8SerialCLKRate << 8 ;
}else
{
//<!TODO ERROR>
}
SIT_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI1:
CLR_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
/* Write the SSICR0 register with the following configuration */
global_u8SerialCLKRate = (SYS_CLK/(copy_u8BaudRate*SSI1_CLK_PRESCALER))-1 ;
if(global_u8SerialCLKRate>=0 && global_u8SerialCLKRate <=255)
{
SSI1_module->SSICR0 = global_u8SerialCLKRate << 8 ;
}else
{
//<!TODO ERROR>
}
SET_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI2:
CLR_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
/* Write the SSICR0 register with the following configuration */
global_u8SerialCLKRate = (SYS_CLK/(copy_u8BaudRate*SSI2_CLK_PRESCALER))-1 ;
if(global_u8SerialCLKRate>=0 && global_u8SerialCLKRate <=255)
{
SSI2_module->SSICR0 = global_u8SerialCLKRate << 8 ;
}else
{
//<!TODO ERROR>
}
SET_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI3:
CLR_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
/* Write the SSICR0 register with the following configuration */
global_u8SerialCLKRate = (SYS_CLK/(copy_u8BaudRate*SSI3_CLK_PRESCALER))-1 ;
if(global_u8SerialCLKRate>=0 && global_u8SerialCLKRate <=255)
{
SSI3_module->SSICR0 = global_u8SerialCLKRate << 8 ;
}else
{
//<!TODO ERROR>
}
CLR_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
break ;
}
}
void SSI_voidChangeProtocol(SSI_Channel copy_SSIChennal,SSI_Protocol_Mode copy_protocolMode)
{
switch(copy_SSIChennal)
{
case SSI0:
CLR_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
switch(copy_protocolMode)
{
case SPI :
CLR_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_4);
CLR_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_5);
break ;
case TI_SSF :
CLR_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_5);
break;
case MICROWIRE:
SET_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI0_module->SSICR0 , SSI_CR0_FRF_5);
break;
}
SET_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI1:
CLR_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
switch(copy_protocolMode)
{
case SPI :
CLR_BIT(SSI1_module->SSICR0 , SSI_CR0_FRF_4);
CLR_BIT(SSI1_module->SSICR0 , SSI_CR0_FRF_5);
break ;
case TI_SSF :
CLR_BIT(SSI1_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI1_module->SSICR0 , SSI_CR0_FRF_5);
break;
case MICROWIRE:
SET_BIT(SSI1_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI1_module->SSICR0 , SSI_CR0_FRF_5);
break;
}
SET_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI2:
CLR_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
switch(copy_protocolMode)
{
case SPI :
CLR_BIT(SSI2_module->SSICR0 , SSI_CR0_FRF_4);
CLR_BIT(SSI2_module->SSICR0 , SSI_CR0_FRF_5);
break ;
case TI_SSF :
CLR_BIT(SSI2_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI2_module->SSICR0 , SSI_CR0_FRF_5);
break;
case MICROWIRE:
SET_BIT(SSI2_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI2_module->SSICR0 , SSI_CR0_FRF_5);
break;
}
SET_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI3:
CLR_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
switch(copy_protocolMode)
{
case SPI :
CLR_BIT(SSI3_module->SSICR0 , SSI_CR0_FRF_4);
CLR_BIT(SSI3_module->SSICR0 , SSI_CR0_FRF_5);
break ;
case TI_SSF :
CLR_BIT(SSI3_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI3_module->SSICR0 , SSI_CR0_FRF_5);
break;
case MICROWIRE:
SET_BIT(SSI3_module->SSICR0 , SSI_CR0_FRF_4);
SET_BIT(SSI3_module->SSICR0 , SSI_CR0_FRF_5);
break;
}
SET_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
break ;
}
}
void SSI_voidChangeDataSize(SSI_Channel copy_SSIChennal,u8 copy_u8DataSize)
{
switch(copy_SSIChennal)
{
case SSI0:
CLR_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
if(copy_u8DataSize>=4 && copy_u8DataSize<=16)
{
SSI0_module->SSICR0 |= (0xFF & copy_u8DataSize) ;
}
else
{
//<!TODO ERROR>
}
SET_BIT(SSI0_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI1:
CLR_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
if(copy_u8DataSize>=4 && copy_u8DataSize<=16)
{
SSI1_module->SSICR0 |= (0xFF & copy_u8DataSize) ;
}
else
{
//<!TODO ERROR>
}
SET_BIT(SSI1_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI2:
CLR_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
if(copy_u8DataSize>=4 && copy_u8DataSize<=16)
{
SSI2_module->SSICR0 |= (0xFF & copy_u8DataSize) ;
}
else
{
//<!TODO ERROR>
}
SET_BIT(SSI2_module->SSICR1,SSI_CR1_SSE);
break ;
case SSI3:
CLR_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
if(copy_u8DataSize>=4 && copy_u8DataSize<=16)
{
SSI3_module->SSICR0 |= (0xFF & copy_u8DataSize) ;
}
else
{
//<!TODO ERROR>
}
SET_BIT(SSI3_module->SSICR1,SSI_CR1_SSE);
break ;
}
}
void SSI_voidEnableInt(SSI_Channel copy_SSIChennal ,Interrupt_Type copy_IntType)
{
switch(copy_SSIChennal)
{
case SSI0:
switch(copy_IntType)
{
case Receive_Overrun_Interrupt : SET_BIT(SSI0_module->SSIIM , SSI_IM_RORIM); break ;
case Receive_TimeOut_Interrupt : SET_BIT(SSI0_module->SSIIM , SSI_IM_RTIM); break ;
case Receive_FIFO_Interrupt : SET_BIT(SSI0_module->SSIIM , SSI_IM_RXIM); break ;
case Transmit_FIFO_Interrupt : SET_BIT(SSI0_module->SSIIM , SSI_IM_TXIM); break ;
case All_Interrupts :
SET_BIT(SSI0_module->SSIIM , SSI_IM_RORIM);
SET_BIT(SSI0_module->SSIIM , SSI_IM_RTIM);
SET_BIT(SSI0_module->SSIIM , SSI_IM_RXIM);
SET_BIT(SSI0_module->SSIIM , SSI_IM_TXIM);
break ;
}
break;
case SSI1:
switch(copy_IntType)
{
case Receive_Overrun_Interrupt : SET_BIT(SSI1_module->SSIIM , SSI_IM_RORIM); break ;
case Receive_TimeOut_Interrupt : SET_BIT(SSI1_module->SSIIM , SSI_IM_RTIM); break ;
case Receive_FIFO_Interrupt : SET_BIT(SSI1_module->SSIIM , SSI_IM_RXIM); break ;
case Transmit_FIFO_Interrupt : SET_BIT(SSI1_module->SSIIM , SSI_IM_TXIM); break ;
case All_Interrupts :
SET_BIT(SSI1_module->SSIIM , SSI_IM_RORIM);
SET_BIT(SSI1_module->SSIIM , SSI_IM_RTIM);
SET_BIT(SSI1_module->SSIIM , SSI_IM_RXIM);
SET_BIT(SSI1_module->SSIIM , SSI_IM_TXIM);
break ;
}
break;
case SSI2:
switch(copy_IntType)
{
case Receive_Overrun_Interrupt : SET_BIT(SSI2_module->SSIIM , SSI_IM_RORIM); break ;
case Receive_TimeOut_Interrupt : SET_BIT(SSI2_module->SSIIM , SSI_IM_RTIM); break ;
case Receive_FIFO_Interrupt : SET_BIT(SSI2_module->SSIIM , SSI_IM_RXIM); break ;
case Transmit_FIFO_Interrupt : SET_BIT(SSI2_module->SSIIM , SSI_IM_TXIM) ;break ;
case All_Interrupts :
SET_BIT(SSI2_module->SSIIM , SSI_IM_RORIM);
SET_BIT(SSI2_module->SSIIM , SSI_IM_RTIM);
SET_BIT(SSI2_module->SSIIM , SSI_IM_RXIM);
SET_BIT(SSI2_module->SSIIM , SSI_IM_TXIM);
break ;
}
break;
case SSI3:
switch(copy_IntType)
{
case Receive_Overrun_Interrupt : SET_BIT(SSI3_module->SSIIM , SSI_IM_RORIM); break ;
case Receive_TimeOut_Interrupt : SET_BIT(SSI3_module->SSIIM , SSI_IM_RTIM); break ;
case Receive_FIFO_Interrupt : SET_BIT(SSI3_module->SSIIM , SSI_IM_RXIM); break ;
case Transmit_FIFO_Interrupt : SET_BIT(SSI3_module->SSIIM , SSI_IM_TXIM); break ;
case All_Interrupts :
SET_BIT(SSI3_module->SSIIM , SSI_IM_RORIM);
SET_BIT(SSI3_module->SSIIM , SSI_IM_RTIM);
SET_BIT(SSI3_module->SSIIM , SSI_IM_RXIM);
SET_BIT(SSI3_module->SSIIM , SSI_IM_TXIM);
break ;
}
break;
}
}
void SSI_voidDisableInt(SSI_Channel copy_SSIChennal ,Interrupt_Type copy_IntType)
{
switch(copy_SSIChennal)
{
case SSI0:
switch(copy_IntType)
{
case Receive_Overrun_Interrupt : CLR_BIT(SSI0_module->SSIIM , SSI_IM_RORIM); break ;
case Receive_TimeOut_Interrupt : CLR_BIT(SSI0_module->SSIIM , SSI_IM_RTIM); break ;
case Receive_FIFO_Interrupt : CLR_BIT(SSI0_module->SSIIM , SSI_IM_RXIM); break ;
case Transmit_FIFO_Interrupt : CLR_BIT(SSI0_module->SSIIM , SSI_IM_TXIM) ;break ;
case All_Interrupts :
CLR_BIT(SSI0_module->SSIIM , SSI_IM_RORIM);
CLR_BIT(SSI0_module->SSIIM , SSI_IM_RTIM);
CLR_BIT(SSI0_module->SSIIM , SSI_IM_RXIM);
CLR_BIT(SSI0_module->SSIIM , SSI_IM_TXIM);
break ;
}
break;
case SSI1:
switch(copy_IntType)
{
case Receive_Overrun_Interrupt : CLR_BIT(SSI1_module->SSIIM , SSI_IM_RORIM); break ;
case Receive_TimeOut_Interrupt : CLR_BIT(SSI1_module->SSIIM , SSI_IM_RTIM); break ;
case Receive_FIFO_Interrupt : CLR_BIT(SSI1_module->SSIIM , SSI_IM_RXIM); break ;
case Transmit_FIFO_Interrupt : CLR_BIT(SSI1_module->SSIIM , SSI_IM_TXIM); break ;
case All_Interrupts :
CLR_BIT(SSI1_module->SSIIM , SSI_IM_RORIM);
CLR_BIT(SSI1_module->SSIIM , SSI_IM_RTIM);
CLR_BIT(SSI1_module->SSIIM , SSI_IM_RXIM);
CLR_BIT(SSI1_module->SSIIM , SSI_IM_TXIM);
break ;
}
break;
case SSI2:
switch(copy_IntType)
{
case Receive_Overrun_Interrupt : CLR_BIT(SSI2_module->SSIIM , SSI_IM_RORIM); break ;
case Receive_TimeOut_Interrupt : CLR_BIT(SSI2_module->SSIIM , SSI_IM_RTIM); break ;
case Receive_FIFO_Interrupt : CLR_BIT(SSI2_module->SSIIM , SSI_IM_RXIM); break ;
case Transmit_FIFO_Interrupt : CLR_BIT(SSI2_module->SSIIM , SSI_IM_TXIM); break ;
case All_Interrupts :
CLR_BIT(SSI2_module->SSIIM , SSI_IM_RORIM);
CLR_BIT(SSI2_module->SSIIM , SSI_IM_RTIM);
CLR_BIT(SSI2_module->SSIIM , SSI_IM_RXIM);
CLR_BIT(SSI2_module->SSIIM , SSI_IM_TXIM);
break ;
}
break;
case SSI3:
switch(copy_IntType)
{
case Receive_Overrun_Interrupt : CLR_BIT(SSI3_module->SSIIM , SSI_IM_RORIM); break ;
case Receive_TimeOut_Interrupt : CLR_BIT(SSI3_module->SSIIM , SSI_IM_RTIM); break ;
case Receive_FIFO_Interrupt : CLR_BIT(SSI3_module->SSIIM , SSI_IM_RXIM); break ;
case Transmit_FIFO_Interrupt : CLR_BIT(SSI3_module->SSIIM , SSI_IM_TXIM); break ;
case All_Interrupts :
CLR_BIT(SSI3_module->SSIIM , SSI_IM_RORIM);
CLR_BIT(SSI3_module->SSIIM , SSI_IM_RTIM);
CLR_BIT(SSI3_module->SSIIM , SSI_IM_RXIM);
CLR_BIT(SSI3_module->SSIIM , SSI_IM_TXIM);
break ;
}
break;
}
}
void SSI_voidTransmitSynch(SSI_Channel copy_SSIChennal ,u16 copy_u16DataBeTransmited)
{
/* Must Select the slave by making active-low slave select line low GPIOA->DATA */
switch(copy_SSIChennal)
{
case SSI0:
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI0_module->SSISR);
SSI0_module->SSIDR = (copy_u16DataBeTransmited);
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI0_module->SSISR);
break ;
case SSI1:
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI1_module->SSISR);
SSI1_module->SSIDR = (copy_u16DataBeTransmited);
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI1_module->SSISR);
break ;
case SSI2:
/* Wait Until Buss Be IDLE */
BUS_BUSY(SSI1_module->SSISR);
SSI1_module->SSIDR = (copy_u16DataBeTransmited);
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI1_module->SSISR);
break ;
case SSI3:
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI3_module->SSISR);
SSI3_module->SSIDR = (copy_u16DataBeTransmited);
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI2_module->SSISR);
break ;
}
// Must Deselect the slave
}
void SSI_voidTransmitAsynch(SSI_Channel copy_SSIChennal ,u16 copy_u16DataBeTransmited,void(*callBack)(u8))
{
global_u8TX_RX_State = 1 ;
/* Must Select the slave by making active-low slave select line low GPIOA->DATA */
switch(copy_SSIChennal)
{
case SSI0:
Callback_TX_SSI0 = callBack ;
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI0_module->SSISR);
/* Enable Transmit_FIFO_Interrupt */
SSI_voidEnableInt(SSI0,Transmit_FIFO_Interrupt);
/* Transmit DATA */
SSI0_module->SSIDR = (copy_u16DataBeTransmited);
break ;
case SSI1:
Callback_TX_SSI1 = callBack ;
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI1_module->SSISR);
/* Enable Transmit_FIFO_Interrupt */
SSI_voidEnableInt(SSI1,Transmit_FIFO_Interrupt);
/* Transmit DATA */
SSI1_module->SSIDR = (copy_u16DataBeTransmited);
break ;
case SSI2:
Callback_TX_SSI2 = callBack ;
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI2_module->SSISR);
/* Enable Transmit_FIFO_Interrupt */
SSI_voidEnableInt(SSI2,Transmit_FIFO_Interrupt);
/* Transmit DATA */
SSI2_module->SSIDR = (copy_u16DataBeTransmited);
break ;
case SSI3:
Callback_TX_SSI3 = callBack ;
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI3_module->SSISR);
/* Enable Transmit_FIFO_Interrupt */
SSI_voidEnableInt(SSI3,Transmit_FIFO_Interrupt);
/* Transmit DATA */
SSI3_module->SSIDR = (copy_u16DataBeTransmited);
break ;
}
// Must Deselect the slave
}
u16 SSI_voidRecieveSynch(SSI_Channel copy_SSIChennal)
{
u16 local_u16DataBeRecieved = 0 ;
switch(copy_SSIChennal)
{
case SSI0 :
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI0_module->SSISR);
local_u16DataBeRecieved = SSI0_module->SSIDR ;
break ;
case SSI1 :
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI1_module->SSISR);
local_u16DataBeRecieved = SSI1_module->SSIDR ;
break ;
case SSI2 :
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI2_module->SSISR);
local_u16DataBeRecieved = SSI2_module->SSIDR ;
break ;
case SSI3 :
/* Wait Until Buss Be IDLE*/
BUS_BUSY(SSI3_module->SSISR);
local_u16DataBeRecieved = SSI3_module->SSIDR ;
break ;
}
return local_u16DataBeRecieved;
}
void __vector_7(void)
{
if(global_u8TX_RX_State == 1 )
{
// TRANSMIT
Callback_TX_UART0();
global_u8TX_RX_State=0;
}
else if(global_u8TX_RX_State == 2 )
{
//RECIEVE
global_u8TX_RX_State =0 ;
}
SET_BIT(SSI0_module->SSIICR , SSI_ICR_RTIC ) ;
SET_BIT(SSI0_module->SSIICR , SSI_ICR_RORIC ) ;
}
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 27 August 2020 */
/*********************************************************************************/
#ifndef SCB_CONFIG_H
#define SCB_CONFIG_H
/*
*SCB_GROUP_SUB_SELECTION : FOR DETERMINE NUMBER OF GROUPS AND SUBGROUPS
OPTIONS :
SCB_16_GROUP_0_SUB
SCB_8_GROUP_2_SUB
SCB_4_GROUP_4_SUB
SCB_2_GROUP_8_SUB
SCB_0_GROUP_16_SUB
*/
#define SCB_GROUP_SUB_SELECTION SCB_16_GROUP_0_SUB
#endif
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 26 August 2020 */
/*********************************************************************************/
#ifndef NVIC_PRIVATE_H
#define NVIC_PRIVATE_H
#define NVIC_BASE_ADDRESS 0xE000E100
/* REGISTER BOUNDARY ADDRESSES */
#define NVIC_ISER ((volatile u32 *)(NVIC_BASE_ADDRESS + 0x000))
#define NVIC_ICER ((volatile u32 *)(NVIC_BASE_ADDRESS + 0x080))
#define NVIC_ISPR ((volatile u32 *)(NVIC_BASE_ADDRESS + 0x100))
#define NVIC_ICPR ((volatile u32 *)(NVIC_BASE_ADDRESS + 0x180))
#define NVIC_IABR ((volatile u32 *)(NVIC_BASE_ADDRESS + 0x200))
#define NVIC_IPR ((volatile u32 *)(NVIC_BASE_ADDRESS + 0x300))
#define NVIC_STIR ((volatile u32 *)(NVIC_BASE_ADDRESS + 0xE00))
#endif
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 2 September 2020 */
/*********************************************************************************/
#ifndef I2C_PRIVATE_H
#define I2C_PRIVATE_H
/******************************************************************************
* Reg Description
*******************************************************************************/
#define I2C0_BASE_ADDRESS 0x40020000
#define I2C1_BASE_ADDRESS 0x40021000
#define I2C2_BASE_ADDRESS 0x40022000
#define I2C3_BASE_ADDRESS 0x40023000
/* Offsets */
//Master
#define I2CMSA 0x000
#define I2CMCS 0x004
#define I2CMDR 0x008
#define I2CMTPR 0x00C
#define I2CMIMR 0x010
#define I2CMRIS 0x014
#define I2CMMIS 0x018
#define I2CMICR 0x01C
#define I2CMCR 0x020
#define I2CMCLKOCNT 0x024
#define I2CMBMON 0x02C
#define I2CMCR2 0x038
//Slave
#define I2CSOAR 0x800
#define I2CSCSR 0x804
#define I2CSDR 0x808
#define I2CSIMR 0x80C
#define I2CSRIS 0x810
#define I2CSMIS 0x814
#define I2CSICR 0x818
#define I2CSOAR2 0x81C
#define I2CSACKCTL 0x820
//Common
#define I2CPP 0xFC0
#define I2CPC 0xFC4
#define I2C0_I2CMCR *((volatile u32 * ) (I2C0_BASE_ADDRESS+I2CMCR))
#define I2C0_I2CMTPR *((volatile u32 * ) (I2C0_BASE_ADDRESS+I2CMTPR))
#define I2C0_I2CMSA *((volatile u32 * ) (I2C0_BASE_ADDRESS+I2CMSA))
#define I2C0_I2CMCS *((volatile u32 * ) (I2C0_BASE_ADDRESS+I2CMCS))
#define I2C0_I2CMDR *((volatile u32 * ) (I2C0_BASE_ADDRESS+I2CMDR ))
#define I2C0_I2CSOAR *((volatile u32 * ) (I2C0_BASE_ADDRESS+I2CSOAR ))
#define I2C0_I2CSCSR *((volatile u32 * ) (I2C0_BASE_ADDRESS+I2CSCSR ))
/******************************************************************************
* Configuration Constants
*******************************************************************************/
#define DISABLE 0
#define ENABLE 1
#define SCL_LP 6
#define SCL_HP 4
#define ENABLE_MASTER SET_BIT(I2C0_I2CMCR,I2C_MCR_MFE)
#define DISABLE_MASTER CLR_BIT(I2C0_I2CMCR,I2C_MCR_MFE)
#define ENABLE_SLAVE SET_BIT(I2C0_I2CMCR,I2C_MCR_SFE)
#define DISABLE_SLAVE CLR_BIT(I2C0_I2CMCR,I2C_MCR_SFE)
#define TPR_EQN(SPEED) (SYS_CLK/(2*(SCL_LP + SCL_HP)*SPEED))-1
#define Standard_speed 100000
#define FastMode_speed 400000
#define FastMode_Plus_speed 1000000
#define High_speed 3330000
//*****************************************************************************
//
// The following are defines for the bit fields in the I2C_O_MCR register.
//
//*****************************************************************************
#define I2C_MCR_GFE 6 // I2C Glitch Filter Enable
#define I2C_MCR_SFE 5 // I2C Slave Function Enable
#define I2C_MCR_MFE 4 // I2C Master Function Enable
#define I2C_MCR_LPBK 0 // I2C Loopback
//*****************************************************************************
//
// The following are defines for the bit fields in the I2C_O_MSA register.
//
//*****************************************************************************
#define I2C_MSA_R_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the I2C_O_MCS register.
//
//*****************************************************************************
#define I2C_MCS_CLKTO 7 // Clock Timeout Error
#define I2C_MCS_BUSBSY 6 // Bus Busy
#define I2C_MCS_IDLE 5 // I2C Idle
#define I2C_MCS_ARBLST 4 // Arbitration Lost
#define I2C_MCS_DATACK 3 // Acknowledge Data
#define I2C_MCS_ADRACK 2 // Acknowledge Address
#define I2C_MCS_ERROR 1 // Error
#define I2C_MCS_BUSY 0 // I2C Busy
//*****************************************************************************
//
// The following are defines for the bit fields in the I2C_O_MCS register.
//
//*****************************************************************************
#define I2C_MCS_HS 4 // High-Speed Enable
#define I2C_MCS_ACK 3 // Data Acknowledge Enable
#define I2C_MCS_STOP 2 // Generate STOP
#define I2C_MCS_START 1 // Generate START
#define I2C_MCS_RUN 0 // I2C Master Enable
/* IRQs */
void __vector_8(void) __attribute__(( signal , used )); //I2C0
void __vector_37(void) __attribute__(( signal , used )); //I2C1
void __vector_68(void) __attribute__(( signal , used )); //I2C2
void __vector_69(void) __attribute__(( signal , used )); //I2C3
#endif
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 26 August 2020 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "NVIC_interface.h"
#include "NVIC_private.h"
#include "NVIC_config.h"
#include "SCB_interface.h"
void NVIC_voidEnableInterrupt ( u8 Copy_u8IntNumber )
{
if(Copy_u8IntNumber <= 31)
{
SET_BIT(NVIC_ISER[0] , Copy_u8IntNumber );
}
else if (Copy_u8IntNumber <= 59 )
{
Copy_u8IntNumber -= 32 ;
SET_BIT(NVIC_ISER[1] , Copy_u8IntNumber );
}
else
{
/* <TODO> ERROR OUT OF INTERRUPT NUMBERS */
}
}
void NVIC_voidDisableInterrupt ( u8 Copy_u8IntNumber )
{
if(Copy_u8IntNumber <= 31)
{
SET_BIT(NVIC_ICER[0] , Copy_u8IntNumber );
}
else if (Copy_u8IntNumber <= 59 )
{
Copy_u8IntNumber -= 32 ;
SET_BIT(NVIC_ICER[1] , Copy_u8IntNumber );
}
else
{
/* <TODO> ERROR OUT OF INTERRUPT NUMBERS */
}
}
void NVIC_voidSetPenddingFlag ( u8 Copy_u8IntNumber )
{
if(Copy_u8IntNumber <= 31)
{
SET_BIT(NVIC_ISPR[0] , Copy_u8IntNumber );
}
else if (Copy_u8IntNumber <= 59 )
{
Copy_u8IntNumber -= 32 ;
SET_BIT(NVIC_ISPR[1] , Copy_u8IntNumber );
}
else
{
/* <TODO> ERROR OUT OF INTERRUPT NUMBERS */
}
}
void NVIC_voidClearPenddingFlag( u8 Copy_u8IntNumber )
{
if(Copy_u8IntNumber <= 31)
{
SET_BIT(NVIC_ICPR[0] , Copy_u8IntNumber );
}
else if (Copy_u8IntNumber <= 59 )
{
Copy_u8IntNumber -= 32 ;
SET_BIT(NVIC_ICPR[1] , Copy_u8IntNumber );
}
else
{
/* <TODO> ERROR OUT OF INTERRUPT NUMBERS */
}
}
u8 NVIC_u8GetInterruptStatus ( u8 Copy_u8IntNumber )
{
u8 LOC_u8ActiveBitStatues = 0 ;
if(Copy_u8IntNumber <= 31)
{
LOC_u8ActiveBitStatues = GET_BIT(NVIC_IABR[0] , Copy_u8IntNumber );
}
else if (Copy_u8IntNumber <= 59 )
{
Copy_u8IntNumber -= 32 ;
LOC_u8ActiveBitStatues = GET_BIT(NVIC_IABR[1] , Copy_u8IntNumber );
}
else
{
/* <TODO> ERROR OUT OF INTERRUPT NUMBERS */
}
return LOC_u8ActiveBitStatues ;
}
void NVIC_voidSetPeriority(u8 Copy_u8IntNumber , u8 Copy_u8GroupPriority , u8 Copy_u8SubGroupPriority)
{
u8 LOC_u8SetIprRegValue = 0 ;
u32 LOC_u32NumOfGrousAndSub = SCB_u32PriorityInit();
/* Copy_u8GroupPriority<<((NO - 0x05FA0300 ) / 0x100 To get Number of bits of sub group */
LOC_u8SetIprRegValue = Copy_u8SubGroupPriority | (Copy_u8GroupPriority<<((LOC_u32NumOfGrousAndSub - 0x05FA0300 ) / 0x100 ) );
if (Copy_u8IntNumber < 60 )
{
NVIC_IPR[Copy_u8IntNumber] = (LOC_u8SetIprRegValue << 4 );
}
else
{
/* <TODO> ERROR OUT OF INTERRUPT NUMBERS */
}
}
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 2 September 2020 */
/*********************************************************************************/
#ifndef SSI_PRIVATE_H
#define SSI_PRIVATE_H
typedef struct
{
volatile u32 SSICR0 ; //SSI Control 0
volatile u32 SSICR1 ; //SSI Control 1
volatile u32 SSIDR ; //SSI Data
volatile u32 SSISR ; //SSI Status
volatile u32 SSICPSR ; //SSI Clock Prescale
volatile u32 SSIIM ; //SSI Interrupt Mask
volatile u32 SSIRIS ; //SSI Raw Interrupt Status
volatile u32 SSIMIS ; //SSI DMA Control
volatile u32 SSIICR ; //SSI DMA Control
volatile u32 SSIDMACTL ; //SSI DMA Control
volatile u32 SSICC ; //SSI Clock Configuration
volatile u32 SSIPeriphID4 ; //SSI PrimeCell Identification 4
volatile u32 SSIPeriphID5 ; //SSI PrimeCell Identification 5
volatile u32 SSIPeriphID6 ; //SSI PrimeCell Identification 6
volatile u32 SSIPeriphID7 ; //SSI PrimeCell Identification 7
volatile u32 SSIPeriphID0 ; //SSI PrimeCell Identification 0
volatile u32 SSIPeriphID1 ; //SSI PrimeCell Identification 1
volatile u32 SSIPeriphID2 ; //SSI PrimeCell Identification 2
volatile u32 SSIPeriphID3 ; //SSI PrimeCell Identification 3
volatile u32 SSIPCellID0 ; //SSI PrimeCell Identification 0
volatile u32 SSIPCellID1 ; //SSI PrimeCell Identification 1
volatile u32 SSIPCellID2 ; //SSI PrimeCell Identification 2
volatile u32 SSIPCellID3 ; //SSI PrimeCell Identification 3
}SSI_Registers;
#define SSI0_module ((volatile SSI_Registers *)0x40008000)
#define SSI1_module ((volatile SSI_Registers *)0x40009000)
#define SSI2_module ((volatile SSI_Registers *)0x4000A000)
#define SSI3_module ((volatile SSI_Registers *)0x4000B000)
/******************************************************************************
* Configuration Constants
*******************************************************************************/
#define MASTER_OPERATION 0x00000000
#define SLAVE_MOD_OP_ENABLE 0x00000004
#define SLAVE_MOD_OP_DISABLE 0x0000000C
#define SYSTEM_CLK 0x00000000
#define PIOS_CLK 0x00000005
#define IDLE_LOW 0
#define IDLE_HIGH 1
#define CAPTURE_AT_FIRST_CLK_EDGE 0
#define CAPTURE_AT_SECOND_CLK_EDGE 2
//*****************************************************************************
//
// The following are defines for the bit fields in the SSI_O_CR1 register.
//
//*****************************************************************************
#define SSI_CR1_EOT 4 // End of Transmission
#define SSI_CR1_MS 2 // SSI Master/Slave Select
#define SSI_CR1_SSE 1 // SSI Synchronous Serial Port
#define SSI_CR1_LBM 0 // SSI Loopback Mode
//*****************************************************************************
//
// The following are defines for the bit fields in the SSI_O_CR0 register.
//
//*****************************************************************************
#define SSI_CR0_SPH 7 // SSI Serial Clock Phase
#define SSI_CR0_SPO 6 // SSI Serial Clock Polarity
#define SSI_CR0_FRF_4 4 // Frame Format
#define SSI_CR0_FRF_5 5 // Frame Format
//*****************************************************************************
//
// The following are defines for the bit fields in the SSI_O_SR register.
//
//*****************************************************************************
#define SSI_SR_BSY 4 // SSI Busy Bit
#define SSI_SR_RFF 3 // SSI Receive FIFO Full
#define SSI_SR_RNE 2 // SSI Receive FIFO Not Empty
#define SSI_SR_TNF 1 // SSI Transmit FIFO Not Full
#define SSI_SR_TFE 0 // SSI Transmit FIFO Empty
//*****************************************************************************
//
// The following are defines for the bit fields in the SSI_O_IM register.
//
//*****************************************************************************
#define SSI_IM_TXIM 3 // SSI Transmit FIFO Interrupt Mask
#define SSI_IM_RXIM 2 // SSI Receive FIFO Interrupt Mask
#define SSI_IM_RTIM 1 // SSI Receive Time-Out Interrupt
#define SSI_IM_RORIM 0 // SSI Receive Overrun Interrupt
//*****************************************************************************
//
// The following are defines for the bit fields in the SSI_O_ICR register.
//
//*****************************************************************************
#define SSI_ICR_RTIC 1 // SSI Receive Time-Out Interrupt
#define SSI_ICR_RORIC 0 // SSI Receive Overrun Interrupt
/* IRQs */
void __vector_7(void) __attribute__(( signal , used )); //SSI0
void __vector_34(void) __attribute__(( signal , used )); //SSI0
void __vector_57(void) __attribute__(( signal , used )); //SSI0
void __vector_58(void) __attribute__(( signal , used )); //SSI0
#endif
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 2 September 2020 */
/*********************************************************************************/
#ifndef I2C_INTERFACE_H
#define I2C_INTERFACE_H
typedef enum
{
I2C0,
I2C1,
I2C2,
I2C3
}I2C_Chennal;
typedef enum
{
Master_Transmit,
Master_Receive,
Slave_Transmit,
Slave_Receive
}I2C_Mode;
typedef enum
{
Standard,
Fast_Mode,
Fast_Mode_Plus,
High_Speed_Mode
}Transmission_speeds;
/* PUBLIC FUNCTIONS */
void I2C_voidInit(I2C_Chennal copy_I2CChennalSelect, I2C_Mode copy_I2CModeSelect,Transmission_speeds copy_I2CSpeed,u8 copy_u8SalveAddress);
void I2C_voidMasterEnable(I2C_Chennal copy_I2CChennalSelect);
void I2C_voidMasterDisable(I2C_Chennal copy_I2CChennalSelect);
void I2C_voidMaterTransmitMassege(I2C_Chennal copy_I2CChennalSelect, u8 copy_u8Data);
u8 I2C_voidMaterRecieveMassege(I2C_Chennal copy_I2CChennalSelect);
void I2C_voidSlaveTransmitMassege(I2C_Chennal copy_I2CChennalSelect, u8 copy_u8Data);
u8 I2C_voidSlaveRecieveMassege(I2C_Chennal copy_I2CChennalSelect);
#endif
<file_sep>/*
* GccApplication2.cpp
*
* Created: 8/16/2021 2:28:52 PM
* Author : Abnaby
*/
#include "BIT_MATH.h"
#include "STD_TYPES.h"
#include "uart_interface.h"
#include "NVIC_interface.h"
void whenRecieve(u8);
int main(void)
{
/* I can't Extract UART IRQ in NVIC */
NVIC_voidEnableInterrupt(21);
/* Initialize UART1 with BuadRate 9600 , one stop bit, NO-FIFO and 8-bit frame length */
UART_voidInit(UART1 , 9600 , 2, TWO_STOP_BIT, DISABLE_FIFO, 8);
/* ENABLE UART1 */
UART_voidControl(UART1,DISABLE) ;
UARTx_charReceiverAsynch(UART1,whenRecieve);
while (1)
{
}
}
void whenRecieve(u8 data)
{
if(data >= 'a' && data <= 'z')
{
data = data - ('a' - 'A');
UARTx_voidTransmitterSynch(UART1,data);
}
else
{
data = data+1 ;
UARTx_voidTransmitterSynch(UART1,data);
}
}
<file_sep>/**********************************************************************/
/* Author : <NAME> */
/* Date : 15 Aug 2021 */
/* Version : V01 */
/********************************************************************/
#ifndef UART_INTERFACE_H_
#define UART_INTERFACE_H_
#define FRAME_LENGTH_5_BIT 0
#define FRAME_LENGTH_6_BIT 2
#define FRAME_LENGTH_7_BIT 4
#define FRAME_LENGTH_8_BIT 6
typedef enum {
ENABLE_INTRUPRTS,
DISAPLE_INTRUPRTS
}UART_INTERRUPT;
typedef enum{
UART1 = 0,
UART2,
UART3,
UART4,
UART5,
UART6,
UART7
}UART_CHANNEL;
typedef enum
{
EVEN_PARITY,
ODD_PARITY ,
DISABLE_PARITY
}UART_PARITY ;
typedef enum
{
ONE_STOP_BIT,
TWO_STOP_BIT
}UART_STOPBIT;
typedef enum
{
ENABLE_FIFO,
DISABLE_FIFO
}UART_FIFO;
#define DISABLE 0
#define ENABLE 1
void UART_voidInit(UART_CHANNEL channel,u16 copy_u16BaudRate,UART_PARITY Parity,UART_STOPBIT stopBitType,UART_FIFO FIFO_mode, u8 copy_u8FrameLength);
void UART_voidControl(UART_CHANNEL channel,u8 copy_u8State);
u8 UARTx_charReceiverSynch(UART_CHANNEL channel);
//
void UARTx_charReceiverAsynch(UART_CHANNEL channel,void(*callBack)(u8));
void UARTx_voidTransmitterSynch(UART_CHANNEL channel,char TransmittedData);
void UARTx_voidTransmitterAsynch(UART_CHANNEL channel,char TransmittedData,void(*callBack)(void));
#endif<file_sep>#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "I2C_interface.h"
int main(void)
{
/* FOR I2C ONLY */
I2C_voidInit(I2C0, Master_Transmit,Standard,0x05) ;
I2C_voidMasterEnable(I2C0);
I2C_voidMaterTransmitMassege(I2C0,'a');
while(1)
{
}
}
<file_sep>/********************************************************************/
/* Author : <NAME> */
/* Date : 15 Aug 2021 */
/* Version : V01 */
/* Description : Private UART Frame */
/********************************************************************/
#ifndef UART_PRIVATE_H_
#define UART_PRIVATE_H_
#define PORTA 0
#define PORTB 1
#define PORTC 2
#define PORTD 3
#define PORTE 4
#define PORTF 5
/******************************* UART Base Address ******************************/
#define UART0_BASE_ADDRESS 0x4000C000
#define UART1_BASE_ADDRESS 0x4000D000
#define UART2_BASE_ADDRESS 0x4000E000
#define UART3_BASE_ADDRESS 0x4000F000
#define UART4_BASE_ADDRESS 0x40010000
#define UART5_BASE_ADDRESS 0x40011000
#define UART6_BASE_ADDRESS 0x40012000
#define UART7_BASE_ADDRESS 0x40013000
#define UARTx_CLK_BASE_ADDRESS 0x400FE000
#define GPIO_CLK_BASE_ADDRESS 0x400FE000
#define PORTA_BASE_ADDRESS 0x40004000
#define PORTB_BASE_ADDRESS 0x40005000
#define PORTC_BASE_ADDRESS 0x40006000
#define PORTD_BASE_ADDRESS 0x40007000
#define PORTE_BASE_ADDRESS 0x40024000
#define PORTF_BASE_ADDRESS 0x40025000
#define NVIC_BASE_ADDRESS 0xE000E100
/******************************* UARTx Offesets ******************************/
#define UARTDR_OFFSET 0x000
#define UARTRSR_OFFSET 0x004
#define UARTECR_OFFSET 0x004
#define UARTFR_OFFSET 0x018
#define UARTILPR_OFFSET 0x020
#define UARTIBRD_OFFSET 0x024
#define UARTFBRD_OFFSET 0x028
#define UARTLCRH_OFFSET 0x02C
#define UARTCTL_OFFSET 0x030
#define UARTIFLS_OFFSET 0x034
#define UARTIM_OFFSET 0x038
#define UARTRIS_OFFSET 0x03C
#define UARTMIS_OFFSET 0x040
#define UARTICR_OFFSET 0x044
#define UARTDMACTL_OFFSET 0x048
#define UART9BITADDR_OFFSET 0x0A4
#define UART9BITAMASK_OFFSET 0x0A8
#define UARTPP_OFFSET 0xFC0
#define UARTCC_OFFSET 0xFC8
#define RCGCUART_OFFSET 0x618
#define RCGCGPIO_OFFSET 0x608
#define GPIODEN_OFFSET 0x51C
#define GPIOAFSEL_OFFSET 0x420
#define GPIOPCTL_OFFSET 0x52C
/******************************* Used UARTx Reg ******************************/
// Enable/Disable UART
#define UARTx_RCGCUART *((volatile u32 * ) (UARTx_CLK_BASE_ADDRESS+RCGCUART_OFFSET))
#define UARTx_RCGCGPIO *((volatile u32 * ) (GPIO_CLK_BASE_ADDRESS+RCGCGPIO_OFFSET))
#define GPIOADEN *((volatile u32 * ) (PORTA_BASE_ADDRESS+GPIODEN_OFFSET))
#define GPIOAFSEL *((volatile u32 * ) (PORTA_BASE_ADDRESS+GPIOAFSEL_OFFSET))
#define GPIOPCTL *((volatile u32 * ) (PORTA_BASE_ADDRESS+GPIOPCTL_OFFSET))
#define UART0IBRD *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTIBRD_OFFSET))
#define UART0FBRD *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTFBRD_OFFSET))
#define UART0CTL *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTCTL_OFFSET))
#define UARTL0CRH *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTLCRH_OFFSET))
#define UART0FR *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTFR_OFFSET))
#define UART0DR *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTDR_OFFSET))
#define UART0IM *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTIM_OFFSET))
#define UART0ICR *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTICR_OFFSET))
#define UART0RIS *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTRIS_OFFSET))
#define UART0LCRH *((volatile u32 * ) (UART0_BASE_ADDRESS+UARTRIS_OFFSET))
/* IRQs */
void __vector_5(void) __attribute__(( signal , used ));
#endif<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 2 September 2020 */
/*********************************************************************************/
#ifndef BIT_MATH_H
#define BIT_MATH_H
#define SET_BIT(VAR,BIT_NUM) VAR |= (1 << BIT_NUM)
#define CLR_BIT(VAR,BIT_NUM) VAR &= ~(1<<BIT_NUM)
#define TOG_BIT(VAR,BIT_NUM) VAR ^= (1 << BIT_NUM)
#define GET_BIT(VAR,BIT_NUM) VAR = ((1 >> BIT_NUM) & 1 )
#define NULL (void *)0
#endif
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 11 September 2020 */
/*********************************************************************************/
#ifndef CAN_PRIVATE_H
#define CAN_PRIVATE_H
typedef struct{
volatile u32 CANCTL ;
volatile u32 CANSTS ;
volatile u32 CANERR ;
volatile u32 CANBIT ;
volatile u32 CANINT ;
volatile u32 CANTST ;
volatile u32 CANBRPE ;
volatile u32 CANIF1CRQ ;
volatile u32 CANIF1CMSK ;
volatile u32 CANIF1MSK1 ;
volatile u32 CANIF1MSK2 ;
volatile u32 CANIF1ARB1 ;
volatile u32 CANIF1ARB2 ;
volatile u32 CANIF1MCTL ;
volatile u32 CANIF1DA1 ;
volatile u32 CANIF1DA2 ;
volatile u32 CANIF1DB1 ;
volatile u32 CANIF1DB2 ;
volatile u32 CANIF2CRQ ;
volatile u32 CANIF2CMSK ;
volatile u32 CANIF2MSK1 ;
volatile u32 CANIF2MSK2 ;
volatile u32 CANIF2ARB1 ;
volatile u32 CANIF2ARB2 ;
volatile u32 CANIF2MCTL ;
volatile u32 CANIF2DA1 ;
volatile u32 CANIF2DA2 ;
volatile u32 CANIF2DB1 ;
volatile u32 CANIF2DB2 ;
volatile u32 CANTXRQ1 ;
volatile u32 CANTXRQ2 ;
volatile u32 CANNWDA1 ;
volatile u32 CANNWDA2 ;
volatile u32 CANMSG1INT ;
volatile u32 CANMSG2INT ;
volatile u32 CANMSG1VAL ;
volatile u32 CANMSG2VAL ;
}CAN_Registers;
#define CAN0_Chennal ((volatile CAN_Registers *)0x40040000)
#define CAN1_Chennal ((volatile CAN_Registers *)0x40041000)
/******************************************************************************
* Configuration Constants
*******************************************************************************/
#define TX 0
#define TX_REMOTE 1
#define RX 3
#define RX_REMOTE 4
//*****************************************************************************
//
// This is the maximum number that can be stored as an 11bit Message
// identifier.
//
//*****************************************************************************
#define CAN_MAX_11BIT_MSG_ID 0x7ff
//*****************************************************************************
//
// ID Object maximum number and minmum number.
//
//*****************************************************************************
#define ID_OBJ_MAX 32
#define ID_OBJ_MIN 1
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_CTL register.
//
//*****************************************************************************
#define CAN_CTL_TEST 7 // Test Mode Enable
#define CAN_CTL_CCE 6 // Configuration Change Enable
#define CAN_CTL_DAR 5 // Disable Automatic-Retransmission
#define CAN_CTL_EIE 3 // Error Interrupt Enable
#define CAN_CTL_SIE 2 // Status Interrupt Enable
#define CAN_CTL_IE 1 // CAN Interrupt Enable
#define CAN_CTL_INIT 0 // Initialization
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_IF1CRQ register.
//
//*****************************************************************************
#define CAN_IF1CRQ_BUSY 15 // Busy Flag
#define CAN_IF1CRQ_MNUM_M 0x0000003F // Message Number
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_IF1CMSK register.
//
//*****************************************************************************
#define CAN_IF1CMSK_WRNRD 7 // Write, Not Read
#define CAN_IF1CMSK_MASK 6 // Access Mask Bits
#define CAN_IF1CMSK_ARB 5 // Access Arbitration Bits
#define CAN_IF1CMSK_CONTROL 4 // Access Control Bits
#define CAN_IF1CMSK_CLRINTPND 3 // Clear Interrupt Pending Bit
#define CAN_IF1CMSK_NEWDAT 2 // Access New Data
#define CAN_IF1CMSK_TXRQST 2 // Access Transmission Request
#define CAN_IF1CMSK_DATAA 1 // Access Data Byte 0 to 3
#define CAN_IF1CMSK_DATAB 0 // Access Data Byte 4 to 7
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_TST register.
//
//*****************************************************************************
#define CAN_TST_RX 7 // Receive Observation
#define CAN_TST_TX_H 6 // Transmit Control
#define CAN_TST_TX_L 5 // Transmit Control
#define CAN_TST_LBACK 4 // Loopback Mode
#define CAN_TST_SILENT 3 // Silent Mode
#define CAN_TST_BASIC 2 // Basic Mode
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_BIT register.
//
//*****************************************************************************
#define CAN_BIT_TSEG2_M 12 // Time Segment after Sample Point
#define CAN_BIT_TSEG1_M 8 // Time Segment Before Sample Point
#define CAN_BIT_SJW_M 6 // (Re)Synchronization Jump Width
#define CAN_BIT_BRP_M 0 // Baud Rate Prescaler
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_IF1MCTL register.
//
//*****************************************************************************
#define CAN_IF1MCTL_NEWDAT 15 // New Data
#define CAN_IF1MCTL_MSGLST 14 // Message Lost
#define CAN_IF1MCTL_INTPND 13 // Interrupt Pending
#define CAN_IF1MCTL_UMASK 12 // Use Acceptance Mask
#define CAN_IF1MCTL_TXIE 11 // Transmit Interrupt Enable
#define CAN_IF1MCTL_RXIE 10 // Receive Interrupt Enable
#define CAN_IF1MCTL_RMTEN 9 // Remote Enable
#define CAN_IF1MCTL_TXRQST 8 // Transmit Request
#define CAN_IF1MCTL_EOB 7 // End of Buffer
#define CAN_IF1MCTL_DLC_M 0x0000000F // Data Length Code
#define CAN_IF1MCTL_DLC_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_IF1ARB2 register.
//
//*****************************************************************************
#define CAN_IF1ARB2_MSGVAL 15 // Message Valid
#define CAN_IF1ARB2_XTD 14 // Extended Identifier
#define CAN_IF1ARB2_DIR 13 // Message Direction
#define CAN_IF1ARB2_ID_M 0x00001FFF // Message Identifier
#define CAN_IF1ARB2_ID_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_IF1MSK1 register.
//
//*****************************************************************************
#define CAN_IF1MSK1_IDMSK_M 0x0000FFFF // Identifier Mask
#define CAN_IF1MSK1_IDMSK_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_IF1MSK2 register.
//
//*****************************************************************************
#define CAN_IF1MSK2_MXTD 15 // Mask Extended Identifier
#define CAN_IF1MSK2_MDIR 14 // Mask Message Direction
#define CAN_IF1MSK2_IDMSK_M 0x00001FFF // Identifier Mask
#define CAN_IF1MSK2_IDMSK_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_IF1ARB1 register.
//
//*****************************************************************************
#define CAN_IF1ARB1_ID_M 0x0000FFFF // Message Identifier
#define CAN_IF1ARB1_ID_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_STS register.
//
//*****************************************************************************
#define CAN_STS_BOFF 7 // Bus-Off Status
#define CAN_STS_EWARN 6 // Warning Status
#define CAN_STS_EPASS 5 // Error Passive
#define CAN_STS_RXOK 4 // Received a Message Successfully
#define CAN_STS_TXOK 3 // Transmitted a Message Successfully
#define CAN_STS_LEC_M 0x00000007 // Last Error Code
#define CAN_STS_LEC_NONE 0x00000000 // No Error
#define CAN_STS_LEC_STUFF 0x00000001 // Stuff Error
#define CAN_STS_LEC_FORM 0x00000002 // Format Error
#define CAN_STS_LEC_ACK 0x00000003 // ACK Error
#define CAN_STS_LEC_BIT1 0x00000004 // Bit 1 Error
#define CAN_STS_LEC_BIT0 0x00000005 // Bit 0 Error
#define CAN_STS_LEC_CRC 0x00000006 // CRC Error
#define CAN_STS_LEC_NOEVENT 0x00000007 // No Event
//*****************************************************************************
//
// The following are defines for the bit fields in the CAN_O_ERR register.
//
//*****************************************************************************
#define CAN_ERR_RP 15 // Received Error Passive
#define CAN_ERR_REC_M 0x00007F00 // Receive Error Counter
#define CAN_ERR_TEC_M 0x000000FF // Transmit Error Counter
#define CAN_ERR_REC_S 8
#define CAN_ERR_TEC_S 0
/* Equations */
#define BRP_RANGE_CHECK(BRP_VALUE) (BRP_VALUE>= 0x00 && BRP_VALUE <= 0x03F)
#define SJW_RANGE_CHECK(SJW_VALUE) (SJW_VALUE>= 0x00 && SJW_VALUE <= 0x03)
#define TSEG1_RANGE_CHECK(TSEG1_VALUE) (TSEG1_VALUE>= 0x00 && TSEG1_VALUE <= 0x0F)
#define TSEG2_RANGE_CHECK(TSEG2_VALUE) (TSEG2_VALUE>= 0x00 && TSEG2_VALUE <= 0x07)
#define WAIT_BUS_BE_UNBUSY(CAN_IF2CRQ_Reg) while((GET_BIT(CAN_IF2CRQ_Reg,CAN_IF1CRQ_BUSY)) == 1)
#define SUCCESSFUL_MSG_OBJ_TRANSMISSION(CAN_CHENNAL_CANNWDA1_REG) (GET_BIT(CAN_CHENNAL_CANNWDA1_REG , 0) == 0)
#define NEW_DATA_AVAILABE(CAN_CHENNAL_MCTL_REG) ((GET_BIT(CAN_CHENNAL_MCTL_REG , CAN_IF1MCTL_NEWDAT)) == 1)
#define CHECK_DLC_IN_RANGE(value) (value >= 0x0 && value <= 0xF)
#define LOST_SOME_DATA(REG) (GET_BIT(REG,CAN_IF1MCTL_MSGLST) == 1 )
/* private fn */
static u8 CAN_u8MessageObjectConfig(u8 TX_RX_RM , CAN_MassegeObject *psMsgObject ,FIFO_Mode copy_FIFOStatues , u16 *local_u16CMSK ,u16 *copy_u16ArbReg1 , u16 *copy_u16ArbReg2, u16 *copy_u16MCTL,u16 *copy_u16MskReg1, u16 *copy_u16MskReg2 , u32 copy_u32ObjID );
static void CAN_voidMessageAsyncObjectConfig(u8 Tx_RX ,u16 *copy_u16MCTL );
static void CAN_voidReadDataHandling(u8 *pui8Data, u32 *pui32Register, u32 ui32Size);
static u8 CAN_u8RecieveMessageObjectConfig(CAN_channel channelNumber, CAN_MassegeObject *psMsgObject , u32 copy_u32ObjID );
static void CAN_voidWriteDataHandling(u8 *pu8Data, u32 *pu32Register, u32 ui32Size);
/* IRQs */
void __vector_39(void) __attribute__(( signal , used )); //CAN0
void __vector_40(void) __attribute__(( signal , used )); //CAN1
#endif
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 2 September 2020 */
/*********************************************************************************/
#ifndef SSI_INTERFACE_H
#define SSI_INTERFACE_H
typedef enum{
SSI0 = 0,
SSI1,
SSI2,
SSI3
}SSI_Channel ;
typedef enum{
Slave=0,
Master,
}SSI_Mode ;
typedef enum{
SysCLK=0,
PIOSC
}SSI_CLK_Mode ;
typedef enum
{
SPI=0,
TI_SSF,
MICROWIRE
}SSI_Protocol_Mode;
typedef enum
{
ENABLE,
DISABLE
}Interrupt_State ;
typedef enum
{
Receive_Overrun_Interrupt =0 ,
Receive_TimeOut_Interrupt,
Receive_FIFO_Interrupt,
Transmit_FIFO_Interrupt,
All_Interrupts
}Interrupt_Type;
/* PUBLIC FUNCTIONS */
void SSI_voidInit(SSI_Channel copy_SSIChennal,SSI_Mode copy_workingMode,SSI_CLK_Mode copy_CLKSelection,u8 copy_u8BaudRate,SSI_Protocol_Mode copy_protocolMode,u8 copy_u8DataSize);
void SSI_voidChangeBuadRate(SSI_Channel copy_SSIChennal,u8 copy_u8BaudRate);
void SSI_voidChangeDataSize(SSI_Channel copy_SSIChennal,u8 copy_u8DataSize);
void SSI_voidChangeProtocol(SSI_Channel copy_SSIChennal,SSI_Protocol_Mode copy_protocolMode);
void SSI_voidChangeSSIMode(SSI_Channel copy_SSIChennal,SSI_Mode copy_workingMode);
void SSI_voidDisable(SSI_Channel copy_SSIChennal);
void SSI_voidEnable(SSI_Channel copy_SSIChennal);
void SSI_voidEnableInt(SSI_Channel copy_SSIChennal ,Interrupt_Type copy_IntType);
void SSI_voidTransmitSynch(SSI_Channel copy_SSIChennal ,u16 copy_u16DataBeTransmited);
void SSI_voidTransmitAsynch(SSI_Channel copy_SSIChennal ,u16 copy_u16DataBeTransmited,void(*callBack)(u8));
u16 SSI_voidRecieveSynch(SSI_Channel copy_SSIChennal);
void SSI_voidDisableInt(SSI_Channel copy_SSIChennal ,Interrupt_Type copy_IntType);
#endif
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 12 September 2020
/* Descroption: Tx Example */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "CAN_interface.h"
/*
A counter that keeps track of the number of times the TX interrupt has
occurred, which should match the number of TX messages that were sent.
*/
volatile u32 Global_ui32MsgCount = 0;
void CAN_IntTxHandler(void);
int main(void)
{
/* peripheral clock must be enabled using the RCGC0 register */
/* the clock to the appropriate GPIO module must be enabled via the RCGC2 */
/* Set the GPIO AFSEL bits for the appropriate pins */
/* Set the GPIO AFSEL bits for the appropriate pins */
/* Make Msg Object */
CAN_MassegeObject CAN_Msg ;
u8 *MsgData ;
u32 u32MsgData ;
MsgData = (u8 *)&u32MsgData;
u8 Error = 1 ;
/* Initialize the message object that will be used for sending CAN */
CAN_Msg.copy_u32MsgID = 1 ;
CAN_Msg.copy_u32MsgIDMask = 0 ;
CAN_Msg.copy_u8ExtendedFrameFlag = 0 ;
CAN_Msg.copy_u8FilterExtendedIdentifierFlag = 0 ;
CAN_Msg.copy_u8FilterMsgDirectionFlag = 0 ;
CAN_Msg.copy_u32MsgLength = sizeof(MsgData);
CAN_Msg.pointer_MsgData = MsgData ;
/* Bit Timing Parameters For Bit Rate = 1000 */
BitTiming_Parameter CAN_TimingParmeters ;
CAN_TimingParmeters.BaudRatePrescaler_BRP = 1 ;
CAN_TimingParmeters.TimeSegmentBeforeSamplePoint_TSEG1 = 13 ;
CAN_TimingParmeters.TimeSegmentAfterSamplePoint_TSEG2 = 2 ;
CAN_TimingParmeters.SynchronizationJumpWidth_SJW = 1 ;
/* Init CAN Module */
CAN_voidInit(CAN0,NormalMode,&CAN_TimingParmeters);
/* Enable Statues And Error Interrupt */
CAN_voidInterruptEnable(CAN0,All_Interrupts);
/* Enable the CAN interrupt on the processor (NVIC). */
while(1)
{
/* Send the CAN message Asymch using object number 1 (not the same thing as CAN ID, which is also 1 in this example). */
Error = CAN_u8TransmitMessageObjectAsync(CAN0,1,&CAN_Msg,Enable_FIFO,CAN_IntTxHandler);
if(Error != 1)
{
Error = CAN_u8TransmitMessageObjectAsync(CAN0,1,&CAN_Msg,Enable_FIFO,CAN_IntTxHandler);
}
else
{
/* Get Next Byte To Transmit */
u32MsgData++;
}
}
//return 0;
}
void CAN_IntTxHandler(void)
{
Global_ui32MsgCount++ ;
}
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01.1 */
/* Date : 12 September 2020 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "CAN_interface.h"
#include "CAN_private.h"
#include "CAN_config.h"
static u8 global_u8TX_RX_State ;
static void (*Callback_TX_CAN0) (void) = NULL ;
static void (*Callback_TX_CAN1) (void) = NULL ;
static void (*Callback_RX_CAN0) (void) = NULL ;
static void (*Callback_RX_CAN1) (void) = NULL ;
#define CONFIG_MODE_ENABLE(CAN_CHENNAL) SET_BIT(CAN_CHENNAL , CAN_CTL_INIT)
#define CONFIG_MODE_DISABLE(CAN_CHENNAL) CLR_BIT(CAN_CHENNAL , CAN_CTL_INIT)
#define ENABLE_GLOBAL_INT(CAN_CHENNAL_CTL_REG) SET_BIT(CAN_CHENNAL_CTL_REG,CAN_CTL_IE)
#define DISABLE_GLOBAL_INT(CAN_CHENNAL_CTL_REG) CLR_BIT(CAN_CHENNAL_CTL_REG,CAN_CTL_IE)
void CAN_voidInit(CAN_channel channelNumber,CAN_Mode WorkingMode,BitTiming_Parameter *BitRateParameter)
{
switch(channelNumber)
{
case CAN0 :
/* Enter Configuration Mode */
CONFIG_MODE_ENABLE(CAN0_Chennal -> CANCTL);
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
/* Enter Mode*/
SET_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_TEST ) ;
switch(WorkingMode)
{
case NormalMode :
/* Normal Mode Selection As Basic Mode */
CLR_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_TEST ) ;
SET_BIT(CAN0_Chennal -> CANTST , CAN_TST_BASIC) ;
break ;
case LoopbackMode :
/* LoopbackMode Enable */
SET_BIT(CAN0_Chennal -> CANTST , CAN_TST_LBACK ) ;
break ;
case SilentMode :
/* in silent mode, the CAN controller does not transmit data but instead monitors the bus */
/* SilentMode Enable */
SET_BIT( CAN0_Chennal -> CANTST , CAN_TST_SILENT);
break ;
case LoopbackWithSilentMode :
/* LoopbackMode Enable */
SET_BIT(CAN0_Chennal -> CANTST , CAN_TST_LBACK ) ;
/* SilentMode Enable */
SET_BIT( CAN0_Chennal -> CANTST , CAN_TST_SILENT);
break ;
}
/* Setting the CCE bit to edit CANBIT Register */
SET_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_CCE) ;
/* SET BIT PARAMETERS */
if(TSEG2_RANGE_CHECK((BitRateParameter -> TimeSegmentAfterSamplePoint_TSEG2 )))
{CAN0_Chennal-> CANBIT = ((BitRateParameter -> TimeSegmentAfterSamplePoint_TSEG2 ) << CAN_BIT_TSEG2_M );}
else { /* <!TODO ERRO> Out of Range */ }
if(TSEG1_RANGE_CHECK((BitRateParameter -> TimeSegmentBeforeSamplePoint_TSEG1)))
{CAN0_Chennal-> CANBIT = ((BitRateParameter -> TimeSegmentBeforeSamplePoint_TSEG1 ) << CAN_BIT_TSEG1_M);}
else { /* <!TODO ERRO> Out of Range */ }
if(SJW_RANGE_CHECK(BitRateParameter -> SynchronizationJumpWidth_SJW))
{CAN0_Chennal-> CANBIT = ((BitRateParameter -> SynchronizationJumpWidth_SJW ) << CAN_BIT_SJW_M );}
else { /* <!TODO ERRO> Out of Range */ }
if(BRP_RANGE_CHECK(BitRateParameter -> BaudRatePrescaler_BRP))
{CAN0_Chennal-> CANBIT = ((BitRateParameter -> BaudRatePrescaler_BRP ) << CAN_BIT_BRP_M ) ;}
else { /* <!TODO ERRO> Out of Range */ }
/* Disable All Interrupts */
CLR_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_IE ) ;
CLR_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_SIE ) ;
CLR_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_EIE ) ;
/* Exit Configuration Mode */
CONFIG_MODE_DISABLE(CAN0_Chennal -> CANCTL) ;
break ;
case CAN1 :
/* Enter Configuration Mode */
CONFIG_MODE_ENABLE(CAN1_Chennal -> CANCTL);
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN1_Chennal -> CANIF1CRQ) ;
/* Enter TEST Mode*/
SET_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_TEST ) ;
switch(WorkingMode)
{
case NormalMode :
/* Normal Mode Selection As Basic Mode */
CLR_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_TEST ) ;
SET_BIT(CAN1_Chennal -> CANTST , CAN_TST_BASIC) ;
break ;
case LoopbackMode :
/* LoopbackMode Enable */
SET_BIT(CAN1_Chennal -> CANTST , CAN_TST_LBACK ) ;
break ;
case SilentMode :
/* in silent mode, the CAN controller does not transmit data but instead monitors the bus */
/* SilentMode Enable */
SET_BIT( CAN1_Chennal -> CANTST , CAN_TST_SILENT);
break ;
case LoopbackWithSilentMode :
/* LoopbackMode Enable */
SET_BIT(CAN1_Chennal -> CANTST , CAN_TST_LBACK ) ;
/* SilentMode Enable */
SET_BIT( CAN1_Chennal -> CANTST , CAN_TST_SILENT);
break ;
}
/* Setting the CCE bit to edit CANBIT Register */
SET_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_CCE) ;
/* SET BIT PARAMETERS */
if(TSEG2_RANGE_CHECK((BitRateParameter -> TimeSegmentAfterSamplePoint_TSEG2 )))
{CAN1_Chennal-> CANBIT = ((BitRateParameter -> TimeSegmentAfterSamplePoint_TSEG2 ) << CAN_BIT_TSEG2_M );}
else { /* <!TODO ERRO> Out of Range */ }
if(TSEG1_RANGE_CHECK((BitRateParameter -> TimeSegmentBeforeSamplePoint_TSEG1)))
{CAN1_Chennal-> CANBIT = ((BitRateParameter -> TimeSegmentBeforeSamplePoint_TSEG1 ) << CAN_BIT_TSEG1_M);}
else { /* <!TODO ERRO> Out of Range */ }
if(SJW_RANGE_CHECK(BitRateParameter -> SynchronizationJumpWidth_SJW))
{CAN1_Chennal-> CANBIT = ((BitRateParameter -> SynchronizationJumpWidth_SJW ) << CAN_BIT_SJW_M );}
else { /* <!TODO ERRO> Out of Range */ }
if(BRP_RANGE_CHECK(BitRateParameter -> BaudRatePrescaler_BRP))
{CAN1_Chennal-> CANBIT = ((BitRateParameter -> BaudRatePrescaler_BRP ) << CAN_BIT_BRP_M ) ;}
else { /* <!TODO ERRO> Out of Range */ }
/* Disable All Interrupts */
CLR_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_IE ) ;
CLR_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_SIE ) ;
CLR_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_EIE ) ;
/* Exit Configuration Mode */
CONFIG_MODE_DISABLE(CAN1_Chennal -> CANCTL) ;
break ;
}
}
void CAN_voidInterruptEnable(CAN_channel channelNumber , Interrupt_Type copy_IntType)
{
switch(channelNumber)
{
case CAN0 :
/* Enter Configuration Mode */
CONFIG_MODE_ENABLE(CAN0_Chennal -> CANCTL);
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
/* Enable Global Interrupt */
ENABLE_GLOBAL_INT(CAN0_Chennal -> CANCTL);
switch(copy_IntType)
{
case Status_Interrupt : SET_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_SIE); break ;
case Error_Interrupt : SET_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_EIE); break ;
case All_Interrupts :
SET_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_SIE);
SET_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_EIE);
break ;
}
/* Exit Configuration Mode */
CONFIG_MODE_DISABLE(CAN0_Chennal -> CANCTL) ;
break ;
case CAN1 :
/* Enter Configuration Mode */
CONFIG_MODE_ENABLE(CAN1_Chennal -> CANCTL);
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN1_Chennal -> CANIF1CRQ) ;
/* Enable Global Interrupt */
ENABLE_GLOBAL_INT(CAN1_Chennal -> CANCTL);
switch(copy_IntType)
{
case Status_Interrupt : SET_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_SIE); break ;
case Error_Interrupt : SET_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_EIE); break ;
case All_Interrupts :
SET_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_SIE);
SET_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_EIE);
break ;
}
/* Exit Configuration Mode */
CONFIG_MODE_DISABLE(CAN1_Chennal -> CANCTL) ;
break ;
}
}
void CAN_voidInterruptDisable(CAN_channel channelNumber , Interrupt_Type copy_IntType)
{
switch(channelNumber)
{
case CAN0 :
/* Enter Configuration Mode */
CONFIG_MODE_ENABLE(CAN0_Chennal -> CANCTL);
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
/* Disable Global Interrupt */
switch(copy_IntType)
{
case Status_Interrupt : CLR_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_SIE); break ;
case Error_Interrupt : CLR_BIT(CAN0_Chennal -> CANCTL , CAN_CTL_EIE); break ;
case All_Interrupts :
DISABLE_GLOBAL_INT(CAN0_Chennal -> CANCTL);
break ;
}
/* Exit Configuration Mode */
CONFIG_MODE_DISABLE(CAN0_Chennal -> CANCTL) ;
break ;
case CAN1 :
/* Enter Configuration Mode */
CONFIG_MODE_ENABLE(CAN1_Chennal -> CANCTL);
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN1_Chennal -> CANIF1CRQ) ;
switch(copy_IntType)
{
case Status_Interrupt : CLR_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_SIE); break ;
case Error_Interrupt : CLR_BIT(CAN1_Chennal -> CANCTL , CAN_CTL_EIE); break ;
case All_Interrupts :
/* Disable Global Interrupt */
DISABLE_GLOBAL_INT(CAN1_Chennal -> CANCTL);
break ;
}
/* Exit Configuration Mode */
CONFIG_MODE_DISABLE(CAN1_Chennal -> CANCTL) ;
break ;
}
}
u8 CAN_u8TransmitMessageObjectSync(CAN_channel channelNumber,u32 copy_u32ObjID , CAN_MassegeObject *psMsgObject , FIFO_Mode copy_FIFOStatues)
{
u8 local_u8ErrorState = 1 ;
u16 local_u16CMSK = 0 ;
u16 local_u16ArbReg1 = 0 , local_u16ArbReg2 = 0, local_u16MCTL = 0,local_u16MskReg1 = 0,local_u16MskReg2 = 0;
/* GET REG VALUES FOR THIS CONFIGURATION */
local_u8ErrorState = CAN_u8MessageObjectConfig(TX,&psMsgObject ,copy_FIFOStatues , local_u16CMSK , local_u16ArbReg1,local_u16ArbReg2,local_u16MCTL,local_u16MskReg1,local_u16MskReg2,copy_u32ObjID) ;
if(local_u8ErrorState == 0 ) {return 0 ;}
switch(channelNumber)
{
case CAN0 :
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
CAN_voidWriteDataHandling(psMsgObject -> pointer_MsgData,CAN0_Chennal->CANIF1DA1 , psMsgObject -> copy_u32MsgLength ) ;
// Update Registers
CAN0_Chennal -> CANIF1CMSK = local_u16CMSK ;
CAN0_Chennal -> CANIF1MSK1 = local_u16MskReg1 ;
CAN0_Chennal -> CANIF1MSK2 = local_u16MskReg2 ;
CAN0_Chennal -> CANIF1ARB1 = local_u16ArbReg1 ;
CAN0_Chennal -> CANIF1ARB2 = local_u16ArbReg2 ;
CAN0_Chennal -> CANIF1MCTL = local_u16MCTL ;
/* Finally Set MSG Object Selects one of the 32 message objects in the message RAM for data
transfer. The message objects are numbered from 1 to 32 */
CAN0_Chennal -> CANIF1CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
/* Wait Until Transmit */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
break ;
case CAN1 :
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN1_Chennal -> CANIF1CRQ) ;
CAN_voidWriteDataHandling(psMsgObject -> pointer_MsgData,CAN1_Chennal->CANIF1DA1 , psMsgObject -> copy_u32MsgLength ) ;
// Update Registers
CAN1_Chennal -> CANIF1CMSK = local_u16CMSK ;
CAN1_Chennal -> CANIF1MSK1 = local_u16MskReg1 ;
CAN1_Chennal -> CANIF1MSK2 = local_u16MskReg2 ;
CAN1_Chennal -> CANIF1ARB1 = local_u16ArbReg1 ;
CAN1_Chennal -> CANIF1ARB2 = local_u16ArbReg2 ;
CAN1_Chennal -> CANIF1MCTL = local_u16MCTL ;
/* Finally Set MSG Object Selects one of the 32 message objects in the message RAM for data
transfer. The message objects are numbered from 1 to 32 */
CAN1_Chennal -> CANIF1CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
/* Wait Until Transmit */
WAIT_BUS_BE_UNBUSY(CAN1_Chennal -> CANIF1CRQ) ;
break ;
}
return local_u8ErrorState ;
}
u8 CAN_u8TransmitMessageObjectAsync(CAN_channel channelNumber,u32 copy_u32ObjID , CAN_MassegeObject *psMsgObject , FIFO_Mode copy_FIFOStatues,void(*callBack)(void))
{
u8 local_u8ErrorState = 1 ;
u16 local_u16CMSK = 0 ;
u16 local_u16ArbReg1 = 0 , local_u16ArbReg2 = 0, local_u16MCTL = 0,local_u16MskReg1 = 0,local_u16MskReg2 = 0;
/* GET REG VALUES FOR THIS CONFIGURATION */
local_u8ErrorState = CAN_u8MessageObjectConfig(TX,&psMsgObject ,copy_FIFOStatues , local_u16CMSK , local_u16ArbReg1,local_u16ArbReg2,local_u16MCTL,local_u16MskReg1,local_u16MskReg2,copy_u32ObjID) ;
/* SET Async Fn */
CAN_voidMessageAsyncObjectConfig(1 ,&local_u16MCTL ) ;
/* Check ERROR */
if(local_u8ErrorState == 0 ) {return 0 ;}
switch(channelNumber)
{
case CAN0 :
/* Set Callback Function */
Callback_TX_CAN0 = callBack ;
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
CAN_voidWriteDataHandling(psMsgObject -> pointer_MsgData,CAN0_Chennal->CANIF1DA1 , psMsgObject -> copy_u32MsgLength ) ;
// Update Registers
CAN0_Chennal -> CANIF1CMSK = local_u16CMSK ;
CAN0_Chennal -> CANIF1MSK1 = local_u16MskReg1 ;
CAN0_Chennal -> CANIF1MSK2 = local_u16MskReg2 ;
CAN0_Chennal -> CANIF1ARB1 = local_u16ArbReg1 ;
CAN0_Chennal -> CANIF1ARB2 = local_u16ArbReg2 ;
CAN0_Chennal -> CANIF1MCTL = local_u16MCTL ;
/* Finally Set MSG Object Selects one of the 32 message objects in the message RAM for data
transfer. The message objects are numbered from 1 to 32 */
CAN0_Chennal -> CANIF1CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
break ;
case CAN1 :
/* Set Callback Function */
Callback_TX_CAN1 = callBack ;
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN1_Chennal -> CANIF1CRQ) ;
CAN_voidWriteDataHandling(psMsgObject -> pointer_MsgData,CAN1_Chennal->CANIF1DA1 , psMsgObject -> copy_u32MsgLength ) ;
// Update Registers
CAN1_Chennal -> CANIF1CMSK = local_u16CMSK ;
CAN1_Chennal -> CANIF1MSK1 = local_u16MskReg1 ;
CAN1_Chennal -> CANIF1MSK2 = local_u16MskReg2 ;
CAN1_Chennal -> CANIF1ARB1 = local_u16ArbReg1 ;
CAN1_Chennal -> CANIF1ARB2 = local_u16ArbReg2 ;
CAN1_Chennal -> CANIF1MCTL = local_u16MCTL ;
/* Finally Set MSG Object Selects one of the 32 message objects in the message RAM for data
transfer. The message objects are numbered from 1 to 32 */
CAN1_Chennal -> CANIF1CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
break ;
}
return local_u8ErrorState ;
}
static u8 CAN_u8MessageObjectConfig(u8 TX_RX_RM , CAN_MassegeObject *psMsgObject ,FIFO_Mode copy_FIFOStatues , u16 *local_u16CMSK ,u16 *copy_u16ArbReg1 , u16 *copy_u16ArbReg2, u16 *copy_u16MCTL,u16 *copy_u16MskReg1, u16 *copy_u16MskReg2 , u32 copy_u32ObjID )
{
u8 local_u8ErrorState = 1 ;
/* Check ID Object Range */
if(copy_u32ObjID >= ID_OBJ_MIN && copy_u32ObjID <= ID_OBJ_MAX)
{ local_u8ErrorState = 0 ; return local_u8ErrorState ; }
/* Transfer the data in the CANIFn registers to the CAN message object specified by the MNUM field in the CAN Command Request (CANIFnCRQ). */
SET_BIT(*local_u16CMSK , CAN_IF1CMSK_WRNRD ) ;
/* transfer data bytes 0-3 in message object to CANIFnDA1 and CANIFnDA2. */
SET_BIT(*local_u16CMSK , CAN_IF1CMSK_DATAA ) ;
/* transfer data bytes 4-7 in message object to CANIFnDA1 and CANIFnDA2. */
SET_BIT(*local_u16CMSK, CAN_IF1CMSK_DATAB ) ;
/* transfer the control bits into the interface registers */
SET_BIT(*local_u16CMSK, CAN_IF1CMSK_CONTROL ) ;
/* Check Extended Frame */
if((psMsgObject->copy_u32MsgID > CAN_MAX_11BIT_MSG_ID) || (psMsgObject-> copy_u8ExtendedFrameFlag == 1))
{
// Set the 29 bits of Identifier mask that were requested.
*copy_u16MskReg1 = psMsgObject->copy_u32MsgID & CAN_IF1MSK1_IDMSK_M ;
*copy_u16MskReg2 = (psMsgObject->copy_u32MsgID >> 16) & CAN_IF1MSK2_IDMSK_M ;
// Set the 29 bits of Identifier mask that were requested.
*copy_u16ArbReg1 = psMsgObject->copy_u32MsgID & CAN_IF1ARB1_ID_M ;
*copy_u16ArbReg2 = (psMsgObject->copy_u32MsgID >> 16) & CAN_IF1ARB2_ID_M ;
// Mark the message as valid and set the extended ID bit.
SET_BIT(*copy_u16ArbReg2 , CAN_IF1ARB2_XTD ) ;
}
else
{
// Lower 16 bit are unused so set them to zero.
*copy_u16MskReg1 = 0 ;
*copy_u16ArbReg1 = 0 ;
*copy_u16MskReg2 = (psMsgObject->copy_u32MsgID << 2) &(CAN_IF1MSK2_IDMSK_M ) ; // I don't care about last two lSB
*copy_u16ArbReg2 = (psMsgObject->copy_u32MsgID << 2) &(CAN_IF1ARB2_XTD ) ; // I don't care about last two lSB
}
switch (TX_RX_RM)
{
case TX :
/* Set the TXRQST bit */
SET_BIT(*copy_u16MCTL , CAN_IF1MCTL_TXRQST) ;
/* Set Transmit Direction */
SET_BIT(*copy_u16ArbReg2 , CAN_IF1ARB2_DIR ) ;
break ;
case RX :
*copy_u16ArbReg2 = 0 ;
break ;
case TX_REMOTE :
/* Set the TXRQST bit */
SET_BIT(*copy_u16MCTL , CAN_IF1MCTL_TXRQST) ;
/* Waiting Data So I'm Reciever */
CLR_BIT(*copy_u16ArbReg2 , CAN_IF1ARB2_DIR ) ;
break ;
case RX_REMOTE :
/* CLR the TXRQST bit */
CLR_BIT(*copy_u16MCTL , CAN_IF1MCTL_TXRQST) ;
/* So I'm Transmitter */
SET_BIT(*copy_u16ArbReg2 , CAN_IF1ARB2_DIR ) ;
break ;
}
// Set Extended Filter
if (psMsgObject -> copy_u8FilterExtendedIdentifierFlag == 1 )
{
SET_BIT(*copy_u16MskReg2,CAN_IF1MSK2_MXTD ) ;
// Set the UMASK bit to enable using the mask register.
SET_BIT(*copy_u16MCTL ,CAN_IF1MCTL_UMASK) ;
//Set the MASK bit so that this gets transferred to the Message Object.
SET_BIT(*local_u16CMSK , CAN_IF1CMSK_MASK ) ;
}
// filter on the message direction field.
if ( psMsgObject -> copy_u8FilterMsgDirectionFlag == 1)
{
SET_BIT(*copy_u16MskReg2,CAN_IF1MSK2_MDIR ) ;
// Set the UMASK bit to enable using the mask register.
SET_BIT(*copy_u16MCTL ,CAN_IF1MCTL_UMASK) ;
//Set the MASK bit so that this gets transferred to the Message Object.
SET_BIT(*local_u16CMSK , CAN_IF1CMSK_MASK ) ;
}
// Transfer ID + DIR + XTD + MSGVAL of the message object into the Interface registers(Message object).
SET_BIT(*local_u16CMSK , CAN_IF1CMSK_ARB ) ;
/* SET DLC */
if(CHECK_DLC_IN_RANGE(psMsgObject-> copy_u32MsgLength))
{
*copy_u16MCTL |= ((psMsgObject-> copy_u32MsgLength)& CAN_IF1MCTL_DLC_M) ;
}
else
{
//<!TODO ERROR>
local_u8ErrorState = 0 ; return local_u8ErrorState ;
}
/* FIFO MODE */
switch(copy_FIFOStatues)
{
case Enable_FIFO:
CLR_BIT(*local_u16CMSK ,CAN_IF1MCTL_EOB ) ;
break ;
case Disable_FIFO: SET_BIT(*local_u16CMSK ,CAN_IF1MCTL_EOB ) ; break ;
}
return local_u8ErrorState ;
}
u8 CAN_u8RecieveMessageObjectSync(CAN_channel channelNumber,u32 copy_u32ObjID , CAN_MassegeObject *psMsgObject , FIFO_Mode copy_FIFOStatues)
{
/* Passing Parameters */
u8 local_u8ErrorState = 1 ;
u16 local_u16CMSK = 0 ;
u16 local_u16ArbReg1 = 0 , local_u16ArbReg2 = 0, local_u16MCTL = 0,local_u16MskReg1 = 0,local_u16MskReg2 = 0;
/* Initalize Msg Object */
local_u8ErrorState = CAN_u8MessageObjectConfig(RX ,&psMsgObject,copy_FIFOStatues , &local_u16CMSK ,&local_u16ArbReg1 , &local_u16ArbReg2 ,&local_u16MCTL ,&local_u16MskReg1, &local_u16MskReg2 ,copy_u32ObjID );
if(local_u8ErrorState == 0 ) {return 0 ;}
switch(channelNumber)
{
case CAN0 :
// Update F1 Registers
CAN0_Chennal -> CANIF1CMSK = local_u16CMSK ;
CAN0_Chennal -> CANIF1MSK1 = local_u16MskReg1 ;
CAN0_Chennal -> CANIF1MSK2 = local_u16MskReg2 ;
CAN0_Chennal -> CANIF1ARB1 = local_u16ArbReg1 ;
CAN0_Chennal -> CANIF1ARB2 = local_u16ArbReg2 ;
CAN0_Chennal -> CANIF1MCTL = local_u16MCTL ;
CAN0_Chennal -> CANIF1CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
CAN_u8RecieveMessageObjectConfig(CAN0,&psMsgObject ,copy_u32ObjID);
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
break ;
case CAN1 :
// Update F1 Registers
CAN1_Chennal -> CANIF1CMSK = local_u16CMSK ;
CAN1_Chennal -> CANIF1MSK1 = local_u16MskReg1 ;
CAN1_Chennal -> CANIF1MSK2 = local_u16MskReg2 ;
CAN1_Chennal -> CANIF1ARB1 = local_u16ArbReg1 ;
CAN1_Chennal -> CANIF1ARB2 = local_u16ArbReg2 ;
CAN1_Chennal -> CANIF1MCTL = local_u16MCTL ;
CAN1_Chennal -> CANIF1CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
CAN_u8RecieveMessageObjectConfig(CAN1,&psMsgObject ,copy_u32ObjID);
/* Makesure Bus Now is unbusy no message to/from bus */
WAIT_BUS_BE_UNBUSY(CAN1_Chennal -> CANIF1CRQ) ;
break ;
}
return local_u8ErrorState ;
}
u8 CAN_u8RecieveMessageObjectAsync(CAN_channel channelNumber,u32 copy_u32ObjID , CAN_MassegeObject *psMsgObject , FIFO_Mode copy_FIFOStatues,void(*callBack)(void))
{
/* Passing Parameters */
u8 local_u8ErrorState = 1 ;
u16 local_u16CMSK = 0 ;
u16 local_u16ArbReg1 = 0 , local_u16ArbReg2 = 0, local_u16MCTL = 0,local_u16MskReg1 = 0,local_u16MskReg2 = 0;
/* Initalize Msg Object */
local_u8ErrorState = CAN_u8MessageObjectConfig(RX ,&psMsgObject,copy_FIFOStatues , &local_u16CMSK ,&local_u16ArbReg1 , &local_u16ArbReg2 ,&local_u16MCTL ,&local_u16MskReg1, &local_u16MskReg2 ,copy_u32ObjID );
if(local_u8ErrorState == 0 ) {return 0 ;}
/* Set RXIE */
CAN_voidMessageAsyncObjectConfig(RX,&local_u16MCTL);
switch(channelNumber)
{
case CAN0 :
/* Set Callback Function */
Callback_RX_CAN0 = callBack ;
// Update F1 Registers
CAN0_Chennal -> CANIF1CMSK = local_u16CMSK ;
CAN0_Chennal -> CANIF1MSK1 = local_u16MskReg1 ;
CAN0_Chennal -> CANIF1MSK2 = local_u16MskReg2 ;
CAN0_Chennal -> CANIF1ARB1 = local_u16ArbReg1 ;
CAN0_Chennal -> CANIF1ARB2 = local_u16ArbReg2 ;
CAN0_Chennal -> CANIF1MCTL = local_u16MCTL ;
CAN0_Chennal -> CANIF1CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
CAN_u8RecieveMessageObjectConfig(CAN0,&psMsgObject ,copy_u32ObjID);
break ;
case CAN1 :
/* Set Callback Function */
Callback_RX_CAN1 = callBack ;
// Update F1 Registers
CAN1_Chennal -> CANIF1CMSK = local_u16CMSK ;
CAN1_Chennal -> CANIF1MSK1 = local_u16MskReg1 ;
CAN1_Chennal -> CANIF1MSK2 = local_u16MskReg2 ;
CAN1_Chennal -> CANIF1ARB1 = local_u16ArbReg1 ;
CAN1_Chennal -> CANIF1ARB2 = local_u16ArbReg2 ;
CAN1_Chennal -> CANIF1MCTL = local_u16MCTL ;
CAN1_Chennal -> CANIF1CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
CAN_u8RecieveMessageObjectConfig(CAN1,&psMsgObject ,copy_u32ObjID);
break ;
}
return local_u8ErrorState ;
}
static u8 CAN_u8RecieveMessageObjectConfig(CAN_channel channelNumber, CAN_MassegeObject *psMsgObject , u32 copy_u32ObjID )
{
u8 Error_Number ;
u16 local_u16IF2CMSK ;
u16 MaskReg1 = 0 ,MaskReg2 = 0 , ArbReg1 = 0 ,ArbReg2 = 0 ,MCTL =0 ;
/* transfer data bytes 0-3 in message object to CANIFnDA1 and CANIFnDA2. */
SET_BIT(local_u16IF2CMSK , CAN_IF1CMSK_DATAA ) ;
/* transfer data bytes 4-7 in message object to CANIFnDA1 and CANIFnDA2. */
SET_BIT(local_u16IF2CMSK, CAN_IF1CMSK_DATAB ) ;
/* transfer the control bits into the interface registers */
SET_BIT(local_u16IF2CMSK, CAN_IF1CMSK_CONTROL ) ;
/* Transfer ID + DIR + XTD + MSGVAL of the message object into the Interface registers. */
SET_BIT(local_u16IF2CMSK, CAN_IF1CMSK_ARB ) ;
/* Transfer ID + DIR + XTD + MSGVAL of the message object into the Interface registers. */
SET_BIT(local_u16IF2CMSK, CAN_IF1CMSK_MASK ) ;
switch(channelNumber)
{
case CAN0:
CAN0_Chennal->CANIF2CMSK = local_u16IF2CMSK ;
/* Transfer the message object to Interface Register specified by ui32ObjID */
CAN0_Chennal -> CANIF2CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
/* BUS BUSY Transmit ID */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
// Read out the IF Registers.
MaskReg1= CAN0_Chennal -> CANIF2MSK1 ;
MaskReg2= CAN0_Chennal -> CANIF2MSK2 ;
ArbReg1 = CAN0_Chennal -> CANIF2ARB1 ;
ArbReg2 = CAN0_Chennal -> CANIF2ARB2 ;
MCTL = CAN0_Chennal -> CANIF2MCTL;
break ;
case CAN1: CAN1_Chennal->CANIF2CMSK = local_u16IF2CMSK ;
/* Transfer the message object to the message object specified by ui32ObjID */
CAN1_Chennal -> CANIF2CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
/* BUS BUSY Transmit ID */
WAIT_BUS_BE_UNBUSY(CAN1_Chennal -> CANIF1CRQ) ;
// Read out the IF Registers.
MaskReg1= CAN1_Chennal -> CANIF2MSK1 ;
MaskReg2= CAN1_Chennal -> CANIF2MSK2 ;
ArbReg1 = CAN1_Chennal -> CANIF2ARB1 ;
ArbReg2 = CAN1_Chennal -> CANIF2ARB2 ;
MCTL = CAN1_Chennal ->CANIF2MCTL ;
break ;
}
/* CHECK FRAME SIZE */
if(GET_BIT(ArbReg2 , CAN_IF1ARB2_XTD ) == 0 )
{
//An 11-bit Standard Identifier is used for this message object.
psMsgObject -> copy_u8ExtendedFrameFlag = 0 ;
// Set ID
psMsgObject ->copy_u32MsgID = ((ArbReg2&CAN_IF1ARB2_ID_M) >> 2) ;
}
else
{
// An 11-bit Standard Identifier is used for this message object.
psMsgObject -> copy_u8ExtendedFrameFlag = 1 ;
// Set ID
psMsgObject ->copy_u32MsgID = (((ArbReg2&CAN_IF1ARB1_ID_M) << 16) | ArbReg1) ;
}
/* MSG VALIDATE */
if(LOST_SOME_DATA(MCTL))
{
/* LOST DATA */
Error_Number = 1 ;
}
/* Check if ID Masking Used */
if(GET_BIT(MCTL , CAN_IF1MCTL_UMASK) == 1 )
{
/* Check Frame Size */
if(psMsgObject -> copy_u8ExtendedFrameFlag)
{
// Extended Frame
psMsgObject -> copy_u32MsgIDMask = ((MaskReg2 & CAN_IF1MSK2_IDMSK_M) << 16 ) | MaskReg1 ;
psMsgObject -> copy_u8FilterExtendedIdentifierFlag = 1 ;
}
else
{
//Standard Frame
psMsgObject -> copy_u32MsgIDMask = ((MaskReg2 & CAN_IF1MSK2_IDMSK_M) >> 2 ) ;
}
// Indicate if direction filtering was enabled.
if(GET_BIT(MaskReg2,CAN_IF1MSK2_MDIR))
{
psMsgObject -> copy_u8FilterMsgDirectionFlag = 1 ;
}
}
/* CHECK IF NEW DATA EXIST */
if(NEW_DATA_AVAILABE(MCTL))
{
/* Check MSG Length */
psMsgObject ->copy_u32MsgLength = MCTL & CAN_IF1MCTL_DLC_M ;
/* Makesure That's Not Remote Frame */
if(psMsgObject -> copy_u8ExtendedFrameFlag == 0 )
{
switch(channelNumber)
{
case CAN0:
CAN_voidReadDataHandling (psMsgObject -> pointer_MsgData , CAN0_Chennal->CANIF2DA1,psMsgObject->copy_u32MsgLength) ;
/* Clear New Data Flag optional */
CLR_BIT(CAN0_Chennal->CANIF2CMSK ,CAN_IF1CMSK_NEWDAT ) ;
/* Transfer the message object to the message object specified by ui32ObjID */
CAN0_Chennal -> CANIF2CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
/* BUS BUSY Transmit ID */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
break ;
case CAN1:
CAN_voidReadDataHandling (psMsgObject -> pointer_MsgData , CAN1_Chennal->CANIF2DA1,psMsgObject->copy_u32MsgLength) ;
/* Clear New Data Flag optional */
CLR_BIT(CAN1_Chennal->CANIF2CMSK ,CAN_IF1CMSK_NEWDAT ) ;
/* Transfer the message object to the message object specified by ui32ObjID */
CAN1_Chennal -> CANIF2CRQ = copy_u32ObjID & CAN_IF1CRQ_MNUM_M ;
/* BUS BUSY Transmit ID */
WAIT_BUS_BE_UNBUSY(CAN0_Chennal -> CANIF1CRQ) ;
break ;
}
}
else
{
/* Remote Frame Not Data Frame */
Error_Number = 2 ;
}
}
else
{
/* No New Data Available */
Error_Number = 3 ;
}
return Error_Number ;
}
static void CAN_voidWriteDataHandling(u8 *pu8Data, u32 *pu32Register, u32 ui32Size)
{
u32 Local_u32Counter = 0 ;
u32 Local_u32Data = 0 ;
for (Local_u32Counter =0 ; Local_u32Counter < ui32Size ; Local_u32Counter++ )
{
Local_u32Data = pu8Data[Local_u32Counter];
if(Local_u32Counter < ui32Size )
{
Local_u32Counter++ ;
Local_u32Data |= (Local_u32Data << 8);
Local_u32Counter++ ;
}
*(pu32Register++) = Local_u32Data;
}
}
static void CAN_voidReadDataHandling(u8 *pui8Data, u32 *pui32Register, u32 ui32Size)
{
u32 ui32Idx, ui32Value;
//
// Loop always copies 1 or 2 bytes per iteration.
//
for(ui32Idx = 0; ui32Idx < ui32Size; )
{
//
// Read out the data 16 bits at a time since this is how the registers
// are aligned in memory.
//
ui32Value = pui32Register++;
//
// Store the first byte.
//
pui8Data[ui32Idx++] = (u8)ui32Value;
//
// Only read the second byte if needed.
//
if(ui32Idx < ui32Size)
{
pui8Data[ui32Idx++] = (u8)(ui32Value >> 8);
}
}
}
static void CAN_voidMessageAsyncObjectConfig(u8 Tx_RX ,u16 *copy_u16MCTL )
{
switch(Tx_RX)
{
case 1 :
//TX
SET_BIT(*copy_u16MCTL , CAN_IF1MCTL_TXIE ) ;
global_u8TX_RX_State = 1 ;
break ;
case 2 :
//RX
SET_BIT(*copy_u16MCTL , CAN_IF1MCTL_RXIE ) ;
global_u8TX_RX_State = 2 ;
break ;
default : break ;
}
}
u8 CAN_u8ErrorCounterGet (CAN_channel channelNumber , u8 *p_u8TX_Count, u8 *p_u8RX_Count)
{
u32 Local_u32RegErrorVal = 0 ;
switch(channelNumber)
{
case CAN0 :
Local_u32RegErrorVal = CAN0_Chennal->CANERR ;
break ;
case CAN1 :
Local_u32RegErrorVal = CAN1_Chennal->CANERR ;
break ;
}
*p_u8RX_Count = (Local_u32RegErrorVal & CAN_ERR_REC_M) >> CAN_ERR_REC_S ;
*p_u8TX_Count = (Local_u32RegErrorVal & CAN_ERR_TEC_M) >> CAN_ERR_TEC_S ;
if(GET_BIT(Local_u32RegErrorVal,CAN_ERR_RP))
{
return 1 ;
}
else
{
return 0;
}
}
void __vector_39(void)
{
if(global_u8TX_RX_State == 1 )
{
// TRANSMIT
Callback_TX_CAN0();
global_u8TX_RX_State=0;
}
else if(global_u8TX_RX_State == 2 )
{
//RECIEVE
Callback_RX_CAN0();
global_u8TX_RX_State =0 ;
}
/* Clear Flag */
}
void __vector_40(void)
{
if(global_u8TX_RX_State == 1 )
{
// TRANSMIT
Callback_TX_CAN1();
global_u8TX_RX_State=0;
}
else if(global_u8TX_RX_State == 2 )
{
//RECIEVE
Callback_RX_CAN1();
global_u8TX_RX_State =0 ;
}
/* Clear Flag */
CLR_BIT(CAN1_Chennal->CANSTS , CAN_STS_TXOK ) ;
CLR_BIT(CAN1_Chennal->CANSTS , CAN_STS_RXOK ) ;
}
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 12 September 2020
/* Descroption: Rx Example */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "CAN_interface.h"
/*
A counter that keeps track of the number of times the RX interrupt has
occurred, which should match the number of RX messages that were sent.
*/
volatile u32 Global_ui32MsgCount = 0;
void CAN_IntRxHandler(void);
int main(void)
{
/* peripheral clock must be enabled using the RCGC0 register */
/* the clock to the appropriate GPIO module must be enabled via the RCGC2 */
/* Set the GPIO AFSEL bits for the appropriate pins */
/* Set the GPIO AFSEL bits for the appropriate pins */
/* Make Msg Object */
CAN_MassegeObject CAN_Msg ;
u8 *MsgData ;
u32 u32MsgData ;
MsgData = (u8 *)&u32MsgData;
u8 Error = 1 ;
/* Initialize the message object that will be used for sending CAN */
/* In order to receive any CAN ID, the ID and mask must both
be set to 0, and the ID filter enabled. */
CAN_Msg.copy_u32MsgID = 0 ;
CAN_Msg.copy_u32MsgIDMask = 0 ;
CAN_Msg.copy_u8ExtendedFrameFlag = 0 ;
CAN_Msg.copy_u8FilterExtendedIdentifierFlag = 0 ;
CAN_Msg.copy_u8FilterMsgDirectionFlag = 0 ;
CAN_Msg.copy_u32MsgLength = 8;
CAN_Msg.pointer_MsgData = MsgData ;
/* Bit Timing Parameters For Bit Rate = 1000 */
BitTiming_Parameter CAN_TimingParmeters ;
CAN_TimingParmeters.BaudRatePrescaler_BRP = 1 ;
CAN_TimingParmeters.TimeSegmentBeforeSamplePoint_TSEG1 = 13 ;
CAN_TimingParmeters.TimeSegmentAfterSamplePoint_TSEG2 = 2 ;
CAN_TimingParmeters.SynchronizationJumpWidth_SJW = 1 ;
/* Init CAN Module */
CAN_voidInit(CAN0,NormalMode,&CAN_TimingParmeters);
/* Enable Statues And Error Interrupt */
CAN_voidInterruptEnable(CAN0,All_Interrupts);
/* Enable the CAN interrupt on the processor (NVIC). */
while(1)
{
/* CAN will receive any message on the bus, and an interrupt will occur.
Use message object 1 for receiving messages (this is not the same as
the CAN ID which can be any value in this example it will not effect in object number). */
Error = CAN_u8RecieveMessageObjectAsync(CAN0,1,&CAN_Msg,Enable_FIFO,CAN_IntRxHandler);
if(Error != 1)
{
Error = CAN_u8RecieveMessageObjectAsync(CAN0,1,&CAN_Msg,Enable_FIFO,CAN_IntRxHandler);
}
else
{
/* Get Next Byte To Transmit */
u32MsgData++;
}
}
//return 0;
}
void CAN_IntRxHandler(void)
{
Global_ui32MsgCount++ ;
}
<file_sep>## Configuration before compile
### uart_config.h File :
you must add CPU Frequency in this form 8MHz = 8000000UL
```c
#define F_CPU 8000000UL
```
## Development :
| Function Name | Usage | Parameter | return |
| ------ | ------ | ------ | ------ |
| UART_voidInit() | Initialize UART Parameters .|`UART_CHANNEL channel` - <a href="#UART_CHANNEL">channel</a> <br /> `u16 copy_u16BaudRate` - <a href="#UART_BaudRate">BaudRate</a> <br /> `UART_PARITY Parity` - <a href="#UART_PARITY">Parity</a> <br /> `UART_STOPBIT stopBitType` - <a href="#UART_STOPBIT">stopBitType</a><br /> `UART_FIFO FIFO_mode` - <a href="#UART_FIFOMode">FIFO_mode</a><br /> `u8 copy_u8FrameLength` - <a href="#UART_FrameLength">copy_u8FrameLength</a><br />|`void`|
| UART_voidControl() | Control UARTx Disablle or Enable. |`UART_CHANNEL channel` - <a href="#UART-CHANNEL">channel</a> <br />`u8 copy_u8State` - <a href="#UART_Control"> copy_u8State</a> <br />| `void`|
| UARTx_charReceiverSynch() | receive data `Synchronously` in u8 . |`UART_CHANNEL channel` - <a href="#UART-CHANNEL">channel</a> | `u8`|
| UARTx_charReceiverAsynch() | receive data `Asynchronously` in pointer to function execute when receiving done. |`UART_CHANNEL channel` - <a href="#UART-CHANNEL">channel</a> <br/> `void(*callBack)(u8)` - Pointer to Function receiving data in u8 parameter | `void`|
| UARTx_voidTransmitterSynch() | transmit data `Synchronously` using u8 parameter. |`UART_CHANNEL channel` - <a href="#UART-CHANNEL">channel</a> <br/> `char TransmittedData` - char to be transmit. | `void`|
| UARTx_voidTransmitterAsynch() | transmit data `Asynchronously` in pointer to function execute when transmit successfully. |`UART_CHANNEL channel` - <a href="#UART-CHANNEL">channel</a> <br/> `char TransmittedData` - char to be transmit. <br/> `void(*callBack)(void)` - Pointer to Function execute after transmit data successfully. | `void`|
### UART_CHANNEL
| Parameter Name | Description | RX Pin | TX Pin |
| ------ | ------ | ------ | ------ |
| UART1 | For UART1 | PA0 | PA1 |
| UART2 | For UART2 | PC4 | PC5 |
| UART3 | For UART3 | PD6 | PD7 |
| UART4 | For UART4 | PC6 | PC7 |
| UART5 | For UART5 | PC4 | PC5 |
| UART6 | For UART6 | PE4 | PE5 |
| UART7 | For UART7 | PD4 | PD5 |
### UART_BaudRate
| BaudRate Example |
| ------ |
| 9600 |
| 112500 |
### UART_PARITY
| Parameter Name | Description |
| ------ | ------ |
| EVEN_PARITY | Enables even parity, which generates and checks for even num- ber of l’s in the data and parity bits during transmission and reception. |
| ODD_PARITY | Enables odd parity, which generates and checks for odd num- ber of l’s in the data and parity bits during transmission and reception. |
| DISABLE_PARITY | Disables parity. |
### UART_STOPBIT
| Parameter Name | Description |
| ------ | ------ |
| ONE_STOP_BIT | one stop bit is transmitted at the end of UART frame. |
| TWO_STOP_BIT | two stop bit is transmitted at the end of UART frame. |
### UART_FIFOMode
| Parameter Name | Description |
| ------ | ------ |
| ENABLE_FIFO | The transmit and receive FIFO buffers are enabled. |
| DISABLE_FIFO | The FIFOs are disabled (Character mode). The FIFOs become 1-byte-deep holding registers. |
### UART_FrameLength
| Parameter Name | Description |
| ------ | ------ |
| 5 | Frame Length Will Be 5-bit. |
| 6 | Frame Length Will Be 6-bit. |
| 7 | Frame Length Will Be 7-bit. |
| 8 | Frame Length Will Be 8-bit. |
### UART_Control
| Parameter Name | Description |
| ------ | ------ |
| ENABLE | For enable UARTx channel. |
| DISABLE | For disable UARTx channel. |
<file_sep># SeimensEDA_Tasks
Embedded System Track in Siemens Academy of Excellence for Undergrad Students.
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 2 September 2020 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "I2C_interface.h"
#include "I2C_private.h"
#include "I2C_config.h"
#define BUS_BUSY(I2Cx) while((GET_BIT(I2Cx,I2C_MCS_BUSBSY)) == 1){}
void I2C_voidInit(I2C_Chennal copy_I2CChennalSelect, I2C_Mode copy_I2CModeSelect,Transmission_speeds copy_I2CSpeed,u8 copy_u8SalveAddress)
{
switch(copy_I2CChennalSelect)
{
case I2C0 :
//calculate the SCL period
switch(copy_I2CSpeed)
{
case Standard :
CLR_BIT(I2C0_I2CMTPR,7);
CLR_BIT(I2C0_I2CMCS,I2C_MCS_HS);
I2C0_I2CMTPR = TPR_EQN(Standard_speed) ;
break ;
case Fast_Mode :
CLR_BIT(I2C0_I2CMTPR,7);
CLR_BIT(I2C0_I2CMCS,I2C_MCS_HS);
I2C0_I2CMTPR = TPR_EQN(FastMode_speed) ;
break;
case Fast_Mode_Plus :
CLR_BIT(I2C0_I2CMTPR,7);
CLR_BIT(I2C0_I2CMCS,I2C_MCS_HS);
I2C0_I2CMTPR = TPR_EQN(FastMode_Plus_speed) ;
break;
case High_Speed_Mode :
SET_BIT(I2C0_I2CMTPR,7);
SET_BIT(I2C0_I2CMCS,I2C_MCS_HS);
I2C0_I2CMTPR = TPR_EQN(High_speed) ;
break;
}
switch(copy_I2CModeSelect)
{
case Master_Transmit :
ENABLE_MASTER;
DISABLE_SLAVE;
// Mode select.
#if I2C0_GLITCH_FILTER == ENABLE
SET_BIT(I2C0_I2CMCR,I2C_MCR_GFE);
#else
CLR_BIT(I2C0_I2CMCR,I2C_MCR_GFE);
#endif
//write slave addresse 7bit and R/W bit.
I2C0_I2CMSA = (copy_u8SalveAddress << 1 );
//data byte is acknowledged automatically
SET_BIT(I2C0_I2CMCS,I2C_MCS_ACK);
CLR_BIT(I2C0_I2CMSA,I2C_MSA_R_S); //AS TX
break ;
case Master_Receive :
ENABLE_MASTER;
DISABLE_SLAVE;
// Mode select.
#if I2C0_GLITCH_FILTER == ENABLE
SET_BIT(I2C0_I2CMCR,I2C_MCR_GFE);
#else
CLR_BIT(I2C0_I2CMCR,I2C_MCR_GFE);
#endif
//write slave addresse 7bit and R/W bit.
I2C0_I2CMSA = (copy_u8SalveAddress << 1 );
//data byte is acknowledged automatically
SET_BIT(I2C0_I2CMCS,I2C_MCS_ACK);
SET_BIT(I2C0_I2CMSA,I2C_MSA_R_S); //AS RX
break ;
case Slave_Transmit :
DISABLE_MASTER;
ENABLE_SLAVE;
// Set slave addresse
I2C0_I2CSOAR = copy_u8SalveAddress ;
/* enable slave operation */
SET_BIT(I2C0_I2CSCSR,0);
break ;
case Slave_Receive :
DISABLE_MASTER;
ENABLE_SLAVE;
// Set slave addresse
I2C0_I2CSOAR = copy_u8SalveAddress ;
/* enable slave operation */
SET_BIT(I2C0_I2CSCSR,0);
break ;
}
break ;
case I2C1 :
switch(copy_I2CModeSelect)
{
case Master_Transmit : break ;
case Master_Receive : break ;
case Slave_Transmit : break ;
case Slave_Receive : break ;
}
break ;
case I2C2 :
switch(copy_I2CModeSelect)
{
case Master_Transmit : break ;
case Master_Receive : break ;
case Slave_Transmit : break ;
case Slave_Receive : break ;
}
break ;
case I2C3 :
switch(copy_I2CModeSelect)
{
case Master_Transmit : break ;
case Master_Receive : break ;
case Slave_Transmit : break ;
case Slave_Receive : break ;
}
break ;
}
}
void I2C_voidDisableSlaveOperation(I2C_Chennal copy_I2CChennalSelect)
{
switch(copy_I2CChennalSelect)
{
case I2C0 :
CLR_BIT(I2C0_I2CSCSR,0);
break ;
case I2C1 : break ;
case I2C2 : break ;
case I2C3 : break ;
}
}
void I2C_voidEnableSlaveOperation(I2C_Chennal copy_I2CChennalSelect)
{
switch(copy_I2CChennalSelect)
{
case I2C0 :
SET_BIT(I2C0_I2CSCSR,0);
break ;
case I2C1 : break ;
case I2C2 : break ;
case I2C3 : break ;
}
}
void I2C_voidMasterEnable(I2C_Chennal copy_I2CChennalSelect)
{
switch(copy_I2CChennalSelect)
{
case I2C0:
//Set RUN bit to make MASTER TX and RX.
SET_BIT(I2C0_I2CMCS,I2C_MCS_RUN);
break ;
case I2C1: break ;
case I2C2: break ;
case I2C3: break ;
}
}
void I2C_voidMasterDisable(I2C_Chennal copy_I2CChennalSelect)
{
switch(copy_I2CChennalSelect)
{
case I2C0:
SET_BIT(I2C0_I2CMCS,I2C_MCS_STOP) ;
break ;
case I2C1: break ;
case I2C2: break ;
case I2C3: break ;
}
}
void I2C_voidMaterTransmitMassege(I2C_Chennal copy_I2CChennalSelect, u8 copy_u8Data)
{
switch (copy_I2CChennalSelect)
{
case I2C0:
I2C0_I2CMDR = copy_u8Data ;
//Start Condition
SET_BIT(I2C0_I2CMCS,I2C_MCS_START);
//Set RUN bit to make MASTER TX and RX.
SET_BIT(I2C0_I2CMCS,I2C_MCS_RUN);
// Polling
BUS_BUSY(I2C0_I2CMCS);
//Error Detection
if(GET_BIT(I2C0_I2CMCS,I2C_MCS_ERROR))
{
//<!TODO ERROR STATE>
// return error
}
break ;
case I2C1:break ;
case I2C2:break ;
case I2C3:break ;
}
}
void I2C_voidSlaveTransmitMassege(I2C_Chennal copy_I2CChennalSelect, u8 copy_u8Data)
{
switch (copy_I2CChennalSelect)
{
case I2C0:
I2C0_I2CMDR = copy_u8Data ;
//Polling
while(GET_BIT(I2C0_I2CSCSR,1) == 1 ); //RECIEVE DATA
break ;
case I2C1:break ;
case I2C2:break ;
case I2C3:break ;
}
}
u8 I2C_voidMaterRecieveMassege(I2C_Chennal copy_I2CChennalSelect)
{
u8 Data = 0 ;
switch(copy_I2CChennalSelect)
{
case I2C0:
//Start Condition
SET_BIT(I2C0_I2CMCS,I2C_MCS_START);
//Set RUN bit to make MASTER TX and RX.
SET_BIT(I2C0_I2CMCS,I2C_MCS_RUN);
//CLR STOP
CLR_BIT(I2C0_I2CMCS,I2C_MCS_STOP) ;
//Polling
BUS_BUSY(I2C0_I2CMCS);
//Error Detection
if(GET_BIT(I2C0_I2CMCS,I2C_MCS_ERROR))
{
//<!TODO ERROR STATE>
// return error
}
Data = I2C0_I2CMDR ;
break ;
case I2C1: break ;
case I2C2: break ;
case I2C3: break ;
}
return Data ;
}
u8 I2C_voidSlaveRecieveMassege(I2C_Chennal copy_I2CChennalSelect)
{
u8 Data = 0 ;
switch(copy_I2CChennalSelect)
{
case I2C0:
//Polling
while(GET_BIT(I2C0_I2CSCSR,0) == 1 ); //RECIEVE DATA
Data = I2C0_I2CMDR ;
break ;
case I2C1: break ;
case I2C2: break ;
case I2C3: break ;
}
return Data ;
}
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 27 August 2020 */
/*********************************************************************************/
#ifndef SCB_PRIVATE_H
#define SCB_PRIVATE_H
#define SCB_BASE_ADDRESS 0xE000ED00
/* REGISTER BOUNDARY ADDRESSES */
#define SCB_ACTLR *((volatile u32 *) SCB_BASE_ADDRESS + 0x00)
#define SCB_CPUID *((volatile u32 *) SCB_BASE_ADDRESS + 0x00)
#define SCB_ICSR *((volatile u32 *) SCB_BASE_ADDRESS + 0x04)
#define SCB_VTOR *((volatile u32 *) SCB_BASE_ADDRESS + 0x08)
#define SCB_AIRCR *((volatile u32 *) SCB_BASE_ADDRESS + 0x0C)
#define SCB_SCR *((volatile u32 *) SCB_BASE_ADDRESS + 0x10)
#define SCB_CCR *((volatile u32 *) SCB_BASE_ADDRESS + 0x14)
#define SCB_SHPR ((volatile u32 *) SCB_BASE_ADDRESS + 0x18)
#define SCB_SHCRS *((volatile u32 *) SCB_BASE_ADDRESS + 0x24)
#define SCB_CFSR *((volatile u32 *) SCB_BASE_ADDRESS + 0X28)
#define SCB_HFSR *((volatile u32 *) SCB_BASE_ADDRESS + 0x2C)
#define SCB_MMAR *((volatile u32 *) SCB_BASE_ADDRESS + 0x34)
#define SCB_BFAR *((volatile u32 *) SCB_BASE_ADDRESS + 0x38)
/* REGISTER VECT KEY */
#define SCB_AIRCR_VECT_KEY 0x05FA
/* GROUP SELECTION PRIORITY */
#define SCB_16_GROUP_0_SUB 0x3 //0b011 // 4 bits for group (IPR) ==> Group
#define SCB_8_GROUP_2_SUB 0x4 //0b100 // 3 bits for group and 1 bit for sub
#define SCB_4_GROUP_4_SUB 0x5 //0b101 // 2 bits for group and 2 bit for sun
#define SCB_2_GROUP_8_SUB 0x6 //0b110 // 1 bit for group and 3 bits for sub
#define SCB_0_GROUP_16_SUB 0x7 //0b111 // 0 bit for group and 4 bits for sub
#endif
<file_sep>/**************************************************************************/
/* Author : Mohamed */
/* Date : 26 January 2021 */
/* Version : V01 */
/**************************************************************************/
#ifndef STD_TYPES_H
#define STD_TYPES_H
typedef unsigned char u8;
typedef unsigned int u16;
typedef unsigned long int u32;
#endif<file_sep>#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "SSI_interface.h"
int main(void)
{
/* CLK */
SYSCTL->RCGCSSI |= 0x1; // Enable and provide a clock to SPI0
SYSCTL->RCGCGPIO |= 0x1; // Enable and provide a clock to GPIO PortA
/* Must Select the slave by making active-low slave select line low GPIOA->DATA */
GPIOA->AFSEL |= 0x3C; // Enable alternate functions on PA2, PA3, PA4, PA5
GPIOA->PCTL |= 0x222200; // Assign SPI signals to PA2, PA3, PA4, PA5
GPIOA->DEN |= 0x3C; // Enable digital functions for PA2, PA3, PA4, PA5
GPIOA->DIR |= 0x8; // Set PA3 as output
GPIOA->DATA |= 0x8; // Make slave select line high when idle
/* Init SPI0
on : SSI0 MasterMode using SysCLK 11500bitPerSecond SPI_Frame 7-bit Data size*/
void SSI_voidInit(SSI0,Master,SysCLK, 11500 ,SPI,7);
void SSI_voidEnable(SSI0);
void SSI_voidTransmitSynch(SSI0 ,'A');
while(1)
{
}
return 0;
}
<file_sep>/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 2 September 2020 */
/*********************************************************************************/
#ifndef SSI_CONFIG_H
#define SSI_CONFIG_H
/* NOTE THAT BaudRate= SysClk/(SSIn_CLK_PRESCALER * (1 + Serial CLK Rate))
U Enter
BaudRate in BitPerSecond
SysClk
SSIn_CLK_PRESCALER even Number
*/
/****************************************************************/
/** Enter the CPU FREQ */
/** F_CPU can be : */
/* 16MHz = 16000000UL */
/* 8MHz = 8000000UL */
/****************************************************************/
#define SYS_CLK 8000000UL
/*
*SSI0_CLK_PRESCALER : This value must be an even number from 2 to 254
OPTIONS IF USED SSI0:
even number from 2 to 254
*/
#define SSI0_CLK_PRESCALER 2
/*
*SSI1_CLK_PRESCALER : This value must be an even number from 2 to 254
OPTIONS IF USED SSI1:
even number from 2 to 254
*/
#define SSI1_CLK_PRESCALER 2
/*
*SSI2_CLK_PRESCALER : This value must be an even number from 2 to 254
OPTIONS IF USED SSI2 :
even number from 2 to 254
*/
#define SSI2_CLK_PRESCALER 2
/*
*SSI3_CLK_PRESCALER : This value must be an even number from 2 to 254
OPTIONS IF USED SSI3:
even number from 2 to 254
*/
#define SSI3_CLK_PRESCALER 2
/*
*SSI0_IDLE_STATE :
OPTIONS IF USED SSI0:
IDLE_LOW
IDLE_HIGH
if Select High, then software must also configure the GPIO port pin signal as a pull-up in the GPIO Pull-Up Select
*/
#define SSI0_IDLE_STATE IDLE_HIGH
/*
*SSI0_DATA_CAPTURING :
OPTIONS IF USED SSI0:
CAPTURE_AT_FIRST_CLK_EDGE
CAPTURE_AT_SECOND_CLK_EDGE
*/
#define SSI0_DATA_CAPTURING CAPTURE_AT_SECOND_CLK_EDGE
#endif
<file_sep>/**************************************************************************/
/* Author : Mohamed */
/* Date : 26 January 2021 */
/* Version : V01 */
/**************************************************************************/
#ifndef BIT_MATH_H
#define BIT_MATH_H
#define SET_BIT(VAR,BIT_NUM) VAR |= (1 << BIT_NUM)
#define CLR_BIT(VAR,BIT_NUM) VAR &= ~(1<<BIT_NUM)
#define TOG_BIT(VAR,BIT_NUM) VAR ^= (1 << BIT_NUM)
#define GET_BIT(VAR,BIT_NUM) VAR = ((1 >> BIT_NUM) & 1 )
#define NULL (void *)0
#endif | 08109eed35e9281d5f615ed90ab8afe159ec59be | [
"Markdown",
"C"
] | 28 | C | Abnaby/SeimensEDA | 8222374e1eef57f8178bccc4f96acae39b2ef0b4 | 47e48c89deda2c7a949f59e94516ce83b9894034 |
refs/heads/master | <file_sep>package com.company;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("example");
frame.setSize(500,500);
JPanel panel = new JPanel();
JLabel label = new JLabel();
label.setText("Mój label");
JButton przycisk1 = new JButton();
JButton przycisk2 = new JButton();
Dimension wymiary = new Dimension(250, 20);
przycisk1.setText("button one");
przycisk2.setText("button two");
przycisk1.setLocation(1,2);
przycisk2.setLocation(10,2);
przycisk1.setPreferredSize(wymiary);
przycisk2.setPreferredSize(wymiary);
frame.setLocationRelativeTo(null);
panel.add(label);
panel.add(przycisk1);
panel.add(przycisk2);
frame.add(panel);
frame.setVisible(true);
frame.repaint(1,2,3,4);
}
}
| 829543f37590f01f8ff21faa79414d3cb51d08e2 | [
"Java"
] | 1 | Java | Leithain/helloJava | 0ff4c8cb581523b0b7c0164e6dd1bb611272622d | d236522c52e354245b48cc2d2ec039867811bd99 |
refs/heads/main | <repo_name>nathanmaru/WhatNote<file_sep>/EventListeners/NoteListener.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Firebase.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WhatNote.Data_Models;
using WhatNote.Helpers;
namespace WhatNote.EventListeners
{
public class NoteListener : Java.Lang.Object, IValueEventListener
{
List<Note> noteList = new List<Note>();
public event EventHandler<NoteDataEventArgs> NoteRetrived;
public class NoteDataEventArgs : EventArgs
{
public List<Note> Note { get; set; }
}
public void OnCancelled(DatabaseError error)
{
}
public void OnDataChange(DataSnapshot snapshot)
{
if (snapshot.Value != null)
{
var child = snapshot.Children.ToEnumerable<DataSnapshot>();
noteList.Clear();
foreach (DataSnapshot noteData in child)
{
Note note = new Note();
note.ID = noteData.Key;
note.NoteTitle = noteData.Child("noteTitle").Value.ToString();
note.NoteContent = noteData.Child("noteContent").Value.ToString();
note.NoteDate = noteData.Child("noteDate").Value.ToString();
noteList.Add(note);
}
NoteRetrived.Invoke(this, new NoteDataEventArgs { Note = noteList });
}
}
public void Create()
{
DatabaseReference noteRef = AppDataHelper.GetDatabase().GetReference("note");
noteRef.AddValueEventListener(this);
}
public void DeleteNote(string key)
{
DatabaseReference reference = AppDataHelper.GetDatabase().GetReference("note/" + key);
reference.RemoveValue();
}
}
}<file_sep>/Activities/ViewNoteContentActivity.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using Firebase.Database;
using FR.Ganfra.Materialspinner;
using Java.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WhatNote.Adapter;
using WhatNote.Data_Models;
using WhatNote.EventListeners;
using WhatNote.Helpers;
using SupportV7 = Android.Support.V7.App;
namespace WhatNote.Activities
{
[Activity(Label = "ViewNoteContentActivity")]
public class ViewNoteContentActivity : Activity
{
EditText noteTitleText;
EditText noteContentText;
Button updateButton;
string id;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.ViewNoteContent);
string key = Intent.GetStringExtra("key");
string title = Intent.GetStringExtra("noteTitle");
string content = Intent.GetStringExtra("noteContent");
string notedate = Intent.GetStringExtra("noteDate");
// Create your application here
noteTitleText = (EditText)FindViewById(Resource.Id.noteTitleText);
noteContentText = (EditText)FindViewById(Resource.Id.noteContentText);
updateButton = (Button)FindViewById(Resource.Id.submitButton);
noteTitleText.Text = title;
noteContentText.Text = content;
id = key;
updateButton.Click += UpdateButton_Click;
//SetupStatusSPinner();
//RetriveData();
}
private void UpdateButton_Click(object sender, EventArgs e)
{
string title = noteTitleText.Text;
string content = noteContentText.Text;
var date = DateTime.Now;
string noteDate = date.ToString("dd/MM/yyyy, hh:mm");
SupportV7.AlertDialog.Builder saveDataAlert = new SupportV7.AlertDialog.Builder(updateButton.Context);
saveDataAlert.SetTitle("Note Update");
saveDataAlert.SetMessage("Do you want to update this Note?");
saveDataAlert.SetPositiveButton("OK", (senderAlert, args) =>
{
AppDataHelper.GetDatabase().GetReference("note/" + id + "/noteTitle").SetValue(title);
AppDataHelper.GetDatabase().GetReference("note/" + id + "/noteContent").SetValue(content);
AppDataHelper.GetDatabase().GetReference("note/" + id + "/noteDate").SetValue(noteDate);
Toast.MakeText(updateButton.Context, "Note Updated!", ToastLength.Short).Show();
var intent = new Intent(this, typeof(MainActivity));
StartActivity(intent);
});
saveDataAlert.SetNegativeButton("Cancel", (senderAlert, args) =>
{
saveDataAlert.Dispose();
});
saveDataAlert.Show();
}
}
}<file_sep>/Activities/LoginActivity.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WhatNote.Activities
{
[Activity(Label = "LoginActivity")]
public class LoginActivity : Activity
{
TextInputLayout username;
TextInputLayout password;
Button loginButton;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.LoginPage);
// Create your application here
username = (TextInputLayout)FindViewById(Resource.Id.usernameText);
password = (TextInputLayout)FindViewById(Resource.Id.passwordText);
loginButton = (Button)FindViewById(Resource.Id.loginButton);
loginButton.Click += LoginButton_Click;
}
private void LoginButton_Click(object sender, EventArgs e)
{
///Checks the account
}
}
}<file_sep>/MainActivity.cs
using Android.App;
using Android.OS;
using Android.Runtime;
using AndroidX.AppCompat.App;
using Android.Widget;
using Android.Support.V7.Widget;
using System.Collections.Generic;
using WhatNote.Data_Models;
using WhatNote.Fragments;
using Android.Content;
using WhatNote.Activities;
using WhatNote.EventListeners;
using System.Linq;
using WhatNote.Adapter;
namespace WhatNote
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
ImageView searchButton;
EditText searchText;
ImageView addButton;
RecyclerView myRecyclerView;
TextView whatNote;
List<Note> NoteList;
NoteAdapter adapter;
NoteListener noteListener;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
myRecyclerView = (RecyclerView)FindViewById(Resource.Id.MyRecyclerView);
addButton = (ImageView)FindViewById(Resource.Id.addButton);
searchButton = (ImageView)FindViewById(Resource.Id.searchButton);
searchText = (EditText)FindViewById(Resource.Id.searchText);
whatNote = (TextView)FindViewById(Resource.Id.whatNote);
searchButton.Click += SearchButton_Click;
searchText.TextChanged += SearchText_TextChanged;
addButton.Click += AddButton_Click;
whatNote.Click += WhatNote_Click;
RetriveData();
}
private void SearchText_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
{
List<Note> SearchResult =
(from note in NoteList
where note.NoteTitle.ToLower().Contains(searchText.Text.ToLower()) ||
note.NoteContent.ToLower().Contains(searchText.Text.ToLower())select note).ToList();
adapter = new NoteAdapter(SearchResult);
myRecyclerView.SetAdapter(adapter);
}
private void WhatNote_Click(object sender, System.EventArgs e)
{
var intent = new Intent(this, typeof(LoginActivity));
StartActivity(intent);
}
public void RetriveData()
{
noteListener = new NoteListener();
noteListener.Create();
noteListener.NoteRetrived += NoteListener_NoteRetrived;
}
private void NoteListener_NoteRetrived(object sender, NoteListener.NoteDataEventArgs e)
{
NoteList = e.Note;
SetupRecyclerView();
}
private void AddButton_Click(object sender, System.EventArgs e)
{
var intent = new Intent(this, typeof(Add_Note));
StartActivity(intent);
/*addNoteFragment = new AddNoteFragment();
var trans = SupportFragmentManager.BeginTransaction();
addNoteFragment.Show(trans, "new note");*/
}
private void SetupRecyclerView()
{
myRecyclerView.SetLayoutManager(new Android.Support.V7.Widget.LinearLayoutManager(myRecyclerView.Context));
adapter = new NoteAdapter(NoteList);
adapter.DeleteItemClick += Adapter_DeleteItemClick;
adapter.ItemClick += Adapter_ItemClick;// this after setting up adapter
myRecyclerView.SetAdapter(adapter);
}
///When a recycle viewItem is click
private void Adapter_ItemClick(object sender, NoteAdapterClickEventArgs e)
{
string key = NoteList[e.Position].ID;
string noteTitle = NoteList[e.Position].NoteTitle;
string noteContent = NoteList[e.Position].NoteContent;
string noteDate = NoteList[e.Position].NoteDate;
var intent = new Intent(this, typeof(ViewNoteContentActivity));
intent.PutExtra("key", key);
intent.PutExtra("noteTitle", noteTitle);
intent.PutExtra("noteContent", noteContent);
intent.PutExtra("noteDate", noteDate);
StartActivity(intent);
}
private void Adapter_DeleteItemClick(object sender, NoteAdapterClickEventArgs e)
{
string key = NoteList[e.Position].ID;
Android.Support.V7.App.AlertDialog.Builder deleteNote = new Android.Support.V7.App.AlertDialog.Builder(this);
deleteNote.SetTitle("Delete Note");
deleteNote.SetMessage("Are you sure you want to delete this note?");
deleteNote.SetPositiveButton("Continue", (deleteAlert, args) =>
{
noteListener.DeleteNote(key);
Toast.MakeText(this, "Note Deleted!", ToastLength.Short).Show();
});
deleteNote.SetNegativeButton("Cancel", (deleteAlert, args) =>
{
deleteNote.Dispose();
});
deleteNote.Show();
}
private void SearchButton_Click(object sender, System.EventArgs e)
{
if(searchText.Visibility == Android.Views.ViewStates.Gone)
{
searchText.Visibility = Android.Views.ViewStates.Visible;
}
else
{
searchText.ClearFocus();
searchText.Visibility = Android.Views.ViewStates.Gone;
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}<file_sep>/DataModel/Note.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WhatNote.Data_Models
{
public class Note
{
public string ID { get; set; }
public string NoteTitle { get; set; }
public string NoteContent { get; set; }
public string NoteDate { get; set; }
}
}<file_sep>/Fragments/AddNoteFragment.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Util;
using Android.Views;
using Android.Widget;
using FR.Ganfra.Materialspinner;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WhatNote;
namespace WhatNote.Fragments
{
public class AddNoteFragment : Android.Support.V4.App.DialogFragment
{
TextInputLayout noteTitleText;
TextInputLayout noteContentText;
Button submitButton;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
View view = inflater.Inflate(Resource.Layout.AddNote, container, false);
noteTitleText = (TextInputLayout)view.FindViewById(Resource.Id.noteTitleText);
noteContentText = (TextInputLayout)view.FindViewById(Resource.Id.noteContentText);
submitButton = (Button)view.FindViewById(Resource.Id.submitButton);
return view;
}
}
}<file_sep>/Activities/AddNoteActivity.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Widget;
using Firebase.Database;
using FR.Ganfra.Materialspinner;
using Java.Util;
using System;
using System.Collections.Generic;
using WhatNote.Helpers;
using SupportV7 = Android.Support.V7.App;
namespace WhatNote.Activities
{
[Activity(Label = "Add_Note")]
public class Add_Note : Activity
{
TextInputLayout noteTitleText;
TextInputLayout noteContentText;
Button submitButton;
ArrayAdapter<string> adapter;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.AddNote);
// Create your application here
noteTitleText = (TextInputLayout)FindViewById(Resource.Id.noteTitleText);
noteContentText = (TextInputLayout)FindViewById(Resource.Id.noteContentText);
submitButton = (Button)FindViewById(Resource.Id.submitButton);
submitButton.Click += SubmitButton_Click;
}
private void SubmitButton_Click(object sender, EventArgs e)
{
string noteTitle = noteTitleText.EditText.Text;
string noteContent = noteContentText.EditText.Text;
var date = DateTime.Now;
string noteDate = date.ToString("dd/MM/yyyy, hh:mm");
HashMap noteInfo = new HashMap();
noteInfo.Put("noteTitle", noteTitle);
noteInfo.Put("noteContent", noteContent);
noteInfo.Put("noteDate", noteDate);
SupportV7.AlertDialog.Builder saveDataAlert = new SupportV7.AlertDialog.Builder(submitButton.Context);
saveDataAlert.SetTitle("Note Save");
saveDataAlert.SetMessage("Do you want to save this Note?");
saveDataAlert.SetPositiveButton("OK", (senderAlert, args) =>
{
DatabaseReference newNoteRef = AppDataHelper.GetDatabase().GetReference("note").Push();
newNoteRef.SetValue(noteInfo);
Toast.MakeText(submitButton.Context, "Note Saved!", ToastLength.Short).Show();
var intent = new Intent(this, typeof(MainActivity));
StartActivity(intent);
});
saveDataAlert.SetNegativeButton("Cancel", (senderAlert, args) =>
{
saveDataAlert.Dispose();
});
saveDataAlert.Show();
}
}
} | dcf400910cd4f3049e317b1a68432fd165f33704 | [
"C#"
] | 7 | C# | nathanmaru/WhatNote | ca10ffcb9f05699b5d3489f1205f6198b36d3217 | 72a5e75f6f5a43dc0ace68d90db5be0025ed6a9a |
refs/heads/master | <file_sep># *Libera*: Network Hypervisor for Programmable Network Virtualization in Datacenters
## Paper
When you use or reference this software, please cite the following paper.
+ [<NAME>, <NAME>, <NAME> and <NAME>, "Libera for Programmable Network Virtualization," in IEEE Communications Magazine, April 2020.](https://ieeexplore.ieee.org/document/9071987)
## Contents
+ [Introduction](#introduction)
+ [*Libera* workflow](#workflow)
+ [Tutorial](#tutorial)
+ [Source code installation](#install)
+ [References](#reference)
+ [Others](#others)
+ [Contacts](#contacts)
<a name="introduction"></a>
## Introduction
This documentation includes the step-by-step instructions to run and test *Libera* framework.
*Libera* is SDN-based network hypervisor that creates multiple virtual networks (VNs) for tenants. This software is developed based on OpenVirteX, which is originally developed by ONF (Open Networking Foundation). Now, OpenVirteX and *Libera* are both managed by Korea University.
<a name="workflow"></a>
## *Libera* workflow
### Initialization
The following figure shows the initialization of *Libera* and creation of VN.
<img src="https://openvirtex.com/wp-content/uploads/2019/11/flow1.jpg" width="80%" height="80%">
### VN programming
Also, the figure below shows the basic network program sequence between physical network, Libera, and VN controller.
<img src="https://openvirtex.com/wp-content/uploads/2019/11/flow2.jpg" width="60%" height="60%">
<a name="tutorial"></a>
## Tutorial
We provide a VM-based tutorial that is easy to follow.
### Preparation
+ Install virtualbox software: [https://www.virtualbox.org/](https://www.virtualbox.org/)
+ Get the virtual machines we have prepared - [Here!](https://drive.google.com/drive/folders/12JCu5ltiH0ITGq_nP-zRaOQT-05uEQ8i?usp=sharing)
+ Note that the password for the account is *<PASSWORD>*
+ "Mininet" VM for emulating physical network
+ "Libera" VM for running *Libera* framework
+ "ONOS" for running ONOS controller as VN controller
+ Open the provided VMs through virtual box (see [here](https://www.virtualbox.org/manual/UserManual.html#ovf) for the steps)
> Note that while opening the VMs, **you should check "MAC address policy" to include all adapters MAC addresses!** If you choose "Include only NAT network adapter MAC addresses", the pre-configured static IPs do not work!
+ Check whether the network connections work between VMs through *ping*.
+ Mininet: 10.0.0.1 / Libera: 10.0.0.2 / ONOS: 10.0.0.3
+ [Mininet] Ping to *Libera* or ONOS
```shell
ping 10.0.0.2
ping 10.0.0.3
```
+ [Libera] Ping to ONOS
```shell
ping 10.0.0.3
```
### Enjoy the programmable virtual SDN!
+ [Mininet] Physical network creation
We create a physical topology as shown in the figure below. Use the python file that automates the creation of the topology!
```shell
sudo python internet2_OF13.py
```
<img src="https://openvirtex.com/wp-content/uploads/2014/04/topo.png" width="50%" height="50%">
- If you create physical network repeatedly, put the following command to get rid of the created Mininet emulations.
```shell
sudo mn -c
```
+ [Libera] Execute *Libera* framework
```shell
cd /home/libera/Libera
sh scripts/libera.sh –-db-clear
```
When the physical network is initiated, the logs for physical topology discovery appears in [Libera] as follows:

Wait for a moment until the entire network is discovered.
+ [ONOS] Run the ONOS controller to be used as VN controller
For the tenant to directly program its VN, we use ONOS, which is widely-used. The ONOS VM provides the script to build multiple ONOS controllers for multi-tenant evaluations.
```shell
sudo sh onos_multiple.sh -t 1 -i 10.0.0.3
```
- -t: the number of tenants
- -i: IP address
When the initiation is finished, you can check the ONOS GUI to check whether it works normally.
- URL: http://10.0.0.3:20000/onos/ui/ [Should access from ONOS VM].
- Account: ID - karaf, PW - karaf
<img src="https://openvirtex.com/wp-content/uploads/2019/11/3.jpg" width="40%" height="40%"> <img src="https://openvirtex.com/wp-content/uploads/2019/11/4.jpg" width="40%" height="40%">
+ [Libera] Now, create the VN topology.
We input several commands in *Libera* to create the following VN topology:
<img src="https://openvirtex.com/wp-content/uploads/2014/04/vnet1.png" width="50%" height="50%">
Each virtual switch, port, and link is created by single command. Fortunately, we provide a script for the above VN topology as follow. Enter the following command from a new shell.
```shell
cd /home/libera/Libera/utils
sh examplevn.sh
```
When the VN topology creation is finished, the topology appears in the ONOS VM!
<img src="https://openvirtex.com/wp-content/uploads/2019/11/5.jpg" width="50%" height="50%">
+ [Mininet] VN is ready. Let's create network traffic.
Since our network topology allows network connections between H_SEA_1 and H_LAX_2, let's ping them. (Note that the following command is entered in the Mininet)
```shell
h_SEA_1 ping -c10 h_LAX_2
```
As shown in the figure below, the packets normally goes. This is because the ONOS VN controller programmed network routing to its virtual switches, and it is appropriately installed in the physical network.
<img src="https://openvirtex.com/wp-content/uploads/2019/11/6.jpg" width="50%" height="50%">
<a name="install"></a>
## Source code installation
*Libera* is built based on OpenVirteX, so you can follow the installation guide of OpenVirteX [here](https://openvirtex.com/getting-started/installation/).
When following the guide, please clone the repository of Libera, not the OpenVirteX. Also, run the VNC with ONOS, not the Floodlight.
<a name="reference"></a>
## References
It is welcomed to reference the following papers for *Libera* framework.
+ TBD
<a name="others"></a>
## Others
We tested *Libera* framework only with Ubuntu 14.04 version.
Basic structure and APIs for this hypervisor is shared with OpenVirteX (as shown [here](https://www.openvirtex.com)).
<a name="contacts"></a>
## Contacts
+ This project is under the lead of Professor <NAME>.
+ Contributors: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Anumeha, <NAME>
+ Mailing list: [Here](https://groups.google.com/forum/#!forum/ovx-discuss) - We share mailing list with OpenVirteX
<file_sep># Open-source compliance discovered by FOSSLight Scanner
This directory includes the open-source compliance of Libera found by FossLight.
The FOSSLight Scanner is composed of a Prechecker, Dependency Scanner, Source Code Scanner, and Binary Scanner. The scanning process is carried out in the following order:
1. **Prechecker**
- Checks the copyright and license rule within the source code
2. **Dependency Scanner**
- A tool that extracts open-source information while recursively traversing the dependencies of the package manager
3. **Source Scanner**
- Uses ScanCode to search for strings in the source code and find copyright and license phrases
4. **Binary Scanner**
- A tool that extracts binary files and lists of binary files. If there is open-source information included in the searched binary in the database, it outputs it
The verification was done through fosslight v.1.7.11 in a Python 3.8 virtualenv environment on Ubuntu 20.04.6 LTS (Linux 5.4.0-148-generic).
The results include information such as the path of the source code, Open Source Software (OSS) information, License information, download path, homepage, Copyright, etc.
<file_sep>python ovxctl.py -n createNetwork tcp:10.0.0.3:10000 10.0.0.0 16
python ovxctl.py -n createSwitch 1 fc00:db20:35b:7399::5
python ovxctl.py -n createSwitch 1 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b
python ovxctl.py -n createSwitch 1 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b
python ovxctl.py -n createPort 1 fc00:db20:35b:7399::5 1
python ovxctl.py -n createPort 1 fc00:db20:35b:7399::5 5
python ovxctl.py -n createPort 1 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b 5
python ovxctl.py -n createPort 1 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b 6
python ovxctl.py -n createPort 1 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b 5
python ovxctl.py -n createPort 1 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b 2
python ovxctl.py -n connectLink 1 fdf8:f53e:61e4::18 2 fc00:e968:6179::de52:7100 1 spf 1
python ovxctl.py -n connectLink 1 fc00:e968:6179::de52:7100 2 fdf8:f53e:61e4::18 1 spf 1
python ovxctl.py -n connectHost 1 fdf8:f53e:61e4::18 1 00:00:00:00:01:01
python ovxctl.py -n connectHost 1 fdf8:f53e:61e4::18 2 00:00:00:00:03:02
python ovxctl.py -n startNetwork 1
<file_sep><!--
~
~ ******************************************************************************
~ Copyright 2019 Korea University & Open Networking Foundation
~
~ 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.
~ ******************************************************************************
~ Developed by Libera team, Operating Systems Lab of Korea University
~ ******************************************************************************
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.onrc.openvirtex</groupId>
<artifactId>Libera</artifactId>
<packaging>jar</packaging>
<version>0.1</version>
<name>Libera</name>
<url>https://openvirtex.com/</url>
<properties>
<cobertura-maven-plugin.version>2.6</cobertura-maven-plugin.version>
<findbugs-plugin.version>2.5.3</findbugs-plugin.version>
<findbugs.effort>Max</findbugs.effort>
<findbugs.excludeFilterFile>config/findbugs/exclude.xml</findbugs.excludeFilterFile>
<checkstyle-plugin.version>2.12</checkstyle-plugin.version>
<!-- To publish javadoc to github,
uncomment com.github.github site-maven-plugin and
see https://github.com/OPENNETWORKINGLAB/ONOS/pull/425
<github.global.server>github</github.global.server>
-->
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<configuration>
<charset>UTF-8</charset>
<locale>en</locale>
</configuration>
</plugin>
<plugin>
<!-- Note: the checkstyle configuration is also in the reporting section -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-plugin.version}</version>
<configuration>
<configLocation>config/checkstyle/sun_checks.xml</configLocation>
<propertiesLocation>${basedir}/config/checkstyle/checkstyle_maven.properties</propertiesLocation>
<failsOnError>false</failsOnError>
<logViolationsToConsole>true</logViolationsToConsole>
</configuration>
<executions>
<execution>
<id>validate-checkstyle</id>
<phase>verify</phase>
<goals>
<goal>checkstyle</goal>
</goals>
<!-- Uncomment this once we have cleaned up the code
<goals>
<goal>check</goal>
</goals>
-->
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
<executions>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<forkMode>always</forkMode>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>${cobertura-maven-plugin.version}</version>
<configuration>
<instrumentation>
<ignores>
<ignore>org.slf4j.*</ignore>
</ignores>
<excludes>
<exclude>org/openflow/**/*.class</exclude>
</excludes>
</instrumentation>
<check/>
</configuration>
<executions>
<execution>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Note: the findbugs configuration is also in the reporting section -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>${findbugs-plugin.version}</version>
<configuration>
<effort>${findbugs.effort}</effort>
<excludeFilterFile>${findbugs.excludeFilterFile}</excludeFilterFile>
</configuration>
<executions>
<execution>
<id>validate-findbugs</id>
<phase>verify</phase>
<goals>
<goal>findbugs</goal>
<!-- Uncomment this goal to make the build fail on findbugs errors -->
<!--<goal>check</goal>-->
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.1</version>
<configuration>
<!--
Note: Exclusion definition exists in multiple places.
- In file ${findbugs.excludeFilterFile} defined at top of pom.xml
- maven-checkstyle-plugin configuration in pom.xml
- maven-pmd-plugin configuration in pom.xml
(under build and reporting)
-->
<excludes>
<exclude>**/org/openflow/**</exclude>
</excludes>
<rulesets>
<ruleset>${basedir}/config/pmd/ovx_ruleset.xml</ruleset>
</rulesets>
</configuration>
<executions>
<execution>
<id>validate-pmd</id>
<phase>verify</phase>
<goals>
<goal>pmd</goal>
<goal>cpd</goal>
<!-- Uncomment this goal to make the build fail on pmd errors -->
<!--<goal>check</goal>-->
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>net.onrc.openvirtex.core.Libera</mainClass>
</configuration>
<executions>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>net.onrc.openvirtex.core.Libera</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>Libera</finalName>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<excludeDefaults>true</excludeDefaults>
<outputDirectory>${project.build.directory}/site</outputDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<configuration>
<charset>UTF-8</charset>
<locale>en</locale>
</configuration>
</plugin>
<plugin>
<!-- Note: the checkstyle configuration is also in the build section -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-plugin.version}</version>
<configuration>
<configLocation>config/checkstyle/sun_checks.xml</configLocation>
<propertiesLocation>${basedir}/config/checkstyle/checkstyle_maven.properties</propertiesLocation>
<!--
Note: Exclusion definition exists in multiple places.
- In file ${findbugs.excludeFilterFile} defined at top of pom.xml
- maven-checkstyle-plugin configuration in pom.xml
- maven-pmd-plugin configuration in pom.xml
(under build and reporting)
-->
</configuration>
<reportSets>
<reportSet>
<reports>
<report>checkstyle</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>${findbugs-plugin.version}</version>
<configuration>
<effort>${findbugs.effort}</effort>
<excludeFilterFile>${findbugs.excludeFilterFile}</excludeFilterFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.1</version>
<configuration>
<!--
Note: Exclusion definition exists in multiple places.
- In file ${findbugs.excludeFilterFile} defined at top of pom.xml
- maven-checkstyle-plugin configuration in pom.xml
- maven-pmd-plugin configuration in pom.xml
(under build and reporting)
-->
<excludes>
<exclude>**/org/openflow/**</exclude>
</excludes>
<rulesets>
<ruleset>${basedir}/config/pmd/ovx_ruleset.xml</ruleset>
</rulesets>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>${cobertura-maven-plugin.version}</version>
</plugin>
</plugins>
</reporting>
<repositories>
<repository>
<id>jsonrpc4j-webdav-maven-repo</id>
<name>jsonrpc4j maven repository</name>
<url>http://jsonrpc4j.googlecode.com/svn/maven/repo/</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>jsonrpc2-base</artifactId>
<version>1.35</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>jsonrpc2-server</artifactId>
<version>1.10.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.0.5.v20130815</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-security</artifactId>
<version>9.0.5.v20130815</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-http</artifactId>
<version>9.0.5.v20130815</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>9.0.5.v20130815</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-rc1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-rc1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.0-rc1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>args4j</groupId>
<artifactId>args4j</artifactId>
<version>2.0.25</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.googlecode.concurrent-trees</groupId>
<artifactId>concurrent-trees</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jboss.netty</groupId>
<artifactId>netty</artifactId>
<version>3.2.9.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>org.jacoco.agent</artifactId>
<version>0.6.3.201306030806</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>openflowj</artifactId>
<version>0.9.2.onos</version>
</dependency>
</dependencies>
<profiles>
<!-- Jenkins by default defines a property BUILD_NUMBER which is used to
enable the profile. -->
<profile>
<id>jenkins</id>
<activation>
<property>
<name>env.BUILD_NUMBER</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>${cobertura-maven-plugin.version}</version>
<configuration>
<formats>
<format>xml</format>
</formats>
<check/>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>cobertura</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
<file_sep>/*
*
* ******************************************************************************
* Copyright 2019 Korea University & Open Networking Foundation
*
* 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.
* ******************************************************************************
* Developed by Libera team, Operating Systems Lab of Korea University
* ******************************************************************************
*
*/
package net.onrc.openvirtex.messages;
import net.onrc.openvirtex.elements.address.IPMapper;
import net.onrc.openvirtex.elements.datapath.OVXSwitch;
import net.onrc.openvirtex.elements.port.OVXPort;
import net.onrc.openvirtex.exceptions.ActionVirtualizationDenied;
import net.onrc.openvirtex.exceptions.DroppedMessageException;
import net.onrc.openvirtex.messages.actions.OVXAction;
import net.onrc.openvirtex.messages.actions.OVXActionUtil;
import net.onrc.openvirtex.messages.actions.VirtualizableAction;
import net.onrc.openvirtex.protocol.OVXMatch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.projectfloodlight.openflow.exceptions.OFParseError;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.match.Match;
import org.projectfloodlight.openflow.protocol.match.MatchField;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.HexString;
import net.onrc.openvirtex.elements.OVXmodes.OVXmodeHandler;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class OVXPacketOut extends OVXMessage implements Devirtualizable {
private final Logger log = LogManager.getLogger(OVXPacketOut.class
.getName());
private Match match = null;
private final List<OFAction> approvedActions = new LinkedList<OFAction>();
public OVXPacketOut(OFMessage msg) {
super(msg);
}
public OVXPacketOut(final byte[] pktData, final short inPort,
final short outPort, OFVersion ofVersion) {
super(null);
OFActions ofActions = OFFactories.getFactory(ofVersion).actions();
final ArrayList<OFAction> actions = new ArrayList<OFAction>();
OFActionOutput actionOutput = ofActions.buildOutput()
.setPort(OFPort.of(outPort))
.setMaxLen((short) 65535)
.build();
actions.add(actionOutput);
this.setOFMessage(OFFactories.getFactory(ofVersion).buildPacketOut()
.setInPort(OFPort.of(inPort))
.setBufferId(OFBufferId.NO_BUFFER)
.setActions(actions)
.setData(pktData)
.build()
);
}
public OFPacketOut getPacketOut() {
return (OFPacketOut)this.getOFMessage();
}
@Override
public void devirtualize(final OVXSwitch sw) throws OFParseError {
this.log.debug("devirtualize");
//this.log.info(HexString.toHexString(this.getPacketOut().getData()));
OVXPort inport = sw.getPort(this.getPacketOut().getInPort().getShortPortNumber());
OVXMatch ovxMatch = null;
if (this.getPacketOut().getBufferId() == OFBufferId.NO_BUFFER) {
if (this.getPacketOut().getData().length <= 14) {
this.log.error("PacketOut has no buffer or data {}; dropping",
this);
sw.sendMsg(OVXMessageUtil.makeErrorMsg(OFBadRequestCode.BAD_LEN, this), sw);
return;
}
this.match = OVXMessageUtil.loadFromPacket(
this.getPacketOut().getData(),
this.getPacketOut().getInPort().getShortPortNumber(),
sw.getOfVersion()
);
this.log.debug("Data Length = " + this.getPacketOut().getData().length);
this.log.debug(this.match.toString());
ovxMatch = new OVXMatch(this.match);
ovxMatch.setPktData(this.getPacketOut().getData());
} else {
final OVXPacketIn cause = sw.getFromBufferMap(this.getPacketOut().getBufferId().getInt());
if (cause == null) {
this.log.error(
"Unknown buffer id {} for virtual switch {}; dropping",
this.getPacketOut().getBufferId().getInt(), sw);
return;
}
this.match = OVXMessageUtil.loadFromPacket(
cause.getPacketIn().getData(),
this.getPacketOut().getInPort().getShortPortNumber(),
sw.getOfVersion()
);
this.setOFMessage(this.getPacketOut().createBuilder()
.setBufferId(cause.getPacketIn().getBufferId())
.build()
);
ovxMatch = new OVXMatch(this.match);
ovxMatch.setPktData(cause.getPacketIn().getData());
if (cause.getPacketIn().getBufferId() == OFBufferId.NO_BUFFER) {
this.setOFMessage(this.getPacketOut().createBuilder()
.setData(cause.getPacketIn().getData())
.build()
);
}
}
for (final OFAction act : this.getPacketOut().getActions()) {
try {
OVXAction action2 = OVXActionUtil.wrappingOVXAction(act);
((VirtualizableAction) action2).virtualize(sw, this.approvedActions, ovxMatch);
} catch (final ActionVirtualizationDenied e) {
this.log.warn("Action {} could not be virtualized; error: {}",
act, e.getMessage());
sw.sendMsg(OVXMessageUtil.makeError(e.getErrorCode(), this), sw);
return;
} catch (final DroppedMessageException e) {
this.log.debug("Dropping packetOut {}", this);
return;
} catch (final NullPointerException e) {
this.log.debug("Action {} could not be supported", act);
return;
}
}
if (U16.f(this.getPacketOut().getInPort().getShortPortNumber()) <
U16.f(OFPort.MAX.getShortPortNumber())) {
this.setOFMessage(this.getPacketOut().createBuilder()
.setInPort(OFPort.of(inport.getPhysicalPortNumber()))
.build()
);
}
//this.prependRewriteActions(sw);
if (OVXmodeHandler.getOVXmode() != 1)
this.prependRewriteActions(sw);
this.setOFMessage(this.getPacketOut().createBuilder()
.setActions(this.approvedActions)
.build()
);
if (U16.f(this.getPacketOut().getInPort().getShortPortNumber()) <
U16.f(OFPort.MAX.getShortPortNumber())) {
OVXMessageUtil.translateXid(this, inport);
}
this.log.debug("Sending packet-out to sw {}: {}", sw.getName(), this);
//this.log.info(HexString.toHexString(this.getPacketOut().getData()));
//log.info(this.getPacketOut().toString());
sw.sendSouth(this, inport);
}
private void prependRewriteActions(final OVXSwitch sw) {
if(this.getOFMessage().getVersion() == OFVersion.OF_10)
prependRewriteActionsVer10(sw);
else
prependRewriteActionsVer13(sw);
}
private void prependRewriteActionsVer13(final OVXSwitch sw) {
if(this.match.get(MatchField.IPV4_SRC) != null) {
OFActionSetField ofActionSetField = this.factory.actions().buildSetField()
.setField(this.factory.oxms().ipv4Src(
IPv4Address.of(
IPMapper.getPhysicalIp(
sw.getTenantId(),
this.match.get(MatchField.IPV4_SRC).getInt()))))
.build();
this.approvedActions.add(0, ofActionSetField);
}
if(this.match.get(MatchField.IPV4_DST) != null) {
OFActionSetField ofActionSetField = this.factory.actions().buildSetField()
.setField(this.factory.oxms().ipv4Dst(
IPv4Address.of(
IPMapper.getPhysicalIp(
sw.getTenantId(),
this.match.get(MatchField.IPV4_DST).getInt()))))
.build();
this.approvedActions.add(0, ofActionSetField);
}
}
private void prependRewriteActionsVer10(final OVXSwitch sw) {
if(this.match.get(MatchField.IPV4_SRC) != null) {
OFActionSetNwSrc srcAct = this.factory.actions().buildSetNwSrc()
.setNwAddr(IPv4Address.of(IPMapper.getPhysicalIp(sw.getTenantId(),
this.match.get(MatchField.IPV4_SRC).getInt())))
.build();
this.approvedActions.add(0, srcAct);
}
if(this.match.get(MatchField.IPV4_DST) != null) {
OFActionSetNwDst dstAct = this.factory.actions().buildSetNwDst()
.setNwAddr(IPv4Address.of(IPMapper.getPhysicalIp(sw.getTenantId(),
this.match.get(MatchField.IPV4_DST).getInt())))
.build();
this.approvedActions.add(0, dstAct);
}
}
@Override
public int hashCode() {
return this.getOFMessage().hashCode();
}
}
<file_sep>#!/bin/sh
OVXHOME=`dirname $0`/..
OVX_JAR="${OVXHOME}/target/Libera.jar"
JVM_OPTS="-Xms512m -Xmx2g"
## If you want JaCoCo Code Coverage reports... uncomment line below
#JVM_OPTS="$JVM_OPTS -javaagent:${OVXHOME}/lib/jacocoagent.jar=dumponexit=true,output=file,destfile=${OVXHOME}/target/jacoco.exec"
JVM_OPTS="$JVM_OPTS -XX:+TieredCompilation"
JVM_OPTS="$JVM_OPTS -XX:+UseCompressedOops"
#JVM_OPTS="$JVM_OPTS -XX:+UseConcMarkSweepGC -XX:+AggressiveOpts -XX:+UseFastAccessorMethods"
JVM_OPTS="$JVM_OPTS -XX:MaxInlineSize=8192 -XX:FreqInlineSize=8192"
#JVM_OPTS="$JVM_OPTS -XX:CompileThreshold=1500 -XX:PreBlockSpin=8"
if [ ! -e ${OVX_JAR} ]; then
cd ${OVXHOME}
echo "Packaging Libera for you..."
mvn package > /dev/null
cd -
fi
echo "Starting Libera..."
java ${JVM_OPTS} -Dlog4j.configurationFile=${OVXHOME}/config/log4j2.xml -Djavax.net.ssl.keyStore=${OVXHOME}/config/sslStore -jar ${OVX_JAR} $@
| 8542e0685a8bb0db239b4590d1c7d4dc98f74d9a | [
"Markdown",
"Java",
"Maven POM",
"Shell"
] | 6 | Markdown | os-libera/Libera | 08a3a652c07c6f331d3575ba8ccce897ce249d94 | f8a99d830789716e559d7813f118d2f0ddae41dc |
refs/heads/master | <repo_name>Zircod/LuLuShop<file_sep>/feedback/js/script.js
//checkbox отсутсвия отчества
function lackPatronymic(){
var patronymic_none= document.getElementById('patronymic_none');
var patronymic= document.getElementById("patronymic");
var result = '';
if (patronymic_none.checked){
patronymic.style.display="none";
}else if(patronymic.value.length > 3) {
patronymic.style.display="block";
result = "Отчество Введено корректно";
console.log(patronymic.value);
console.log(patronymic.value.length);
}else if(patronymic.value.length <= 3){
patronymic.style.display="block";
result = "Введите корректное Отчество";
console.log(patronymic.value);
}
document.getElementById('info').innerHTML = result;
return false;
}
//selector типа соединения email/телефон
function typeConnection(){
var connect = document.getElementById('connect').value;
var email = document.getElementById("email");
var phone = document.getElementById("phone");
var result = '';
console.log(connect);
if (connect == "email"){
email.style.display="block";
phone.style.display="none";
email.value="";
console.log(connect);
}else if (connect == "телефон"){
phone.style.display="block";
email.style.display="none";
phone.value="";
console.log(connect);
}else if (connect == ""){
phone.style.display="none";
email.style.display="none";
phone.value="";
email.value="";
console.log(connect);
}
document.getElementById('info').innerHTML = result;
return false;
}
//запрос отправлен
function checkForm() {
var surname = document.getElementById('surname').value;
var name = document.getElementById('name').value;
var patronymic = document.getElementById('patronymic');
var patronymic_none = document.getElementById('patronymic_none');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var request = document.getElementById('request').value;
var connect = document.getElementById('connect').value;
var result = '';
console.log(surname);
console.log(connect);
if (surname == "" || name == "" || request == ""){
result = "Заполните все поля";
}else if (surname.length <= 3 || surname.length > 20){
result = "Введите корректную фамилию";
}else if (name.length <= 3 || name.length > 20) {
result = "Введите корректное имя";}
//checkbox отсутсвия отчества
else if (patronymic_none.checked){
patronymic.style.display="none";
patronymic.value="";
}else if(patronymic.value.length > 3) {
patronymic.style.display="block";
console.log(patronymic.value);
console.log(patronymic.value.length);
}else if(patronymic.value.length <= 3){
patronymic.style.display="block";
result = "Введите корректное отчество";
console.log(patronymic.value);
}
//Не срабатывает здесь или select работает или checkbox????
else if (connect == ""){
result = "Выберите тип связи";
phone.style.display="none";
email.style.display="none";
phone.value="";
email.value="";
}else if (connect == "email"){
email.style.display="block";
phone.style.display="none";
phone.value="";
console.log(email.value);
}else if (connect == "телефон"){
phone.style.display="block";
email.style.display="none";
phone.value="";
}
if (result != "") {
document.getElementById('info').innerHTML = result;
} else {
alert("Запрос отправлен");
}
return false;
}
/*
//checkbox отсутсвия отчества
function lackPatronymic(){
var patronymic_none= document.getElementById('patronymic_none');
var patronymic= document.getElementById("patronymic");
var result = '';
if (patronymic_none.checked){
patronymic.style.display="none";
patronymic.value="";
}else {
patronymic.style.display="block";
if(patronymic.value <= 1){
result = "введите отчесто";
document.getElementById('info').innerHTML = result;
}else{
return false;
}
}
}
//selector типа соединения email/телефон
function typeConnection(){
var connect = document.getElementById('connect').value;
var email = document.getElementById("email");
var phone = document.getElementById("phone");
console.log(connect);
if (connect == "email" ){
email.style.display="block";
phone.style.display="none";
}else if (connect == "телефон"){
phone.style.display="block";
email.style.display="none";
}else if (connect == ""){
phone.style.display="none";
email.style.display="none";
}
return false;
}
*/
/*
//запрос отправлен
function checkRequest(){
var request= document.getElementById('request').value;
console.log(request);
if (request == ""){
alert("Введите сообщение");
}else {
alert("Запрос отправлен");
}
return false;
}*/ | 091bc72c68d7ac304c16d151e6963addf80376a8 | [
"JavaScript"
] | 1 | JavaScript | Zircod/LuLuShop | 4c3951fcd8a6eacea67173ee36cc2f3335f9631e | 4f910117c6422d001f20c75b8cd463e3341da459 |
refs/heads/master | <file_sep>//
// TabBarViewController.swift
// HW 4
//
// Created by <NAME> on 2/24/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class TabBarViewController: UIViewController {
var homeViewController: UIViewController!
var searchViewController: UIViewController!
var accountViewController: UIViewController!
var trendingViewController: UIViewController!
@IBOutlet weak var contentView: UIView!
@IBOutlet var buttons: [UIButton]!
var viewControllers: [UIViewController]!
var selectedIndex: Int = 0
var fadeTransition: FadeTransition!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Access the ViewController that you will be transitioning too, a.k.a, the destinationViewController.
let destinationViewController = segue.destinationViewController
// Set the modal presentation style of your destinationViewController to be custom.
destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom
// Create a new instance of your fadeTransition.
fadeTransition = FadeTransition()
// Tell the destinationViewController's transitioning delegate to look in fadeTransition for transition instructions.
destinationViewController.transitioningDelegate = fadeTransition
// Adjust the transition duration. (seconds)
fadeTransition.duration = 0.4
}
override func viewDidLoad() {
super.viewDidLoad()
// set up storyboard
let storyboard = UIStoryboard(name: "Main", bundle: nil)
homeViewController = storyboard.instantiateViewControllerWithIdentifier("homeViewController")
searchViewController = storyboard.instantiateViewControllerWithIdentifier("searchViewController")
accountViewController = storyboard.instantiateViewControllerWithIdentifier("accountViewController")
trendingViewController = storyboard.instantiateViewControllerWithIdentifier("trendingViewController")
viewControllers = [homeViewController, searchViewController, accountViewController, trendingViewController]
onTabButtonPress(buttons[selectedIndex])
buttons[selectedIndex].selected = true
}
@IBAction func onTabButtonPress(sender: UIButton) {
// set the button indexes
let previousIndex = selectedIndex
selectedIndex = sender.tag
sender.selected = true
// set the VC indexes
let previousVC = viewControllers[previousIndex]
let currentVC = viewControllers[selectedIndex]
// set the unselected button state
buttons[previousIndex].selected = false
// remove the previous view controller
previousVC.willMoveToParentViewController(nil)
previousVC.view.removeFromSuperview()
previousVC.removeFromParentViewController()
// add the current view controller
addChildViewController(currentVC)
// adjust the size of the view controller
currentVC.view.frame = contentView.frame
contentView.addSubview(currentVC.view)
currentVC.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// ComposeViewController.swift
// HW 4
//
// Created by <NAME> on 2/24/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class ComposeViewController: UIViewController {
@IBOutlet weak var textCompose: UIImageView!
@IBOutlet weak var photoCompose: UIImageView!
@IBOutlet weak var quoteCompose: UIImageView!
@IBOutlet weak var linkCompose: UIImageView!
@IBOutlet weak var chatCompose: UIImageView!
@IBOutlet weak var videoCompose: UIImageView!
var topRowStartingYPos = CGFloat(224)
var bottomRowStartingYPos = CGFloat(340)
var bottomHideYPos = CGFloat(600)
var topHideYPos = CGFloat(-800)
override func viewWillAppear(animated: Bool) {
textCompose.center.y = bottomHideYPos
photoCompose.center.y = bottomHideYPos
quoteCompose.center.y = bottomHideYPos
linkCompose.center.y = bottomHideYPos
chatCompose.center.y = bottomHideYPos
videoCompose.center.y = bottomHideYPos
}
override func viewDidAppear(animated: Bool) {
// first appearance - photo
UIView.animateWithDuration(0.2, delay: 0.1, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.photoCompose.center.y = self.topRowStartingYPos
}, completion: nil)
// second appearance - chat
UIView.animateWithDuration(0.2, delay: 0.2, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.chatCompose.center.y = self.bottomRowStartingYPos
}, completion: nil)
// third appearance - quote
UIView.animateWithDuration(0.2, delay: 0.3, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.quoteCompose.center.y = self.topRowStartingYPos
}, completion: nil)
// fourth appearance - text
UIView.animateWithDuration(0.2, delay: 0.4, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.textCompose.center.y = self.topRowStartingYPos
}, completion: nil)
// fifth appearance - link
UIView.animateWithDuration(0.2, delay: 0.5, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.linkCompose.center.y = self.bottomRowStartingYPos
}, completion: nil)
// sixth appearance - video
UIView.animateWithDuration(0.2, delay: 0.6, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.videoCompose.center.y = self.bottomRowStartingYPos
}, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func didPressDismiss(sender: UIButton) {
// first disappearance - photo
UIView.animateWithDuration(0.2, delay: 0.1, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.photoCompose.center.y = self.topHideYPos
}, completion: nil)
// second disappearance - chat
UIView.animateWithDuration(0.2, delay: 0.2, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.chatCompose.center.y = self.topHideYPos
}, completion: nil)
// third disappearance - quote
UIView.animateWithDuration(0.2, delay: 0.3, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.quoteCompose.center.y = self.topHideYPos
}, completion: nil)
// fourth disappearance - text
UIView.animateWithDuration(0.2, delay: 0.4, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.textCompose.center.y = self.topHideYPos
}, completion: nil)
// fifth disappearance - link
UIView.animateWithDuration(0.2, delay: 0.5, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.linkCompose.center.y = self.topHideYPos
}, completion: nil)
// sixth disappearance - video
UIView.animateWithDuration(0.2, delay: 0.6, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.videoCompose.center.y = self.topHideYPos
}) { (Bool) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep># Codepath HW 4
Tumblr Tab Bar View Controller
Time spent: ~3 hours
Completed user stories:
Required:
- [x] Tapping on Home, Search, Account, or Trending should show the respective screen and highlight the tab bar button.
- [x] Compose button should modally present the compose screen.
Optional:
- [x] Compose screen is faded in while the buttons animate in.
- [x] Login button should show animate the login form over the view controller.
- [x] Show the custom loading indicator by playing the sequence of pngs.
GIF:

| 7c0b131cba116387ad8945da3bf01ee9f9e14425 | [
"Swift",
"Markdown"
] | 3 | Swift | alvinhsia/Codepath-Assignment-4 | edd0bb3a4e8277d51b0d5187d2e5a09f1bcd6b2d | bc4dbd952c7a22514327b41e72eea537b76f1f39 |
refs/heads/master | <repo_name>Bdhakshn-ford/Restock-Notifier<file_sep>/restock_Notifier/src/main/java/com/guitarshack/restockalert/RestockAlert.java
package com.guitarshack.restockalert;
public interface RestockAlert {
void send(String s);
}
<file_sep>/restock_Notifier/src/main/java/com/guitarshack/restockalert/ServiceBuilder.java
package com.guitarshack.restockalert;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceBuilder {
public ServiceBuilder() {
}
<T> T buildService(Class<T> serviceType, String baseUrl) {
Retrofit retrofitClient = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofitClient.create(serviceType);
}
}<file_sep>/restock_Notifier/src/test/java/com/guitarshack/restockalert/RestockCalculatorTestBase.java
package com.guitarshack.restockalert;
import org.junit.Before;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public abstract class RestockCalculatorTestBase {
protected SalesHistory salesHistory;
private ReStockCalculator restockCalculator;
private Product product;
private Calendar calendar = Calendar.getInstance();
@Before
public void setUp() {
Today today = () -> {
calendar.set(2019, Calendar.DECEMBER, 11, 00, 00, 00);
return calendar.getTime();
};
createSalesHistory();
restockCalculator = new HistoricalSalesRestockCalculator(today, salesHistory);
product = new Product(757, 0,"",0,0,14);
}
public abstract void createSalesHistory();
public Date createDate(int year, int month, int date) {
calendar.set(year, month, date, 00,00,00);
return calendar.getTime();
}
public abstract Date expectedStartDate();
public abstract Date expectedEndDate();
@Test
public void returnsTotalSalesForDateRange(){
assertEquals(10, restockCalculator.calculateReStockLevel(product));
}
@Test
public void usesCorrectStartDate(){
Date date = expectedStartDate();
restockCalculator.calculateReStockLevel(product);
verify(salesHistory, times(1)).getSalesForDateRange(anyInt(), eq(date), anyObject());
}
@Test
public void usesCorrectEndDate() {
Date endDate = expectedEndDate();
restockCalculator.calculateReStockLevel(product);
verify(salesHistory, times(1)).getSalesForDateRange(anyInt(), anyObject(), eq(endDate));
}
}
<file_sep>/restock_Notifier/src/test/java/com/guitarshack/restockalert/contract/SalesHistoryContractTest.java
package com.guitarshack.restockalert.contract;
import com.guitarshack.restockalert.HttpNetwork;
import com.guitarshack.restockalert.Network;
import com.guitarshack.restockalert.SalesHistoryTestBase;
public class SalesHistoryContractTest extends SalesHistoryTestBase {
@Override
public Network getNetwork() {
return new HttpNetwork();
}
}
<file_sep>/restock_Notifier/src/test/java/com/guitarshack/restockalert/unit/RestockCalculatorWithoutOneYearsSalesHistoryTest.java
package com.guitarshack.restockalert.unit;
import com.guitarshack.restockalert.RestockCalculatorTestBase;
import com.guitarshack.restockalert.SalesHistory;
import java.util.Calendar;
import java.util.Date;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RestockCalculatorWithoutOneYearsSalesHistoryTest extends RestockCalculatorTestBase {
@Override
public void createSalesHistory() {
salesHistory = mock(SalesHistory.class);
when(salesHistory.getSalesForDateRange(anyInt(),anyObject(),anyObject())).thenReturn(0,10);
}
@Override
public Date expectedStartDate() {
return createDate(2019, Calendar.NOVEMBER, 28);
}
@Override
public Date expectedEndDate() {
return createDate(2019, Calendar.DECEMBER, 11);
}
}
<file_sep>/restock_Notifier/src/main/java/com/guitarshack/restockalert/HttpNetwork.java
package com.guitarshack.restockalert;
import retrofit2.Call;
import java.io.IOException;
import java.util.Objects;
public class HttpNetwork implements Network {
@Override
public <T> T getData(Call<T> call) {
try {
return Objects.requireNonNull(call.execute().body());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}<file_sep>/restock_Notifier/src/main/java/com/guitarshack/restockalert/SalesHistoryService.java
package com.guitarshack.restockalert;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface SalesHistoryService {
@GET("/sales?action=total")
Call<TotalSales> getSalesHistory(@Query("productId") int productId, @Query("startDate") String startDate, @Query("endDate") String endDate);
}
<file_sep>/restock_Notifier/src/main/java/com/guitarshack/restockalert/WarehouseService.java
package com.guitarshack.restockalert;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface WarehouseService {
@GET("product")
Call<Product> getProduct(@Query("id") int id);
}
<file_sep>/restock_Notifier/src/test/java/com/guitarshack/restockalert/SalesHistoryTestBase.java
package com.guitarshack.restockalert;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.assertEquals;
public abstract class SalesHistoryTestBase {
@Test
public void getTotalSalesForGivenDateRange(){
SalesHistory salesHistory = new SalesHistoryApi(getNetwork(), "https://gjtvhjg8e9.execute-api.us-east-2.amazonaws.com/default/");
Calendar calendar = Calendar.getInstance();
calendar.set(2019, Calendar.JULY, 17);
Date startDate = calendar.getTime();
calendar.set(2019, Calendar.JULY, 27);
Date endDate = calendar.getTime();
assertEquals(20, salesHistory.getSalesForDateRange(811, startDate, endDate));
}
public abstract Network getNetwork();
}
<file_sep>/restock_Notifier/src/main/java/com/guitarshack/restockalert/Warehouse.java
package com.guitarshack.restockalert;
public interface Warehouse {
Product getProduct(int id);
}
| 0959b5fd3b760c682ec53b2d38c656659967a561 | [
"Java"
] | 10 | Java | Bdhakshn-ford/Restock-Notifier | a64c4da49084c6d3d29dcaff904d816bb23de6c7 | e028d3bcda5333d95404b565ecb25b7382a80db5 |
refs/heads/master | <file_sep>export const PLAY = 'PLAY';
export const PAUSE = 'PAUSE';
export const UPDATE_CURRENT_TIME = 'UPDATE_CURRENT_TIME';
export const UPDATE_BUFFERED = 'UPDATE_BUFFERED';
export const UPDATE_DURATION = 'UPDATE_DURATION';
export const UPDATE_TIME = 'UPDATE_TIME';
export const HYDRATE_SESSIONS = 'HYDRATE_SESSIONS';
export const UPDATE_SRC = 'UPDATE_SRC';
export const UPDATE_VOLUME = 'UPDATE_VOLUME';
export const UPDATE_QUEUE = 'UPDATE_QUEUE';
export const UPDATE_SPEED = 'UPDATE_SPEED';
<file_sep>import axios from 'axios';
import crypto from 'crypto';
import {readdirSync, statSync} from 'fs';
import path, {join, normalize} from 'path';
import {CONSTANTS} from '../constants';
import {buildInsertQuery, query, trans} from './data';
import {workFiles} from './fileWorker';
import {cleanUp} from './janitor';
import {objectToProps} from './mapper';
import {Audiobook, validate} from './schema';
import {getDetail, getDetailLink, scraper} from './scraper';
const dirs = (path: string) =>
readdirSync(path).filter(f => statSync(join(path, f)).isDirectory());
const fileSync = () => {
// check if there are any new files...
const path = CONSTANTS.folderPath;
console.log(`checking path: ${path}`);
const files = dirs(path);
console.log(`found ${files.length} files...`);
return files.map(f => normalize(`${path}/${f}`));
};
const weakHash = (input: string) =>
crypto
.createHash('md5')
.update(input)
.digest('hex');
export const init = async () => {
const files = fileSync();
const hashes = files.map(f => ({
folder: f,
hash: weakHash(f),
}));
await validate();
const dbItems = await query('SELECT * FROM audiobook', []);
const itemsNotInDb = hashes.filter(
i => !(dbItems.rows as Array<Audiobook>).map(r => r.id).includes(i.hash)
);
const itemsNotInFolder = (dbItems.rows as Array<Audiobook>)
.map(r => r.id)
.filter(f => !hashes.map(h => h.hash).includes(f));
console.log(
`found ${itemsNotInFolder.length} items that need to be removed as they don't exist in the folder anymore`
);
await cleanUp(itemsNotInFolder);
console.log(`found ${itemsNotInDb.length} items not in db...`);
console.log('fetching metadata if required...');
const allItemPromises = itemsNotInDb.map(async item => {
console.log(`checking ${item.folder}`);
const keywords = item.folder
.split(path.sep)
.pop()
.trim();
console.log(`hitting ${keywords}`);
const resp = await axios.get(
`https://www.audible.com/search?keywords=${keywords}`
);
const detailLink = await getDetailLink(resp.data);
const detailResp = await axios.get(detailLink);
const description = await getDetail(detailResp.data);
const audiobook = await scraper(
item.hash,
resp.data,
item.folder,
description,
detailLink
);
const fileData = await workFiles(item.folder, item.hash);
await trans(async client => {
const props = objectToProps(audiobook);
const audioBookQuery = buildInsertQuery('audiobook', props);
await client.query('SET search_path TO schema,public;');
await client.query(
audioBookQuery,
props.map(p => p.value)
);
const fileDataPromises = fileData.map(async fd => {
const fileQuery = buildInsertQuery('file', fd);
await client.query(
fileQuery,
fd.map(p => p.value)
);
});
await Promise.all(fileDataPromises);
});
});
await Promise.all(allItemPromises);
console.log('init complete...');
};
<file_sep>import {File} from '../../../server/src/core/schema';
import {
PAUSE,
PLAY,
UPDATE_BUFFERED,
UPDATE_DURATION,
UPDATE_QUEUE,
UPDATE_SPEED,
UPDATE_SRC,
UPDATE_VOLUME,
} from '../constants/actionTypes';
import {TimeAction} from './timeStateAction';
export interface PlayerAction {
type: typeof PLAY | typeof PAUSE;
}
export interface UpdateBuffered {
type: typeof UPDATE_BUFFERED;
buffered: number;
}
export interface UpdateDuration {
type: typeof UPDATE_DURATION;
duration: number;
}
export interface UpdateVolumeAction {
type: typeof UPDATE_VOLUME;
volume: number;
}
export interface UpdateQueueAction {
type: typeof UPDATE_QUEUE;
queue: Array<File>;
}
export interface UpdateSpeedAction {
type: typeof UPDATE_SPEED;
speed: number;
}
export interface UpdateSrcAction {
type: typeof UPDATE_SRC;
src: string;
fileId: string;
title: string;
}
export type PlayerActionTypes =
| PlayerAction
| TimeAction
| UpdateBuffered
| UpdateDuration
| UpdateSrcAction
| UpdateVolumeAction
| UpdateQueueAction
| UpdateSpeedAction;
<file_sep>

/badge.svg)
A place to store your audiobooks
[Installing on unraid](https://github.com/jonocairns/aubri/wiki/Installing-on-Unraid)



## Development
[](https://github.com/jonocairns/aubri/issues)
[](https://github.com/jonocairns/aubri/pulls)
[](https://hub.docker.com/r/jonocairns/aubri)
### Requirements
1. Docker
2. nodejs
3. yarn
4. Auth0 account (set client in `./client/.env`)
5. install FFMPEG
Getting started:
1. Clone the repository
2. In the root folder run `docker-compose up`, this will spin up postgres (note: you may need to login (localhost:8080) to create a perminant login first)
3. Open 2 terminals, one in `./client` and one in `./server`.
4. Run `yarn install` in both client and server folders.
5. Copy the `.env.example` to `.env` and set all the variables (in both client and server)
6. Add audio books to `./server/data`
7. Run `yarn start` in both client and server
<file_sep>declare module '@ffmpeg-installer';
<file_sep>import {Audiobook, File} from '../../server/src/core/schema';
export interface PlayerState {
fileId: string;
playing: boolean;
buffered: number;
currentTime: number;
duration: number;
src: string;
title: string;
volume: number;
speed: number;
queue: Array<File>;
}
export interface BookState {
books: Array<{book: Audiobook; files: Array<string>}>;
}
export interface TimeState {
[key: string]: number;
}
export interface State {
player: PlayerState;
time: TimeState;
books: BookState;
}
<file_sep>import dotenv from 'dotenv';
import jwt from 'express-jwt';
import jwksRsa from 'jwks-rsa';
dotenv.config();
export const checkJwt = jwt({
// Dynamically provide a signing key
// based on the kid in the header and
// the signing keys provided by the JWKS endpoint.
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${process.env.REACT_APP_AUTH0_DOMAIN}/.well-known/jwks.json`,
}),
// Validate the audience and the issuer.
audience: `http://localhost:6969`,
issuer: `https://${process.env.REACT_APP_AUTH0_DOMAIN}/`,
algorithms: ['RS256'],
});
<file_sep>import {Request, Response} from 'express';
import fs from 'fs';
import decode from 'jwt-decode';
import {query, trans} from '../core/data';
import {File} from '../core/schema';
import {strongHash} from './audio';
interface ParamsDictionary {
[id: string]: string;
}
export const play = async (req: Request<ParamsDictionary>, res: Response) => {
try {
const id = req.params.id;
const results = await query('SELECT * FROM file WHERE id = $1', [id]);
const book = (results.rows[0] as File).location;
console.log(`playing ${book}`);
const stat = fs.statSync(book);
const range = req.headers.range;
let readStream: fs.ReadStream;
if (range !== undefined) {
const parts = range.replace(/bytes=/, '').split('-');
const partialStart = parts[0];
const partialEnd = parts[1];
if (
(isNaN(Number(partialStart)) && partialStart.length > 1) ||
(isNaN(Number(partialEnd)) && partialEnd.length > 1)
) {
console.log('ERR_INCOMPLETE_CHUNKED_ENCODING');
return res.sendStatus(500).end(); //ERR_INCOMPLETE_CHUNKED_ENCODING
}
const start = parseInt(partialStart, 10);
const end = partialEnd ? parseInt(partialEnd, 10) : stat.size - 1;
const contentLength = end - start + 1;
res.status(206).header({
'Content-Type': 'audio/mpeg',
'Content-Length': contentLength,
'Content-Range': 'bytes ' + start + '-' + end + '/' + stat.size,
});
readStream = fs.createReadStream(book, {start: start, end: end});
} else {
res.header({
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size,
});
readStream = fs.createReadStream(book);
}
readStream.pipe(res);
req.on('close', () => {
console.log('request closed... killing stream');
readStream.destroy();
});
readStream.on('error', (e: Error) => {
res.sendStatus(404);
});
} catch (err) {
console.log(err);
}
};
export const download = async (
req: Request<ParamsDictionary>,
res: Response
) => {
try {
const id = req.params.id;
const results = await query('SELECT * FROM file WHERE id = $1', [id]);
const book = (results.rows[0] as File).location;
res.download(book);
} catch (e) {
console.log(e);
}
};
export interface User {
sub: string;
iss: string;
aud: Array<string>;
iat: number;
exp: number;
azp: string;
scope: string;
}
export const getUser = (req: Request) => {
const authorization = req.headers.authorization.split(' ')[1];
return decode(authorization) as User;
};
export const save = async (req: Request<ParamsDictionary>, res: Response) => {
const id = req.params.id;
const userId = getUser(req).sub;
const time = req.params.time;
const hashedUserId = strongHash(userId);
const items = await query(
'SELECT * FROM session WHERE userId = $1 AND fileId = $2',
[hashedUserId, id]
);
if (items.rows.length === 0) {
await trans(c =>
c.query('INSERT INTO session(userId,fileId,time) VALUES($1,$2,$3)', [
hashedUserId,
id,
time,
])
);
} else {
await trans(c =>
c.query(
'UPDATE session SET time = $1 WHERE userId = $2 AND fileId = $3',
[time, hashedUserId, id]
)
);
}
console.log(`saved ${id}`);
res.status(200).json({});
};
<file_sep>import {join} from 'path';
export const CONSTANTS = {
folderPath: process.env.DATA || join(__dirname, `../../../data`),
};
<file_sep>FROM node:12-alpine
WORKDIR /usr/src/app
RUN apk add ffmpeg
ARG REACT_APP_AUTH0_CLIENT_ID=setme
ENV REACT_APP_AUTH0_CLIENT_ID=${REACT_APP_AUTH0_CLIENT_ID}
RUN echo ${REACT_APP_AUTH0_CLIENT_ID}
ARG REACT_APP_AUTH0_DOMAIN=setme
ENV REACT_APP_AUTH0_DOMAIN=${REACT_APP_AUTH0_DOMAIN}
ARG REACT_APP_API_BASE_URL=/
ENV REACT_APP_API_BASE_URL=${REACT_APP_API_BASE_URL}
ARG DATABASE_URL=setme
ENV DATABASE_URL=${DATABASE_URL}
ARG DATABASE_SSL=setme
ENV DATABASE_SSL=${DATABASE_SSL}
COPY server/package.json server/yarn.lock ./server/
COPY client/package.json client/yarn.lock ./client/
WORKDIR /usr/src/app/server
RUN yarn install --pure-lockfile
WORKDIR /usr/src/app/client
RUN yarn install --pure-lockfile
WORKDIR /usr/src/app
COPY . .
WORKDIR /usr/src/app/server
RUN yarn run build
WORKDIR /usr/src/app/client
RUN yarn run build
RUN rm -rf node_modules
WORKDIR /usr/src/app/server
EXPOSE 6969
CMD [ "node", "dist/src/server.js" ]<file_sep>import dotenv from 'dotenv';
import {Pool, PoolClient} from 'pg';
dotenv.config();
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.DATABASE_SSL === 'true',
});
export const buildInsertQuery = (
tableName: string,
props: Array<{prop: string; value: string | number}>
) =>
`INSERT INTO ${tableName}(${props.map(p => p.prop)}) VALUES(${props.map(
(p, i) => `$${i + 1}`
)})`;
export const query = async (text: string, params: Array<string>) => {
const client = await pool.connect();
try {
return pool.query(text, params);
} catch (e) {
console.log(e);
throw e;
} finally {
client.release();
}
};
export const trans = async (fnc: (client: PoolClient) => void) => {
const client = await pool.connect();
try {
await client.query('BEGIN');
await fnc(client);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
};
<file_sep>import {useCallback, useEffect, useRef, useState} from 'react';
export const useInterval = (callback: any, delay: any) => {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
const tick = () => {
(savedCallback as any).current();
};
if (delay) {
const id = setInterval(() => {
tick();
}, delay);
return () => clearInterval(id);
}
}, [delay]);
};
export const useWindowSize = () => {
const validWindow = typeof window === 'object';
const getSize = useCallback(() => {
const size = {
width: validWindow ? window.innerWidth : undefined,
height: validWindow ? window.innerHeight : undefined,
};
return size;
}, [validWindow]);
const [size, setSize] = useState(getSize());
useEffect(() => {
function handleResize() {
setSize(getSize());
}
if (validWindow) {
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}
}, [getSize, validWindow]);
return size;
};
<file_sep>import {combineReducers} from 'redux';
import {playerReducer} from './player';
import {timeReducer} from './time';
export const rootReducer = combineReducers({
player: playerReducer,
time: timeReducer,
});
export type RootState = ReturnType<typeof rootReducer>;
<file_sep>import {useEffect, useRef, useState} from 'react';
import {useInterval, useWindowSize} from './useInterval';
const WINDOW = 'window';
const PARENT = 'parent';
export const useInfiniteScroll = ({
loading,
hasNextPage,
onLoadMore,
threshold = 150,
checkInterval = 200,
scrollContainer = WINDOW,
}: any) => {
const ref = useRef();
const {height: windowHeight, width: windowWidth} = useWindowSize();
const [listen, setListen] = useState(true);
useEffect(() => {
if (!loading) {
setListen(true);
}
}, [loading]);
const getParentSizes = () => {
const parentNode = (ref?.current as any).parentNode;
const parentRect = parentNode.getBoundingClientRect();
const {top, bottom, left, right} = parentRect;
return {top, bottom, left, right};
};
const getBottomOffset = () => {
const rect = (ref?.current as any).getBoundingClientRect();
const bottom = rect.bottom;
let bottomOffset = bottom - (windowHeight || 0);
if (scrollContainer === PARENT) {
const {bottom: parentBottom} = getParentSizes();
// Distance between bottom of list and its parent
bottomOffset = bottom - parentBottom;
}
return bottomOffset;
};
const isParentInView = () => {
const parent = ref.current ? (ref?.current as any).parentNode : null;
if (parent) {
const {left, right, top, bottom} = getParentSizes();
if (left > (windowWidth || 0)) {
return false;
} else if (right < 0) {
return false;
} else if (top > (windowHeight || 0)) {
return false;
} else if (bottom < 0) {
return false;
}
}
return true;
};
const listenBottomOffset = () => {
if (listen && !loading && hasNextPage) {
if (ref.current) {
if (scrollContainer === PARENT) {
if (!isParentInView()) {
// Do nothing if the parent is out of screen
return;
}
}
// Check if the distance between bottom of the container and bottom of the window or parent
// is less than "threshold"
const bottomOffset = getBottomOffset();
const validOffset = bottomOffset < threshold;
if (validOffset) {
onLoadMore();
}
}
}
};
useInterval(
() => {
listenBottomOffset();
},
// Stop interval when there is no next page.
checkInterval
);
return ref;
};
<file_sep>export const searchSchema = [
{
name: 'year',
target: '.releaseDateLabel span',
multi: false,
translate: (item: string): string => {
const parsedDate = Date.parse(item);
if (!isNaN(parsedDate)) {
return new Date(item).toISOString();
}
return new Date().toISOString();
},
},
{name: 'title', target: '.bc-list-item h3 a', multi: false},
{name: 'subtitle', target: '.subtitle span', multi: false},
{name: 'author', target: '.authorLabel span a', multi: true},
{name: 'narrator', target: '.narratorLabel span a', multi: false},
{
name: 'runtime',
target: '.runtimeLabel span',
multi: false,
translate: (searchItem: string): number =>
searchItem
.split(' ')
.filter(r => !isNaN(Number(r)))
.map(a => Number(a))
.map((a, i) => (i === 0 ? a * 60 : a))
.reduce((a, b) => a + b, 0) || 0,
},
{name: 'language', target: '.languageLabel span', multi: false},
{
name: 'stars',
target: '.ratingsLabel .bc-pub-offscreen',
multi: false,
translate: (item: string): number => Number(item.split(' ').shift()) || 0,
},
{
name: 'ratings',
target: '.ratingsLabel .bc-color-secondary',
multi: false,
translate: (item: string): number =>
Number(
item
.replace(/,/g, '')
.split(' ')
.shift()
) || 0,
},
];
<file_sep>import chokidar from 'chokidar';
import {CONSTANTS} from '../constants';
import {init} from './file';
export const watcher = () => {
const watcher = chokidar.watch(CONSTANTS.folderPath, {
ignored: /^\./,
persistent: true,
});
let hasStarted = false;
watcher
.on('addDir', async path => {
if (hasStarted) {
console.log(`Directory ${path} has been added`);
await init();
}
})
.on('unlinkDir', async path => {
await init();
console.log(`Directory ${path} has been removed`);
})
.on('error', error => console.log(`Watcher error: ${error}`))
.on('ready', () => {
hasStarted = true;
console.log('Initial scan complete. Ready for changes');
});
};
<file_sep>import {detailPage, searchPage} from '../__mocks__/pages';
import {getDetail, scraper} from '../src/core/scraper';
import {
ratingsStringToNumber,
runtimeStringToNumber,
starsStringToNumber,
stringToUtc,
} from '../src/core/scraperUtils';
describe('scraper tests', () => {
it('can convert date string to UTC', () => {
const input = '2013-03-21';
const output = stringToUtc(input);
expect(output).toBe('2013-03-21T00:00:00.000Z');
});
it('can runtime as a string in to a number', () => {
const input = '10 hrs and 24 mins';
const output = runtimeStringToNumber(input);
expect(output).toBe(60 * 10 + 24);
});
it('can runtime as a string when only has minutes', () => {
const input = '24 mins';
const output = runtimeStringToNumber(input);
expect(output).toBe(24);
});
it('can convert star ratings to numbers', () => {
const ratings = 3.5;
const input = `${ratings} out of 5`;
const output = starsStringToNumber(input);
expect(output).toBe(ratings);
});
it('can convert raw ratings to numbers', () => {
const ratings = 343554;
const input = `${ratings} ratings`;
const output = ratingsStringToNumber(input);
expect(output).toBe(ratings);
});
it('should correctly scrape the search page', async () => {
const link = 'https://link.com';
const obj = await scraper('id', searchPage, 'folder', 'description', link);
expect(obj.title).toBe('The Martian');
expect(obj.subtitle).toBe('');
expect(obj.narrator).toBe('<NAME>');
expect(obj.author).toBe('<NAME>');
expect(obj.runtime).toBe(653);
expect(obj.language).toBe('English');
expect(obj.stars).toBe(5);
expect(obj.image).toBe(
'https://m.media-amazon.com/images/I/51Lr5rAN6cL._SL500_.jpg'
);
expect(obj.link).toBe(link);
});
it('should correctly scrape the detail page', async () => {
const description = getDetail(detailPage);
expect(description).not.toBeNull();
expect(description).not.toBe('');
});
});
<file_sep>import {PlayerActionTypes} from '../actions/playerStateAction';
import {
PAUSE,
PLAY,
UPDATE_BUFFERED,
UPDATE_CURRENT_TIME,
UPDATE_DURATION,
UPDATE_QUEUE,
UPDATE_SPEED,
UPDATE_SRC,
UPDATE_VOLUME,
} from '../constants/actionTypes';
import {PlayerState} from '../State';
const initialState: PlayerState = {
fileId: '',
playing: false,
buffered: 0,
currentTime: 0,
duration: 0,
src: '',
title: '',
volume: 1,
queue: [],
speed: 1,
};
export const playerReducer = (
state = initialState,
action: PlayerActionTypes
): PlayerState => {
switch (action.type) {
case PLAY:
return {
...state,
playing: true,
};
case PAUSE:
return {
...state,
playing: false,
};
case UPDATE_CURRENT_TIME:
return {
...state,
currentTime: action.payload.time,
};
case UPDATE_DURATION:
return {
...state,
duration: action.duration,
};
case UPDATE_BUFFERED:
return {
...state,
buffered: action.buffered,
};
case UPDATE_VOLUME:
return {
...state,
volume: action.volume,
};
case UPDATE_QUEUE:
return {
...state,
queue: action.queue,
};
case UPDATE_SPEED:
return {
...state,
speed: action.speed,
};
case UPDATE_SRC:
return {
...state,
src: action.src,
fileId: action.fileId,
title: action.title,
};
default:
return state;
}
};
<file_sep>export const stringToUtc = (dateString: string): string => {
const parsedDate = Date.parse(dateString);
if (!isNaN(parsedDate)) {
return new Date(dateString).toISOString();
}
return new Date().toISOString();
};
export const runtimeStringToNumber = (runtimeString: string): number => {
const numbers = runtimeString.split(' ').filter(r => !isNaN(Number(r)));
return (
numbers
.map(a => Number(a))
.map((a, i) => (i === 0 && numbers.length > 1 ? a * 60 : a))
.reduce((a, b) => a + b, 0) || 0
);
};
export const starsStringToNumber = (item: string): number =>
Number(item.split(' ').shift()) || 0;
export const ratingsStringToNumber = (item: string): number =>
Number(
item
.replace(/,/g, '')
.split(' ')
.shift()
) || 0;
<file_sep>export const objectToProps = (object: any) => {
return Object.keys(object).map(key => ({
prop: key,
value: object[key],
}));
};
<file_sep>import ffmpeg, {FfprobeData} from 'fluent-ffmpeg';
import {basename} from 'path';
import {promisify} from 'util';
import {readDirAsync, strongHash} from '../controllers/audio';
import {objectToProps} from './mapper';
import {File} from './schema';
const probeP = promisify(ffmpeg.ffprobe);
export const workFiles = async (folder: string, bookId: string) => {
const files = await readDirAsync(folder);
const filePromises = files.map(async location => {
const meta = (await probeP(location)) as FfprobeData;
const id = strongHash(`${bookId}${location}`);
const tags = meta.format.tags as {title?: string};
return objectToProps({
id,
bookId,
duration: meta.format.duration,
size: meta.format.size,
bitrate: meta.format.bit_rate,
format: meta.format.format_name,
dateCreatedUtc: new Date().toISOString(),
lastUpdatedUtc: new Date().toISOString(),
location,
filename: basename(location),
title: (tags && tags.title) || '',
} as File);
});
return Promise.all(filePromises);
};
<file_sep>import {Session} from '../../../server/src/core/schema';
import {HYDRATE_SESSIONS, UPDATE_CURRENT_TIME} from '../constants/actionTypes';
export interface TimeAction {
type: typeof UPDATE_CURRENT_TIME;
payload: {id: string; time: number};
}
export interface HydrateTimeAction {
type: typeof HYDRATE_SESSIONS;
sessions: Array<Session>;
}
export type TimeActionTypes = TimeAction | HydrateTimeAction;
<file_sep>import {TimeActionTypes} from '../actions/timeStateAction';
import {HYDRATE_SESSIONS, UPDATE_CURRENT_TIME} from '../constants/actionTypes';
import {TimeState} from '../State';
const initialState: TimeState = {};
export const timeReducer = (
state = initialState,
action: TimeActionTypes
): TimeState => {
switch (action.type) {
case HYDRATE_SESSIONS:
return {
...state,
...Object.assign(
{},
...action.sessions.map(s => ({[s.fileid]: Number(s.time)}))
),
};
case UPDATE_CURRENT_TIME:
return {
...state,
[action.payload.id]: action.payload.time,
};
default:
return state;
}
};
<file_sep>import {DBSchema, openDB} from 'idb';
interface MyDB extends DBSchema {
books: {
value: {
blob: Blob;
};
key: string;
indexes: {};
};
}
export const save = async (blob: Blob, key: string) => {
const db = await openDB<MyDB>('my-db', 1, {
upgrade(db) {
db.createObjectStore('books');
},
});
await db.put('books', {blob}, key);
};
export const remove = async (key: string) => {
const db = await openDB<MyDB>('my-db', 1, {
upgrade(db) {
db.createObjectStore('books');
},
});
await db.delete('books', key);
};
export const get = async (key: string) => {
const db = await openDB<MyDB>('my-db', 1, {
upgrade(db) {
db.createObjectStore('books');
},
});
const result = await db.get('books', key);
if (result) {
return URL.createObjectURL(result.blob);
}
return result;
};
<file_sep>import crypto from 'crypto';
import {Request, Response} from 'express';
import {readdir, stat} from 'fs';
import {join} from 'path';
import {promisify} from 'util';
import {query} from '../core/data';
import {Audiobook} from '../core/schema';
import {getUser} from './play';
const readdirP = promisify(readdir);
const statP = promisify(stat);
export const readDirAsync = async (
dir: string,
allFiles: Array<string> = []
) => {
const files = (await readdirP(dir)).map(f => join(dir, f));
allFiles.push(...files);
await Promise.all(
files.map(
async f => (await statP(f)).isDirectory() && readDirAsync(f, allFiles)
)
);
return allFiles.filter(f => f.indexOf('.mp3') > -1);
};
export const list = async (req: Request, res: Response) => {
const take = 10;
const currentCount = req.params.count ?? take;
const searchQuery = req.params.query
? ` WHERE lower(title) similar to '%(${req.params.query})%'`
: '';
console.log(searchQuery);
const total = await query(`SELECT COUNT(*) FROM audiobook${searchQuery}`, []);
const hasMore = Number(total.rows[0].count) > currentCount;
const audiobookResult = await query(
`SELECT * FROM audiobook${searchQuery} OFFSET $1 ROWS FETCH NEXT $2 ROWS ONLY`,
[currentCount.toString(), take.toString()]
);
const books = audiobookResult.rows as Array<Audiobook>;
const fileResult = await query(
`SELECT * FROM file WHERE bookId IN (SELECT id FROM audiobook)`,
[]
);
const allFiles = fileResult.rows;
const returnSet = books.map(b => ({
...b,
files: allFiles.filter(af => b.id === af.bookid),
}));
res.json({
items: returnSet,
hasMore,
});
};
interface ParamsDictionary {
[id: string]: string;
}
const salt = crypto
.createHash('md5')
.update(process.env.REACT_APP_AUTH0_DOMAIN)
.digest('hex');
export const strongHash = (input: string) =>
crypto
.createHash('sha512')
.update(input + salt)
.digest('hex');
export const item = async (req: Request<ParamsDictionary>, res: Response) => {
const id = req.params.id;
const userId = getUser(req).sub;
const hashedUserId = strongHash(userId);
const d = await query('SELECT * FROM audiobook WHERE id = $1', [id]);
const row = d.rows[0] as Audiobook;
const {rows} = await query(`SELECT * FROM file WHERE bookId = $1`, [row.id]);
const session = await query(`SELECT * FROM session WHERE userId = $1`, [
hashedUserId,
]);
res.json({
...row,
files: rows,
sessions: session.rows,
});
};
<file_sep>import cheerio from 'cheerio';
import {Audiobook} from './schema';
import {
ratingsStringToNumber,
runtimeStringToNumber,
starsStringToNumber,
stringToUtc,
} from './scraperUtils';
export const scraper = async (
id: string,
searchHtml: string,
folder: string,
description: string,
link: string
): Promise<Audiobook> => {
const searchPage = cheerio.load(searchHtml);
const firstItem = searchPage('.productListItem')[0];
const root = searchPage(firstItem);
const getString = (selector: string) => {
return root
.find(selector)
.toArray()
.map(d => d.children.map(c => c.data))
.reduce((acc, val) => acc.concat(val), [])
.join(', ');
};
const getImage = () =>
root.find('.responsive-product-square img')[0]?.attribs['src'] || '';
const title = getString('.bc-list-item h3 a');
const subtitle = getString('.subtitle span');
const year = new Date(stringToUtc(getString('.releaseDateLabel span')));
const narrator = getString('.narratorLabel span a');
const author = getString('.authorLabel span a');
const runtime = runtimeStringToNumber(getString('.runtimeLabel span'));
const language = getString('.languageLabel span')
.split(':')
.pop()
.trim();
const stars = starsStringToNumber(
getString('.ratingsLabel .bc-pub-offscreen')
);
const ratings = ratingsStringToNumber(
getString('.ratingsLabel .bc-color-secondary')
);
const image = getImage();
return {
id,
title,
subtitle,
year,
narrator,
author,
runtime,
language,
stars,
ratings,
image,
folder,
description,
link,
lastUpdatedUtc: new Date(),
dateCreatedUtc: new Date(),
};
};
export const getDetailLink = async (searchHtml: string) => {
const searchPage = cheerio.load(searchHtml);
const firstItem = searchPage('.productListItem')[0];
const root = searchPage(firstItem);
const detailLink =
root
.find('.bc-list-item h3 a')
.toArray()
.pop()
?.attribs['href']?.split('?')
?.shift() || '';
return `https://www.audible.com${detailLink}`;
};
export const getDetail = (detailHtml: string) => {
const detailPage = cheerio.load(detailHtml);
return (
detailPage('.productPublisherSummary')
.find('.bc-text')
.html() || ''
);
};
<file_sep>import {trans} from './data';
export const cleanUp = async (itemsNotInFolder: Array<string>) => {
const promises: Array<Promise<void>> = [];
itemsNotInFolder.forEach(f => {
const promise = trans(async c => {
const file = await c.query('SELECT * FROM audiobook where id = $1', [f]);
const result = (await file).rows[0];
const files = await c.query('SELECT * FROM file WHERE bookid = $1', [f]);
const fileIds = files.rows.map(f => f.id);
console.log(`deleting ${result.title}`);
await c.query(
`DELETE FROM session WHERE fileid IN (${fileIds.map(
(f, i) => `$${i + 1}`
)})`,
fileIds
);
await c.query('DELETE FROM file WHERE bookid = $1', [f]);
await c.query('DELETE FROM audiobook WHERE id = $1', [f]);
});
promises.push(promise);
});
return promises;
};
<file_sep>DATABASE_URL=postgres://user:example@docker.for.win.localhost:5432/audi
DATABASE_SSL=false
REACT_APP_AUTH0_CLIENT_ID=
REACT_APP_AUTH0_DOMAIN=
DATA=C:\\path\\to\\books<file_sep>import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import fs from 'fs';
import path from 'path';
import {checkJwt} from './auth';
import {item, list} from './controllers/audio';
import {download, play, save} from './controllers/play';
import {settings} from './controllers/settings';
import {init} from './core/file';
import {watcher} from './core/watcher';
dotenv.config();
(async function main() {
try {
await init();
watcher();
} catch (err) {
console.log(err);
}
})();
const app = express();
app.on('error', console.log);
app.use(cors());
app.listen(6969, () => {
console.log('[NodeJS] Application Listening on Port 6969');
});
const staticFiles = path.join(__dirname, '../../../client/build');
if (fs.existsSync(staticFiles)) {
console.log(`found static files @ ${staticFiles}`);
app.use('/', express.static(staticFiles));
} else {
console.log('could not find static files.');
}
// no auth here but uses the fileID (sha512 hash + salt) that is ONLY provided to the client on authenticated routes.
app.get('/api/audio/play/:id', play);
app.get('/api/audio/download/:id', download);
app.get('/api/audio/save/:id/:time', checkJwt, save);
app.get('/api/audio/grid/:count/:query?', checkJwt, list);
app.get('/api/audio/:id', checkJwt, item);
app.get('/api/settings', settings);
app.get('*', (req, res) => {
res.sendFile(`${staticFiles}/index.html`);
});
app.use((err: Error, req: any, res: any, next: any) => {
console.log(err.name);
console.log(err.message);
if (err.name === 'UnauthorizedError') {
res.status(401).send('Unauthorized');
} else {
res.status(500).send('Something broke!');
}
});
<file_sep>#!/bin/bash
set -ex
PARENT_DIR=$(basename "${PWD%/*}")
CURRENT_DIR="${PWD##*/}"
IMAGE_NAME="$PARENT_DIR/$CURRENT_DIR"
TAG="${1}"
REGISTRY="hub.docker.com"
docker build -t ${REGISTRY}/${IMAGE_NAME}:${TAG} .
docker tag ${REGISTRY}/${IMAGE_NAME}:${TAG} ${REGISTRY}/${IMAGE_NAME}:latest
docker push ${REGISTRY}/${IMAGE_NAME}
docker tag ${REGISTRY}/${IMAGE_NAME}:latest ${REGISTRY}/${IMAGE_NAME}:${TAG}
docker push ${REGISTRY}/${IMAGE_NAME}<file_sep>import dotenv from 'dotenv';
import {Request, Response} from 'express';
dotenv.config();
export interface Settings {
clientId: string;
domain: string;
audience: string;
}
export const settings = async (req: Request, res: Response) => {
const settings: Settings = {
clientId: process.env.REACT_APP_AUTH0_CLIENT_ID,
domain: process.env.REACT_APP_AUTH0_DOMAIN,
audience: `http://localhost:6969`,
};
res.json(settings);
};
<file_sep>REACT_APP_API_BASE_URL=http://localhost:6969/<file_sep>import {query, trans} from './data';
interface Schema {
column: string;
type: 'text' | 'decimal' | 'integer' | 'date' | 'serial';
isNull?: boolean;
isKey?: boolean;
reference?: string;
}
const audiobook: Array<Schema> = [
{column: 'id', type: 'text', isNull: false, isKey: true},
{column: 'title', type: 'text', isNull: false},
{column: 'subtitle', type: 'text', isNull: false},
{column: 'description', type: 'text', isNull: false},
{column: 'image', type: 'text', isNull: false},
{column: 'author', type: 'text', isNull: false},
{column: 'folder', type: 'text', isNull: false},
{column: 'narrator', type: 'text', isNull: false},
{column: 'runtime', type: 'integer', isNull: false},
{column: 'language', type: 'text', isNull: false},
{column: 'link', type: 'text', isNull: false},
{column: 'stars', type: 'decimal', isNull: false},
{column: 'ratings', type: 'integer', isNull: false},
{column: 'year', type: 'date', isNull: false},
{column: 'lastUpdatedUtc', type: 'date', isNull: false},
{column: 'dateCreatedUtc', type: 'date', isNull: false},
];
export interface Audiobook {
id: string;
title: string;
subtitle: string;
image: string;
description: string;
folder: string;
author: string;
narrator: string;
runtime: number;
language: string;
link: string;
stars: number;
ratings: number;
year: Date;
lastUpdatedUtc: Date;
dateCreatedUtc: Date;
}
const session: Array<Schema> = [
{column: 'id', type: 'serial', isNull: false, isKey: true},
{column: 'userId', type: 'text', isNull: false},
{column: 'fileId', type: 'text', isNull: false, reference: 'file(id)'},
{column: 'time', type: 'decimal', isNull: false},
];
export interface Session {
id: number;
userId: string;
fileid: string;
time: number;
}
const file: Array<Schema> = [
{column: 'id', type: 'text', isNull: false, isKey: true},
{column: 'bookId', type: 'text', isNull: false, reference: 'audiobook(id)'},
{column: 'duration', type: 'decimal', isNull: false},
{column: 'size', type: 'decimal', isNull: false},
{column: 'bitrate', type: 'decimal', isNull: false},
{column: 'format', type: 'text', isNull: false},
{column: 'location', type: 'text', isNull: false},
{column: 'title', type: 'text', isNull: false},
{column: 'fileName', type: 'text', isNull: false},
{column: 'lastUpdatedUtc', type: 'date', isNull: false},
{column: 'dateCreatedUtc', type: 'date', isNull: false},
];
export interface File {
id: string;
bookId: string;
duration: number;
size: number;
bitrate: number;
format: string;
location: string;
title: string;
filename: string;
}
export const schema = [
{
name: 'audiobook',
schema: audiobook,
},
{
name: 'file',
schema: file,
},
{
name: 'session',
schema: session,
},
];
export const validate = async () => {
console.log('validating schema');
for (const s of schema) {
console.log(`checking schema ${s.name}`);
const tableExistance = await query(
'SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2);',
['public', s.name]
);
const exists = tableExistance.rows[0].exists;
console.log(`schema ${s.name} exists? ${exists}`);
if (!exists) {
await trans(async client => {
await client.query('SET search_path TO schema,public');
await client.query(
`CREATE TABLE ${s.name} (${s.schema.map(s => {
const reference = s.reference ? `REFERENCES ${s.reference}` : '';
const key = s.isKey ? 'PRIMARY KEY' : '';
const isNull = s.isNull ? '' : 'NOT NULL';
return `${s.column} ${s.type} ${isNull} ${key} ${reference}`;
})})`
);
});
}
}
};
| ec47548964c5fc2b28f4d94d1a47928ba3d8fa99 | [
"Markdown",
"TypeScript",
"Dockerfile",
"Shell"
] | 33 | TypeScript | jonocairns/aubri | 1b40bc227b2ac391bd49c98ca359ca6d214c468e | 6c2291248f13028cf2501c004e8d39746a20ee8d |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <D:\编程练习\InsertSort\qgsort.h>
int main()
{
int s, n, size, max;
int* temp;
int begin, mid, end;
n = 100;
int* a;
int i;
i = 0;
a = (int*)malloc((n) * sizeof(int));
FILE* fp = fopen("C:\\Users\\king\\Desktop\\data.txt", "r");
if (!fp)
{
printf("can't open file\n");
return -1;
}
while (!feof(fp))
{
fscanf(fp, "%5d", &a[i]);
i++;
}
printf("\n");
fclose(fp);
while (1)
{
printf("******请输入您的选择******\n");
printf("******1.插入排序******\n");
printf("******2.归并排序******\n");
printf("******4.快速排序(递归版)******\n");
printf("******5.计数排序******\n");
printf("******6.基数计数排序******\n");
scanf_s("%d", &s);
switch (s)
{
case 1:
{ clock_t start_time; }
clock_t start_time = clock();
{
insertSort(a, n);
}
clock_t end_time = clock();
printf("Running time is: %lfms\n", (double)(end_time - start_time) / CLOCKS_PER_SEC * 1000);
printf("\n");
break;
case 2:
{ clock_t start_time; }
clock_t start2_time = clock();
{
begin = a[0];
end = a[n - 1];
mid = a[(n - 1) / 2];
temp = (int*)malloc((end - begin + 1) * sizeof(int));//申请空间
Mergeaay(a, begin, mid, end, temp);
free(temp);
}
clock_t end2_time = clock();
printf("Running time is: %lfms\n", (double)(end2_time - start2_time) / CLOCKS_PER_SEC * 1000);
printf("\n");
break;
case 4:
//快速排序(递归版)
{ clock_t start_time; }
clock_t start3_time = clock();
{
begin = a[0];
end = a[n - 1];
mid = a[(n - 1) / 2];
temp = (int*)malloc((end - begin + 1) * sizeof(int));//申请空间
MergeSort(a, begin, mid, end, temp);
free(temp);
}
clock_t end3_time = clock();
printf("Running time is: %lfms\n", (double)(end3_time - start3_time) / CLOCKS_PER_SEC * 1000);
printf("\n");
break;
case 5:
//计数排序
{ clock_t start_time; }
clock_t start4_time = clock();
{
int min;
min = a[0];
max = a[0];
size = max - min + 1;
CountSort(a, size, max);
}
clock_t end4_time = clock();
printf("Running time is: %lfms\n", (double)(end4_time - start4_time) / CLOCKS_PER_SEC * 1000);
printf("\n");
break;
case 6:
//基数计数排序
{ clock_t start_time; }
clock_t start5_time = clock();
{
int min, max;
min = a[0];
max = a[0];
size = max - min + 1;//数组长度
for (int i = 0; i < size; i++)//得到最大值和最小值
{
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
RadixCountSort(a, size);
}
clock_t end5_time = clock();
printf("Running time is: %lfms\n", (double)(end5_time - start5_time) / CLOCKS_PER_SEC * 1000);
printf("\n");
break;
system("pause");
system("cls");
}
}
return 0;
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <D:\编程练习\InsertSort\qgsort.h>
#define MAX 200000
#define BASE 10
//插入排序
void insertSort(int* a, int n)
{
int i, j, key;
for (i = 1; i < n; i++)
{
key = a[i];
j = i - 1;
while ((j >= 0) && (a[j] > key))
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
//归并排序(合并数组)
void Mergeaay(int* a, int begin, int mid, int end, int* temp)
{
int i, k;
int left_begin = begin;//左边部分的头部
int left_end = mid;//左边部分的头尾部
int right_begin = mid + 1;//右边部分的头部
int right_end = end;//右边部分的头尾部
for (k = 0; left_begin <= left_end && right_begin <= right_end; k++)// 比较两个指针所指向的元素
{
if (a[left_begin] <= a[right_begin])//将小的数放到temp中,并且指向后一个数
{
temp[k] = a[left_begin++];
}
else
{
temp[k] = a[right_begin++];
}
}
if (left_begin <= left_end) //若第一个序列有剩余,直接复制出来粘到合并序列尾
{
for (i = left_begin; i <= left_end; i++)
temp[k++] = a[i];
}
if (right_begin <= right_end)//若第二个序列有剩余,直接复制出来粘到合并序列尾
{
for (i = right_begin; i <= right_end; i++)
temp[k++] = a[i];
}
for (i = 0; i < end - begin + 1; i++)
a[begin + i] = temp[i];
}
// 归并排序
void MergeSort(int* a, int begin, int end, int* temp)
{
int mid = 0;
if (begin < end)
{
mid = (begin + end) / 2;
MergeSort(a, begin, mid, temp);
MergeSort(a, mid + 1, end, temp);
Mergeaay(a, begin, mid, end, temp);
}
}
//快速排序(递归版)
void QuickSort_Recursion(int* a, int begin, int end)
{
if (begin < end)//判断区间是否只有一个数
{
int temp = a[begin]; //将区间的第一个数作为基准数
int i = begin; //从左到右进行查找时的“指针”,指示当前左位置
int j = end; //从右到左进行查找时的“指针”,指示当前右位置
while (i < j) //不重复遍历
{
while (i<j && a[j] > temp)//找到小于等于基准元素的数a[j]
j--;
a[i] = a[j];//将右边小于等于基准元素的数填入左边相应位置
while (i < j && a[i] <= temp)//找到大于等于基准元素的数a[i]
i++;
a[j] = a[i];//将左边大于等于基准元素的数填入右边相应位置
}
a[i] = temp; //将基准元素填入相应位置
QuickSort_Recursion(a, begin, i - 1);//对基准元素的左边子区间进行相似的快速排序
QuickSort_Recursion(a, i + 1, end);//对基准元素的右边子区间进行相似的快速排序
}
}
////快速排序(非递归版)
//void QuickSort(int* a, int size)
//{
//
//}
////快速排序(枢轴存放)
//int Partition(int* a, int begin, int end)
//{
//
//}
//计数排序
void CountSort(int* a, int size, int max)
{
int min;
min = a[0];
max = a[0];
size = max - min + 1;//数组长度
for (int i = 0; i < size; i++)//得到最大值和最小值
{
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
int* count = (int*)calloc(size, sizeof(int));//计数数组
int i = 0;
for (i = 0; i < size; i++)
{
count[i] = 0;//初始化计数数组
}
for (i = 0; i < size; i++)
{
count[a[i] - min] = count[a[i] - min]++;//统计元素出现的次数
}
for (i = 0; i < (size - 1); i++)
{
count[i + 1] = count[i + 1] + count[i];//将count中数据表示为元素在结果数组中最后的位置
}
int* result = (int*)calloc(size, sizeof(int));//结果数组
int j;
for (j = 0; j < size; j++)
{
result[count[a[j] - min] - 1] = a[j];//将元素添加到结果数组中对应位置
count[a[j] - min]--;//添加元素后,计数数组标记的位置向前加一
}
for (int i = 0; i < size; i++)
{
a[i] = result[i];//将排序好的数据赋值到a
}
free(count);
free(result);//释放内存
}
//基数计数排序
void RadixCountSort(int* a, int size)
{
int i, m = a[0], exp = 1;
int min, max;
min = a[0];
max = a[0];
size = max - min + 1;//数组长度
for (int i = 0; i < size; i++)//得到最大值和最小值
{
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
int* b = (int*)calloc(size, sizeof(int));//计数数组
int* bucket = (int*)calloc(size, sizeof(int));//计数数组
for (i = 1; i < size; i++)
{
if (a[i] > m)
{
m = a[i];
}
}
while (m / exp > 0)//判断位上是否有数
{
int bucket[BASE] = { 0 };//初始化
for (i = 0; i < size; i++)
{
bucket[(a[i] / exp) % BASE]++;//统计元素出现的次数
}
for (i = 1; i < BASE; i++)
{
bucket[i] += bucket[i - 1];//将bucket中数据表示为元素在结果数组中最后的位置
}
for (i = size - 1; i >= 0; i--)
{
b[--bucket[(a[i] / exp) % BASE]] = a[i];//按个位数排序
}
for (i = 0; i < size; i++)
{
a[i] = b[i];//将排序好的数组赋值给a
}
exp *= BASE;
}
free(bucket);
free(b);
}
//颜色排序
//void ColorSort(int* a, int size)
//{
//
//}<file_sep># QG训练营数据挖掘组第四周周记:
2020年4月19日
## 生活随记
这周学习状况不好,周一有点放松自己。
## 一周总结
不知道怎么回事,心态不好。真的是心态一点都不好。明明基础很差了,周一还放纵自己,周五同学要开学了,也去找朋友玩了。反正这周过的一点都不满意。第四周的大组作业啊,我真的是做废了。太难了吧。可好像也没有多么难,群里的小伙伴都早早的写完了。我基本上把时间都花在研究这些排序上了。啊,我感觉好难啊。怎么也想不出快速排序的迭代形式怎么写。想不出师兄给的接口怎么用。心态真的炸了。我真的好菜,却一点也不知道珍惜时间,还放纵自己。气死了。眼看自己差距与别人越来越大,有点浮躁,却也有点不思进取?状态好烂。难受,这次作业真的没了。
## 存在问题
不思进取,浪费时间。不知道抓紧时间好好学习,老想着怎么放纵自己。
## 下周规划
下周好好做考核作业,力所能及的往多了做,能实现一个是一个。到了中期了,不能因为自己的懒散而前功尽弃啊。耐下心来,沉住气,好好学习!!这周的作业好愧疚,下周可以问同学要一份,参考一下人家怎么写的。加油吧!
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
int* a;
int i;
i = 0;
a = (int*)malloc((100) * sizeof(int));
FILE* fp = fopen("C:\\Users\\king\\Desktop\\data.txt", "r");
if (!fp)
{
printf("can't open file\n");
return -1;
}
while (!feof(fp))
{
fscanf(fp, "%5d", &a[i]);
printf("%5d", a[i]);
i++;
}
printf("\n");
fclose(fp);
return 0;
}<file_sep>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<math.h>
int main(void)
{
srand(time(NULL));//先种种子
int i, j, s = 0;
FILE* fp = NULL;
for (i = 0; i < 100; i++) //产生随机数
{
j = rand() % 10000;
printf("j:%d\n", j);
fp = fopen("C:\\Users\\king\\Desktop\\data.txt", "a");//在指定目录下创建.txt文件
fprintf(fp, "%5d", j); //把随机数写进文件
fclose(fp);
}
return 0;
}
| 96b1d5a3fb28f63cd7bc035517bbfa926078e8c2 | [
"Markdown",
"C"
] | 5 | C | TommieKing/disicizuoye | ffe72902472c3ac3c5fe5a767806636439071d51 | 0fed926afadd4a07442cad8bd71bf3fc2e4a3420 |
refs/heads/master | <repo_name>waqar-baig/cr_tournament<file_sep>/app/channels/chat_rooms_channel.rb
class ChatRoomsChannel < ApplicationCable::Channel
def subscribed
stream_from "chat_rooms_#{params['chat_room_id']}_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def card_banned(data)
# @team = Team.create!(name: data['message'])
# @team.teams_matches.create(match_id: data['chat_room_id'])
data['action'] = 'card_banned'
MessageBroadcastJob.perform_later(data)
end
def card_selected(data)
data['action'] = 'card_selected'
MessageBroadcastJob.perform_later(data)
end
end<file_sep>/app/javascript/src/reducers/visibilityFilter.js
// const visibilityFilter = (state = 'SHOW_ALL', action) => {
// switch (action.type) {
// case 'SET_VISIBILITY_FILTER':
// return action.filter
// default:
// return state
// }
// }
export function visibilityFilter(state=true, action) {
switch (action.type) {
case 'SELECT_TYPES': case 'SELECT_RARITY':
return {
rarity: action.rarity || state.rarity,
cardType: action.cardType || state.cardType
}
default:
return state
}
}
<file_sep>/app/views/matches/show.json.jbuilder
json.match do
json.id @match.id
json.uuid @match.uuid
json.teams @match.teams do |team|
json.id team.id
json.name team.name
json.players team.players do |player|
json.id player.id
json.name player.name
json.nickName player.nick_name
end
end
end
<file_sep>/app/javascript/src/containers/SelectedDeckList.jsx
import React from 'react'
import { connect } from 'react-redux'
import SelectedDeck from '../components/SelectedDeck'
const mapStateToProps = state => {
return {
playerDeck: state.playerDeck
}
}
const mapDispatchToProps = dispatch => {
return {
playerDeck: []
}
}
const SelectedDeckList = connect(mapStateToProps)(SelectedDeck)
export default SelectedDeckList<file_sep>/app/javascript/src/containers/VisibleCardList.js
import { connect } from 'react-redux'
import { cardsFetchData, handleChange, selectRarity, selectTypes } from '../actions'
import CardList from '../components/CardList'
const getVisibleCards = (cards=[], filter) => {
let _cards = cards
if (filter.rarity && filter.rarity != 'All') {
_cards = _cards.filter(c => c.rarity == filter.rarity)
}
if (filter.cardType && filter.cardType != 'All') {
_cards = _cards.filter(c => c.type == filter.cardType)
}
return _cards;
}
const mapStateToProps = state => {
return {
cards: getVisibleCards(state.cards, state.visibilityFilter),
isLoading: state.cardsIsLoading,
isHold: state.isHold,
visibilityFilter: state.visibilityFilter
}
}
const mapDispatchToProps = dispatch => {
return {
fetchData: url => {
dispatch(cardsFetchData(url))
},
logChange: (option, name) => {
if (name == "rarity") {
dispatch(selectRarity(option))
}
else if (name == "types") {
dispatch(selectTypes(option))
}
}
}
}
const VisibleCardList = connect(
mapStateToProps,
mapDispatchToProps
)(CardList)
export default VisibleCardList<file_sep>/app/jobs/message_broadcast_job.rb
class MessageBroadcastJob < ApplicationJob
queue_as :default
def perform(card)
ActionCable.server.broadcast "chat_rooms_1_channel", card
end
private
def render_message(message)
TeamsController.render partial: 'teams/team', locals: {team: message}
end
end<file_sep>/app/javascript/src/components/ModalExample.js
import React, { Component } from 'react';
import Modal from 'react-modal';
const customStyles = {
content : {
top : '50%',
left : '50%',
right : 'auto',
bottom : 'auto',
marginRight : '-50%',
transform : 'translate(-50%, -50%)'
}
};
class ModalExample extends Component {
constructor(props) {
super();
this.state = {
modalIsOpen: true,
canClose: false,
};
this.teams = props.teams;
this.setCurrentPlayer = this.setCurrentPlayer.bind(this);
}
closeModal() {
if (this.state.canClose) {
this.setState({ modalIsOpen: false });
}
}
setCurrentPlayer(player) {
console.log('current player: ' + player.name)
this.props.currentPlayer(player);
Stage.setCurrentPlayer(player)
this.setState({ modalIsOpen: false })
}
render() {
let teams = this.teams.map((team, index)=> {
return <Team obj={team} onSelect={this.setCurrentPlayer} currentPlayer={this.props.currentPlayer} />
})
return (
<div>
<button onClick={this.openModal}>Open Modal</button>
<Modal
isOpen={this.state.modalIsOpen}
onAfterOpen={this.afterOpenModal}
onRequestClose={this.closeModal}
style={customStyles}
contentLabel="Example Modal"
>
<h3 ref={subtitle => this.subtitle = subtitle}>Who are you?</h3>
<div className="row">{teams}</div>
</Modal>
</div>
);
}
}
class Team extends Component {
constructor(props) {
super();
this.team = props.obj
}
render() {
// const players = this.team.players.map((player, index)=> {
// return [<Player obj={player} handleSelect={this.props.onSelect} currentPlayer={this.props.currentPlayer} />, <br/>]
const team = <a className="btn btn-primary" onClick={this.props.onSelect.bind(this, team)}><h4>{this.team.name}</h4></a>
// })
return <div className="col-md-6">{team}</div>
}
}
// class Player extends Component {
// render() {
// return <a className="btn btn-primary" onClick={this.props.handleSelect.bind(this, this.props.obj)}><h4>{this.props.obj.name}</h4></a>
// }
// }
export default ModalExample;<file_sep>/app/javascript/src/App.js
import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';
import Card from './components/Card';
import BannedList from './components/BannedList';
import SelectedDeck from './components/SelectedDeck';
import Home from './components/Home';
import ModalExample from './components/ModalExample';
class stage {
constructor() { this.currentStage = 'hold' }
setCurrentPlayer(player) {
this.currentPlayer = player
this.goToBanning();
}
setCurrentTeam(team) {
this.currentTeam = team;
}
getStage() { return this.currentStage; }
isBanning() { return this.currentStage == 'banning' }
goToBanning() { this.currentStage = 'banning' }
isSelection() { return this.currentStage == 'selection' }
goToSelection() { this.currentStage = 'selection' }
isHold() { return this.currentStage == 'hold'}
setHold() { this.currentStage = 'hold'}
}
window.Stage = new stage()
class App extends Component {
constructor(props) {
super();
this.match = props.match
Stage.setCurrentTeam(props.team)
if (props.willStart) {
Stage.goToBanning();
}
this.state = {
cards: [],
bannedList: []
};
this.components = {
bannedList: '',
cards: ''
}
this.banCard = this.banCard.bind(this)
this.currentPlayer = {};
this.setCurrentPlayer = this.setCurrentPlayer.bind(this)
this.cardBanned = false;
this.playerDeck = []
}
componentWillMount() {
}
componentDidMount() {
axios.get('/cards.json')
.then(res => {
const cards = res.data
console.log(cards)
this.setState({ cards: cards, bannedList: this.state.bannedList });
});
var that = this
Socket.cable.subscriptions.create(
{
channel: "ChatRoomsChannel",
chat_room_id: '1'
}, {
received (data) {
if (that.state.bannedList.length == 2) { Stage.goToSelection() }
if (data.playerID == that.currentPlayer.id) {
return
}
// findCard(data['message'])
that.state.cards.forEach((_card)=> {
if (_card.idName == data.message){
_card.isBanned = true;
that.state.bannedList.push(_card);
if (that.state.bannedList.length == 2) { Stage.goToSelection() }
that.setState({_card})
return
}
})
// this.state.cards.push()
}
});
}
setCurrentPlayer(player) {
this.currentPlayer = player
window.currentPlayer = player
this.setState({ player })
}
banCard(card) {
if (this.isBanned) {
this.playerDeck.push({...card})
// return alert('already banned')
} else {
this.isBanned = true;
card.isBanned = true;
this.state.bannedList.push(card);
}
this.setState({card})
}
render(){
var bannedList = this.state.bannedList;
var cardList = this.state.cards.map((card, index)=>{
if (card.isBanned) {return}
return <Card info={card} index={index} onCardClick={this.banCard} key={index}></Card>;
})
this.components.bannedList = <BannedList list={bannedList} player={this.currentPlayer}></BannedList>;
this.components.cards = <div className='col-md-6 selection-deck'><div className="row">{ cardList }</div></div>;
this.components.selectedDeck = <div className="col-md-6 selected-deck"><SelectedDeck playerDeck={this.playerDeck} opponentDeck={this.opponentDeck}/></div>;
var playerBoard = <div className="row">
{this.components.cards}
{this.components.selectedDeck}
</div>;
console.log(this.match);
return ([this.components.bannedList, playerBoard])
}
}
export default App;
<file_sep>/app/models/match.rb
class Match < ApplicationRecord
has_many :teams_matches
has_many :teams, through: :teams_matches
has_many :players, through: :teams
def as_json(opts = nil)
more = {}
more[:teams] = teams
attributes.merge(more)
end
end
<file_sep>/app/javascript/src/actions/index.js
let nextTodoId = 0
export const addTodo = text => {
return {
type: 'ADD_TODO',
id: nextTodoId++,
text
}
}
export const handleCardClick = card => {
if (card.state.cardsBanned.length >=2 && window.canSelectCard) {
return selectCard(card)
} else if (window.canBanCard) {
return banCard(card)
} else {
return {
type: 'HOLD'
}
}
}
export const setVisibilityFilter = filter => {
return {
type: 'SET_VISIBILITY_FILTER',
filter
}
}
export const selectCard = card => {
return {
type: 'SELECT_CARD',
card
}
}
export const opponentBannedCard = card => {
return {
type: 'OPPONENT_BAN_CARD',
card
}
}
export const opponentSelectedCard = card => {
return {
type: 'OPPONENT_SELECT_CARD',
card
}
}
export const banCard = card => {
return {
type: 'BAN_CARD',
card
}
}
// need to use async
export const handleChange = (option, name) => {
if (name == "rarity") {
return selectRarity(option)
}
else if (name == "types") {
return selectTypes(option)
}
}
export function cardsIsLoading(bool) {
return {
type: 'CARDS_IS_LOADING',
isLoading: bool
};
}
export function cardsFetchDataSuccess(cards) {
return {
type: 'CARDS_FETCH_DATA_SUCCESS',
cards
};
}
export function cardsFetchData(url) {
return (dispatch) => {
dispatch(cardsIsLoading(true));
fetch(url)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(cardsIsLoading(false));
return response;
})
.then((response) => response.json())
.then((cards) => dispatch(cardsFetchDataSuccess(cards)));
};
}
export function selectRarity(option) {
return {
type: 'SELECT_RARITY',
rarity: option
}
}
export function selectTypes(option) {
return {
type: 'SELECT_TYPES',
cardType: option
}
}
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :players
get 'matches/show'
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
mount ActionCable.server => '/cable'
resources :matches
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: 'hello_world#index'
end
<file_sep>/app/javascript/src/components/CardList.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { cardsIsLoading, cardsFetchData } from '../actions';
import Card from './Card';
class CardList extends Component {
constructor(props) {
super(props);
this.selectedRarity = this.props.selectedRarity,
this.rarities = [
{
name: 'Select Rarity',
value: 'All',
},
{
name: 'Common',
value: 'Common',
},
{
name: 'Rare',
value: 'Rare',
},
{
name: 'Epic',
value: 'Epic',
},
{
name: 'Legendary',
value: 'Legendary',
},
],
this.types = [
{
name: 'Select Type',
value: 'All',
},
{
name: 'Troop',
value: 'Troop',
},
{
name: 'Spell',
value: 'Spell',
},
{
name: 'Building',
value: 'Building',
},
]
}
componentDidMount() {
console.log('inside componentDidMount')
this.props.fetchData('/cards.json');
}
render() {
const createItem = (item, key) =>
<option
key={key}
value={item.value}
>
{item.name}
</option>;
let backdrop = <div />
if (this.props.isLoading) {
return <p>Loading…</p>;
} else if (this.props.isHold) {
backdrop = <div className="backdrop" />
}
return(
<div className="CardList col-md-8">
{backdrop}
<div className="row cardFilter">
<select className="rarityCardFilter" onChange={event => this.props.logChange(event.target.value, name="rarity")}>
{this.rarities.map(createItem)}
</select>
<select className="typeCardFilter" onChange={event => this.props.logChange(event.target.value, name="types")}>
{this.types.map(createItem)}
</select>
</div>
<div className="row">
{this.props.cards.map(card => (
<Card key={card._id} {...card} />
))}
</div>
</div>
);
}
}
export default CardList;
<file_sep>/app/controllers/matches_controller.rb
class MatchesController < ApplicationController
def show
@match = Match.find(params[:id])
@team = @match.teams.find_by(id: params[:team_id])
if @team.blank?
render text: '<h3>Team not found</h3>', layout: false
end
end
end
<file_sep>/app/javascript/src/containers/OpponentCardList.jsx
import React from 'react'
import { connect } from 'react-redux'
import OpponentCard from '../components/OpponentCard'
import { opponentSelectedCard } from '../actions'
const mapStateToProps = state => {
return {
opponentCards: state.opponentCards
}
}
const mapDispatchToProps = dispatch => {
Socket.cable.subscriptions.create(
{
channel: "ChatRoomsChannel",
chat_room_id: '1'
}, {
received (data) {
console.log('opponentSelectedCard')
if (data.team_id == window.currentTeamId || data.action == 'card_banned') {
return
}
window.canSelectCard = true
dispatch(opponentSelectedCard({_id: data.card_id, idName: data.card_name}))
}
});
return {
}
}
const OpponentCardList = connect(mapStateToProps, mapDispatchToProps)(OpponentCard)
export default OpponentCardList<file_sep>/app/models/team.rb
class Team < ApplicationRecord
has_many :teams_matches
has_many :matches, through: :teams_matches
has_many :players
# after_create_commit { MessageBroadcastJob.perform_later(self) }
def as_json(opts = nil)
more = {}
more[:players] = players
attributes.merge(more)
end
end
<file_sep>/app/javascript/packs/application.js
import ReactOnRails from 'react-on-rails';
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk';
import todoApp from '../src/reducers'
import App from '../src/components/App'
window.currentTeamId = window.location.search.split('=')[1];
let store = createStore(todoApp, applyMiddleware(thunk))
// This is how react_on_rails can see the HelloWorld in the browser.
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
<file_sep>/app/javascript/src/components/OpponentCard.jsx
import React, { Component } from 'react';
import { connect } from 'react-redux'
class OpponentCard extends Component {
render() {
var cardList = ''
console.log('inside OpponentCard.length: '+ this.props.opponentCards.length)
if (this.props.opponentCards.length == 0) {
cardList = <div className="col-md-12"><h3>Your opponent's card will appear here!</h3></div>
} else {
cardList = this.props.opponentCards.map((card, index)=>{
let item = (<div className="Item pull-left ml-10">
<img src={"/assets/cards/" + card.idName + ".png"} />
</div>)
return item;
})
}
return ([<div className="OpponentCard row">{cardList}</div>]);
}
}
export default OpponentCard
<file_sep>/app/javascript/src/components/App.jsx
import React from 'react'
import SelectedDeckList from '../containers/SelectedDeckList'
import VisibleCardList from '../containers/VisibleCardList'
import BannedList from './BannedList'
import OpponentCardList from '../containers/OpponentCardList'
const App = () => (
<div className="">
<SelectedDeckList />
<div className="row">
<VisibleCardList />
<div className="col-md-4">
<BannedList />
<OpponentCardList />
</div>
</div>
</div>
)
export default App | 7c407c43cf579048d94aa6fcc9881dd6cb171fe9 | [
"JavaScript",
"Ruby"
] | 18 | Ruby | waqar-baig/cr_tournament | 162e23fa76af61ebb292ee11b8296423d62cff04 | b2a4b436bf687fa8922adfdd4dedc4f1c8f48670 |
refs/heads/master | <repo_name>cfdeboer/openacademy<file_sep>/wizard.py
# -*- coding: utf-8 -*-
from openerp import models,fields,api
class Wizard (models.TransientModel):
_name= 'openacademy.wizard'
def _default_sessions(self):
print self.env['openacademy.session'].browse(self._context.get('active_ids'))
return self.env['openacademy.session'].browse(self._context.get('active_ids'))
session_ids = fields.Many2many('openacademy.session',string="Sessions",
required=True, default=_default_sessions)
attendee_ids = fields.Many2many('openacademy.attendee', string='Attendees')
def _default_courses(self):
print self.env['openacademy.course'].browse(self._context.get('active_ids'))
return self.env['openacademy.course'].browse(self._context.get('active_ids'))
course_ids = fields.Many2many('openacademy.course',string="Courses",
required=True, default=_default_courses)
@api.multi
def subscribe(self):
for session in self.session_ids:
session.attendee_ids |= self.attendee_ids
return {}
@api.multi
def add_sessions(self):
for course in self.course_ids:
course.session_ids |= self.session_ids
return {}
<file_sep>/models/models.py
# -*- coding: utf-8 -*-
from openerp import models, fields, api, exceptions
class Teachers(models.Model):
_name= "openacademy.teachers"
partner_id=fields.Many2one('res.partner', string='Teacher id', required=False)
# next statment inhibits Administrator from making new contacts
# _inherit = 'res.partner'
name = fields.Char(string='Teachers')
session_ids=fields.One2many('openacademy.session',
'teacher_id', string='Sessions to teach' )
session_amount = fields.Integer(string="Number of sessions",compute="number_of_sessions")
age = fields.Integer("Age", required=False)
@api.constrains('age')
# @api.one
def constrain_age(self):
if self.age <= 20:
raise exceptions.ValidationError(
("Age of teacher must be at least 21!"))
def number_of_sessions(self):
for teacher in self:
teacher.session_amount = len(teacher.session_ids)
#@api.constrains('session_amount')
#def constrain_session_amount(self):
# if self.session_amount < 2:
## raise exceptions.ValidationError("More Sessions please")
class Course(models.Model):
_name = 'openacademy.course'
_order = 'session_ids'
name = fields.Char(string= "Title", required=True)
description = fields.Text(string="description")
session_ids=fields.One2many('openacademy.session', 'course_id',
string="Sessions no.")
sessions_list=fields.Char(string='session list',
compute='list_the_sessions')
attendee_ids=fields.Many2many('openacademy.attendee','name',
string='Course Attendees' )
attendee_list=fields.Char(string='Course Attendee list: ',
compute='list_the_attendees')
total_course_sessions=fields.Char(string='total sessions in course',
compute='calculate_total_sess' )
average_sess = fields.Char(string= 'average sessions',
compute='sess_div_courses')
teacher_names= fields.Char(string="Course Teachers",
compute='list_the_teachers' )
# @api.multi
# def copy(self, default=None):
# default = dict(default or {})
# copied_count = self.search_count(
# [('name', '=like', u"Copy of {}%".format(self.name))])
# if not copied_count:
# new_name = u"Copy of {}".format(self.name)
# else:
# new_name = u"Copy of {} ({})".format(self.name, copied_count)
# default['name'] = new_name
# return super(Course, self).copy(default)
# _sql_constraints = [ ('name_description_check',
# 'CHECK(name != description)',
# "The title of the course should not be the description"),
##
# ('name_unique',
# 'UNIQUE(name)',
# "The course title must be unique"),
# ]
#
@api.constrains('attendee_ids')
def constrain_attendee(self):
message=["Attendees can subscribe to a session, not a course, or the world turns to chaos!"]
for course in self:
for attendee in self.attendee_ids:
if attendee.name:
raise exceptions.ValidationError(message[0])
def calculate_total_sess(self):
for course in self:
course.total_course_sessions= len(course.session_ids)
def sess_div_courses(self):
all_courses = self.env['openacademy.course'].search_count([])
all_sessions = self.env['openacademy.session'].search_count([])
course_average = 1.0*all_sessions/all_courses
#print "all courses: ", all_courses, " all sessions: ", all_sessions
for course in self:
course.average_sess= course_average
def list_the_teachers(courses):
for course in courses:
course_teachers_list=[]
for session_id in course.session_ids:
for teacher_id in session_id:
teacher_name = session_id.teacher_id.name
if teacher_name and teacher_name not in course_teachers_list:
# print "Session: ",session_id.name ,", teacher name: ", teacher_name
course_teachers_list.append(teacher_name)
course_teachers_string=str( ', '.join(course_teachers_list))
course.teacher_names=course_teachers_string
def list_the_sessions(courses):
for course in courses:
course_session_list=[]
for session_id in course.session_ids:
if session_id.name:
# print "Session: ",session_id.name
course_session_list.append(session_id.name)
# print "Course_session_list: ", course_session_list
course_session_string = str( ', '.join(course_session_list))
# print course_session_string
course.sessions_list = course_session_string
def list_the_attendees(courses):
for course in courses:
course_attendee_list=[]
for session_id in course.session_ids:
for attendee in session_id.attendee_ids:
attendee_name= attendee.name
if attendee_name not in course_attendee_list:
#print "In course: "+ attendee_name
course_attendee_list.append(attendee_name)
course_attendee_string=str(', '.join(course_attendee_list))
course.attendee_list=course_attendee_string
class Session(models.Model):
_name = 'openacademy.session'
name = fields.Char(string="Session title or no.")
description = fields.Text(string='Session name', required=False)
duration = fields.Float(digits=(6, 2), help="Duration in days")
start_date = fields.Date(default=fields.Date.today)
lunch= fields.Boolean("Vegetarian food available", default=False)
course_id= fields.Many2one('openacademy.course', string='Course')
attendee_ids=fields.Many2many('openacademy.attendee','attendee_ids',
string= 'Session Attendee id')
teacher_id = fields.Many2one('openacademy.teachers', string="Teacher")
vegies_per_session = fields.Char(string="vegetarians in session",
compute='veggies' )
attendees_per_session= fields.Char(string= "Attendees per session",
compute='num_attendees')
attendee_list=fields.Char(string='Session attendee list: ',
compute='list_the_attendees')
color = fields.Integer()
def veggies(self):
for session in self:
vegies_count_per_session=0
for attendee in session.attendee_ids:
if attendee.vegetarian:
vegies_count_per_session += 1
session.vegies_per_session = vegies_count_per_session
#--number of attendees er session
def num_attendees(self):
for session in self:
count_session_attendees=0
for attendee in session.attendee_ids:
count_session_attendees += 1
session.attendees_per_session=count_session_attendees
def list_the_attendees(sessions):
for session in sessions:
session_attendee_list=[]
for attendee in session.attendee_ids:
attendee_name= attendee.name
if attendee_name and attendee_name not in session_attendee_list:
#print "in session: "+attendee_name
session_attendee_list.append(attendee_name)
session_attendee_string=str(', '.join(session_attendee_list))
session.attendee_list=session_attendee_string
class Attendee(models.Model):
_name='openacademy.attendee'
#partner_id=fields.Many2one('res.partner', string='Attendee id', required=False)
# next statment inhibits Administrator from making new contacts
# _inherit = 'res.partner'
name = fields.Char(string='Attendee')
vegetarian = fields.Boolean(string="vegetarian", default=False)
attendee_ids=fields.Many2many('res.partner',
string= 'Attendee id')
attendee_id_info=fields.Char(string="ID", compute="attendee_info")
total_vegetarians= fields.Char(string ="total vegetarians", \
compute = "count_vegetarians")
sessions= fields.Many2many('openacademy.session','attendee_ids',
string='Participates in session:')
def count_vegetarians(self):
count = 0
for attendees in self:
if (attendees.vegetarian==True):
count += 1
for a in self:
a.total_vegetarians= count
def attendee_info(self):
for attendee in self:
name = ""
idname=attendee.attendee_ids.name
if idname:
name=idname
else:
name="No id"
attendee.attendee_id_info=name
<file_sep>/readme.txt
the new branch without leaves
| c191c8c60a01b34d199992174293c91cf4a39dc5 | [
"Python",
"Text"
] | 3 | Python | cfdeboer/openacademy | 3794520af1d479ee6dbdff655e78686cb0d410d1 | bbd0bab6a1d132d5fb1b431b5ab4ce6f3e55ff3b |
refs/heads/master | <file_sep>const React = require('react');
const styled = require('@stiligita/core').default
const react = require('@stiligita/react').default
const {CREATE_COMPONENT, CREATE_SELECTOR, PROCESSOR, GET_NAME} = require('@stiligita/constants')
const Abcq = require('abcq').default;
const DEFAULT_THEME = require('./default-theme');
const shortid = new Abcq()
const safelyAlphanumeric = (a, b) => {
const propA = a.split(':')[0]
const propB = b.split(':')[0]
const propAPre = propA.split('-')[0]
const propBPre = propB.split('-')[0]
if (propAPre > propBPre) {
return 1
}
if (propAPre < propBPre) {
return -1
}
if (propA > propB) {
return 1
}
if (propA < propB) {
return -1
}
return 0
}
const sortCSSProps = rules => {
return rules
.split(';')
.filter(x => Boolean(x.trim()))
.filter(x => x.split(':').every(f => f.trim() !== ''))
.sort(safelyAlphanumeric)
.join(';')
}
const shortId = (key, keys) => shortid.encode(keys.indexOf(key))
const defaultId = (key, keys) => key
const createComponent = (strings, args, tag, defaultProps) => {
const amendedDefaultProps = Object.assign({theme: DEFAULT_THEME}, defaultProps);
const Component = react(strings, args, tag, amendedDefaultProps);
return (props) => {
const name = process.env.DEBUG === 'true' ? Component.displayName : null;
return <Component {...props} data-name={name}/>;
};
}
const createClassName = (hash, mode) => {
switch (mode) {
case 'css':
return `.${hash}`;
case 'html':
return {className: hash};
}
};
shortId.stiligita = GET_NAME
defaultId.stiligita = GET_NAME
sortCSSProps.stiligita = PROCESSOR
createComponent.stiligita = CREATE_COMPONENT;
createClassName.stiligita = CREATE_SELECTOR;
styled
.before(sortCSSProps)
.use(createComponent)
.use(shortId)
.use(createClassName)
module.exports = styled;
<file_sep>const {render} = require('../');
const {example, fixture} = require('./utils');
test('render qrcode', async () => {
expect.assertions(0);
const input = await fixture('qrcode.json');
const result = render(input);
await example('qrcode.svg', result);
});
<file_sep>const React = require('react');
const color = require('./color');
const styled = require('./styled');
module.exports = Word;
function Word(props) {
return [
(props.inverse || props.bg) &&
<StyledWordBackground
bg={props.bg}
fg={props.fg}
height={props.theme.fontSize * props.theme.lineHeight}
inverse={props.inverse}
width={props.children.length > 0 ? props.children.length : 0}
x={props.x * props.theme.fontSize * 0.6}
y={props.y - props.theme.fontSize}
/>,
<StyledWord
bg={props.bg}
bold={props.bold}
fg={props.fg}
inverse={props.inverse}
theme={props.theme}
underline={props.underline}
x={props.x * props.theme.fontSize * 0.6}
y={props.y}
>
{props.children}
</StyledWord>
];
}
const BG_FILL = props => props.inverse ? fg(props, props.theme) : bg(props, props.theme);
const TEXT_FILL = props => props.inverse ? bg(props, props.theme) : fg(props, props.theme);
const DECORATION = props => props.underline ? 'underline' : null;
const FONT_WEIGHT = props => props.bold ? 'bold' : null;
const StyledWordBackground = styled.rect`
fill: ${BG_FILL};
`;
const StyledWord = styled.text`
fill: ${TEXT_FILL};
text-decoration: ${DECORATION};
font-weight: ${FONT_WEIGHT};
white-space: pre;
`;
function bg(props, theme) {
const b = typeof props.bg === 'undefined' ? theme.background : props.bg;
return color(b, theme, theme.background);
}
function fg(props, theme) {
const d = props.bold ? theme.bold : theme.text;
// Bold takes precedence if fg is undefined or 0
if (props.bold && !props.fg) {
return color(theme.bold, theme);
}
const f = typeof props.fg === 'undefined' ? d : props.fg;
return color(f, theme, d);
}
<file_sep>const React = require('react');
module.exports = Frame;
function Frame(props) {
return (
<svg x={props.offset * props.width}>
<use xlinkHref="#a"/>
{props.children}
</svg>
);
}
<file_sep>const {render} = require('..');
const {example, fixture} = require('./utils');
jest.setTimeout(10000);
test('render commitlint', async () => {
expect.assertions(0);
const input = await fixture('example.json');
const result = render(input, {window: true});
await example('commitlint.svg', result);
});
test('render commitlint', async () => {
expect.assertions(0);
const input = await fixture('example.json');
const result = render(input, {window: true, width: 80, height: 20});
await example('commitlint-sized.svg', result);
});
test('render commitlint 1 to 5', async () => {
expect.assertions(0);
const input = await fixture('example.json');
const result = render(input, {window: true, from: 1000, to: 2000});
await example('commitlint-1-to-5.svg', result);
});
test('render commitlint 5', async () => {
expect.assertions(0);
const input = await fixture('example.json');
const result = render(input, {window: true, at: 5000});
await example('commitlint-at-5.svg', result);
});
<file_sep>const {render} = require('../');
const {example, fixture} = require('./utils');
jest.setTimeout(20000);
test('render lolcat', async () => {
expect.assertions(0);
const input = await fixture('lolcat.json');
const result = render(input);
await example('lolcat.svg', result);
});
<file_sep>const rgb = require('ansi-to-rgb');
module.exports = color;
function color(input, theme, fallback) {
if (!input) {
return null;
}
if (Array.isArray(input)) {
return `rgb(${input.join(', ')})`;
}
const c = theme[input];
if (c) {
return `rgb(${c.join(', ')})`;
}
const r = rgb[Number(input)];
if (r) {
return `rgb(${r.join(', ')})`;
}
if (!fallback) {
throw new TypeError(`color: Unknown ANSI color ${input}`);
}
return color(fallback);
}
<file_sep>const React = require('react');
const Cursor = require('./Cursor');
const Word = require('./Word');
const styled = require('./styled');
module.exports = Registry;
function Registry(props) {
return (
<defs>
{props.items.map(item => {
switch(item.type) {
case 'line':
return <LineSymbol key={item.id} theme={props.theme} {...item}/>;
default:
throw new TypeEror(`Unknown Registry item of type ${item.type}`);
}
})}
{props.hasFrames && [
<symbol id="a" key="a">
<StyledBackground
height={props.frameHeight}
width={props.frameWidth}
x="0"
y="0"
/>
</symbol>,
props.hasCursors && (
<symbol id="b" key="b">
<Cursor
height={props.theme.fontSize * props.theme.lineHeight}
theme={props.theme}
width={props.theme.fontSize * 0.66}
/>
</symbol>
)
]
}
</defs>
);
}
function LineSymbol(props) {
return (
<symbol id={props.id}>
{props.words.map((word, index) => (
<Word
bg={word.attr.bg}
bold={word.attr.bold}
fg={word.attr.fg}
inverse={word.attr.inverse}
key={index}
theme={props.theme}
underline={word.attr.underline}
x={word.x}
y={props.theme.fontSize}
>
{word.children}
</Word>
))}
</symbol>
);
}
const StyledBackground = styled.rect`
fill: transparent;
`;
<file_sep>const {render} = require('../');
const {example, fixture} = require('./utils');
test('render with custom theme', async() => {
expect.assertions(1);
const input = await fixture('theme.json');
const theme = {
0: [40, 45, 53], // Black
1: [232, 131, 136], // Red
2: [168, 204, 140], // Green
3: [219, 171, 121], // Yellow
4: [113, 190, 242], // Blue
5: [210, 144, 228], // Magenta
6: [102, 194, 205], // Cyan
7: [185, 191, 202], // White
8: [111, 119, 131], // Light Black
9: [232, 131, 136], // Light Red
10: [168, 204, 140], // Light Green
11: [219, 171, 121], // Light Yellow
12: [115, 190, 243], // Light Blue
13: [210, 144, 227], // Light Magenta
14: [102, 194, 205], // Light Cyan
15: [255, 255, 255], // Light White
background: [40, 45, 53], // background color
bold: [185, 192, 203], // Default bold text color
cursor: [111, 118, 131], // Cursor color
text: [185, 192, 203], // Default text color,
fontSize: 1.67,
lineHeight: 1.3,
fontFamily: 'foobarFamily,monospace'
};
const result = render(input, { theme: theme });
expect(/foobarFamily/.test(result)).toBe(true);
await example('theme.svg', result);
})
<file_sep>const React = require('react');
module.exports = Viewbox;
function Viewbox(props) {
return (
<g>
{props.children}
</g>
);
}
<file_sep>const React = require('react');
const {renderToStaticMarkup} = require('react-dom/server');
const {ServerStyleSheet} = require('@stiligita/stylesheets');
module.exports = Document;
function Document(props) {
const sheet = new ServerStyleSheet()
const content = render(props);
const css = sheet.getStyleTag();
const __html = `${css}${content}`;
return (
<svg
dangerouslySetInnerHTML={{__html}}
height={props.height * 10}
viewBox={[0, 0, props.width, props.height].join(' ')}
width={props.width * 10}
x={props.x}
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
y={props.y}
/>
);
}
function render(props) {
return renderToStaticMarkup(React.Children.only(props.children));
}
<file_sep>const {flatMap, entries, groupBy, isEqual} = require('lodash');
const hash = require('object-hash');
module.exports = toViewModel;
function toViewModel(options) {
const {cursor: cursorOption, cast, theme, from, to} = options;
const liner = getLiner(cast);
const stamps = cast.frames
.filter(([stamp], i, fs) => stamp >= from && stamp <= to)
.map(([stamp], i) => stamp - from);
const fontSize = theme.fontSize;
const lineHeight = theme.lineHeight;
const height = typeof options.height === 'number' ? options.height : cast.height;
const frames = cast.frames
.filter(([stamp], i, fs) => stamp >= from && stamp <= to)
.map(([delta, data], i) => [delta, data, liner(data)])
.map(([stamp, data, l], index) => {
const lines = l
.map((chars, y) => {
const words = toWords(chars);
return {
y: y * fontSize * lineHeight,
words,
hash: hash(words),
ref: null
};
});
const cursor = data.cursor || data.screen.cursor;
const cl = lines[cursor.y] || {y: 0};
cursor.x = cursor.x + 2;
cursor.y = Math.max(0, cl.y - 1);
cursor.visible = cursorOption === false ? false : cursor.visible;
return {
cursor,
lines,
stamp: (Math.round(stamp * 100) / 100) - from
};
});
const candidates = flatMap(frames, 'lines').filter(line => line.words.length > 0);
const hashes = groupBy(candidates, 'hash');
const registry = entries(hashes)
.filter(([_, lines]) => lines.length > 1)
.map(([hash, [line]], index) => {
const id = index + 1;
const words = line.words.slice(0);
frames.forEach(frame => {
frame.lines
.filter(line => line.hash === hash)
.forEach(l => {
l.words = [];
l.id = id;
});
});
return {type: 'line', words, id};
});
return {
width: cast.width,
displayWidth: cast.witdh,
height: cast.height,
displayHeight: height * fontSize * lineHeight,
duration: to - from,
registry,
stamps,
frames
};
}
function getLiner(cast) {
switch (cast.version) {
case 0:
return (data) => toOne(data.lines);
default:
return (data) => data.screen.lines;
}
}
function toWords(chars) {
return chars
.reduce((words, [point, attr]) => {
if (words.length === 0) {
words.push({
attr,
x: 0,
children: '',
offset: 0
});
}
const word = words[words.length - 1];
const children = String.fromCodePoint(point);
if (children === ' ' && !('bg' in attr) && !attr.inverse) {
word.offset = word.offset + 1;
return words;
}
if (isEqual(word.attr, attr) && word.offset === 0) {
word.children += children;
} else {
words.push({
attr,
x: word.x + word.children.length + word.offset,
children,
offset: 0
});
}
return words;
}, [])
.filter((word, i, words) => {
if ('bg' in word.attr || word.attr.inverse) {
return true;
}
const trimmed = word.children.trim();
const after = words.slice(i + 1);
if ((trimmed === '' || trimmed === '⏎')) {
return false;
}
return true;
});
}
function toOne(arrayLike) {
return Object.entries(arrayLike)
.sort((a, b) => a[0] - b[0])
.map(e => e[1])
.map(words => words.reduce((chars, word) => {
const [content, attr] = word;
chars.push(...content.split('').map(char => [char.codePointAt(0), attr]));
return chars;
}, []), []);
}
<file_sep>> Share terminal sessions via SVG and CSS
# svg-term
* Render [asciinema][asciinema] asciicast to animated SVG
* Use custom themes
* Share asciicast everywhere
```sh
npm install svg-term
```
## Usage
```js
const fs = require('fs');
const {promisify} = require('util');
const readFile = promisify(fs.readFile);
const {render} = require('svg-term');
(async () => {
const data = String(await readFile('./asciicast.json'));
const svg = render(data);
// => <svg>...</svg>
})()
```
## API
```ts
// `input` can be string/object of v1 or v2:
// https://github.com/asciinema/asciinema/blob/develop/doc
// or an already loaded cast:
// https://github.com/marionebl/load-asciicast
//
// `options` won't take effect if `input` is an already loaded cast.
render(input: string, options?: Options): string
interface Options {
/**
* ANSI theme to use
* - has to contain all keys if specified
* - defaults to Atom One theme if omitted
**/
theme?: Theme;
/** Render with a framing window, defaults to false */
window?: boolean;
/** Idle time limit in milliseconds */
idle?: number,
/** Frames per second limit, see https://github.com/marionebl/svg-term/issues/13 */
fps?: number,
/** Lower bound of timeline to render in milliseconds */
from?: number;
/** Upper bound of timeline to render in milliseconds */
to?: number;
/** Timestamp of single frame to render in milliseconds **/
at?: number;
}
interface Theme {
/** ANSI Black */
0: RGBColor;
/** ANSI Red */
1: RGBColor;
/** ANSI Green */
2: RGBColor;
/** ANSI Yellow */
3: RGBColor;
/** ANSI Blue */
4: RGBColor;
/** ANSI Magenta */
5: RGBColor;
/** ANSI Cyan */
6: RGBColor;
/** ANSI White */
7: RGBColor;
/** ANSI Light Black */
8: RGBColor;
/** ANSI Light Red */
9: RGBColor;
/** ANSI Light Green */
10: RGBColor;
/** ANSI Light Yellow */
11: RGBColor;
/** ANSI Light Blue */
12: RGBColor;
/** ANSI Light Magenta */
13: RGBColor;
/** ANSI Light Cyan */
14: RGBColor;
/** ANSI Light White */
15: RGBColor;
/** Default background color */
background: RGBColor;
/** Default color for bold text */
bold: RGBColor;
/** Cursor color */
cursor: RGBColor;
/** Default text color */
text: RGBColor
/** Default font size */
fontSize: number;
/** Default line height */
lineHeight: number;
/** Default font family */
fontFamily: string;
}
type RGBColor = [number, number, number];
```
---
[asciinema]: https://asciinema.org/
<file_sep>const React = require('react');
const keyframes = require('@stiligita/keyframes').default;
const styled = require('./styled');
module.exports = Reel;
const PERCEPTIBLE = 1 / 60;
function magnitude(x) {
const y = Math.abs(x);
if (y > 1) {
return 0;
}
const result = Math.floor(Math.log(y) / Math.log(10) + 1);
return result === 0 ? result : -1 * result;
}
function Reel(props) {
if (props.duration === 0) {
return (
<svg
x="0"
y="0"
width={props.width}
>
{props.children}
</svg>
);
}
const factor = Math.pow(10, magnitude(PERCEPTIBLE / (props.duration / 100)) + 1);
const p = s => Math.round((s / (props.duration / 100)) * factor) / factor;
const animation = keyframes`
${props.stamps.map((stamp, i) => `
${p(stamp)}% {
transform: translateX(-${props.frameWidth * i}px);
}
`).join('\n')}
`;
return (
<StyledAnimationStage
animation={animation}
duration={props.duration}
>
<svg
x="0"
y="0"
width={props.width}
>
{props.children}
</svg>
</StyledAnimationStage>
);
}
const StyledAnimationStage = styled.g`
animation-name: ${props => props.animation};
animation-duration: ${props => props.duration}s;
animation-iteration-count: infinite;
animation-timing-function: steps(1, end);
`;
<file_sep>const {render} = require('../');
const {example, fixture} = require('./utils');
test('render with styling', async () => {
expect.assertions(0);
const input = await fixture('styles.json');
const result = render(input);
await example('styling.svg', result);
});
| 254775077ef9896668a6e0d771a76c437ba0e35d | [
"JavaScript",
"Markdown"
] | 15 | JavaScript | ngocdaothanh/svg-term | 8eedd6aa895b37d3d63fda1cc7cbb4dace53fe1e | cb594394575b765086e439a2e5e82784300a1251 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
# Generate PKI with leaf certificates
set -e
# Log function
:: ()
{
echo -e "\033[36m#\033[0m \033[1;36m$*\033[0m"
}
# Vars
VERBOSE=""
BASE=$PWD
BUILD_DIR=$PWD/build
# Read input
while [ "$#" -gt 0 ]; do
key="$1"
case "$key" in
-d)
DOMAIN="$2"
shift
;;
-n)
NAME="$2"
shift
;;
--verbose)
VERBOSE=1
set -x
;;
*)
NAME="$1"
DOMAIN="$2"
shift
;;
esac
shift
done
# Check
if [[ -z "$DOMAIN" || -z "$NAME" ]]; then
:: "No DOMAIN or NAME given!"
exit 1
fi
# Setup
DOMAIN_SLUGGED=$(echo $DOMAIN | sed s/\\./_/g)
:: "Preparing directory structure"
# cleanup first
rm -rf $BUILD_DIR
CA_BASE=$BUILD_DIR/ca
mkdir -p $CA_BASE
cd $CA_BASE
mkdir certs csr newcerts private
chmod 700 private
touch index.txt
echo 1000 > serial
sed \
-e "s/%DOMAIN_BASE%/${DOMAIN}/" \
-e "s/%DOMAIN_WILDCARD%/*.${DOMAIN}/" \
$BASE/files/openssl.cnf.tmpl > $BUILD_DIR/openssl.cnf
OPENSSL_CONFIG=$BUILD_DIR/openssl.cnf
:: "CA: creating key"
openssl genrsa -out private/ca.key 2048
chmod 400 private/ca.key
:: "CA: creating certificate"
openssl req -config $OPENSSL_CONFIG \
-key private/ca.key \
-new -x509 -days 3650 -sha256 -extensions v3_ca \
-subj "/CN=${NAME} Development CA" \
-out certs/ca.pem
chmod 444 certs/ca.pem
:: "Server: creating private key"
openssl genrsa -out private/${DOMAIN_SLUGGED}.key 2048
chmod 400 private/${DOMAIN_SLUGGED}.key
:: "Server: creating certificate signing request"
openssl req -config $OPENSSL_CONFIG \
-key private/${DOMAIN_SLUGGED}.key \
-new -sha256 \
-subj "/CN=*.${DOMAIN}" \
-out csr/${DOMAIN_SLUGGED}.csr
:: "CA: signing server certificate"
openssl ca -config $OPENSSL_CONFIG \
-extensions server_cert -batch -days 2830 -notext -md sha256 \
-in csr/${DOMAIN_SLUGGED}.csr \
-out certs/${DOMAIN_SLUGGED}.crt
chmod 444 certs/${DOMAIN_SLUGGED}.crt
:: "Preparing export"
cd $BUILD_DIR
mkdir export/
cp $CA_BASE/certs/*.crt export/
cp $CA_BASE/private/${DOMAIN_SLUGGED}.key export/<file_sep># PKI Generator for Wildcard Certificates
Bash scripts for generating a PKI including a CA and leaf certificate.
The leaf certificate will be a wildcard certificate.
## Usage
Simply run `./gen.sh <general name> <domain>` in this folder, where
* `<general name>` is just a name for the CA prepended before "Development CA"
* `<domain>` is your base domain (e.g. `dev.local`, the wildcard will be prepended!) | 6ee989b78c112cf478282d0da4ce5bb03232860d | [
"Markdown",
"Shell"
] | 2 | Shell | jdoubleu/pkigen-wildcard | 4ea0ddbd4a3136c1aa5886b8f64d85ff1d2947e8 | 2442634e2cf22585a1a0d6210474d3be46b69c2c |
refs/heads/master | <repo_name>GerrayJr/iBuy<file_sep>/app/src/main/java/com/apps/gerrykyalo/ibuy/ConsumerLogin.java
package com.apps.gerrykyalo.ibuy;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
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.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class ConsumerLogin extends AppCompatActivity implements View.OnClickListener {
private EditText logEmail, logPass;
private Button logBtn;
private TextView tvRegister;
private FirebaseAuth auth;
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.consumer_login);
logEmail = findViewById(R.id.con_email);
logPass = findViewById(R.id.con_password);
logBtn = findViewById(R.id.btn_login);
logBtn.setOnClickListener(this);
tvRegister = findViewById(R.id.tv_register);
tvRegister.setOnClickListener(this);
dialog = new ProgressDialog(this);
auth = FirebaseAuth.getInstance();
}
private void loginUser() {
String email = logEmail.getText().toString().trim();
String password = logPass.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Enter Email!!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Enter Password!!", Toast.LENGTH_SHORT).show();
return;
}
dialog.setMessage("Please Wait");
dialog.show();
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
dialog.dismiss();
if (task.isSuccessful()) {
finish();
Toast.makeText(ConsumerLogin.this, "Success", Toast.LENGTH_SHORT).show();
Intent prof = new Intent(ConsumerLogin.this, ConsumerMap.class);
startActivity(prof);
} else {
Toast.makeText(ConsumerLogin.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onClick(View view) {
if (view == logBtn) {
loginUser();
}
if (view == tvRegister) {
startActivity(new Intent(this, ConsumerRegister.class));
}
}
}
| c555a330936ad993703dbbe94700c44355a1e8b3 | [
"Java"
] | 1 | Java | GerrayJr/iBuy | b1d3f133b5d23c34b96739a5411a37235d95f6c7 | cee4968a3fc0f27cb0126857ccf3d0ea16b547bc |
refs/heads/master | <file_sep>/**
*
*/
package snuggin.popup.actions;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.MarkerAnnotation;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import snuggin.refactorings.VisitorBasedRefactoring;
public final class InjectToMyRefactoring extends VisitorBasedRefactoring {
private boolean _usesInject = false;
@Override
public boolean visit(CompilationUnit node) {
_usesInject = false;
return super.visit(node);
}
@Override
public void endVisit(CompilationUnit node) {
if (_usesInject) {
imports().insertLast(newStaticImport("wheel.lang.Environments.my"), null);
}
}
@Override
public void endVisit(ImportDeclaration node) {
if (node.getName().toString().equals("sneer.kernel.container.Inject")) {
remove(node);
}
}
@Override
public void endVisit(MarkerAnnotation node) {
// remove @Inject
if (isInjectAnnotation(node))
remove(node);
}
@Override
public void endVisit(FieldDeclaration node) {
// from: @Inject ... Service foo;
// to: ... Service foo = my(Service.class);
if (isInjected(node)) {
rewriteInjectedField(node);
_usesInject = true;
}
}
private void rewriteInjectedField(FieldDeclaration node) {
removeStaticModifier(node);
initializeToMy(node);
}
private void initializeToMy(FieldDeclaration node) {
for (Object f : node.fragments()) {
final VariableDeclarationFragment declaration = (VariableDeclarationFragment) f;
final MethodInvocation value = newMethodInvocation("my", newTypeLiteral(copy(node.getType())));
rewrite().set(declaration, VariableDeclarationFragment.INITIALIZER_PROPERTY, value, null);
}
}
private void removeStaticModifier(FieldDeclaration node) {
for (Object m : node.modifiers()) {
if (isStaticModifier(m)) {
remove(ASTNode.class.cast(m));
break;
}
}
}
private boolean isStaticModifier(Object m) {
return m instanceof Modifier
&& Modifier.class.cast(m).isStatic();
}
private boolean isInjected(FieldDeclaration node) {
for (Object m : node.modifiers())
if (m instanceof MarkerAnnotation)
if (isInjectAnnotation((MarkerAnnotation)m))
return true;
return false;
}
private boolean isInjectAnnotation(final MarkerAnnotation annotation) {
return annotation.getTypeName().toString().equalsIgnoreCase("Inject");
}
private ListRewrite imports() {
return rewrite().getListRewrite(compilationUnit(), CompilationUnit.IMPORTS_PROPERTY);
}
}
<file_sep>package snuggin.builder;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
public class SneerBuilder extends IncrementalProjectBuilder {
public static final String BUILDER_ID = "snuggin.sneerBuilder";
/*
* (non-Javadoc)
*
* @see org.eclipse.core.internal.events.InternalBuilder#build(int,
* java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
*/
protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
throws CoreException {
if (kind == FULL_BUILD) {
fullBuild(monitor);
} else {
IResourceDelta delta = getDelta(getProject());
if (delta == null) {
fullBuild(monitor);
} else {
incrementalBuild(delta, monitor);
}
}
return null;
}
void checkJavaFile(IProgressMonitor monitor, IResource resource) {
if (!isJavaFile(resource)) return;
final IFile file = (IFile) resource;
deleteMarkers(file);
final CompilationUnit ast = parse(monitor, file);
ast.accept(new CheckingVisitor(file, ast));
}
private CompilationUnit parse(IProgressMonitor monitor, IFile file) {
final ICompilationUnit element = (ICompilationUnit) JavaCore.create(file);
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(element);
parser.setResolveBindings(true);
final CompilationUnit ast = (CompilationUnit) parser.createAST(monitor);
return ast;
}
private boolean isJavaFile(IResource resource) {
return resource instanceof IFile && resource.getName().endsWith(".java");
}
private void deleteMarkers(IFile file) {
try {
file.deleteMarkers(CheckingVisitor.MARKER_TYPE, false, IResource.DEPTH_ZERO);
} catch (CoreException ce) {
}
}
protected void fullBuild(final IProgressMonitor monitor)
throws CoreException {
try {
getProject().accept(new IResourceVisitor() {
public boolean visit(IResource resource) {
checkJavaFile(monitor, resource);
//return true to continue visiting children.
return true;
}
});
} catch (CoreException e) {
}
}
protected void incrementalBuild(IResourceDelta delta,
final IProgressMonitor monitor) throws CoreException {
// the visitor does the work.
delta.accept(new IResourceDeltaVisitor() {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
*/
public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
switch (delta.getKind()) {
case IResourceDelta.ADDED:
// handle added resource
checkJavaFile(monitor, resource);
break;
case IResourceDelta.REMOVED:
// handle removed resource
break;
case IResourceDelta.CHANGED:
// handle changed resource
checkJavaFile(monitor, resource);
break;
}
//return true to continue visiting children.
return true;
}
});
}
}
<file_sep>package snuggin.refactorings;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
public class Refactorings {
public static void apply(ICompilationUnit cu, Refactoring refactoring)
throws CoreException {
final RefactoringContext context = new RefactoringContext(parse(cu));
refactoring.apply(context);
cu.applyTextEdit(context.rewriteAST(), null);
cu.save(null, true);
}
public static void apply(IProject project, Refactoring refactoring)
throws Exception {
apply(JavaCore.create(project), refactoring);
}
public static void apply(final IJavaProject javaProject, Refactoring refactoring) throws JavaModelException, Exception {
for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
if (root.getKind() != IPackageFragmentRoot.K_SOURCE)
continue;
forEachPackage(root, refactoring);
}
}
private static CompilationUnit parse(ICompilationUnit cu) {
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(cu);
return (CompilationUnit) parser.createAST(null);
}
private static void forEachPackage(IParent root, Refactoring refactoring)
throws Exception {
for (IJavaElement child : root.getChildren()) {
switch (child.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
forEachPackage((IParent) child, refactoring);
break;
case IJavaElement.COMPILATION_UNIT:
apply((ICompilationUnit) child, refactoring);
break;
}
}
}
public static void apply(IJavaElement element, Refactoring refactoring) throws Exception {
switch (element.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
apply(ICompilationUnit.class.cast(element), refactoring);
break;
case IJavaElement.JAVA_PROJECT:
apply(IJavaProject.class.cast(element), refactoring);
break;
case IJavaElement.PACKAGE_FRAGMENT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
forEachPackage(IParent.class.cast(element), refactoring);
break;
}
}
}
<file_sep>package spikes.adenauer;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class Anything extends JFrame {
private final static String ROOT = "E:\\Musicas";
public static void main(String [] ignored) {
setLookAndFeel();
new Anything();
}
public Anything() {
Container panel = getContentPane();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
panel.add(musicFolders(), c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
panel.add(imageButton(), c);
c.gridx = 2;
c.gridy = 2;
panel.add(label(), c);
setTitle("Imagen button");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(100, 100, 200, 200);
setVisible(true);
}
private JComboBox<String> musicFolders() {
JComboBox<String> folders = new JComboBox<String>();
File root = new File(ROOT);
loadFolders(root, folders);
return folders;
}
private void loadFolders(File root, JComboBox<String> loadedFolders) {
if (root == null) return;
if (root.isFile()) return;
String completePath = root.getAbsolutePath();
if (!(completePath == null) && !completePath.equals(ROOT))
loadedFolders.addItem(removeRootRef(completePath));
for (File entry : root.listFiles()) {
loadFolders(entry, loadedFolders);
}
}
private String removeRootRef(String completePath) {
return (completePath == null) ? "Sem nome" : completePath.replace(ROOT + File.separator, "");
}
private JButton imageButton() {
URL path = getClass().getResource("menu.png");
JButton button = new JButton(new ImageIcon(path));
button.setPreferredSize(new Dimension(20, 20));
button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {
System.out.println("Image button....");
}});
return button;
}
private JLabel label() {
URL path = getClass().getResource("menu.png");
JLabel label = new JLabel(new ImageIcon(path));
label.setPreferredSize(new Dimension(30, 10));
label.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("mouseEntered");
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked");
}
});
label.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
System.out.println("Lost focus");
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("Gain focus");
}
});
return label;
}
private static void setLookAndFeel() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName()))
UIManager.setLookAndFeel(info.getClassName());
} catch (Exception e) {
// Default look and feel will be used.
}
}
}
<file_sep>package spikes.adenauer.network.udp.impl;
import static basis.environments.Environments.my;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import basis.lang.Closure;
import sneer.bricks.hardware.cpu.threads.Threads;
import sneer.bricks.identity.seals.Seal;
import sneer.bricks.pulp.blinkinglights.BlinkingLights;
import sneer.bricks.pulp.blinkinglights.Light;
import sneer.bricks.pulp.blinkinglights.LightType;
import sneer.bricks.pulp.notifiers.Notifier;
import sneer.bricks.pulp.notifiers.Notifiers;
import sneer.bricks.pulp.notifiers.Source;
import sneer.bricks.pulp.reactive.collections.CollectionSignals;
import sneer.bricks.pulp.reactive.collections.SetRegister;
import sneer.bricks.pulp.reactive.collections.SetSignal;
import spikes.adenauer.network.UdpNetworkSpike;
import spikes.adenauer.network.udp.UdpAddressResolver;
public class UdpNetworkImpl implements UdpNetworkSpike {
private DatagramSocket socket;
private final DatagramPacket _packetToReceive = newPacket();
private final DatagramPacket _packetToSend = newPacket();
private final Notifier<Packet> _notifier = my(Notifiers.class).newInstance();
private final SetRegister<Seal> _peersOnline = my(CollectionSignals.class).newSetRegister();
private final Light errorOnReceive = my(BlinkingLights.class).prepare(LightType.ERROR);
public UdpNetworkImpl(int port) throws SocketException {
socket = new DatagramSocket(port);
my(Threads.class).startStepping("UDP Packet Receiver", new Closure() { @Override public void run() {
tryToReceivePacket();
}});
}
private void tryToReceivePacket() {
try {
receivePacket();
my(BlinkingLights.class).turnOffIfNecessary(errorOnReceive);
} catch (IOException e) {
my(BlinkingLights.class).turnOnIfNecessary(errorOnReceive, "Error trying to receive UDP packet.", e);
}
}
private void receivePacket() throws IOException {
socket.receive(_packetToReceive);
//if (endpointsBySeal.containsValue( _packetToReceive.getSocketAddress())) {
Packet packet = newPacket(_packetToReceive);
Seal sender = packet.sender();
_peersOnline.add(sender);
_notifier.notifyReceivers(packet);
//}
}
@Override
public SetSignal<Seal> peersOnline() {
return _peersOnline.output();
}
@Override
public synchronized void send(byte[] data, Seal destination) {
SocketAddress address = my(UdpAddressResolver.class).addressFor(destination);
if (address == null) return;
_packetToSend.setData(data);
_packetToSend.setSocketAddress(address);
try {
socket.send(_packetToSend);
} catch (IOException e) {
throw new basis.lang.exceptions.NotImplementedYet(e); // Fix Handle this exception.
}
}
@Override
public Source<Packet> packetsReceived() {
return _notifier.output();
}
private DatagramPacket newPacket() {
byte[] array = new byte[UdpNetworkSpike.MAX_ARRAY_SIZE];
return new DatagramPacket(array, array.length);
}
private Packet newPacket(DatagramPacket pac) {
byte[] data = new byte[pac.getLength()];
System.arraycopy(pac.getData(), pac.getOffset(), data, 0, data.length);
SocketAddress addressFrom = pac.getSocketAddress();
Seal sender = my(UdpAddressResolver.class).sealFor(addressFrom);
return new UdpPacket(data, sender);
}
// private Signal<Integer> ownPort() {
// return my(Attributes.class).myAttributeValue(OwnPort.class);
// }
final class UdpPacket implements Packet {
private final byte[] _data;
private final Seal _sender;
UdpPacket(byte[] data, Seal sender) {
_data = data;
_sender = sender;
}
@Override
public Seal sender() {
return _sender;
}
@Override
public byte[] data() {
return _data;
}
}
public void close() {
socket.close();
}
}
<file_sep>// Heartbeat (tuple) "Im alive at this IP and port" flooded every 15 seconds
// OwnName
// OwnLocalIp
// OwnPort
//
// PeerLookup (tuple) "Where is this peer?" flooded every 15 seconds for offline peers that are issueing heartbeats
// PeerSeal
//
// PeerSighting (tuple) "I have seen this peer on this IP and Port" sent to whoever did a lookup.
// Seal (peer)
// IP, port
//
package spikes.adenauer.network;
import sneer.bricks.identity.seals.Seal;
import sneer.bricks.pulp.notifiers.Source;
import sneer.bricks.pulp.reactive.collections.SetSignal;
public interface UdpNetworkSpike {
static final int MAX_ARRAY_SIZE = 1024 * 20;
SetSignal<Seal> peersOnline();
void send(byte[] data, Seal destination);
Source<Packet> packetsReceived();
public interface Packet {
Seal sender();
byte[] data();
}
}
<file_sep>package spikes.adenauer.network.udp.tests;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.charset.Charset;
import org.jmock.Expectations;
import org.junit.After;
import org.junit.Test;
import sneer.bricks.hardware.cpu.lang.contracts.WeakContract;
import sneer.bricks.identity.seals.Seal;
import sneer.bricks.pulp.reactive.collections.CollectionChange;
import sneer.bricks.software.folderconfig.testsupport.BrickTestBase;
import spikes.adenauer.network.UdpNetworkSpike.Packet;
import spikes.adenauer.network.udp.UdpAddressResolver;
import spikes.adenauer.network.udp.impl.UdpNetworkImpl;
import basis.brickness.testsupport.Bind;
import basis.lang.Consumer;
import basis.util.concurrent.Latch;
public class UdpSupportTest extends BrickTestBase {
private static final Charset UTF8 = Charset.forName("UTF-8");
private final SocketAddress address1 = new InetSocketAddress("127.0.0.1", 10001);
private final SocketAddress address2 = new InetSocketAddress("127.0.0.1", 10002);
private final Seal seal1 = new Seal(new byte[] {1, 1, 1});
private final Seal seal2 = new Seal(new byte[] {2, 2, 2});
private final UdpNetworkImpl subject1 = createUdpNetwork(10001);
private final UdpNetworkImpl subject2 = createUdpNetwork(10002);
@Bind private final UdpAddressResolver resolver = mock(UdpAddressResolver.class);
@Test
public void packetsToUnknownDestinationsAreIgnored() {
final Seal unknownSeal = new Seal(new byte[] {-1, -1, -1});
expectToResolve(unknownSeal, null);
subject1.send("anything".getBytes(UTF8), unknownSeal);
}
@Test(timeout = 2000)
public void packetSending() {
final Latch latch = new Latch();
@SuppressWarnings("unused") WeakContract packetsRefToAvoidGc =
subject2.packetsReceived().addReceiver(new Consumer<Packet>() { @Override public void consume(Packet packet) {
String received = new String(packet.data());
assertEquals("hello", received);
assertEquals(seal1, packet.sender());
latch.open();
}});
sendData("hello".getBytes(UTF8));
latch.waitTillOpen();
}
@Test(timeout = 2000)
public void receivingPacketMakesSenderBecomeOnline() {
final Latch latch = new Latch();
@SuppressWarnings("unused") WeakContract peersOnlineRefToAvoidGc =
subject2.peersOnline().addReceiver(new Consumer<CollectionChange<Seal>>() { @Override public void consume(CollectionChange<Seal> change) {
if (change.elementsAdded().contains(seal1))
latch.open();
}});
sendData("hello".getBytes(UTF8));
latch.waitTillOpen();
}
private void sendData(byte[] data) {
expectToResolve(seal2, address2);
expectToResolve(address1, seal1);
subject1.send(data, seal2);
}
private void expectToResolve(final Seal seal, final SocketAddress address) {
checking(new Expectations(){{
exactly(1).of(resolver).addressFor(seal);will(returnValue(address));
}});
}
private void expectToResolve(final SocketAddress address, final Seal seal) {
checking(new Expectations(){{
exactly(1).of(resolver).sealFor(address);will(returnValue(seal));
}});
}
private UdpNetworkImpl createUdpNetwork(int port) {
try {
return new UdpNetworkImpl(port);
} catch (SocketException e) {
throw new IllegalStateException(e);
}
}
@After
public void afterUdpTest() {
subject1.close();
subject2.close();
}
}
<file_sep>//package spikes.adenauer.puncher;
//
//import static spikes.adenauer.puncher.SocketAddressUtils.CHARSET;
//import static spikes.adenauer.puncher.SocketAddressUtils.marshal;
//
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.net.InetSocketAddress;
//import java.net.SocketException;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.StringTokenizer;
//
//public class RendezvousServer {
//
// static final int SERVER_PORT = 7070;
//
// private static final Map<String, IpAddresses> addressesByClientId = new HashMap<String, IpAddresses>();
//
// static final String KEEP_ALIVE = "keep alive";
//
// static private DatagramSocket socket;
//
//
// public static void main(String[] ignored ) {
// try {
// initSockets();
// listen();
// } catch (Exception e) {
// println("Failure: " + e.getMessage());
// }
// }
//
//
// private static void initSockets() throws SocketException {
// socket = new DatagramSocket(SERVER_PORT);
// }
//
//
// private static void listen() {
// while (true) {
// try {
// handle(receivePacket());
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
//
//
// private static void handle(DatagramPacket request) throws IOException, UnableToParseAddress {
// StringTokenizer fields = toFields(request);
//
// String firstToken = fields.nextToken();
// if (handleKeepAlive(firstToken)) return;
//
// String callerId = firstToken;
// String localAddress = fields.nextToken();
// String requestedId = fields.nextToken();
//
// keepCallerAddresses(callerId, request, SocketAddressUtils.unmarshal(localAddress));
// rendezvous(callerId, requestedId);
// }
//
//
// private static boolean handleKeepAlive(String firstToken) {
// if (firstToken.equals(KEEP_ALIVE)) {
// System.out.print(".");
// return true;
// }
// System.out.println();
// return false;
// }
//
//
// private static void rendezvous(String callerId, String requestedId) throws IOException {
// IpAddresses caller = addressesByClientId.get(callerId);
// IpAddresses requested = addressesByClientId.get(requestedId);
//
// if (requested == null) {
// println("Requested client '" + requestedId + "' not found.");
// return;
// }
//
// println("Forwarding info to: " + requestedId);
// send(marshal(caller), requested.publicInternetAddress);
// println("Forward info to: " + callerId);
// send(marshal(requested), caller.publicInternetAddress);
// println("=====================================");
// }
//
//
// private static void send(byte[] data, InetSocketAddress dest) throws IOException {
// DatagramPacket packet = new DatagramPacket(data, data.length, dest);
// socket.send(packet);
// println("Sent info: " + new String(packet.getData(), packet.getOffset(), packet.getLength(), CHARSET) + " to address: "+ dest.toString());
// }
//
//
// private static void keepCallerAddresses(String caller, DatagramPacket receivedPacket, InetSocketAddress localAddress) {
// InetSocketAddress publicAddress = (InetSocketAddress)receivedPacket.getSocketAddress();
//
// println("Caller: " + caller + " - Local address: " + localAddress + ", Public address: " + publicAddress);
// addressesByClientId.put(caller, new IpAddresses(publicAddress, localAddress));
// }
//
//
// private static StringTokenizer toFields(DatagramPacket receivedPacket) {
// String result = new String(receivedPacket.getData(), receivedPacket.getOffset(), receivedPacket.getLength(), CHARSET);
// return new StringTokenizer(result.trim(), ";");
// }
//
//
// private static DatagramPacket receivePacket() throws IOException {
// byte[] result = new byte[1024];
// DatagramPacket receivedPacket = new DatagramPacket(result, result.length);
// socket.receive(receivedPacket);
// return receivedPacket;
// }
//
//
// private static void println(String out) {
// System.out.println(out);
// }
//
//}<file_sep>package snuggin.refactorings;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeLiteral;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
public class VisitorBasedRefactoring extends ASTVisitor implements Refactoring {
private RefactoringContext _context;
@Override
public void apply(RefactoringContext context) {
_context = context;
try {
context.compilationUnit().accept(this);
} finally {
_context = null;
}
}
protected CompilationUnit compilationUnit() {
return _context.compilationUnit();
}
protected AST ast() {
return _context.ast();
}
protected ASTRewrite rewrite() {
return _context.rewrite();
}
protected void remove(ASTNode node) {
rewrite().remove(node, null);
}
// TODO: move to a ASTBuilder class
protected Expression newTypeLiteral(Type type) {
final TypeLiteral literal = ast().newTypeLiteral();
literal.setType(type);
return literal;
}
protected MethodInvocation newMethodInvocation(String name, Expression arg) {
final MethodInvocation value = ast().newMethodInvocation();
value.setName(ast().newSimpleName(name));
value.arguments().add(arg);
return value;
}
protected <T extends ASTNode> T copy(final T node) {
return (T) rewrite().createCopyTarget(node);
}
protected ImportDeclaration newStaticImport(final String qualifiedName) {
final ImportDeclaration newImport = ast().newImportDeclaration();
newImport.setStatic(true);
newImport.setName(newName(qualifiedName));
return newImport;
}
protected Name newName(final String qualifiedName) {
return ast().newName(qualifiedName);
}
}
| 6a5ae063d866ded4f40654fe08ce9a625427ccb9 | [
"Java"
] | 9 | Java | d3vgru/sneer | 25d27a5e34c26d395a386ab22b523f44b7612323 | 9434008ae9d78b72a73dcbd376036d7080bb7b35 |
refs/heads/master | <repo_name>RcColes/DH-shopgen<file_sep>/README.md
# DH-shopgen
A shop generator for dark heresy
# Usage
For help on arguments use ```python gen.py --help```
The program takes two required arguments:
```merchant_power``` is a representation of how important the merchant is. In general, the higher this number, the rarer the items that wil be generated.
There is no suggested power for a type of merchant (from underhive scavenger to rogue trader), I reccomend playing with this parameter and finding a value that seems appropriate.
```local_currency``` is a selector for which currency the merchant uses. A sensible default is ```"Throne Gelt"```. If a currency other than Throne Gelt is used, Gelt will also be offered as an option, albeit at a bad exchange rate.
Currently the only other currency option is ```"Guild Scrip"``` (from the world of desoleum). Other currencies should be fairly self explanatory to add.
## Example usage
Thus, a reasonable invocation would be:
```python gen.py 50 "Guild Scrip"```
And in this case produces:
```
Monica Rating 50
Ranged Weapons Guild Scrip Throne Gelt
1x Lasgun ẛ40 ℊ1200
3x Laslock ẛ20 ℊ600
1x Missile Launcher ẛ320 ℊ9600
1x Bow ẛ40 ℊ1200
1x Autopistol ẛ80 ℊ2400
Melee Weapons Guild Scrip Throne Gelt
1x Chainblade ẛ160 ℊ4800
2x Spear ẛ40 ℊ1200
1x Staff ẛ20 ℊ600
1x Shock Maul ẛ160 ℊ4800
Explosives Guild Scrip Throne Gelt
2x Blind Grenade ẛ160 ℊ4800
Weapon Mods Guild Scrip Throne Gelt
1x Modified Stock (Best) ẛ240 ℊ7200
1x Telescopic Sight (Poor) ẛ64 ℊ1920
Ammunition Guild Scrip Throne Gelt
2x Explosive Arrows ẛ160 ℊ4800
Armor Guild Scrip Throne Gelt
2x Heavy Leathers ẛ40 ℊ1200
2x Chainmail Suit ẛ40 ℊ1200
1x Carapace Helm ẛ320 ℊ9600
Gear Guild Scrip Throne Gelt
1x Photo-visor ẛ160 ℊ4800
1x Respirator (Poor) ẛ64 ℊ1920
1x Survival Suit ẛ80 ℊ2400
Drugs Guild Scrip Throne Gelt
2x Iho-Sticks ẛ40 ℊ1200
1x Ration Pack ẛ20 ℊ600
4x Tranq ẛ10 ℊ300
Tools Guild Scrip Throne Gelt
1x Combi-tool ẛ320 ℊ9600
1x Grapnel and Line ẛ40 ℊ1200
1x Pict Recorder (Good) ẛ96 ℊ2880
Currency Guild Scrip Throne Gelt
Balance ẛ781 ℊ1560
Selling table
Rarity Guild Scrip Throne Gelt
Ubiquitous ẛ0 ℊ0
Abundant ẛ5 ℊ60
Plentiful ẛ10 ℊ120
Common ẛ20 ℊ240
Average ẛ40 ℊ480
Scarce ẛ80 ℊ960
Rare ẛ160 ℊ1920
Very Rare ẛ320 ℊ3840
Extremely Rare ẛ640 ℊ7680
Near Unique ẛ1280 ℊ15360
Unique ẛ2560 ℊ30720
```
## Advanced Usage
The ```-s``` or ```--speciality``` flag can be used to specify a comma seperated list of types of items that should be more available.
For example you could create an Adaeptus Mechanicus vendor:
```python gen.py 60 "Throne Gelt" --speciality "Cybernetics"```
Or an arms dealer:
```python gen.py 50 "Throne Gelt" --speciality "Ranged Weapons,Melee Weapons"```
The possible categories are:
* Ranged Weapons
* Melee Weapons
* Explosives
* Weapon Mods
* Ammunition
* Armor
* Force Fields
* Gear
* Drugs
* Tools
* Cybernetics
# How it works
## Item costs
Items costs are calculated to by ```2 ^ rarity```. Thus, a common item is twice as expensive as a ubiquitous one.
## Seeding
The RNG is seeded based on the name and merchant power. Thus, if the same name and power is given the results will be deterministic. This can be handy if you want persistant shops.
## Quality
It will generate items of the 4 qualities, with percentages as follows:
Quality | Percentage
------- | ----------
Poor | 10%
Common | 75%
Good | 10%
Best | 5%
## Stacks
It will sometimes generate more that one of an item. To be honesy, I don't entirely remember what maths I used for this, but I think in general the lower the rarity of the item the higher chance to get multiples in a stack.
<file_sep>/gen.py
#!/bin/python3
from enum import IntEnum
import random
import math
names = [
"Eugenio",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"Alberich",
"<NAME>",
"<NAME>",
"Webbe",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"Matfei",
"<NAME>",
"Jordan",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"Monica",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"Bertradis",
"Ingvill",
"<NAME>",
"<NAME>",
"Yalena",
"<NAME>",
]
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
class Rarity(IntEnum):
UB = 0
AB = 1
PL = 2
CM = 3
AV = 4
SC = 5
RA = 6
VR = 7
ER = 8
NU = 9
UN = 10
def __str__(self):
names = [
"Ubiquitous",
"Abundant",
"Plentiful",
"Common",
"Average",
"Scarce",
"Rare",
"Very Rare",
"Extremely Rare",
"Near Unique",
"Unique",
]
return names[self.value]
class Quality(IntEnum):
P = 0
C = 1
G = 2
B = 3
def __str__(self):
names = [
"Poor",
"Common",
"Good",
"Best",
]
return names[self.value]
def mod(self):
values = [0.8, 1, 1.2, 1.5]
return values[self.value]
class item:
def __init__(self, name, rarity):
self.name = name
self.rar = rarity
self.qual = Quality.C
def set_category(self, cat):
self.cat = cat
def __str__(self):
return self.name
class ItemStack:
def __init__(self, item, amount):
self.item = item
self.amount = amount
self.qual = Quality.C
if self.amount == 1:
rnd = random.randint(0, 100)
if rnd < 10:
self.qual = Quality.P
elif rnd < 85:
self.qual = Quality.C
elif rnd < 95:
self.qual = Quality.G
else:
self.qual = Quality.B
def __str__(self):
main = (str(self.amount) + "x").ljust(4) + str(self.item)
if self.qual != Quality.C:
main += " (" + str(self.qual) + ")"
return main
ranged_weapons = [
item("Bolt Pistol", Rarity.VR),
item("Boltgun", Rarity.VR),
item("Heavy Bolter", Rarity.VR),
item("Storm Bolter", Rarity.ER),
item("Combi-flamer", Rarity.ER),
item("Combi-grav", Rarity.NU),
item("Combi-melta", Rarity.ER),
item("Combi-plasma", Rarity.ER),
item("Hand Flamer", Rarity.RA),
item("Flamer", Rarity.SC),
item("Heavy Flamer", Rarity.RA),
item("Laspistol", Rarity.CM),
item("Lasgun", Rarity.CM),
item("Laslock", Rarity.PL),
item("Long Las", Rarity.SC),
item("Hot-shot Laspistol", Rarity.RA),
item("Hot-shot Lasgun", Rarity.RA),
item("Grenade Launcher", Rarity.AV),
item("Missile Launcher", Rarity.RA),
item("Bolas", Rarity.AV),
item("Bow", Rarity.CM),
item("Crossbow", Rarity.CM),
item("Inferno Pistol", Rarity.NU),
item("Meltagun", Rarity.VR),
item("Plasma Pistol", Rarity.VR),
item("Plasma Gun", Rarity.VR),
item("Autopistol", Rarity.AV),
item("Autogun", Rarity.AV),
item("Autocannon", Rarity.VR),
item("Hand Cannon", Rarity.SC),
item("Heavy Stubber", Rarity.RA),
item("Shotgun", Rarity.AV),
item("Combat Shotgun", Rarity.SC),
item("Sniper Rifle", Rarity.SC),
item("Stub Automatic", Rarity.AV),
item("Stub Revolver", Rarity.PL),
item("Grav Pistol", Rarity.NU),
item("Graviton Gun", Rarity.ER),
item("Needle Pistol", Rarity.VR),
item("Needle Rifle", Rarity.VR),
item("Web Pistol", Rarity.VR),
item("Webber", Rarity.RA),
]
melee_weapons = [
item("Chainaxe", Rarity.SC),
item("Chainblade", Rarity.SC),
item("Chainsword", Rarity.AV),
item("Eviscerator", Rarity.VR),
item("Force Sword", Rarity.NU),
item("Force Staff", Rarity.ER),
item("Great Weapon", Rarity.SC),
item("Hunting Lance", Rarity.SC),
item("Knife", Rarity.PL),
item("Shield", Rarity.CM),
item("Spear", Rarity.CM),
item("Staff", Rarity.PL),
item("Sword", Rarity.CM),
item("Truncheon", Rarity.PL),
item("Warhammer", Rarity.SC),
item("Whip", Rarity.AV),
item("Omnissian Axe", Rarity.ER),
item("Power Fist", Rarity.VR),
item("Power Sword", Rarity.VR),
item("Power Axe", Rarity.VR),
item("Power Maul", Rarity.VR),
item("Shock Maul", Rarity.SC),
item("Shock Whip", Rarity.RA),
]
explosives = [
item("Blind Grenade", Rarity.SC),
item("Choke Grenade", Rarity.SC),
item("Frag Grenade", Rarity.CM),
item("Hallucinogen Grenade",Rarity.SC),
item("Haywire Grenade", Rarity.VR),
item("Krak Grenade", Rarity.RA),
item("Flash Grenade", Rarity.RA),
item("Smoke Grenade", Rarity.CM),
item("Stun Grenade", Rarity.CM),
item("Web Grenade", Rarity.RA),
item("Frag Missile", Rarity.AV),
item("Krak Missile", Rarity.SC),
item("Fire Bomb", Rarity.PL),
item("Melta Bomb", Rarity.VR),
]
weapon_mods = [
item("Aux GL", Rarity.RA),
item("Backpack Ammo Supply",Rarity.SC),
item("Compact", Rarity.AV),
item("Custom Grip", Rarity.RA),
item("Deactivated Safety", Rarity.RA),
item("Expanded Magazine", Rarity.SC),
item("Exterminator", Rarity.CM),
item("Fire Selector", Rarity.RA),
item("Fluid Action", Rarity.RA),
item("Forearm Mount", Rarity.SC),
item("Melee Attachment", Rarity.PL),
item("Modified Stock", Rarity.SC),
item("Mono", Rarity.SC),
item("Motion Predictor", Rarity.VR),
item("Omni Scope", Rarity.NU),
item("Photo Sight", Rarity.VR),
item("Pistol Grip", Rarity.RA),
item("Preysense Sight", Rarity.VR),
item("Quick-Release", Rarity.RA),
item("Laser Sight", Rarity.SC),
item("Reinforced", Rarity.SC),
item("Sacred Inscriptions", Rarity.SC),
item("Silencer", Rarity.PL),
item("Suspensors", Rarity.ER),
item("Targeter", Rarity.RA),
item("Telescopic Sight", Rarity.AV),
item("Tox Dispensor", Rarity.RA),
item("Tripod/Bipod", Rarity.AV),
item("Vox-Operated", Rarity.RA),
]
ammunition = [
item("Amputator Shells", Rarity.ER),
item("Bleeder Rounds", Rarity.RA),
item("Dumdum Bullets", Rarity.SC),
item("Expander Rounds", Rarity.SC),
item("Explosive Arrows", Rarity.SC),
item("Hot-Shot Charge Pack",Rarity.SC),
item("Inferno Shells", Rarity.RA),
item("Man-Stopper Bullets", Rarity.SC),
item("Scrambler Rounds", Rarity.RA),
item("Tempest Bolt Shells", Rarity.NU),
item("Tox Rounds", Rarity.SC),
]
armor = [
item("Heavy Leathers", Rarity.CM),
item("Imperial Robes", Rarity.AV),
item("Armored Bodyglove", Rarity.RA),
item("Chainmail Suit", Rarity.CM),
item("Feudal World Plate", Rarity.SC),
item("Xenos Hide Vest", Rarity.VR),
item("Flak Hemet", Rarity.AV),
item("Flak Gauntlets", Rarity.AV),
item("Light Flak Cloak", Rarity.SC),
item("Flak Vest", Rarity.AV),
item("Flak Cloak", Rarity.SC),
item("Flak Coat", Rarity.AV),
item("IG Flak Armor", Rarity.SC),
item("Mesh Vest", Rarity.RA),
item("Mesh Cloak", Rarity.VR),
item("Carapace Helm", Rarity.RA),
item("Carapace Gauntlets", Rarity.RA),
item("Carapace Greaves", Rarity.RA),
item("Enf. Light Carapace", Rarity.RA),
item("Carapace Chestplate", Rarity.RA),
item("M.T. Carapace", Rarity.VR),
item("Light Power Armor", Rarity.VR),
]
force_fields = [
item("Refractor Field", Rarity.VR),
item("Conversion Field", Rarity.ER),
item("Displacer Field", Rarity.NU),
item("Power Field", Rarity.NU),
item("Vehicle Power Field", Rarity.VR),
]
gear = [
item("Backpack", Rarity.AB),
item("Camo Cloak", Rarity.RA),
item("Chrono", Rarity.PL),
item("Clothing", Rarity.AB),
item("Combat Vest", Rarity.SC),
item("Concealed Holster", Rarity.AV),
item("Deadspace Earpiece", Rarity.VR),
item("Explosive Collar", Rarity.SC),
item("Filtration Plugs", Rarity.CM),
item("Photo-visor", Rarity.SC),
item("Preysense Goggles", Rarity.VR),
item("Rebreather", Rarity.SC),
item("Recoil Glove", Rarity.RA),
item("Respirator", Rarity.AV),
item("Survival Suit", Rarity.AV),
item("Synskin", Rarity.VR),
item("Void Suit", Rarity.SC),
]
drugs = [
item("Amasec", Rarity.AV),
item("Desoleum Fungus", Rarity.SC),
item("De-Tox", Rarity.RA),
item("Frenzon", Rarity.VR),
item("Iho-Sticks", Rarity.CM),
item("Obscura", Rarity.RA),
item("Ration Pack", Rarity.PL),
item("Recaf", Rarity.AB),
item("Sacred Unguents", Rarity.VR),
item("Slaught", Rarity.SC),
item("Spook", Rarity.RA),
item("Stimm", Rarity.AV),
item("Tranq", Rarity.AB),
]
tools = [
item("Auspex", Rarity.SC),
item("Auto Quill", Rarity.SC),
item("Clip/Drop Harness", Rarity.CM),
item("Combi-tool", Rarity.RA),
item("Comm Leech", Rarity.VR),
item("Dataslate", Rarity.CM),
item("Demolitions Kit", Rarity.VR),
item("Diagnosticator", Rarity.RA),
item("Disguise Kit", Rarity.VR),
item("Excruciator Kit", Rarity.VR),
item("Field Suture", Rarity.AV),
item("Glow Globe", Rarity.AB),
item("Stablight", Rarity.AB),
item("Grapnel and Line", Rarity.CM),
item("Grav Chute", Rarity.RA),
item("Hand-Held Targeter", Rarity.SC),
item("Inhaler / Injector", Rarity.CM),
item("Lascutter", Rarity.AV),
item("Loud Hailer", Rarity.SC),
item("Magboots", Rarity.RA),
item("Magnoculars", Rarity.AV),
item("Manacles", Rarity.PL),
item("Medi-kit", Rarity.CM),
item("Micro-bead", Rarity.AV),
item("Monotask Servo-Skull",Rarity.RA),
item("Multicompass", Rarity.NU),
item("Multikey", Rarity.SC),
item("Null Rod", Rarity.NU),
item("Pict Recorder", Rarity.AV),
item("Psy Focus", Rarity.AV),
item("Regicide Set", Rarity.PL),
item("Screamer", Rarity.SC),
item("Signal Jammer", Rarity.RA),
item("Static Generator", Rarity.VR),
item("Stummer", Rarity.AV),
item("Vox-caster", Rarity.SC),
item("Writing Kit", Rarity.PL),
]
cybernetics = [
item("Augur Array", Rarity.RA),
item("Autosanguine", Rarity.VR),
item("Baleful Eye", Rarity.NU),
item("Bionic Arm", Rarity.SC),
item("Bionic Legs", Rarity.SC),
item("Bionic Lungs", Rarity.RA),
item("Bionic Heart", Rarity.VR),
item("Bionic Senses", Rarity.RA),
item("Calculus Implant", Rarity.VR),
item("Cerebral Implant", Rarity.VR),
item("Cranial Armor", Rarity.SC),
item("Ferric Lure Implant", Rarity.VR),
item("Interface Port", Rarity.RA),
item("Internal Reservoir", Rarity.RA),
item("Locator Matrix", Rarity.RA),
item("Luminen Capacitor", Rarity.VR),
item("Maglev Coils", Rarity.VR),
item("Mechadendrite", Rarity.VR),
item("Memorance Implant", Rarity.RA),
item("Mind Impulse Unit", Rarity.RA),
item("MIU Weapon Interface",Rarity.RA),
item("Respiratory Filter", Rarity.RA),
item("Scribe-tines", Rarity.RA),
item("Subskin Armor", Rarity.VR),
item("Synthmuscle", Rarity.RA),
item("Vocal Implant", Rarity.SC),
item("Volitor Implant", Rarity.RA),
]
class Category:
def __init__(self, name, items, bias):
self.name = name
self.items = items
self.bias = bias
def __str__(self):
return self.name
categories = [
Category("Ranged Weapons", ranged_weapons, 0),
Category("Melee Weapons", melee_weapons, 0),
Category("Explosives", explosives, 0),
Category("Weapon Mods", weapon_mods, -10),
Category("Ammunition", ammunition, 0),
Category("Armor", armor, 0),
Category("Force Fields", force_fields, 0),
Category("Gear", gear, 0),
Category("Drugs", drugs, 0),
Category("Tools", tools, 0),
Category("Cybernetics", cybernetics, -10),
]
for category in categories:
for thing in category.items:
thing.set_category(category)
class currency:
def __init__(self, name, symbol, func):
self.name = name
self.symbol = symbol
self.exchange = func
throne_gelt = currency("Throne Gelt", "ℊ", lambda x:x*100)
guild_scrip = currency("Guild Scrip", "ẛ", lambda x:x*5)
currencies = [
throne_gelt,
guild_scrip,
]
def buy(item, curr):
return math.ceil(curr.exchange(2 ** item.rar))
def sell(item, curr):
if item.rar == Rarity.UB:
return 0
return math.floor(curr.exchange(2 ** (item.rar - 1)))
def print_buy_price(stack, curr):
line = str(stack).ljust(32)
line += local_currency.symbol + str(int(buy(stack.item, local_currency) * stack.qual.mod())).ljust(14)
#throne gelt is ubiquitous, if expensive
if local_currency != throne_gelt:
line += throne_gelt.symbol + str(int(buy(stack.item, throne_gelt) * 1.5 * stack.qual.mod()))
print(line)
def print_sell_price(item, curr):
line = str(item).ljust(32)
line += local_currency.symbol + str(sell(item, local_currency)).ljust(14)
#throne gelt is ubiquitous, if expensive
if local_currency != throne_gelt:
line += throne_gelt.symbol + str(int(sell(item, throne_gelt) * 0.6))
print(line)
def print_heading(heading):
print(color.BOLD, end="")
print(heading.ljust(31), local_currency.name.ljust(14), end=" ")
if local_currency != throne_gelt:
print(throne_gelt.name, end = "")
print(color.END)
def roll_item(power, item, category, bonus):
rel_power = power - item.rar ** 2 + bonus + category.bias
roll = random.randint(0, 100)
if roll < rel_power and rel_power - roll < 20:
amount = math.ceil(-1 * (roll - rel_power) / 6 / (item.rar / 2))
else:
amount = 0
return amount
def generate_items(power, seed, specialities):
random.seed(seed)
stock = []
for category in categories:
if category.name.lower() in map(lambda x:x.lower(), specialities):
bonus = 10
elif specialities == ['']:
bonus = 0
else:
bonus = -20
for item in category.items:
amount = roll_item(power, item, category, bonus)
if amount > 0:
stock.append(ItemStack(item, amount))
return stock
def print_buying_table(stock):
stock = sorted(stock, key=lambda x:str(x.item.cat))
for category in categories:
substock = list(filter(lambda x:x.item.cat == category, stock))
if substock != []:
print_heading(str(category))
for stack in substock:
print_buy_price(stack, local_currency)
print()
def generate_fiat(power, seed):
random.seed(seed)
print()
print_heading("Currency")
print("Balance".ljust(32), end="")
example = item("", random.randrange(80, 120) / 100 * power / 7)
print(local_currency.symbol + str(buy(example, local_currency)).ljust(14), end="")
if local_currency != throne_gelt:
print(throne_gelt.symbol + str(int(buy(example, throne_gelt) * 0.1)), end="")
print()
def print_selling_table():
print("\n" + color.BOLD + "Selling table" + color.END)
print()
print_heading("Rarity")
for rarity in Rarity:
example = item(str(rarity), rarity)
print_sell_price(example, local_currency)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("merchant_power",
help="The relative importance of the merchant, from 0 to 100",
type=int,
)
parser.add_argument("local_currency",
help="The currency used by the merchant",
)
parser.add_argument("-n",
"--name",
help="The name of the merchant",
default="",
)
parser.add_argument("-s",
"--speciality",
help="The specialities of the merchant, separated by commas",
default="",
)
args = parser.parse_args()
try:
local_currency = [x for x in currencies if x.name == args.local_currency][0]
except ValueError:
print("Invalid local currency")
exit(1)
name = random.choice(names)
if args.name != "":
name = args.name
print(color.BOLD + name, "Rating", args.merchant_power, color.END)
seed = args.merchant_power
for char in name:
seed += ord(char)
print()
specialities = args.speciality.split(",")
specialities = list(map(lambda x:x.lstrip().rstrip(), specialities))
stock = generate_items(args.merchant_power, seed, specialities)
print_buying_table(stock)
generate_fiat(args.merchant_power, seed)
print_selling_table()
| 473e8d04ea4cd6d752ab3559dbc47e423e3586c0 | [
"Markdown",
"Python"
] | 2 | Markdown | RcColes/DH-shopgen | eba3dd1ecd0d5be592a06eb7df3dffe2c3452d9d | 3d024662a4586db2dc528eb2f4b8141ee68527e4 |
refs/heads/main | <repo_name>ThomasTW935/FrontEndMentor--interactive-pricing-component<file_sep>/script.js
let priceRange = [
{ views: '10K', cost: 8.00 },
{ views: '50K', cost: 12.00 },
{ views: '100K', cost: 16.00 },
{ views: '500k', cost: 24.00 },
{ views: '1M', cost: 36.00 }
]
let views = document.querySelector('.priceComponent__views')
let cost = document.querySelector('.priceComponent__cost')
let inputRange = document.querySelector('.priceComponent__inputRange')
let initialValue = sessionStorage.index ?? 2
let discountToggle = document.querySelector('.priceComponent__toggle')
init()
function init() {
setInputRangeValue(initialValue)
inputRangeEvent()
}
function inputRangeEvent() {
inputRange.addEventListener('change', () => {
setInputRangeValue(inputRange.value)
})
}
function setInputRangeValue(index) {
cost.innerHTML = '$' + priceRange[index].cost + `.00`
views.innerHTML = priceRange[index].views
inputRange.value = index
setSessionStorage(index)
}
function setSessionStorage(value) {
sessionStorage.setItem('index', value)
}
| bcc40a6748aaca7f62f203ddcaf1e126b62e1444 | [
"JavaScript"
] | 1 | JavaScript | ThomasTW935/FrontEndMentor--interactive-pricing-component | aa9f5d60326e826b55746bbe6a7b0181505b070c | 0dc4c14080cd05dd58ebd6781972dad9f2ef41d7 |
refs/heads/master | <file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
namespace Developer_Test
{
public enum CarCategories
{
SmallCar,
Van,
Minibus
}
public class Database : DbContext
{
public DbSet<CarRentals> CarRentals { get; set; }
private string databaseName;
public Database(string databaseName)
{
this.databaseName = databaseName;
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=" + databaseName);
}
}
public class CarRentals
{
[Key]
public string BookingNumber { get; set; }
public DateTime CustomerBirth { get; set; }
public CarCategories CarCategory { get; set; }
public DateTime RentalDate { get; set; }
public int Milage { get; set; }
public DateTime? ReturnDate { get; set; }
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using Developer_Test;
using System;
namespace UnitTests
{
[TestClass]
public class ValidationTests
{
private Model model;
[TestInitialize]
public void TestInitialize()
{
model = new Model("Car_Rentals_Test.db");
model.SaveRental("A33", new DateTime(2000, 07, 19).ToString(), CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 19).ToString(), "80");
model.SaveRental("A43", new DateTime(2000, 07, 19).ToString(), CarCategories.Van.ToString(), new DateTime(2010, 07, 19).ToString(), "50");
model.SaveRental("A53", new DateTime(2000, 07, 19).ToString(), CarCategories.Minibus.ToString(), new DateTime(2010, 07, 19).ToString(), "50");
}
[TestCleanup]
public void CleanUp()
{
model.DropDatabase();
}
[TestMethod]
public void ValidateRentalData_OnlyValidData_Valid()
{
Assert.AreEqual(0, model.ValidateRentalData("A11", new DateTime(2000, 07, 19).ToString(),
CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 22).ToString(), "20"));
}
[TestMethod]
public void ValidateRentalData_EmptyBookingNumber_Invalid()
{
Assert.AreEqual(1, model.ValidateRentalData(string.Empty, new DateTime(2000, 07, 19).ToString(),
CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 22).ToString(), "20"));
}
[TestMethod]
public void ValidateRentalData_DuplicateBookingNumber_Invalid()
{
string duplicateBookingNumber = "A22";
model.SaveRental(duplicateBookingNumber, new DateTime(2000, 07, 19).ToString(), CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 19).ToString(), "80");
Assert.AreEqual(1, model.ValidateRentalData(duplicateBookingNumber, new DateTime(2000, 07, 19).ToString(),
CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 22).ToString(), "20"));
}
[TestMethod]
public void ValidateRentalData_BirthWrongFormat_Invalid()
{
Assert.AreEqual(2, model.ValidateRentalData("A11", "07/2000 00:00:00",
CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 22).ToString(), "20"));
}
[TestMethod]
public void ValidateRentalData_NonExistentCarCategory_Invalid()
{
Assert.AreEqual(3, model.ValidateRentalData("A11", new DateTime(2000, 07, 19).ToString(),
"Not a car", new DateTime(2010, 07, 22).ToString(), "20"));
}
[TestMethod]
public void ValidateRentalData_RentalDateWrongFormat_Invalid()
{
Assert.AreEqual(4, model.ValidateRentalData("A11", new DateTime(2000, 07, 19).ToString(),
CarCategories.SmallCar.ToString(), "22/07 00:00:00", "20"));
}
[TestMethod]
public void ValidateRentalData_MilageNotANumber_Invalid()
{
Assert.AreEqual(5, model.ValidateRentalData("A11", new DateTime(2000, 07, 19).ToString(),
CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 22).ToString(), "abc"));
}
[TestMethod]
public void ValidateRentalData_MilageBelowZero_Invalid()
{
Assert.AreEqual(5, model.ValidateRentalData("A11", new DateTime(2000, 07, 19).ToString(),
CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 22).ToString(), "-2"));
}
[TestMethod]
public void ValidateReturnData_OnlyValidData_Valid()
{
Assert.AreEqual(0, model.ValidateReturnData("A33", "100", new DateTime(2010, 07, 22).ToString()));
}
[TestMethod]
public void ValidateReturnData_NotExistentRental_Invalid()
{
Assert.AreEqual(1, model.ValidateReturnData("A32", "100", new DateTime(2010, 07, 22).ToString()));
}
[TestMethod]
public void ValidateReturnData_RentalAlreadyReturned_Invalid()
{
model.SaveReturnDate("A33", new DateTime(2010, 07, 22).ToString());
Assert.AreEqual(1, model.ValidateReturnData("A33", "100", new DateTime(2010, 07, 22).ToString()));
}
[TestMethod]
public void ValidateReturnData_ReturnMilageNotANumber_Invalid()
{
Assert.AreEqual(2, model.ValidateReturnData("A33", "abc", new DateTime(2010, 07, 22).ToString()));
}
[TestMethod]
public void ValidateReturnData_ReturnMilageBelowRentalMilage_Invalid()
{
Assert.AreEqual(2, model.ValidateReturnData("A33", "70", new DateTime(2010, 07, 22).ToString()));
}
[TestMethod]
public void ValidateReturnData_ReturnDateWrongFormat_Invalid()
{
Assert.AreEqual(3, model.ValidateReturnData("A33", "100", "222010 00:00:00"));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace Developer_Test
{
public class Model
{
public Database database;
private const int baseDayRental = 100, kmPrice = 10;
public Model(string databaseName = "Car_Rentals.db")
{
database = new Database(databaseName);
}
public double CalculatePrice(string bookingNumber, string returnDate, string returnMilage)
{
var rental = database.CarRentals.Where(x => x.BookingNumber == bookingNumber).First();
CarCategories car = rental.CarCategory;
DateTime returnDateConverted;
DateTime.TryParse(returnDate, out returnDateConverted);
int returnMilageConverted;
Int32.TryParse(returnMilage, out returnMilageConverted);
int numberOfDays = (int)Math.Ceiling((returnDateConverted - rental.RentalDate).TotalDays);
int numberOfKm = returnMilageConverted - rental.Milage;
double price = 0;
switch (car)
{
case CarCategories.SmallCar:
price = baseDayRental * numberOfDays;
break;
case CarCategories.Van:
price = baseDayRental * numberOfDays * 1.2 + kmPrice * numberOfKm;
break;
case CarCategories.Minibus:
price = baseDayRental * numberOfDays * 1.7 + (kmPrice * numberOfKm * 1.5);
break;
}
return price;
}
public int ValidateRentalData(string bookingNumber, string customerBirth, string car, string rentalDate, string milage)
{
if (string.IsNullOrEmpty(bookingNumber) || database.CarRentals.Any(x => x.BookingNumber == bookingNumber))
{
return 1;
}
DateTime date;
if (!DateTime.TryParse(customerBirth, out date))
{
return 2;
}
if (!Enum.IsDefined(typeof(CarCategories), car))
{
return 3;
}
if (!DateTime.TryParse(rentalDate, out date))
{
return 4;
}
if (!(Int32.TryParse(milage, out int milageConverted) && milageConverted >= 0))
{
return 5;
}
return 0;
}
public int ValidateReturnData(string bookingNumber, string returnMilage, string returnDate)
{
var rental = database.CarRentals.Where(x => x.BookingNumber == bookingNumber).FirstOrDefault();
if (!(database.CarRentals.Any(x => x.BookingNumber == bookingNumber) && rental.ReturnDate == null))
{
return 1;
}
if (!(Int32.TryParse(returnMilage, out int returnMilageConverted) && returnMilageConverted >= rental.Milage))
{
return 2;
}
if (!DateTime.TryParse(returnDate, out DateTime date))
{
return 3;
}
return 0;
}
public void SaveRental(string bookingNumber, string customerBirth, string car, string rentalDate, string milage)
{
DateTime customerBirthConverted;
DateTime.TryParse(customerBirth, out customerBirthConverted);
CarCategories carCategoryConverted;
Enum.TryParse(car, out carCategoryConverted);
DateTime rentalDateConverted;
DateTime.TryParse(rentalDate, out rentalDateConverted);
int milageConverted;
Int32.TryParse(milage, out milageConverted);
var rental = new CarRentals
{
BookingNumber = bookingNumber,
CustomerBirth = customerBirthConverted,
CarCategory = carCategoryConverted,
RentalDate = rentalDateConverted,
Milage = milageConverted,
ReturnDate = null
};
database.CarRentals.Add(rental);
database.SaveChanges();
}
public void SaveReturnDate(string bookingNumber, string returnDate)
{
DateTime returnDateConverted;
DateTime.TryParse(returnDate, out returnDateConverted);
database.CarRentals.Where(x => x.BookingNumber == bookingNumber).First().ReturnDate = returnDateConverted;
database.SaveChanges();
}
public List<CarRentals> GetAllRentals()
{
return database.CarRentals.OrderByDescending(x => x.RentalDate).ToList();
}
public object[] GetBookingNumberForActiveRentalsAsArray()
{
return database.CarRentals.Where(x => x.ReturnDate == null).Select(x => x.BookingNumber).ToArray();
}
public void DropDatabase()
{
// Only used for testing
database.Database.EnsureDeleted();
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using Developer_Test;
using System.Linq;
using System;
namespace UnitTests
{
[TestClass]
public class DatabaseTests
{
private Model model;
[TestInitialize]
public void TestInitialize()
{
model = new Model("Car_Rentals_Test.db");
model.SaveRental("A33", new DateTime(2000, 07, 19).ToString(), CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 19).ToString(), "80");
}
[TestCleanup]
public void CleanUp()
{
model.DropDatabase();
}
[TestMethod]
public void SaveRental_InsertRentalToDatabase_InDatabase()
{
model.SaveRental("A73", new DateTime(2000, 07, 19).ToString(), CarCategories.Van.ToString(), new DateTime(2010, 07, 19).ToString(), "54");
var savedRental = model.database.CarRentals.Where(x => x.BookingNumber == "A73").FirstOrDefault();
Assert.AreNotEqual(null, savedRental, "Rental not saved");
Assert.AreEqual(CarCategories.Van, savedRental.CarCategory, "Wrong car category");
Assert.AreEqual(54, savedRental.Milage, "Wrong milage");
}
[TestMethod]
public void SaveReturnDate_UpdateReturnTime_InDatabase()
{
model.SaveReturnDate("A33", new DateTime(2010, 07, 21).ToString());
var updatedRental = model.database.CarRentals.Where(x => x.BookingNumber == "A33").First();
Assert.AreEqual(new DateTime(2010, 07, 21).ToString(), updatedRental.ReturnDate.ToString());
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using Developer_Test;
using System;
namespace UnitTests
{
[TestClass]
public class PriceTests
{
// BaseDayRental = 100, kmPrice = 10
private Model model;
[TestInitialize]
public void TestInitialize()
{
model = new Model("Car_Rentals_Test.db");
model.SaveRental("A33", new DateTime(2000, 07, 19).ToString(), CarCategories.SmallCar.ToString(), new DateTime(2010, 07, 19).ToString(), "80");
model.SaveRental("A43", new DateTime(2000, 07, 19).ToString(), CarCategories.Van.ToString(), new DateTime(2010, 07, 19).ToString(), "50");
model.SaveRental("A53", new DateTime(2000, 07, 19).ToString(), CarCategories.Minibus.ToString(), new DateTime(2010, 07, 19).ToString(), "50");
}
[TestCleanup]
public void CleanUp()
{
model.DropDatabase();
}
[TestMethod]
public void CalculatePrice_SmallCarPrice_CorrectPrice()
{
// price = baseDayRental * numberOfDays
Assert.AreEqual(300, model.CalculatePrice("A33", new DateTime(2010, 07, 22).ToString(), "100"));
}
[TestMethod]
public void CalculatePrice_VanPrice_CorrectPrice()
{
// price = baseDayRental * numberOfDays * 1.2 + kmPrice * numberOfKm
Assert.AreEqual(460, model.CalculatePrice("A43", new DateTime(2010, 07, 22).ToString(), "60"));
}
[TestMethod]
public void CalculatePrice_MinibusPrice_CorrectPrice()
{
// price = baseDayRental * numberOfDays * 1.7 + (kmPrice * numberOfKm * 1.5)
Assert.AreEqual(810, model.CalculatePrice("A53", new DateTime(2010, 07, 22).ToString(), "70"));
}
}
}
<file_sep>using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Developer_Test
{
class GUI : Form
{
private Panel mainPanel;
private Button ReturnRentalButton;
private Panel rentalPanel;
private TextBox BookingNumberInput;
private Button newRentalButton;
private DataGridView rentalLog;
private Label label1;
private ComboBox CarCategoryInput;
private TextBox CustomerBirthDateInput;
private TextBox MilageInput;
private TextBox RentalDateInput;
private Label label7;
private Label label6;
private Label label5;
private Label label4;
private Label label3;
private Label label2;
private Button RentalBackButton;
private Button RentalConfirmButton;
private Panel returnPanel;
private Label priceLabel;
private Label label8;
private ComboBox ReturnBookingNumberInput;
private TextBox ReturnDateInput;
private Label label10;
private Label label9;
private Button ReturnBackButton;
private Button ReturnConfimButton;
private Label label11;
private TextBox ReturnMilageInput;
private Model model;
public static void Main()
{
new GUI();
}
public GUI()
{
model = new Model();
InitializeComponent();
this.CarCategoryInput.Items.AddRange(Enum.GetValues(typeof(CarCategories)).Cast<object>().ToArray());
BackToMain(null);
ShowDialog();
}
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
this.newRentalButton = new System.Windows.Forms.Button();
this.mainPanel = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.ReturnRentalButton = new System.Windows.Forms.Button();
this.rentalLog = new System.Windows.Forms.DataGridView();
this.rentalPanel = new System.Windows.Forms.Panel();
this.RentalBackButton = new System.Windows.Forms.Button();
this.RentalConfirmButton = new System.Windows.Forms.Button();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.CarCategoryInput = new System.Windows.Forms.ComboBox();
this.CustomerBirthDateInput = new System.Windows.Forms.TextBox();
this.MilageInput = new System.Windows.Forms.TextBox();
this.RentalDateInput = new System.Windows.Forms.TextBox();
this.BookingNumberInput = new System.Windows.Forms.TextBox();
this.returnPanel = new System.Windows.Forms.Panel();
this.ReturnBackButton = new System.Windows.Forms.Button();
this.ReturnConfimButton = new System.Windows.Forms.Button();
this.label11 = new System.Windows.Forms.Label();
this.ReturnMilageInput = new System.Windows.Forms.TextBox();
this.ReturnDateInput = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.priceLabel = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.ReturnBookingNumberInput = new System.Windows.Forms.ComboBox();
this.mainPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.rentalLog)).BeginInit();
this.rentalPanel.SuspendLayout();
this.returnPanel.SuspendLayout();
this.SuspendLayout();
//
// newRentalButton
//
this.newRentalButton.Location = new System.Drawing.Point(376, 388);
this.newRentalButton.Name = "newRentalButton";
this.newRentalButton.Size = new System.Drawing.Size(75, 23);
this.newRentalButton.TabIndex = 0;
this.newRentalButton.Text = "New Rental";
this.newRentalButton.UseVisualStyleBackColor = true;
this.newRentalButton.Click += new System.EventHandler(this.NewRentalButton_Click);
//
// mainPanel
//
this.mainPanel.Controls.Add(this.label1);
this.mainPanel.Controls.Add(this.ReturnRentalButton);
this.mainPanel.Controls.Add(this.newRentalButton);
this.mainPanel.Controls.Add(this.rentalLog);
this.mainPanel.Location = new System.Drawing.Point(57, 56);
this.mainPanel.Name = "mainPanel";
this.mainPanel.Size = new System.Drawing.Size(615, 424);
this.mainPanel.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(256, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 17);
this.label1.TabIndex = 3;
this.label1.Text = "Rentals";
//
// ReturnRentalButton
//
this.ReturnRentalButton.Location = new System.Drawing.Point(102, 388);
this.ReturnRentalButton.Name = "ReturnRentalButton";
this.ReturnRentalButton.Size = new System.Drawing.Size(80, 23);
this.ReturnRentalButton.TabIndex = 1;
this.ReturnRentalButton.Text = "Return rental";
this.ReturnRentalButton.UseVisualStyleBackColor = true;
this.ReturnRentalButton.Click += new System.EventHandler(this.ReturnRentalButton_Click);
//
// rentalLog
//
this.rentalLog.AllowUserToAddRows = false;
this.rentalLog.AllowUserToDeleteRows = false;
this.rentalLog.AllowUserToResizeRows = false;
this.rentalLog.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.rentalLog.DefaultCellStyle = dataGridViewCellStyle1;
this.rentalLog.Location = new System.Drawing.Point(0, 40);
this.rentalLog.MultiSelect = false;
this.rentalLog.Name = "rentalLog";
this.rentalLog.ReadOnly = true;
this.rentalLog.RowHeadersVisible = false;
this.rentalLog.RowTemplate.ReadOnly = true;
this.rentalLog.ShowCellToolTips = false;
this.rentalLog.ShowEditingIcon = false;
this.rentalLog.Size = new System.Drawing.Size(615, 328);
this.rentalLog.TabIndex = 2;
//
// rentalPanel
//
this.rentalPanel.Controls.Add(this.RentalBackButton);
this.rentalPanel.Controls.Add(this.RentalConfirmButton);
this.rentalPanel.Controls.Add(this.label7);
this.rentalPanel.Controls.Add(this.label6);
this.rentalPanel.Controls.Add(this.label5);
this.rentalPanel.Controls.Add(this.label4);
this.rentalPanel.Controls.Add(this.label3);
this.rentalPanel.Controls.Add(this.label2);
this.rentalPanel.Controls.Add(this.CarCategoryInput);
this.rentalPanel.Controls.Add(this.CustomerBirthDateInput);
this.rentalPanel.Controls.Add(this.MilageInput);
this.rentalPanel.Controls.Add(this.RentalDateInput);
this.rentalPanel.Controls.Add(this.BookingNumberInput);
this.rentalPanel.Location = new System.Drawing.Point(57, 56);
this.rentalPanel.Name = "rentalPanel";
this.rentalPanel.Size = new System.Drawing.Size(615, 424);
this.rentalPanel.TabIndex = 2;
this.rentalPanel.Visible = false;
//
// RentalBackButton
//
this.RentalBackButton.Location = new System.Drawing.Point(376, 388);
this.RentalBackButton.Name = "RentalBackButton";
this.RentalBackButton.Size = new System.Drawing.Size(75, 23);
this.RentalBackButton.TabIndex = 12;
this.RentalBackButton.Text = "Back";
this.RentalBackButton.UseVisualStyleBackColor = true;
this.RentalBackButton.Click += new System.EventHandler(this.RentalBackButton_Click);
//
// RentalConfirmButton
//
this.RentalConfirmButton.Location = new System.Drawing.Point(102, 388);
this.RentalConfirmButton.Name = "RentalConfirmButton";
this.RentalConfirmButton.Size = new System.Drawing.Size(75, 23);
this.RentalConfirmButton.TabIndex = 11;
this.RentalConfirmButton.Text = "Confirm";
this.RentalConfirmButton.UseVisualStyleBackColor = true;
this.RentalConfirmButton.Click += new System.EventHandler(this.RentalConfirmButton_Click);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(37, 184);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(62, 13);
this.label7.TabIndex = 10;
this.label7.Text = "Rental date";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(270, 184);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(75, 13);
this.label6.TabIndex = 9;
this.label6.Text = "Current Milage";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(449, 71);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(65, 13);
this.label5.TabIndex = 8;
this.label5.Text = "CarCategory";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(263, 71);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(110, 13);
this.label4.TabIndex = 7;
this.label4.Text = "Customer date of birth";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(37, 71);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(84, 13);
this.label3.TabIndex = 6;
this.label3.Text = "Booking number";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(256, 20);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 17);
this.label2.TabIndex = 5;
this.label2.Text = "New Rental";
//
// CarCategoryInput
//
this.CarCategoryInput.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.CarCategoryInput.FormattingEnabled = true;
this.CarCategoryInput.Location = new System.Drawing.Point(452, 88);
this.CarCategoryInput.Name = "CarCategoryInput";
this.CarCategoryInput.Size = new System.Drawing.Size(121, 21);
this.CarCategoryInput.TabIndex = 4;
//
// CustomerBirthDateInput
//
this.CustomerBirthDateInput.Location = new System.Drawing.Point(266, 88);
this.CustomerBirthDateInput.Name = "CustomerBirthDateInput";
this.CustomerBirthDateInput.Size = new System.Drawing.Size(124, 20);
this.CustomerBirthDateInput.TabIndex = 3;
//
// MilageInput
//
this.MilageInput.Location = new System.Drawing.Point(273, 200);
this.MilageInput.Name = "MilageInput";
this.MilageInput.Size = new System.Drawing.Size(117, 20);
this.MilageInput.TabIndex = 2;
//
// RentalDateInput
//
this.RentalDateInput.Location = new System.Drawing.Point(40, 200);
this.RentalDateInput.Name = "RentalDateInput";
this.RentalDateInput.Size = new System.Drawing.Size(124, 20);
this.RentalDateInput.TabIndex = 1;
//
// BookingNumberInput
//
this.BookingNumberInput.Location = new System.Drawing.Point(40, 88);
this.BookingNumberInput.Name = "BookingNumberInput";
this.BookingNumberInput.Size = new System.Drawing.Size(124, 20);
this.BookingNumberInput.TabIndex = 0;
//
// returnPanel
//
this.returnPanel.Controls.Add(this.ReturnBackButton);
this.returnPanel.Controls.Add(this.ReturnConfimButton);
this.returnPanel.Controls.Add(this.label11);
this.returnPanel.Controls.Add(this.ReturnMilageInput);
this.returnPanel.Controls.Add(this.ReturnDateInput);
this.returnPanel.Controls.Add(this.label10);
this.returnPanel.Controls.Add(this.label9);
this.returnPanel.Controls.Add(this.priceLabel);
this.returnPanel.Controls.Add(this.label8);
this.returnPanel.Controls.Add(this.ReturnBookingNumberInput);
this.returnPanel.Location = new System.Drawing.Point(57, 56);
this.returnPanel.Name = "returnPanel";
this.returnPanel.Size = new System.Drawing.Size(615, 424);
this.returnPanel.TabIndex = 13;
this.returnPanel.Visible = false;
//
// ReturnBackButton
//
this.ReturnBackButton.Location = new System.Drawing.Point(376, 388);
this.ReturnBackButton.Name = "ReturnBackButton";
this.ReturnBackButton.Size = new System.Drawing.Size(75, 23);
this.ReturnBackButton.TabIndex = 14;
this.ReturnBackButton.Text = "Back";
this.ReturnBackButton.UseVisualStyleBackColor = true;
this.ReturnBackButton.Click += new System.EventHandler(this.ReturnBackButton_Click);
//
// ReturnConfimButton
//
this.ReturnConfimButton.Location = new System.Drawing.Point(102, 388);
this.ReturnConfimButton.Name = "ReturnConfimButton";
this.ReturnConfimButton.Size = new System.Drawing.Size(92, 23);
this.ReturnConfimButton.TabIndex = 13;
this.ReturnConfimButton.Text = "Confirm return";
this.ReturnConfimButton.UseVisualStyleBackColor = true;
this.ReturnConfimButton.Click += new System.EventHandler(this.ReturnConfimButton_Click);
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(229, 91);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(83, 13);
this.label11.TabIndex = 12;
this.label11.Text = "Milage on return";
//
// ReturnMilageInput
//
this.ReturnMilageInput.Location = new System.Drawing.Point(229, 110);
this.ReturnMilageInput.Name = "ReturnMilageInput";
this.ReturnMilageInput.Size = new System.Drawing.Size(100, 20);
this.ReturnMilageInput.TabIndex = 11;
//
// ReturnDateInput
//
this.ReturnDateInput.Location = new System.Drawing.Point(376, 114);
this.ReturnDateInput.Name = "ReturnDateInput";
this.ReturnDateInput.Size = new System.Drawing.Size(138, 20);
this.ReturnDateInput.TabIndex = 10;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(373, 88);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(63, 13);
this.label10.TabIndex = 9;
this.label10.Text = "Return date";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(40, 91);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(84, 13);
this.label9.TabIndex = 8;
this.label9.Text = "Booking number";
//
// priceLabel
//
this.priceLabel.AutoSize = true;
this.priceLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.priceLabel.Location = new System.Drawing.Point(256, 238);
this.priceLabel.Name = "priceLabel";
this.priceLabel.Size = new System.Drawing.Size(0, 16);
this.priceLabel.TabIndex = 7;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.Location = new System.Drawing.Point(270, 25);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(89, 16);
this.label8.TabIndex = 6;
this.label8.Text = "Return Rental";
//
// ReturnBookingNumberInput
//
this.ReturnBookingNumberInput.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ReturnBookingNumberInput.FormattingEnabled = true;
this.ReturnBookingNumberInput.Location = new System.Drawing.Point(43, 114);
this.ReturnBookingNumberInput.Name = "ReturnBookingNumberInput";
this.ReturnBookingNumberInput.Size = new System.Drawing.Size(121, 21);
this.ReturnBookingNumberInput.TabIndex = 5;
this.ReturnBookingNumberInput.SelectedIndexChanged += new System.EventHandler(this.ReturnBookingNumberInput_SelectedIndexChanged);
//
// GUI
//
this.ClientSize = new System.Drawing.Size(746, 528);
this.Controls.Add(this.rentalPanel);
this.Controls.Add(this.mainPanel);
this.Controls.Add(this.returnPanel);
this.Name = "GUI";
this.mainPanel.ResumeLayout(false);
this.mainPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.rentalLog)).EndInit();
this.rentalPanel.ResumeLayout(false);
this.rentalPanel.PerformLayout();
this.returnPanel.ResumeLayout(false);
this.returnPanel.PerformLayout();
this.ResumeLayout(false);
}
private void BackToMain(Panel currentPanel)
{
if (currentPanel != null)
currentPanel.Visible = false;
this.mainPanel.Visible = true;
this.rentalLog.DataSource = model.GetAllRentals();
}
private void NewRentalButton_Click(object sender, EventArgs e)
{
ResetRentalInputs();
this.mainPanel.Visible = false;
this.rentalPanel.Visible = true;
}
private void ReturnRentalButton_Click(object sender, EventArgs e)
{
ResetReturnInputs();
mainPanel.Visible = false;
returnPanel.Visible = true;
}
private void RentalConfirmButton_Click(object sender, EventArgs e)
{
int validationError = model.ValidateRentalData(BookingNumberInput.Text, CustomerBirthDateInput.Text,
CarCategoryInput.Text, RentalDateInput.Text, MilageInput.Text);
this.BookingNumberInput.BackColor = Color.White;
this.CustomerBirthDateInput.BackColor = Color.White;
this.RentalDateInput.BackColor = Color.White;
this.MilageInput.BackColor = Color.White;
switch (validationError)
{
case 0:
model.SaveRental(BookingNumberInput.Text, CustomerBirthDateInput.Text,
CarCategoryInput.Text, RentalDateInput.Text, MilageInput.Text);
BackToMain(rentalPanel);
break;
case 1:
this.BookingNumberInput.Focus();
this.BookingNumberInput.BackColor = Color.Red;
break;
case 2:
this.CustomerBirthDateInput.Focus();
this.CustomerBirthDateInput.BackColor = Color.Red;
break;
case 3:
MessageBox.Show("Invalid car category");
break;
case 4:
this.RentalDateInput.Focus();
this.RentalDateInput.BackColor = Color.Red;
break;
case 5:
this.MilageInput.Focus();
this.MilageInput.BackColor = Color.Red;
break;
}
}
private void RentalBackButton_Click(object sender, EventArgs e)
{
BackToMain(rentalPanel);
}
private void ResetRentalInputs()
{
this.BookingNumberInput.Text = string.Empty;
this.CustomerBirthDateInput.Text = (DateTime.Now.Date.AddYears(-20)).ToString();
this.CarCategoryInput.SelectedIndex = 0;
this.MilageInput.Text = string.Empty;
this.RentalDateInput.Text = DateTime.Now.ToString();
this.BookingNumberInput.BackColor = Color.White;
this.CustomerBirthDateInput.BackColor = Color.White;
this.RentalDateInput.BackColor = Color.White;
this.MilageInput.BackColor = Color.White;
}
private void ReturnConfimButton_Click(object sender, EventArgs e)
{
int validationError = model.ValidateReturnData(this.ReturnBookingNumberInput.Text, this.ReturnMilageInput.Text, this.ReturnDateInput.Text);
this.ReturnMilageInput.BackColor = Color.White;
this.ReturnDateInput.BackColor = Color.White;
switch (validationError)
{
case 0:
double price = model.CalculatePrice(this.BookingNumberInput.Text, this.ReturnDateInput.Text, this.ReturnMilageInput.Text);
model.SaveReturnDate(this.ReturnBookingNumberInput.Text, this.ReturnDateInput.Text);
ResetReturnInputs();
this.priceLabel.Text = "Cost: " + price.ToString();
break;
case 1:
MessageBox.Show("Invalid booking number");
break;
case 2:
this.ReturnMilageInput.Focus();
this.ReturnMilageInput.BackColor = Color.Red;
break;
case 3:
this.ReturnDateInput.Focus();
this.ReturnDateInput.BackColor = Color.Red;
break;
}
}
private void ReturnBackButton_Click(object sender, EventArgs e)
{
BackToMain(returnPanel);
}
private void ReturnBookingNumberInput_SelectedIndexChanged(object sender, EventArgs e)
{
ReturnConfimButton.Enabled = ReturnBookingNumberInput.SelectedIndex != -1;
this.priceLabel.Text = string.Empty;
}
private void ResetReturnInputs()
{
this.ReturnBookingNumberInput.Items.Clear();
this.ReturnBookingNumberInput.Items.AddRange(model.GetBookingNumberForActiveRentalsAsArray());
this.ReturnBookingNumberInput.SelectedIndex = -1;
this.ReturnDateInput.Text = DateTime.Now.ToString();
this.ReturnMilageInput.Text = string.Empty;
this.priceLabel.Text = string.Empty;
ReturnConfimButton.Enabled = false;
this.ReturnMilageInput.BackColor = Color.White;
this.ReturnDateInput.BackColor = Color.White;
}
}
}
| 9563bd2405e71f94a95dbdf4443ce7ffab67d2d9 | [
"C#"
] | 6 | C# | FilipOrnbratt/Developer-Test | 2d6534b20f80e56eed1e08abb76ff77153ae74ce | 89a9a8e456dd143ccf89e593b3a3275711fdc1ea |
refs/heads/master | <repo_name>rrdalmeida/EDA_Project1<file_sep>/plot4.R
# EDA Project 1
require(sqldf)
require(lubridate)
hpc_data <- read.csv.sql("household_power_consumption.txt", header = TRUE, sep = ";", sql = 'select * from file where Date="1/2/2007" or Date="2/2/2007"')
my_pattern <- "([[:digit:]])/([[:digit:]])/"
hpc_data2 <- as.data.frame(lapply(hpc_data, function(x) if(is.character(x)|is.factor(x)) gsub(my_pattern,"0\\1/0\\2/", x) else x))
hpc_data2$datetime = dmy_hms(paste(hpc_data2$Date, hpc_data2$Time))
png(filename = "plot4.png", width = 480, height = 480, units = "px")
par(mfcol=c(2,2))
plot(hpc_data2$datetime, hpc_data2$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab ="")
plot(hpc_data2$datetime, hpc_data2$Sub_metering_1, type="l", ylab="Energy sub metering", xlab ="")
lines(x=hpc_data2$datetime, y=hpc_data2$Sub_metering_2, col="red")
lines(x=hpc_data2$datetime, y=hpc_data2$Sub_metering_3, col="blue")
legend("topright", lty=1, col=c("black", "red", "blue"), legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
plot(hpc_data2$datetime, hpc_data2$Voltage, type="l", ylab="Voltage", xlab ="datetime")
plot(hpc_data2$datetime, hpc_data2$Global_reactive_power, type="l", ylab="Global_reactive_power", xlab ="datetime")
dev.off()
<file_sep>/plot3.R
# EDA Project 1
require(sqldf)
require(lubridate)
hpc_data <- read.csv.sql("household_power_consumption.txt", header = TRUE, sep = ";", sql = 'select * from file where Date="1/2/2007" or Date="2/2/2007"')
my_pattern <- "([[:digit:]])/([[:digit:]])/"
hpc_data2 <- as.data.frame(lapply(hpc_data, function(x) if(is.character(x)|is.factor(x)) gsub(my_pattern,"0\\1/0\\2/", x) else x))
hpc_data2$date_time = dmy_hms(paste(hpc_data2$Date, hpc_data2$Time))
png(filename = "plot3.png", width = 480, height = 480, units = "px")
plot(hpc_data2$date_time, hpc_data2$Sub_metering_1, type="l", ylab="Energy sub metering", xlab ="")
lines(x=hpc_data2$date_time, y=hpc_data2$Sub_metering_2, col="red")
lines(x=hpc_data2$date_time, y=hpc_data2$Sub_metering_3, col="blue")
legend("topright", lty=1, col=c("black", "red", "blue"), legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
dev.off()
<file_sep>/plot1.R
# EDA Project 1
require(sqldf)
require(lubridate)
hpc_data <- read.csv.sql("household_power_consumption.txt", header = TRUE, sep = ";", sql = 'select * from file where Date="1/2/2007" or Date="2/2/2007"')
my_pattern <- "([[:digit:]])/([[:digit:]])/"
hpc_data2 <- as.data.frame(lapply(hpc_data, function(x) if(is.character(x)|is.factor(x)) gsub(my_pattern,"0\\1/0\\2/", x) else x))
hpc_data2$Date <- dmy(hpc_data2$Date)
hpc_data2$Time <- hms(hpc_data2$Time)
png(filename = "plot1.png", width = 480, height = 480, units = "px")
hist(hpc_data2$Global_active_power, breaks=12, col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)")
dev.off()
<file_sep>/plot2.R
# EDA Project 1
require(sqldf)
require(lubridate)
hpc_data <- read.csv.sql("household_power_consumption.txt", header = TRUE, sep = ";", sql = 'select * from file where Date="1/2/2007" or Date="2/2/2007"')
my_pattern <- "([[:digit:]])/([[:digit:]])/"
hpc_data2 <- as.data.frame(lapply(hpc_data, function(x) if(is.character(x)|is.factor(x)) gsub(my_pattern,"0\\1/0\\2/", x) else x))
hpc_data2$date_time = dmy_hms(paste(hpc_data2$Date, hpc_data2$Time))
png(filename = "plot2.png", width = 480, height = 480, units = "px")
plot(hpc_data2$date_time, hpc_data2$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab ="")
dev.off() | 419d7a8d541b987c335298197cc2f527f8ffab6a | [
"R"
] | 4 | R | rrdalmeida/EDA_Project1 | de373152937960226e9747b09bbe24ce44400941 | 3cfef02196f894730829e4361b9beb84aca0f632 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UnlulerUnsuzler.Classes;
namespace UnlulerUnsuzler
{
public partial class UnlulerUnsuzlerForm : Form
{
public UnlulerUnsuzlerForm()
{
InitializeComponent();
}
private void bHesapla_Click(object sender, EventArgs e)
{
string kelime = tbKelime.Text.ToLower();
Unluler sesli = new Unluler();
tbSesli.Text = sesli.Unler(kelime);
tbSessiz.Text = sesli.Unsuzler(kelime);
}
private void bTemizle_Click(object sender, EventArgs e)
{
tbKelime.Clear();
tbSesli.Clear();
tbSessiz.Clear();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnlulerUnsuzler.Classes
{
class Unluler
{
string[] unluler = { "a", "e", "ı", "i", "o", "ö", "u", "ü" };
public string Unler(string kelime)
{
string unlu = "";
for (int i = 0; i <= kelime.Length-1; i++)
{
if (unluler.Contains(kelime[i].ToString()))
{
if (!unlu.Contains(kelime[i].ToString()))
{
unlu = unlu + " " + kelime[i];
}
}
}
return unlu;
}
public string Unsuzler(string kelime)
{
string unsuz = "";
for (int i = 0; i <= kelime.Length - 1; i++)
{
if (!(unluler.Contains(kelime[i].ToString())))
{
if (!unsuz.Contains(kelime[i].ToString()))
{
unsuz = unsuz + " " + kelime[i]; ;
}
}
}
return unsuz;
}
}
}
| 39cef781115206aa469d6c5e71936bb59cab8a5c | [
"C#"
] | 2 | C# | ygulcimen/UnlulerUnsuzler | 3c18d609c1af23e205e2de6637ef5bed8406a093 | ce4524371bdde5f37fa11485e0974b20afca4e55 |
refs/heads/master | <file_sep>var numP = 5; //broj igrača
var deck = [];
var players = [];
var table = [];
var playersCombs = [];
var dealtP = false;
//Napravi špil
for(var i=0; i<52; i++){
deck.push(new Card(Math.floor(i/13), i%13));
}
shuffleCards();
//Napravi igrače
for(var i=0; i<numP; i++){
players.push(new Player);
}
//Deli igračima
dealP();
//Deli sto
flop();
turn();
river();
function produceWinCards(){ //nadji karte u dobitnoj kombinaciji
var combs = getCombinations();
var winner = eval();
var winComb = [0,1,2,3,4,5,6];
var ex1 = 0;
var ex2 = 1;
for(var i=0; i<winner.combInd; i++){
if(ex2<6){
ex2++;
} else if (ex1!=5){
ex1++;
ex2=ex1+1;
}
}
winComb.splice(ex2, 1);
winComb.splice(ex1, 1);
return winComb;
}
function Card(suit,value){
this.suit = suit;
this.value = value;
}
function Player(){
this.money = 1000;
this.pos = players.length;
this.hand = [];
}
function bestScore(scores){
var bestType = scores[0].type;
var bestTypeInd = [];
for(var i=1; i<scores.length; i++){
if(scores[i].type>bestType){
bestType = scores[i].type;
}
}
for(var i=0; i<scores.length; i++){
if(scores[i].type==bestType){
bestTypeInd.push(i);
}
}
var bestInd = bestTypeInd[0];
for(var i=1; i<bestTypeInd.length; i++){
if(compareVal(scores[bestInd].value, scores[bestTypeInd[i]].value)==1){
bestInd = i;
}
}
return {comb: scores[bestInd], ind: bestInd};
}
function sortVal(comb){
do{
var swapDone = false;
for(var i=0; i<comb.length-1; i++){
if(comb[i].value>comb[i+1].value){
var tmp = comb[i];
comb[i] = comb[i+1];
comb[i+1] = tmp;
swapDone = true;
}
}
} while(swapDone);
return comb;
}
function sortSuit(comb){
do{
var swapDone = false;
for(var i=0; i<comb.length-1; i++){
if(comb[i].suit>comb[i+1].suit){
var tmp = comb[i];
comb[i] = comb[i+1];
comb[i+1] = tmp;
swapDone = true;
}
}
} while(swapDone);
return comb;
}
function shuffleCards(moves = 100) {
for(var i=0; i<moves; i++){
var k1 = Math.floor(Math.random() * 52);
var k2;
do {
k2 = Math.floor(Math.random() * 52);
} while (k2 == k1);
tmp = deck[k1];
deck[k1] = deck[k2];
deck[k2] = tmp;
}
}
function dealP(){
for(var i=0; i<numP; i++){
players[i].hand.push(deck.pop());
players[i].hand.push(deck.pop());
//DOM
var para = document.getElementById('players');
var pText = document.createElement('p');
pText.textContent = pText.textContent + 'Player ' + (i+1) + ' ';
for(var j=0; j<2; j++){
if(players[i].hand[j].value<9){
pText.textContent = pText.textContent + (players[i].hand[j].value+2);
} else{
switch(players[i].hand[j].value){
case 9:
pText.textContent = pText.textContent + 'J';
break;
case 10:
pText.textContent = pText.textContent + 'Q';
break;
case 11:
pText.textContent = pText.textContent + 'K';
break;
case 12:
pText.textContent = pText.textContent + 'A';
break;
}
}
switch(players[i].hand[j].suit){
case 0:
pText.textContent = pText.textContent + '♠ ';
break;
case 1:
pText.textContent = pText.textContent + '♣ ';
break;
case 2:
pText.textContent = pText.textContent + '♥ ';
break;
case 3:
pText.textContent = pText.textContent + '♦ ';
break;
}
}
para.appendChild(pText);
}
dealtP = true;
}
function flop(){
for(var i=0; i<3; i++){
table.push(deck.pop());
}
}
function turn(){
table.push(deck.pop());
}
function river(){
turn();
}
function compareVal(a, b){
for(var i=0; i<a.length; i++){
if(a[i]<b[i]){
return 1; //b je veće
} else if(a[i]>b[i]){
return 0; //a je veće
} else{
i++;
}
}
}
function getCombinations(){
//Pravljenje svih kombinacija svih karata igrača i zajedničkih
playersCombs = [];
var playersScores = [];
for(var i=0; i<numP; i++){
comb7 = [players[i].hand[0], players[i].hand[1], table[0], table[1], table[2], table[3], table[4]]; //Sastavljanje skupa 7 karata
combs = [];
numCom = 0; //Broj kombinacija vec dodatih (od 21)
ex1 = 0, ex2 = 1; //Karte koje se ne koriste u kombinaciji
while(numCom<21){
var j = 0; //Indeks skupa 7 karata
var k = 0; //Broj karata dodatih u kombinaciju
comb = [];
while(k<5){
if(j!=ex1 && j!=ex2){
comb[k] = comb7[j];
k++;
}
j++;
}
combs.push(comb);
numCom++;
if(ex2<6){
ex2++;
} else if (ex1!=5){
ex1++;
ex2=ex1+1;
}
}
playersCombs.push(combs);
}
for(var pInd=0; pInd<numP; pInd++){ //za svakog igrača
var playerScore = [];
for (var combInd=0; combInd<21; combInd++){ //i sveku njegovu kombinaciju
var tmpComb = sortVal(playersCombs[pInd][combInd]); //sortiranje kombinacije po vrednosti karte
var score;
var numC = [0,0,0,0,0,0,0,0,0,0,0,0,0];
for(var cardInd=0; cardInd<5; cardInd++){
numC[tmpComb[cardInd].value]++;
}
var kickers = false;
for(var numCInd=12; numCInd>=0; numCInd--){ //za svaki broj karata sa istom vrednoscu (iz kombinacije)
score = {type: null, value:[]};
switch(numC[numCInd]){
case 4:
score.type = 7; //poker
score.value.push(numCInd);
break;
case 3:
score.type = 3; //triling
score.value.push(numCInd);
for(var numCInd2=numCInd-1; numCInd2>=0; numCInd2--){
if(numC[numCInd2]==2){
score.type = 6; //full
score.value.push(numCInd2);
break;
}
}
break;
case 2:
score.value.push(numCInd);
for(var numCInd2=numCInd-1; numCInd2>=0; numCInd2--){
score.type = 1; //par
if(numC[numCInd2]==3){
score.type = 6; //full
score.value.unshift(numCInd2);
break;
} else if(numC[numCInd2]==2){
score.type = 2; //dva para
score.value.push(numCInd2);
break;
}
}
if(score.type == 1 || score.type == 2){
for(var numCInd2=12; numCInd2>=0; numCInd2--){
if(numC[numCInd2]===1){
score.value.push(numCInd2);
}
}
}
break;
}
if(!score.type){ //ako nema istih karata
var straight = true;
if(tmpComb[0].value==0){ //može biti wheel kenta
for(var cardInd=0; cardInd<3; cardInd++){
if(tmpComb[cardInd].value!=tmpComb[cardInd+1].value+1){
straight = false;
break;
}
}
if(straight){
switch(tmpComb[4].value){
case 12: //wheel kenta
score.type = 4; //kenta
score.value.push(0);
break;
case 4: // 23456 kenta
score.type = 4; //kenta
score.value.push(1);
break;
}
}
} else{
for(var cardInd=0; cardInd<4; cardInd++){
if(tmpComb[cardInd].value!=tmpComb[cardInd+1].value+1){
straight = false;
break;
}
}
if(straight){
score.type = 4; //kenta;
score.value.push(tmpComb[0].value + 1);
}
}
var flush = true;
for(var cardInd=0; cardInd<4; cardInd++){
if(tmpComb[cardInd].suit!=tmpComb[cardInd+1].suit){
flush = false;
break;
}
}
if(flush){
if(straight){
if(tmpComb[0] == 8){
score.type = 9; //royal flush
} else{
score.type = 8; //straight flush
score.value = tmpComb[0].value + 1;
}
} else {
score.type = 5; //flush
for(var cardInd=4; cardInd>=0; cardInd--){
score.value.push(tmpComb[cardInd]);
}
}
}
}
if(!score.type){
score.type = 0; //high card
for(var cardInd=4; cardInd>=0; cardInd--){
score.value.push(tmpComb[cardInd].value);
}
}
if(score.type!=0){
break;
}
}
playerScore.push(score);
}
playersScores.push(playerScore);
// console.log(numC);
}
return playersScores;
}
function eval(){
var pScores = getCombinations(); //sve kombinacije svih igrača
var bestPCombInd = []; //indeksi najboljih kombinacija svakog od igrača
var bestPCombs = [];
var bestP;
for (var i=0; i<pScores.length; i++){
var best = bestScore(pScores[i]);
bestPCombInd.push(best.ind);
bestPCombs.push(best.comb);
}
bestP = bestScore(bestPCombs).ind;
return {player: bestP, combInd: bestPCombInd[bestP]};
}
| 57eff1f4dd59a2c5ffc909d84681f0394c3dd215 | [
"JavaScript"
] | 1 | JavaScript | zoranmk/poker | 801bf345c5caf0d046ca64d96e182b35520cffe2 | deebbbdc2c1d030f412306060fc87d668ab4fae9 |
refs/heads/master | <file_sep>install.packages("tidyverse")
library(tidyverse)
library(stringr)
library(dplyr)
library(plyr)
library(ggplot2)
library(reshape2)
install.packages("osmdata")
library(ggmap)
library(osmdata)
library(datasets)
getwd()
##Reading-in data
a<-read.csv('HTL-Reg-SnailLength.csv')
a
##Application of the appropriate data storage structure: [2 Points]
##list
l<-list(a)
l
##data frame
a.df<-as.data.frame(a)
a.df
##matrix
m<-as.matrix(a)
m
##Example of indexing (indexing 2nd row 6th column) [2 points]
a[2,6]
##Subsetting "SSA" from Habitat variable (SP SSA TSA TSP) [2 points]
unique(a$Habitat)
#Subsetting
sub<-subset(a,Habitat=="SSA")
sub
##(1) Ordering [2 points]
a.ord=a[order(a$ShellHeight),]
a.ord
#(2) Ordering/sorting
a.arrange <- arrange(a, ShellHeight, Site)
a.arrange
##(1) Summarizing [5 points]
sum1=tapply(X=a$ShellHeight,INDEX=list(a$Habitat),FUN=fivenum)
sum1
##(2) Summarizing "SSA" subset of Habitat data
sum2=summary(a[a$Habitat=="SSA",]$SnailID/a[a$Habitat=="SSA",]$ShellHeight)
sum2
##Merge or Join data frames [5 points]
#Mean of ShellHeiight
mean.SH<-tapply(X=a$ShellHeight,INDEX=list(a$Quadrat),FUN=mean)
mean.SH
#convert object to data frame-creating a dataframe from mean of ShellHeight
mean.df = data.frame(Quadrat = names(mean.SH), mean = as.numeric(mean.SH))
mean.df
#Variance of ShellHeight
var.SH<-tapply(X=a$ShellHeight,INDEX=list(a$Quadrat),FUN=var)
var.SH
#convert object to data frame-creating a dataframe from Variance of ShellHeight
var.df = data.frame(Quadrat = names(var.SH), var = as.numeric(var.SH))
var.df
#merging the two data frames of Mean and Variance of ShellHeight
merge<-merge(x=mean.df,y=var.df, by="Quadrat")
merge
#Join
Join<-full_join(mean.df, var.df, by="Quadrat")
Join
##Custom Functions [10 points]
switcheroo.if.then<- function(x) {
if (x =="SP")
"Spartina patens"
else if (x =="SSA")
"Stunted Spartina alternifora"
else if (x =="TSA")
"Tall Spartina alternifora"
else
"Transitional Spartina patens"
}
switcheroo.if.then("SP")
switcheroo.if.then("SSA")
switcheroo.if.then("TSA")
switcheroo.if.then("TSP")
##Custom operator(s) [10 points]
'%pooja%'<-function(x,y){2*x + 3*y}
4%pooja%5
##‘ddply’ & 'if else' [10 + 10 points]
a.if<-a[a$Habitat=="SP",]
a.H<- ddply(.data=a, .variables="Habitat",function(x){
H<-unique(x$Habitat)
#ifelse(test=H=="SP",
Habitat_condition<-function(y){
if(H=="SP")
q<-"Spartina patens"
else if(H=="SSA")
q<-"Stunted Spartina alternifora"
else if(H=="TSP")
q<-"Tall Spartina alternifora"
else
q<-"Transitional Spartina patens"
}
x$Habitat_H<-Habitat_condition(y=H)
return(x)
}, .inform=T,.progress = "text")
##Reshaping data with ‘melt’ and/or ‘dcast’ [5 points]
melt1<-melt(data=a,id.vars=c("Quadrat","Habitat"), measure.vars=c("ShellHeight"))
melt1
cast1<-dcast(data=melt1,formula=Quadrat~variable, fun.aggregate=mean)
cast1
##For Loop converting um to m [10 points]
p = data.frame(1:10)
p$meter = NA
names(p) = c("micrometer","meter")
for(x in 1:10){
p[x,]$meter = (p[x,]$micrometer *.000001)
}
##Histogram [5 points]
his<-ggplot(data = a, aes(x = ShellHeight)) +
geom_histogram(binwidth = 5, color="black", fill="yellow")+
facet_wrap(.~Habitat)
his
##Point, bar, or line plot (whichever makes the most sense) [5 points]
point<-ggplot(data = a, aes(x = ShellHeight, y=Habitat)) +
geom_point(color="deeppink")
point
bar<-ggplot(data = a, aes(x=ShellHeight)) +
geom_bar(color="deeppink")+
facet_grid(Habitat~.)
bar
line<- ggplot(data=a, aes(x=ShellHeight,y=Habitat)) + geom_line(color="deeppink")
line
##‘ggplot’ with at least 2 geoms (e.g. point, bar, tile), use one of the ‘scale_’ geoms,
#and adjusting the theme of the plot [10 points]
ggplot(data=a, aes(x=ShellHeight,y=Habitat)) +
geom_point(color="deeppink") +geom_tile()+
scale_fill_continuous(type='viridis')+
theme_bw()
##A map of showing the geographic location where the data was collected [10 points]
getbb('Rhode Island')
map.RI = get_stamenmap(bbox = getbb('Rhode Island'),
zoom = 9, map = 'terrain')
ggmap(map.RI)
##Exporting data set [2 points]
dir.create("C:/Users/pooja/OneDrive/Desktop/R/Final_Project_R")
##Exporting and saving figures from ggplot [2 points]
ggsave("a.jpeg")
| c8a52307a2739bfa222ec7d041db90adb66b9ae1 | [
"R"
] | 1 | R | Pooja123-bit/Final_Project_R | 1b1c016c939d98cf79da03d6d06b39a87b8a5295 | 2681236dd32747d57555f2fd71bd686a9c698a09 |
refs/heads/master | <file_sep>Create a new class Quadrilateral
Create a new class rectangle that inherits from quadrilateral
Create a method area<file_sep>public class Main {
public static void main(String[] args) {
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point p3 = new Point();
p3.setX(5);
p3.setY(6);
Point p4 = p1; // p4 tekhou el pointeur taa l p1
if (p1 == p3) {
System.out.printf("p1 %s is p3 %s \n", p1, p3);
} else {
System.out.printf("p1 %s is not to p3 %s \n", p1, p3);
}
if (p1.equals(p3)) {
System.out.printf("p1 %s is p3 %s \n", p1, p3);
} else {
System.out.printf("p1 %s is not to p3 %s \n", p1, p3);
}
if (p1 == p4) //compare pointers
{
System.out.printf("p1 %s is p4 %s \n", p1, p4);
} else {
System.out.printf("p1 %s is not to p4 %s \n", p1, 4);
}
if (p1.equals(p4)) {
System.out.printf("p1 %s is p4 %s \n", p1, p4);
} else {
System.out.printf("p1 %s is not to p4 %s \n", p1, 4);
}
if ((p1.getX() == p3.getX()) && (p1.getY() == p3.getY())) {
System.out.printf("p1 %s is equal to p3 %s \n", p1, p3);
} else {
System.out.printf("p1 %s is different from p3 %s \n", p1, p3);
}
if ((p1.getX() < p2.getX()) && (p1.getY() < p2.getY())) {
System.out.printf("p1 %s is lower than p2 %s \n", p1, p2);
} else {
System.out.printf("p1 %s is higher than or equal to p2 %s \n", p1, p2);
}
Segment l1 = new Segment(p1, p2);
Segment l2 = new Segment();
Segment l3 = new Segment(p3);
System.out.println("the length of the line between " + l1 + " is equal to: " + l1.getLength());
System.out.println("the length of the line between " + l2 + " is equal to: " + l2.getLength());
System.out.println("the length of the line between " + l3 + " is equal to: " + l3.getLength());
Rectangle r = new Rectangle(l1, l2);
System.out.println("the area of " + r + " is " + r.area());
Square s = new Square(l1, l2);
System.out.println("the area of " + s + " is " + s.area());
Rectangle r1 = s;
System.out.println("The area of " + r1 + " is " + r1.area());
}
}
<file_sep>public class Segment {
private Point p1;
private Point p2;
public Segment() {
this.p1 = new Point();
this.p2 = new Point(0, 1);
}
public Segment(Point p) {
this.p1 = new Point(); //origin
this.p2 = p;
}
public Segment(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
public Point getP1() {
return p1;
}
public void setP1(Point p1) {
this.p1 = p1;
}
public Point getP2() {
return p2;
}
public void setP2(Point p2) {
this.p2 = p2;
}
public double getLength() {
return p1.distanceTo(p2);
}
public String toString() {
return "(" + p1.toString() + "and" + p2.toString() + ")";
}
} | 43360b6b0b2c026c9a0d9a9e846248c0f8b88d3b | [
"Java",
"Text"
] | 3 | Text | SpaceBoyPrince/Geometry_Software | 4c9da2f8b127f559e3265a38961cf664d03842d2 | fc72f56f70c2cedcaa81e9a37502c16ce7869bdd |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericsUI
{
class Program
{
static void Main(string[] args)
{
// Compare Integer
Check<int> obj1 = new Check<int>();
bool intResult = obj1.Compare(2, 3);
// Compare String
Check<string> obj2 = new Check<string>();
bool strResult = obj2.Compare("Ramakrishna", "Ramakrishna");
Console.WriteLine("Integer Comparison: {0}\nString Comparison: {1}", intResult, strResult);
Console.Read();
}
// Generic class to accept all types of data types
class Check<UnknowDataType>
{
// Gerefic function to compare all data types
public bool Compare(UnknowDataType var1, UnknowDataType var2)
{
if (var1.Equals(var2))
{
return true;
}
else
{
return false;
}
}
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Generics_in_classUI
{
class CompareClass
{
public bool Compare(string x, string y)
{
if (x.Equals(y)) return true;
else return false;
}
public bool Compare(int x, int y)
{
if (x.Equals(y)) return true;
else return false;
}
}
class CompareGenericClass<T>
{
public bool Compare(T x, T y)
{
if (x.Equals(y)) return true;
else return false;
}
}
class Program
{
static void Main(string[] args)
{
CompareClass obj = new CompareClass();
bool intresult = obj.Compare(5, 7);
Console.WriteLine("int comapre result:" + intresult);
bool stringresult = obj.Compare("Pavana", "Pavana");
Console.WriteLine("string comapre result:" + stringresult);
CompareGenericClass<string> Ocompare = new CompareGenericClass<string>();
bool stringResult = Ocompare.Compare("Pavana", "Pavana");
Console.WriteLine("Generic string comapre result:" + stringResult);
CompareGenericClass<int> oIntcompare = new CompareGenericClass<int>();
bool integerresult = oIntcompare.Compare(5, 6);
Console.WriteLine("Generic int comapre result:" + integerresult);
}
}
}
<file_sep>using System;
namespace GenericsBL
{
public class Class1
{
}
}
| b2362c61f449a741e36e53ebb34728b37ae56527 | [
"C#"
] | 3 | C# | Pavanas21/Generics | da5ef306afa0b88ffc87ccfab4cd0b198b689dc2 | 3d15cac82ef72e97259f597a15e2e8f4823ef51e |
refs/heads/master | <repo_name>Sanghun-Lee/MultiCounter_2<file_sep>/src/components/Button.js
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Dimensions
} from "react-native";
import Constants from "expo-constants";
import PropTypes from "prop-types";
const screenWidth = Math.round(Dimensions.get("window").width);
export default class Button extends Component {
static propTypes = {
onCreate: PropTypes.func,
onRemove: PropTypes.func
};
static defaultProps = {
onCreate: () => alert("Create"),
onRemove: () => alert("Remove")
};
render() {
return (
<View style={styles.container}>
<View style={styles.statusBar} />
<View style={{ flexDirection: "row" }}>
<TouchableOpacity
onPress={this.props.onCreate}
style={[styles.Button, { backgroundColor: "green" }]}
>
<Text style={styles.text}>생성</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.props.onRemove}
style={[styles.Button, { backgroundColor: "red" }]}
>
<Text style={styles.text}>제거</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
statusBar: {
backgroundColor: "#35CBEE",
height: Constants.statusBarHeight
},
container: {
height: 60,
width: screenWidth
},
text: {
fontSize: 20,
color: "white"
},
Button: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
<file_sep>/src/Main.js
import React, { Component } from "react";
import { View } from "react-native";
import Button from "./components/Button";
import CounterListContainer from "./containers/CounterListContainer";
import { connect } from "react-redux";
import * as actions from "./actions";
import { getRandomColor } from "./utils";
class Main extends Component {
render() {
const { onCreate, onRemove } = this.props;
return (
<View>
<Button onCreate={onCreate} onRemove={onRemove} />
<CounterListContainer />
</View>
);
}
}
// 액션함수 준비
const mapToDispatch = dispatch => ({
onCreate: () => dispatch(actions.create(getRandomColor())),
onRemove: index => dispatch(actions.remove(index))
});
// 리덕스에 연결을 시키고 내보낸다.
export default connect(
null,
mapToDispatch
)(Main);
<file_sep>/src/components/Counter.js
import React, { Component } from "react";
import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
import PropTypes from "prop-types";
class Counter extends Component {
static propTypes = {
index: PropTypes.number,
number: PropTypes.number,
color: PropTypes.string,
onIncrement: PropTypes.func,
onDecrement: PropTypes.func,
onSetColor: PropTypes.func
};
// onIncrement는 props로 CounterContainer.js에 있는
static defaultProps = {
index: 0,
number: 0,
color: "black",
onIncrement: function aa() {
return alert("increment");
},
onDecrement: () => alert("decrement"),
onSetColor: () => alert("onSetColor")
};
render() {
const color = this.props.color;
// const props = this.props;
// console.log(props);
return (
<View style={styles.container}>
<View style={[styles.textView, { backgroundColor: color }]}>
<Text style={styles.text}>{this.props.number}</Text>
</View>
<View style={styles.button}>
<TouchableOpacity
onPress={this.props.onIncrement}
style={styles.buttons}
>
<Text>++</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.props.onDecrement}
style={styles.buttons}
>
<Text>--</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.props.onSetColor}
style={styles.buttons}
>
<Text>C</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
export default Counter;
const styles = StyleSheet.create({
container: {
width: 150,
height: 150,
justifyContent: "center",
alignItems: "center"
},
textView: {
flex: 3,
width: 90,
height: 90,
borderRadius: 45,
justifyContent: "center",
alignItems: "center"
},
text: {
fontSize: 24,
color: "white"
},
button: {
flex: 2,
flexDirection: "row"
},
buttons: {
width: 30,
height: 30,
borderRadius: 5,
backgroundColor: "skyblue",
margin: 3,
justifyContent: "center",
alignItems: "center"
}
});
<file_sep>/README.md
# MultiCounter_2
Redux practice MultiCounter
source : https://velopert.com/3365
| 8f899a13199694251660ff0c73652d1516e37a15 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Sanghun-Lee/MultiCounter_2 | 71cb0a1bb9dab4ea70eb0c9fee3c8f68e7fbea9b | 889ea231ff1a063a5712cd3fce9b8075bbe4457d |
refs/heads/master | <file_sep>import { AxiosRequestConfig, AxiosResponse, AxiosPromise } from "../types"
import { parseHeaders } from "../helpers/headers";
import { createError } from "../helpers/error";
export default function xhr(config: AxiosRequestConfig): AxiosPromise {
return new Promise((resolve, reject) => {
const { data = null, url, method = 'get', headers, responseType, timeout } = config
/**
* @instance request prop
* @name request.status 初始为 0
* @name request.readyState 初始为 0
* @name request.timeout 初始为 0
* @name request.response 初始为 ""
* @name request.responseText 初始为 ""
* @name request.responseType 初始为 ""
* @name request.statusText 初始为 ""
* @name request.onreadystatechange 初始为 null
* @name ...
*/
const request = new XMLHttpRequest()
if (responseType) {
request.responseType = responseType
}
if (timeout) {
request.timeout = timeout
}
// open()方法初始化一个请求, 第三个参数为 boolean,表示是否异步执行操作,默认为 true, 在send()方法发送请求后会立即返回
// 如果 async = false, send() 方法直到收到答复前不会返回
// 如果multipart属性为true则这个必须为true,否则将引发异常。
request.open(method.toUpperCase(), url as string, true)
request.onreadystatechange = function handleLoad() {
/**
* @name readyState=0(UNSENT) 代理被创建,但尚未调用 open() 方法
* @name readyState=1(OPENED) open() 方法已经被调用
* @name readyState=2(HEADERS_RECEIVED) send()方法已经被调用,并且头部和状态已经可获得
* @name readyState=3(LOADING) 下载中,responseText 属性已经包含部分数据
* @name readyState=4(DONE) 下载操作已完成
*/
if (request.readyState !== 4) return
// 当发生网络错误或者超时错误时,status 也是 0
if (request.status === 0) return
// 返回所有的响应头,以 CRLF 分割的字符串,或者 null 如果没有收到任何响应
// 通过 parseHeaders 将 getAllResponseHeaders 获取到的响应头转化为 json 形式
const responseHeaders = parseHeaders(request.getAllResponseHeaders())
const responseData = responseType && responseType !== 'text' ? request.response : request.responseText
// 将 response 封装成 AxiosResponse 类型
const response: AxiosResponse = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
}
// resolve(response)
// 处理响应
handleResponse(response)
}
// 处理网络异常错误
request.onerror = function handleError() {
reject(createError('Network error', config, null, request))
}
// 超时处理
request.ontimeout = function handleTimeout() {
reject(createError(`Timeout of ${timeout} ms exceeded`, config, 'timeout', request))
}
// 当我们传入的 `data` 为空的时候,请求 `header` 配置 `Content-Type` 是没有意义的,于是我们把它删除。
// 设置请求头部的方法,必须在 open 和 send 方法之间调用
Object.keys(headers).forEach(name => {
if (data === null && name.toLowerCase() === 'content-type') {
delete headers[name]
} else {
// 如果多次对同一个请求头赋值,只会生成一个合并了多个值的请求头
request.setRequestHeader(name, headers[name])
}
})
// 处理非 200 状态码
function handleResponse(response: AxiosResponse): void {
if (response.status >= 200 && response.status < 300) {
resolve(response)
} else {
reject(createError(`Request failed with status code ${response.status}`, config, null, request, response))
}
}
// 用于发送 HTTP 请求
// 接受可选参数 data,作为请求主体
// 如果请求方法是 GET 或者 HEAD,则应将请求主体设置为 null。
request.send(data)
})
}
<file_sep>module.exports = function(router) {
router.get('/simple/get', (req, res) => {
res.json({
msg: 'simple request res'
})
})
router.get('/base/get', (req, res) => {
res.json(req.query)
})
router.post('/base/post', (req, res) => {
res.json(req.body)
})
router.post('/base/buffer', (req, res) => {
let msg = []
req.on('data', chunk => {
if (chunk) {
msg.push(chunk)
}
})
req.on('end', () => {
let buf = Buffer.concat(msg)
res.json(buf.toJSON())
})
})
router.get('/error/get', (req, res) => {
if (Math.random() > 0.5) {
res.json({
msg: `请求成功hello world`
})
} else {
res.status(500)
res.end()
}
})
router.get('/error/timeout', function(req, res) {
setTimeout(() => {
res.json({
msg: `超时了啊,hello world`
})
}, 3000)
})
router.get('/extend/get', function(req, res) {
res.json({
msg: 'extend get request res'
})
})
router.options('/extend/options', function(req, res) {
res.end()
})
router.head('/extend/head', function(req, res) {
res.end()
})
router.delete('/extend/delete', function(req, res) {
res.end()
})
router.post('/extend/post', function(req, res) {
res.json(req.body)
})
router.put('/extend/put', function(req, res) {
res.json(req.body)
})
router.patch('/extend/patch', function(req, res) {
res.json(req.body)
})
// 拦截器部分
router.get('/interceptor/get', (req, res) => {
res.end('hello result')
})
// 配置
router.post('/config/post', (req, res) => {
res.json(req.body)
})
}<file_sep>// `url` 为请求的地址,必选属性;而其余属性都是可选属性。`method` 是请求的 HTTP 方法;
// `data` 是 `post`、`patch` 等类型请求的数据,放到 `request body` 中的;
// `params` 是 `get`、`head` 等类型请求的数据,拼接到 `url` 的 `query string` 中的。
export interface AxiosRequestConfig {
url?: string | undefined
method?: Method
data?: any
params?: any
headers?: any
// lib.dom.d.ts 自定义字面量类型
responseType?: XMLHttpRequestResponseType
timeout?: number
// transformRequest:允许在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest?: AxiosTransformer | AxiosTransformer[]
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse?: AxiosTransformer | AxiosTransformer[]
[propName: string]: any // 添加这个属性,主要是为了合并配置那里使用的
}
export interface AxiosTransformer {
(data: any, headers?: any): any
}
export type Method = 'get' | 'GET'
| 'delete' | 'Delete'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
// 响应数据接口类型
export interface AxiosResponse<T = any> {
data: T
status: number
statusText: string
headers: any // 响应头
config: AxiosRequestConfig
request: any
}
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {}
export interface AxiosError extends Error {
config: AxiosRequestConfig
code?: string
request?: any
response?: any
isAxiosError: boolean
}
// 定义混合类型的 Axios 接口,支持 axios.get | axios.post 这种方式去发请求
export interface Axios {
interceptors: {
request: AxiosInterceptorManager<AxiosRequestConfig>
response?: AxiosInterceptorManager<AxiosResponse>
}
request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>
get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
delete<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
options<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
head<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
}
// 混合类型接口 AxiosInstance
// 既有函数类型,又有执行方法
export interface AxiosInstance extends Axios {
<T = any>(config: AxiosRequestConfig): AxiosPromise<T>
// 支持 axios(url, { method: * }) 方式
<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
}
// 拦截器接口
// use 方法接受两个回调函数,一个 resolve,一个 reject
export interface AxiosInterceptorManager<T> {
use(resolved: ResolvedFn<T>, rejected?: RejectedFn): number
// 支持取消拦截器
eject(id: number): void
}
export interface ResolvedFn<T = any> {
(val: T): T | Promise<T>
}
export interface RejectedFn<T = any> {
(error: any): any
}
// 添加静态方法
// create 函数接受一个 `AxiosRequestConfig` 类型配置,作为默认配置的扩展,也可以不传
export interface AxiosStatic extends AxiosInstance {
create(config?: AxiosRequestConfig): AxiosInstance
}
<file_sep>import { AxiosRequestConfig } from "../types"
import { isPlainObject, deepMerge } from '../helpers/util'
// 策略 map
const strats = Object.create(null)
/**
* @param config1 默认配置
* @param config2 自定义配置
*/
export default function mergeConfig (config1: AxiosRequestConfig, config2?: AxiosRequestConfig): AxiosRequestConfig {
if (!config2) {
config2 = {}
}
const config = Object.create(null)
/**
* @function 只接受自定义合并策略,对于`url/params/data`的合并策略如下
*/
const stratKeysFromVal2 = ['url', 'params', 'data']
// 遍历自定义配置
for (let key in config2) {
mergeField(key)
}
for (let key in config1) {
// 遍历默认配置,如果 config2 中不存在 key,就将默认配置合并到 config 中
if (!config2[key]) {
mergeField(key)
}
}
stratKeysFromVal2.forEach(key => {
// key 的值就是 fromVal2Strat
strats[key] = fromVal2Strat
})
function mergeField (key: string): void {
// 通过 key 找到所对应的合并策略函数
// 如果策略对象中不含有 strats[key] 方法,就采用默认策略
// strats[key] 中只会判断 config2 中的值: 如何 value 存在,就直接用 config2 中的值,否则啥也不干
// defaultStrate: typeof val2 !== 'undefined' ? val2 : val1
const strat = strats[key] || defaultStrate
// 如何这里的 config1[key] | config2[key] 报错,那么就是没在 AxiosRequestConfig 中定义索引签名
// warning: [ts] 元素隐式具有 "any" 类型,因为类型“AxiosRequestConfig”没有索引签名。
// warning: [ts] 对象可能为“未定义”。config2![key] 表示我们这 config2 对象肯定存在
config[key] = strat(config1[key], config2![key])
}
return config
}
function fromVal2Strat(val1: any, val2: any): any {
if (typeof val2 !== 'undefined') return val2
}
/**
* @function 默认合并策略,优先取`config2`中的值,因为`config2`是用户自定义的配置
*/
function defaultStrate (val1: any, val2: any): any {
return typeof val2 !== 'undefined' ? val2 : val1
}
const stratKeysDeepMerge = ['headers']
stratKeysDeepMerge.forEach(key => {
strats[key] = deepMergeStrat
})
/**
* @function deepMergeStrat 复杂对象合并策略
* @desc 比如 'headers'
*/
function deepMergeStrat (val1: any, val2: any): any {
if (isPlainObject(val2)) {
// 深拷贝
return deepMerge(val1, val2)
} else if (typeof val2 !== 'undefined') {
return val2
} else if (isPlainObject(val1)) {
return deepMerge(val1)
} else if (typeof val1 !== 'undefined') {
return val1
}
}
<file_sep>import axios from '../../src/index'
// axios({
// method: 'get',
// url: '/base/get',
// params: {
// foo: ['bar', 'baz']
// }
// })
// axios({
// method: 'get',
// url: '/base/get',
// params: {
// foo: {
// bar: 'baz'
// }
// }
// })
// const date = new Date()
// axios({
// method: 'get',
// url: '/base/get',
// params: {
// date
// }
// })
// axios({
// method: 'get',
// url: '/base/get',
// params: {
// foo: '@:$, '
// }
// })
// axios({
// method: 'get',
// url: '/base/get',
// params: {
// foo: 'bar',
// baz: null
// }
// })
// axios({
// method: 'get',
// url: '/base/get#hash',
// params: {
// foo: 'bar'
// }
// })
// axios({
// method: 'get',
// url: '/base/get?foo=bar',
// params: {
// bar: 'baz'
// }
// })
// axios({
// method: 'post',
// url: '/base/post',
// headers: {
// 'content-type': 'application/json;charset=utf-8'
// },
// data: {
// a: 1,
// b: 2
// }
// })
// const arr = new Int32Array([21, 31])
// axios({
// method: 'post',
// url: '/base/buffer',
// data: arr
// })
// const paramsString = 'q=URLUtils.searchParams&topic=api'
// URLSearchParams 构造函数定义了一些使用的方法来处理 URL 的查询字符串
// const searchParams = new URLSearchParams(paramsString)
// 注意: 这里的Content-Type是: application/x-www-form-urlencoded;charset=UTF-8 (form-data)
// 当浏览器发现我们传入的参数是 'URLSearchParams' 类型的参数时,它会自动给请求 header 加上合适的Content-Type
// XMLHttpRequest对象的实例的 send 方法本身是支持我们传入 URLSearchParams 这样的类型参数的
// axios({
// method: 'post',
// url: '/base/post',
// data: searchParams
// })
// promise
axios({
method: 'post',
url: '/base/post',
data: {
a: 1,
b: 2
}
}).then(res => {
// 我们没有指定 responseType。res.data 是 json 字符串类型
// 所以需要一个工具函数 transformResponseData 来处理 response data
console.log('响应1:', res)
})
axios({
method: 'post',
url: '/base/post',
responseType: 'json',
data: {
a: 1111,
b: 2222
}
}).then(res => {
// 指定了 responseType,res.data 是 json对象类型
console.log('响应2:', res)
})
<file_sep>import { AxiosInstance, AxiosRequestConfig, AxiosStatic } from "./types"
import Axios from "./core/Axios"
import { extend } from "./helpers/util"
import defaults from './defaults'
import mergeConfig from './core/mergeConfig'
// AxiosStatic 接口继承自 `AxiosInstance`
function createInstance(config: AxiosRequestConfig): AxiosStatic {
// Axios 原型上最核心的方法就是 request 方法
// 其它比如 get/post/delete 等等这些方法体内都是调用了 request 方法
const context = new Axios(config)
// 由于 request 内部使用到了 this, 所以需要将这个 this 指向绑定到 Axios 实例上,确保调用时不会出现异常
// bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
// instance 是 bind 函数返回的新函数,内部调用 dispatchRequest 方法,dispatchRequest 内部返回了 xhr 方法,即发起请求的核心部分
const instance = Axios.prototype.request.bind(context)
// extend 工具方法,将 Axios 构造函数的所有属性及原型上的方法复制给 instance 方法
// 通过 for...in 赋值
extend(instance, context)
// 当ts无法正确推断出instance 的类型时,通过类型断言来处理
return instance as AxiosStatic
}
// 我们拿到的其实就是 request 混合方法
const axios = createInstance(defaults)
// 提供对外的 create 静态方法,
axios.create = function create(config) {
return createInstance(mergeConfig(defaults, config))
}
export default axios
<file_sep>import { AxiosTransformer } from "../types";
/**
* @param data 可以是请求体,也可以是响应数据
* @param headers 可以是请求头,也可以是响应头
* @param fns fns包含默认的 transformRequest/transformResponse 以及用户定义的 transformRequest/transformResponse
*/
export default function transform(
data: any,
headers: any,
fns?: AxiosTransformer | AxiosTransformer[]
) {
if (!fns) {
return data
}
if (!Array.isArray(fns)) {
fns = [fns]
}
fns.forEach(fn => {
// 调用处理方法
data = fn(data, headers)
})
return data
}
<file_sep>import axios from '../../src/index'
import qs from 'qs'
// axios.defaults.headers.common['test2'] = '123'
// axios({
// url: '/config/post',
// method: 'post',
// data: qs.stringify({
// a: 1
// }),
// headers: {
// test: '666'
// }
// }).then(res => {
// console.log('config res', res)
// })
// 测试 transformRequest 和 transformResponse 属性作用
axios({
transformRequest: [
function(data, headers) {
headers.auth = 'you can set headers prop at here!!!'
return qs.stringify(data)
},
...(axios.defaults.transformRequest)
],
transformResponse: [
...(axios.defaults.transformResponse),
function(data) {
// you can process response datas at here
if (typeof data === 'object') {
data.b = 2222222
data.a += 1
}
return data
}
],
url: '/config/post',
method: 'post',
data: {
a: 1
}
}).then(res => {
console.log('config res: ', res)
})
// 测试 create 方法
const instance = axios.create({
transformRequest: [
function(data, headers) {
headers.auth = 'hello create function'
return qs.stringify(data)
},
...(axios.defaults.transformRequest)
],
transformResponse: [
...(axios.defaults.transformResponse),
function(data) {
// you can process response datas at here
if (typeof data === 'object') {
data.b = 'create function data'
data.a += 1
}
return data
}
]
})
instance({
url: '/config/post',
method: 'post',
data: {
a: 1
}
}).then(res => {
console.log('create funciton res: ', res)
})
<file_sep>// 入口文件
import xhr from "./xhr"
import transform from './transform'
import { bulidURL } from "../helpers/url"
import { processHeaders, flattenHeaders } from "../helpers/headers"
import { transformRequest, transformResponse } from "../helpers/data"
import { AxiosRequestConfig, AxiosResponse, AxiosPromise } from "../types"
export default function dispatchRequest (config: AxiosRequestConfig) {
// 在发送请求之前,先对 config 作处理,包括 url, headers, data
processConfig(config)
// xhr 返回 Promise 实例,使我们可以通过 .then 方式来访问响应数据
return xhr(config).then(res => {
// transformResponseData 方法处理json字符串数据,
// 如果数据是 json 字符串,就将其转为 json 对象
return transformResponseData(res)
})
}
// 处理配置
function processConfig (config: AxiosRequestConfig): void {
// 处理url,对字符,null,undefined,以及各字段做拼接
config.url = transformUrl(config)
// 处理请求头,必须放在处理 data 前面,因为在处理 data 时,transformRequest已经将普通对象转化为字符串了
// config.headers = transformHeaders(config)
// 对请求体做处理,如果data是普通对象,就将其转为json字符串类型
// config.data = transformRequestData(config)
// 通过 transform 函数来转化 request headers and datas
// 主要是为了处理 用户定义的 `transformRequest` 以及默认的 `transformRequest`
// transformRequest 可以设置请求头,也可以处理请求体
config.data = transform(config.data, config.headers, config.transformRequest)
// 合并请求头
config.headers = flattenHeaders(config.headers, config.method!)
}
function transformRequestData(config: AxiosRequestConfig): any {
return transformRequest(config.data)
}
function transformUrl (config: AxiosRequestConfig): string {
const { url, params } = config
// url! 表示类型断言,它一定不为空
return bulidURL(url!, params)
}
function transformHeaders(config: AxiosRequestConfig) {
const { headers = {}, data } = config
return processHeaders(headers, data)
}
function transformResponseData(res: AxiosResponse): AxiosResponse {
// res.data = transformResponse(res.data)
// 可以处理用户在 `transformResponse` 函数中想要处理的响应数据
res.data = transform(res.data, res.config, res.config.transformResponse)
return res
}
<file_sep>import { isPlainObject } from "./util"
// 我们通过执行 `XMLHttpRequest` 对象实例的 `send` 方法来发送请求,并通过该方法的参数设置请求 `body` 数据
// `send` 方法的参数支持 `Document` 和 `BodyInit` 类型
// `BodyInit` 包括了 `Blob`, `BufferSource`, `FormData`, `URLSearchParams`, `ReadableStream`、`USVString`,当没有数据的时候,我们还可以传入 `null`。
export function transformRequest (data: any): any {
if (isPlainObject(data)) {
return JSON.stringify(data)
}
return data
}
export function transformResponse(data: any): any {
if (typeof data === 'string') {
try {
data = JSON.parse(data)
} catch (error) {
// ..
}
}
return data
}
<file_sep>import { ResolvedFn, RejectedFn } from "../types"
interface Interceptor<T> {
resolved: ResolvedFn<T>
rejected?: RejectedFn
}
export default class InterceptorManager<T> {
// interceptors 数组结构,保存含有 resolve 和 reject 属性的对象
// 同时可以含有 null,是因为 eject 方法可以删除拦截器,
private interceptors: Array<Interceptor<T> | null>
constructor() {
this.interceptors = []
}
// axios.interceptors.request.use(function (config) {
// return config;
// }, function (error) {
// return Promise.reject(error)
// })
// 调用 请求 截器调用 use 方法,会收集所有的请求拦截器中的回调函数
// 调用 响应拦 截器调用 use 方法,会收集所有的响应拦截器中的回调函数
use(resolved: RejectedFn<T>, rejected?: RejectedFn): number {
this.interceptors.push({
resolved,
rejected
})
// 为什么要返回 number ?
// 因为 axios 支持取消拦截器,取消的话,就需要找到拦截器对应的下标
// const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
// axios.interceptors.request.eject(myInterceptor);
return this.interceptors.length - 1
}
// 拦截器内部使用,执行拦截器里面的方法
forEach(fn: (interceptor: Interceptor<T>) => void): void {
this.interceptors.forEach(interceptor => {
if (interceptor !== null) {
fn(interceptor)
}
})
}
// 取消拦截器
eject(id: number): void {
// 不能通过 splice 这种方法去删除,会改变数组长度,导致数组下标发生变化就乱了
if (this.interceptors[id]) {
this.interceptors[id] = null
}
}
}
| 1f451a3db2d272b31aaf2b9ab5e17b3c2700ce37 | [
"JavaScript",
"TypeScript"
] | 11 | TypeScript | Hello-Alex-Cheng/ts-axios | fbeca4ca4fff9acc2f0ebb58664bd8eb15bc5a65 | 424486928e9d459e77a69bd1b004ac5052a7abb5 |
refs/heads/master | <file_sep>Files for playing audio via STM
<file_sep>Contains the audio signals
<file_sep>#include "mbed.h"
AnalogOut speaker(PA_4);
Ticker sampletick;
DigitalOut myled(LED1);
//Plays Audio Clip using Array in Flash
//
//setup const array in flash with audio values
//from free wav file conversion tool at
//http://ccgi.cjseymour.plus.com/wavtocode/wavtocode.htm
//see https://os.mbed.com/users/4180_1/notebook/using-flash-to-play-audio-clips/
#include "cylonbyc.h"
#define sample_freq 192000
//get and set the frequency from wav conversion tool GUI
int i=0;
//interrupt routine to play next audio sample from array in flash
void audio_sample ()
{
speaker.write_u16(sound_data[i]);
i++;
if (i>= NUM_ELEMENTS) {
i = 0;
sampletick.detach();
myled = 0;
}
}
int main()
{
while(1) {
myled = 1;
//use a ticker to play send next audio sample value to D/A
sampletick.attach(&audio_sample, 1.0 / sample_freq);
//can do other things while audio plays with timer interrupts
wait(2.0);
}
}
<file_sep># Dolphin Attack on Smart Home Systems
# About
This is the [project website](https://ucla-ece209as-2018w.github.io/Aadithya-Nrithya/) for the course ECE 209 AS. This website contains the necessary material for the project ' Dolphin Attack on Smart Home Systems'. It includes
- Problem statement
- Related Work
- Approach
- Method
- Findings
- Analysis
- Future Work
# Problem Statement
<p align="justify">
There is an increase in the use of Speech Recognition systems developed by Google, Amazon, Apple and Microsoft in mobile phones, laptops and more recently smart home devices. With fast advances in Machine Learning, Artificial Intelligence and Embedded Systems, these speech recognition(SR) systems are making their way into the common man's home, performing everyday tasks [1]. However, there are always vulnerabilities in any technology. One such vulnerability that can be exploited to a attacker's advantage is the non-linearity of the microphones present in the COTS devices. Inaudible sounds (Ultrasonic frequency) can used to attack these devices by exploiting the above vulnerability. The original low frequency components used to modulate the ultrasound carrier are demodulated and interpreted by the SR systems due to this effect. The attack we choose to implement is the portable Dolphin Attack which involves attacking mobile phones and laptops by transmitting attack commands from a smart phone over a ultrasonic transducer [2]. This attack is relatively inexpensive and can be launched on the go. The damage that can be caused to the user can be both mental and monetary. Dolphin commands can be used to accomplish benign tasks like prank calls,order takeouts, schedule Uber and range upto malicious monetary transcations. We analyse different implementations of the portable Dolphin attack and evaluate the results.
</p>
# Related Work
<p align="justify">
Traditionally, several techniques have been used to attack Speech Recognition and Voice Control Systems. An interesting attack on the early generation Alexa in Amazon Echo was entirely unintentional [3] NPR's weekend edition broadcast a listen up section about Alexa which prompted a number of these devices to respond to the story by turning up the thermostat and shopping online. Carlini et al, chose to attack the speech recognition system by hiding the attack commands such that they can be deciphered by the system but remain incomprehensible to the user [4]. This attack is accomplished in both scenarios, when the attackers have knowledge of the SR system's internal structure and when they do not. This work is based on the work of Vaidya et al which involves mangling normal input commands using an audio mangler. This converts them into morphed sounds which retain the acoustic features of the key words [5]. In CommanderSong, attack commands are embedded in songs which are then used to attack the voice control systems [6]. The wireless channel may also be utilized for command injection. Chaouki et al show that specific electromagnetic interference signals can be coupled with the headphones used with smartphones in order to inject voice commands to the speech recognition systems [7]. The attack closest to the Dolphin attack is the Backdoor Attack [8]. Here, two ultrasonic signals, one carrying the attack command and another pilot tone used for original signal reconstruction, are transmitted to the receiver. The microphone non linearities are ultilized to recover the original attack command and activate the speech recognition system. The major difference between the Backdoor and Dolphin Attacks is the way the non linearities are leveraged to achieve the attack. Backdoor uses two ultrasonic signals and frequency modulation as opposed to a single voice signal amplitude modulated on an ultrasonic carrier in the Dolphin Attack. The Dolphin attack is superior to the above approaches in that it can be accomplished without being noticed by the user, without any commodity hardware and is relatively inexpensive.
</p>
# Approach
The DolphinAttack can be accomplished using two methods
- Tabletop Attack
- Portable Attack
## Tabletop Attack
<p align="justify">
This is the original version of the attack, carried out using custom hardware. It consists of :
</p>
- Audio signal source
- Vector signal generator
- Vifa ultrasonic speaker
<p align="justify">
The attack commands are generated using a text to speech converter on a smart phone. The audio output is given to a vector signal generator which is used to modulate the input frequency on a high frequency carrier. The signal generator can be used to sweep over a range of frquencies to find the most effective attack frequency for a given phone model and SR system. The output of the signal generator is connected to a Vifa Ultrasonic speaker which transmits the modulated commands. The attack success can be tested on different SR systems like Siri, Cortana, Google Assistant, Alexa etc on different devices like laptops and mobilephones. However, this method is expensive and space consuming.
</p>
## Portable Attack
<p align="justify">
This is the "on the go" version of the attack, used to test the feasibility of attacking the victim while on the move, walking past him/her, for example. It consists of :
</p>
- Audio signal source
- Audio Amplifier
- Ultrasonic transducer
<p align="justify">
The attack commands are generated by recording the attacker's voice on a smart phone. It is then modulated on software or the output of signal generator from the tabletop attack is stored in the smartphone. This modulated audio signal is given as the input to an audio amplifier through the phone's audio jack. The amplifier output is used to drive the ultrasonic transducer. The range of this attack is slightly limited compared to the tabletop attack but can be increased by increasing the amplifier gain.
</p>
The portable dolphin attack was chosen as the means of attack over the table top attack for two major reasons :
- Low Cost of Implementation
- Reduced Physical Intervention
<p align="justify">
According to the analysis in [1], the cost of implementing the attack through the portable mode was only a few dollars as opposed to the default table top attack which involved using the expensive ultrasonic wideband speaker Vifa and the vector signal generator.
</p>
At the receiver side, the non linearity present in the device's microphone can be modeled as
- out(t ) = A*s<sub>in</sub>(t) + B*(s<sub>in</sub><sup>2</sup>(t))
<p align="justify">
In order to utilize this non linearity to demodulate the the baseband signal, the original voice signal is amplitude modulated using the following function
</p>
- s<sub>in</sub>(t)=m(t)*c(t) + c(t), where c(t)= cos(2*pi*F<sub>c</sub>*t)
<p align="justify">
From the two equations, the signal at the receiver end contains the the intended carrier and it's sideband frequencies and also harmonics and cross products at f<sub>m</sub>, 2(f<sub>c</sub>−f<sub>m</sub>), 2(f<sub>c</sub>+f<sub>m</sub>), 2f<sub>c</sub> , 2f<sub>c</sub>+f<sub>m</sub>, and 2f<sub>c</sub>−f<sub>m</sub>. The microphone is followed by an amplifier and a low pass filter which removes all components above the audible range. However, the original signal,f<sub>m</sub>, remains within the audible range and can be successfully recognized by the speech recognition system to perform the attack.
</p>
# Method
<p align="justify">
The components that are required for carrying out the portable attack include :
</p>
- 3.5 mm Audio Jack pigtail-mono and stereo
- SparkFun Class-D audio amplifier TPA2005D1
- STM32 Nucleo Board
- Samsung S7 Edge as Attack phone
- Multiple Smartphones as Victim
- Ultrasonic transducer (UTR-1440K-TT-R)
- Battery
The Software includes
- Matlab
- Audacity
- Mbed Online Compiler
### Samsung S7 Edge
<p align="justify">
The attack requires carrier frequency - baseband frequency to be greater than 20 kHz. The minimum sampling rate should be twice this value. Most smart phones only support a maximum sampling rate of upto 48 kHz, restricting the transmitted signal to a frequency of 24 kHz. This does not give us a wide range of frequencies to work with. Fortunately, the Samsung Galaxy S7 Edge supports a sampling rate of 192 kHz and lends itself well to constructing the attack.
</p>
### Audio Amplifier
<p align="justify">
The TPA2005D1 is chosen as it is a variable gain audio amplifier meant specifically to drive transducers. The default gain value is 2 but can be increased upto 10, thereby extending the range of the portable attack.
</p>
### Ultrasonic transducer (UTR-1440K-TT-R)
<p align="justify">
The Samsung phone provides a sufficient sampling rate, however it’s speaker's output frequencies are restricted to the audio range.
Thus a narrow band transducer is utilized for transmission of the attack signal over the ultrasonic band of 40 kHz. This particular carrier is chosen as it was the most widely available as opposed to other frequencies like 23 or 25 kHz.
</p>
### Victim devices
The attack was tested on various victim phones like
- Oneplus 5
- Xiaomi Redmi Note 4
- Samsung S6 Edge
- Samsung S7 Edge
Tablet
- Nexus 7
Apple MacBook
Wearable
- Apple Watch
## Initial Attack
<p align="justify">
Input voice signals were recorded on the Samsung S7 and amplitude modulated on a 40 kHz carrier using MATLAB. Two types of modulation were performed. One, using an inbuilt amplitude modulation function on MATLAB and another using the modulation function specific to exploiting the microphone's non linearity, as explained above. Observing the frequency spectrum of the resulting modulated signals showed that the inbuilt function performed supressed carrier modulation while the custom function produces signals at the carrier frequency and two side bands. The output wave file was given as input to the audio amplifier, from the phone, through a 3.5mm stereo audio jack pigtail cable, as the phone had a stereo speaker. However, the amplifier operates on a differential input. So the left and right channels of the audio jack are combined together before connecting to the amplifier. This is powered by a 4.7V battery. The output of the audio amplifier is given as input to the ultrasonic transducer. The attack is tested on the above mentioned victim devices at varying distances and for various input commands like 'What is the temperature ?' , 'Ok Google' etc.,
</p>
<img src="Figures/Dolphin_attack.jpg" width="400" height="400"/>
<figure>
<img src="plots/5Kmonotone.png" alt='missing' />
<figcaption>Matlab Transmitter Side Analysis</figcaption>
</figure>
### Findings
<p align="justify">
We found that the original signal was not reconstructed at the receiver end as expected. Further analysis of individual components was thus required. The audio jack cable output was connected to an oscilloscope. On sweeping the frequencies given as input to the jack from the phone, over a range of 20 Hz-20 kHz, it was found that the sound was cut off at 14kHz. In order to test if this filtering was done by the phone or the audio jack, the same test was repeated using different phones to find the same effect at the same frequency. Also, it was found that the phone could play 18 kHz and possibly beyond by manual testing using commodity earphones. The stereo jack was replaced by a 3.5mm mono jack and the experiment was repeated. This jack was found to cut off frequencies below 16 kHz. A similar phenomenon was observed in Apple earphones beyond 18kHz.
</p>
The link for the audio jack testing can be found [here](https://ucla-ece209as-2018w.github.io/Aadithya-Nrithya/)
<p align="justify">
Additionally, the non linearity model for the microphone at the receiver seemed to hold for the speaker on the attack side as well. This hypothesis was tested by connecting a probe from the laptop to the oscilloscope and playing the high frequency signal. Components within the audible range were observed. This caused frequency components in the audible range that hindered the proper recognition of commands, at the receiver end.
</p>
<img src="Figures/Testing.jpg" width="400" height="400"/>
## Revised Attack
<p align="justify">
The need for the audio jack pigtail cable was eliminated using an STM32 Nucleo Development board with an Mbed OS as the source of the attack signal. The Nucleo is equipped with a 12 bit DAC, the output of which is connected to the audio amplifier and then to the transducer. The setup's viability is first tested using montone signals. Audacity was used as the tool to generate monotone sine waves. The audio signal, sampled at 96 kHz was modulated on MATLAB. The resulting wav file was converted to array of samples stored in a C file using a tool called WAVtoCode Converter. The Mbed online compiler was used for generating the binary. The generated binary was flashed in the flash memory of the Nucleo board, which outputs the data to the DAC.
</p>
<img src="Figures/Revised.jpg" width="400" height="400"/>
### Findings
<p align="justify">
The waveform of the signals at the transmitting and receiving end were generated and analysed using MATLAB and Audacity respectively. In the case of the low frequency monotones, the spectrum of the modulated signals was observed at the expected carrier frequency at the transmitter side. However, the expected harmonic on the receiver side could not be distinguished by plotting the spectrum of the signal recorded on the victim microphone. This was because of ambient noise in the range of a few hertz to almost 20 kHz.
When the frequency of the baseband signal was increased beyond the audible range, definite harmonics were observed on the receiver side
This was tested for different frequencies, receivers and at different locations and found consistent. However, the harmonics were not at the expected frequencies. Also, at 96 kHz, the reconstruction of the DAC output was not satisfactory, so that sampling rate was increased to 192 kHz. The attack did not succeed in activating the Speech Recognition Systems on the various test devices
</p>
<figure>
<img src="plots/Voice.png" alt='missing' />
<figcaption>Matlab Transmitter Side Analysis for voice </figcaption>
</figure>
<figure>
<img src="Figures/revised_receiver.PNG" alt='missing' />
</figure>
<figure>
<img src="Figures/30k_baseband.PNG" width="300" height="300" />
<figcaption> Harmonics at receiver side for 30K baseband </figcaption>
</figure>
# Analysis
<p align="justify">
The audible sounds in the speaker end while playing ultrasonic modulated signals is proof of the success of the non linearity model. The reason for the failure of the attack could be attributed to the lack of availability of the wide range of ultrasonic transducers necessary for testing the attack on different victim devices, to find the ideal attack frequency. We were limited to using a very narrow band 40kHz transducer and later a 25 kHz transducer. Thus modulation could not be done over a range of frequencies to test the one most ideal for the attack. While the DolphinAttack paper mentions the frequency bands at which the attack was successful for different devices, there is no mention of the success rate or attack effectiveness. So a device on which the attack worked for a frequency range of 23-40 kHz could have been 100% successful at one of these frequencies and the other cases could have been due to the influence of external factors.
</p>
# Future Work
<p align="justify">
Moving forward, the attack can be tested using a number of transducers over a range of ultrasonic frequencies. Defence measures such as comparing the original voice signal with the demodulated attack signal at the receiver end and using machine learning techniques such as regression or classification to predict the validity of the input command and allowing only legitimate commands to activate the system should be explored.
</p>
# Acknowledgements
<p align="justify">
We would like to thank Professor <NAME>, Mr. Moustafa and all others at NESL for their guidance and unwavering support over the course of this project.
</p>
# Reference
[1] https://www.inc.com/kevin-j-ryan/internet-trends-7-most-accurate-word-recognition-platforms.html
[2] <NAME>, et al. "Dolphin Attack: Inaudible voice commands." Proceedings of the 2017 ACM SIGSAC Conference on Computer and Communications Security. ACM, 2017.
[3] https://www.digitaltrends.com/home/amazon-echo-alexa-npr/
[4] <NAME>, et al. "Hidden Voice Commands." USENIX Security Symposium. 2016.
[5] <NAME>, et al. "Cocaine noodles: exploiting the gap between human and machine speech recognition." WOOT 15 (2015): 10-11.
[6] <NAME>, et al. "CommanderSong: A Systematic Approach for Practical Adversarial Voice Recognition." arXiv preprint arXiv:1801.08535 (2018).
[7] <NAME>, and <NAME>. "IEMI threats for information security: Remote command injection on modern smartphones." IEEE Transactions on Electromagnetic Compatibility 57.6 (2015): 1752-1755.
[8] <NAME>, <NAME>, and <NAME>. "BackDoor: Sounds that a microphone can record, but that humans can't hear." GetMobile: Mobile Computing and Communications 21.4 (2018): 25-29.
<file_sep>This folder contains samples of the WavtoCode files.
<file_sep>This folder contains all the figures for the Dolphin attack
| 8a06aa0a471ad919512eb796ada23e13811280d5 | [
"Markdown",
"Text",
"C++"
] | 6 | Text | coffeecupee/Aadithya-Nrithya | 7b517882cdabd3401a43e18eca4b8ff326ee5be2 | c80292023449536e53595a80a86f12779b0345b6 |
refs/heads/master | <repo_name>johno/ghclone<file_sep>/readme.md
# ghclone
Git clone shortcut. A bash script bundled with npm.
## Installation
```
$ npm i -g ghclone
```
## Usage
```sh
$ ghclone
GitHub clone shortcut
Usage:
$ ghclone <username>/<repo>
Example:
$ ghclone johnotander/pixyll
```
## License
MIT
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
Crafted with <3 by [<NAME>](http://johnotander.com) ([@4lpine](https://twitter.com/4lpine)).
***
> This package was initially generated with [yeoman](http://yeoman.io) and the [p generator](https://github.com/johnotander/generator-p.git).
<file_sep>/ghclone.sh
#!/usr/bin/env sh
if ! [ $1 ]; then
echo "GitHub clone shortcut\n\n"
echo "Usage:\n $ ghclone <username>/<repo>\n\n"
echo "Example:\n $ ghclone johnotander/pixyll\n"
exit 1
fi
if [ $2 ]; then
GITDIR=${2}
else
TOKENS=$(echo $1 | tr "/" "\n")
for T in $TOKENS
do
LAST_TOKEN=$T
done
GITDIR=$LAST_TOKEN
fi
git clone https://github.com/${1}.git ${GITDIR}
cd ${GITDIR}
| cb65438791cdb19b91dde54af9f8e1a20eab2221 | [
"Markdown",
"Shell"
] | 2 | Markdown | johno/ghclone | 516e5424257b753a86106deb7f3477ea24543eec | f5cd8a37f25f3436adb3a73bc289c9c69a2546fa |
refs/heads/master | <file_sep>import css from 'styled-jsx/css';
export default css`
.side-label {
position: absolute;
top: 30%;
left: 0.2em;
margin: 0;
-webkit-writing-mode: vertical-lr;
-ms-writing-mode: tb-lr;
writing-mode: vertical-lr;
text-orientation: sideways;
text-transform: uppercase;
letter-spacing: 0.15em;
font-size: 0.7em;
text-shadow: 0 0 2px black;
color: rgba(255, 255, 255, 0.3);
}
`;
<file_sep>import React, { Component, Fragment } from 'react';
import Head from 'next/head';
import QRCode from 'qrcode.react';
import Layout from '../layout/layout';
const style = {
root: {
height: '100%',
margin: '0 auto',
display: 'flex',
textAlign: 'center',
color: 'white',
alignItems: 'center',
justifyItems: 'center',
},
qr: {
maxWidth: '100%',
backgroundColor: 'white',
padding: '1.5em',
},
};
class Index extends Component {
state = { url: null };
componentDidMount() {
this.setState({ url: `${window.location.href}sender` });
}
render() {
return (
<Layout title="Enter the matrix" forceLandscape={false}>
{this.state.url && (
<a href="/sender"style={style.root}>
<QRCode
style={style.qr}
value={this.state.url}
renderAs="svg"
size={'30em'}
/>
</a>
)}
</Layout>
);
}
}
export default Index;
<file_sep>import React, { Component, Fragment } from 'react';
import Layout from '../layout/layout';
import io from 'socket.io-client';
import styles from './sender.css.js'
class Sender extends Component {
state = {
controls: null,
};
componentDidMount() {
this.socket = io();
this.socket.on('controls', controls => this.setState({ controls }));
}
emit = (message) => () => {
console.log('outgoing:', message);
this.socket.emit('sender', message);
};
controlImage = ({ icon, value, max, min }) => (
<img
style={{
width: '100%',
transition: 'all .2s ease',
transform: `scale(${((value - min) / (max - min) * 0.9) + 0.1})`
}}
src={`/static/${icon}.svg`}
alt={icon}
/>
);
render() {
const { controls } = this.state;
controls && console.log(controls.map(c => c.value));
return (
<Layout title="Interactive performance">
<div className="sender">
<div className="controls">
{!controls
? <div className="loading">Matrix Operator's Internet of Synths is loading...</div>
: controls.map((control, i) => (
<div key={i} className="control">
<div className="value">{this.controlImage(control)}</div>
<div className="buttons">
<button onClick={this.emit({ control: i, type: '-' })}><div className={`operator minus minus-${control.icon}`} /></button>
<button onClick={this.emit({ control: i, type: '+' })}><div className={`operator plus plus-${control.icon}`} /></button>
</div>
</div>
))
}
</div>
</div>
<style jsx>{styles}</style>
</Layout>
);
}
}
export default Sender;
<file_sep>import css from 'styled-jsx/css';
export default css`
.loading {
text-align: center;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.sender {
display: flex;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
}
.controls {
display: flex;
flex-direction: column;
width: 60%;
height: 75%;
background: linear-gradient(rgba(43, 43, 50, 0.95), rgba(28, 28, 31, 0.95));
border: 1.5px solid rgba(0, 0, 0, 0.7);
border-radius: 10em;
padding: 2.5em 1.5em 4em 1.5em;
}
.control {
flex: 1;
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: center;
padding-bottom: 1em;
border-bottom: 2px solid black;
margin-bottom: 1em;
height: 50%;
}
.control:last-child {
border-bottom: none;
margin-bottom: 0;
padding-bottom: 0;
}
.value {
height: 42%;
width: 42%;
padding: 0.3em;
display: flex;
align-self: center;
}
.buttons {
flex: 1;
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
width: 100%;
height: 80%;
}
button {
width: 40%;
height: 100%;
margin: 0.1em;
background-image: url("/static/button.png");
background-color: transparent;
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
border: 0;
}
button:active {
background-image: url("/static/button-click.png");
}
.operator {
margin: 0 auto;
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
width: 60%;
height: 60%;
}
.minus {
background-image: url("/static/minus.svg");
}
.minus-circle:active {
background-image: url("/static/minus-circle.svg");
}
.minus-hexagon:active {
background-image: url("/static/minus-hexagon.svg");
}
.plus {
background-image: url("/static/plus.svg");
}
.plus-circle:active {
background-image: url("/static/plus-circle.svg");
}
.plus-hexagon:active {
background-image: url("/static/plus-hexagon.svg");
}
`;
<file_sep>const express = require('express');
const next = require('next');
const http = require('http');
const socket = require('socket.io');
let controls = require('./config').map(control => ({ ...control, value: control.min }));
const port = parseInt(process.env.PORT, 10) || 3000;
const nextApp = next({ dev: process.env.NODE_ENV !== 'production' });
const nextRequestHandler = nextApp.getRequestHandler();
const updateValue = (control, type) => {
const operations = {
'+': v => v + control.increment,
'-': v => v - control.increment,
default: v => v,
};
const newValue = (operations[type] || operations.default)(control.value);
return newValue >= control.min && newValue <= control.max
? newValue
: control.value;
};
const handleSender = ({ control: controlIndex, type }) => controls.map((currentControl, index) =>
index === controlIndex
? { ...currentControl, value: updateValue(currentControl, type) }
: currentControl
);
let latestUpdate = new Date();
nextApp.prepare().then(() => {
const app = express();
const httpServer = http.Server(app);
const io = socket(httpServer);
app.get('*', (req, res) => {
return nextRequestHandler(req, res);
});
io.on('connection', function (socket) {
console.log('a user connected');
socket.emit('controls', controls);
socket.on('sender', function (msg) {
console.log('message:', msg);
controls = handleSender(msg);
socket.emit('controls', controls);
const now = new Date();
if(now - latestUpdate >= 200) {
socket.broadcast.emit('controls', controls);
latestUpdate = now;
}
});
});
httpServer.listen(port, '0.0.0.0', err => {
if (err) { throw err }
console.log(`> Ready on http://localhost:${port}`);
});
}).catch(console.error);
<file_sep>import Head from 'next/head';
import './normalize.css';
import styles from './layout.css.js'
export default ({ children, title = 'Default title', forceLandscape = true }) => (
<>
<Head>
<title>{title}</title>
<meta charSet='utf-8' />
<meta name='viewport' content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<meta name="theme-color" content="#1c1c1f" />
</Head>
<style jsx global>{`
body:before {
content: "";
display: block;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: -10;
// background: url(photos/2452.jpg) no-repeat center center;
background: #1c1c1f url("/static/background.png") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
body {
touch-action: manipulation;
color: white;
width: 100%;
height: 100%;
margin: 0;
font-family: monospace;
font-size: 1.3rem;
}
*:focus {
outline: 0 !important;
}
#__next, #content {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
position: absolute;
}
#orientation {
display: none;
width: 100%;
height: 100%;
align-self: center;
margin: 0 auto;
font-size: 3em;
align-items: center;
justify-content: center;
}
@media only screen and (orientation:portrait) {
#content { display: flex; }
#orientation { display: none; }
}
@media only screen and (orientation:landscape) {
#content { display: ${forceLandscape ? 'none' : 'flex'}; }
#orientation { display: ${forceLandscape ? 'flex' : 'none'}; }
}
#preload {
display: none;
}
`}</style>
<div id="preload">
<img src="/static/circle.svg" />
<img src="/static/hexagon.svg" />
<img src="/static/button.png" />
<img src="/static/button-click.png" />
<img src="/static/minus.svg" />
<img src="/static/minus-circle.svg" />
<img src="/static/minus-hexagon.svg" />
<img src="/static/plus.svg" />
<img src="/static/plus-circle.svg" />
<img src="/static/plus-hexagon.svg" />
</div>
<div id="orientation">
<img src="/static/rotate.gif" alt="rotate your device" />
</div>
<div id="content">
<p className="side-label">Internet of Synths - Matrix Operator</p>
{children}
</div>
<style jsx>{styles}</style>
</>
);
| 7c48885f3270450ecad7009884b31cb443286187 | [
"JavaScript"
] | 6 | JavaScript | Xpktro/hackop2 | b50df99ddf622bb4cef45f30403aeed2d527da87 | 4508851fd3c18de796b5617df3d7fcd18598bf3a |
refs/heads/master | <file_sep>const mongoose = require('mongoose');
const validator = require('validator'); //isEmail
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const bcrypt = require('bcryptjs');
// {
// email: '<EMAIL>',
// password: '<PASSWORD>',
// tokens: [{
// access: 'auth', //emai,resettingpasswordd
// token: '<KEY>'
// }]
// }
//User Mongoose model
//schema, so we can add a method in a model
var UserSchema = new mongoose.Schema({
email: {
required: true,
type: String,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: '{value} is not a valid email'
}
},
password: {
type: String,
required: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
//LIMIT WHAT TO RETURN WHEN RES.SEND()
UserSchema.methods.toJSON = function () {
var user = this;
var userObject = user.toObject();
return _.pick(userObject, ['_id', 'email']);
};
UserSchema.methods.generateAuthToken = function() {
var user = this;
var access = 'auth';
var token = jwt.sign({_id: user._id.toHexString(), access}, process.env.JWT_SECRET).toString();
// user.tokens.push({access, token});
user.tokens = user.tokens.concat([{access, token}]);//add array
return user.save().then(() =>{ // return to server as then
return token; //return so i could use $token to chain this with another then() which in this case will be called in the server because of the return above
});
};
UserSchema.methods.removeToken = function(token) {
var user = this;
return user.update({
$pull: {
tokens: {token}
}
});
};
//.static model method while .methods - instance method
//model method
// User.findByToken
//instance method
// user.generateAuthToken
UserSchema.statics.findByToken = function(token) {
var User = this;
var decoded;
try{
decoded = jwt.verify(token, process.env.JWT_SECRET);
} catch (e){
// return new Promise((resolve, reject)=> {
// reject();
// });
// OR SIMPLY
return Promise.reject();
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
'tokens.access': 'auth'
}); //return so we could chain result in authenticate.js
};
UserSchema.statics.findByCredentials = function(email,password) {
var User = this;
return User.findOne({email}).then((user) =>{
if(!user){
return Promise.reject();
}
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, res) => {
if(res){
resolve(user);
} else{
reject();
}
});
});
})
}
//before 'save' saving to user db
UserSchema.pre('save', function(next) {
var user = this;
if(user.isModified('password')){
bcrypt.genSalt(10, (err,salt) => {
bcrypt.hash(user.password, salt, (err,hash) => {
user.password = hash;
next();
});
});
} else{
next();
}
});
var User = mongoose.model('User', UserSchema);
module.exports = {User}; | ba2fb3dbd8da135da174a1045f62e68ef71dc9ea | [
"JavaScript"
] | 1 | JavaScript | arvinlorenz/node-course-2-todo-api | f8d646f318d8d6c5fbf99b791d58ed8156c115b2 | d27895f1baff25874f2c0cdfab8bea466bf6f3f6 |
refs/heads/master | <file_sep># Fashion Store
Barebones online store that offers the customer the ability to add items to a shopping cart, keeping track of the total balance so far and also applying discount vouchers.
Once the user adds/removes an item from the shoppingCart, the balance and number of items in the cart updates automatically.
The app warn the user when an item is out of stock and the item can no longer be added to the shopping cart.
There are three vouchers that can be applied, two of them with specific rules. The vouchers will not be applied if the rules are not met.
Also, only one voucher can be applied.
### Approach
For the sake of simplicity, the app works from the browser and it has a simple Node server used to serve the main page and load the JSON file containing the store date. Using a Node server has the added benefit that it makes the use of template engines possible and hence greatly reduces the amount of HTML coding I needed to do. In this case I used Jade to render the data from the JSON file.
The main functionality is built in JavaScript. The behavior of the ShoppingCart is tested using Jasmine. I used the Red-Green-Refactor cycle to develop it.
The layout is based on Bootstrap with modifications.
### Technologies
* Javascript
* Bootstrap
* JSON
* Node.js with Express
* Jade
* Jasmine
### Project structure
server.js is the starting point for the Node server and it loads the jade files from the views folder and renders them.
The spec folder contains the Jasmine test file for the Shopping Cart.
The public folder is where the ShoppingCart and Voucher models live, in addition to vendor libraries and the JSON file.
main.js is JQuery code that binds the Model with the View.
### Run
Make sure you have node installed. Run
npm install
to install all dependencies and then simply run
node server.js
in the root of the project directory.
Point your browser to http://localhost:3000
### Run tests
open SpecRunner.html
<file_sep>function Voucher(amount){
this.amount = amount;
};
| 8912541dee4fa14cfd7ac17cf3de9c8decb35a10 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | hasulica/fashion-store | b9339178774c6e4a644585d50bc0e62e7ff16fd8 | fdaf02a2fabed2f077bea83a96d58764d607ad07 |
refs/heads/master | <file_sep>#!/usr/bin/python
#import xml.etree.ElementTree as ET
from xml.dom import minidom
from xml.etree import ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
import time
import sys
import re
import netaddr
import fileinput
import hashlib
import shutil
import json
from pprint import pprint
from jnpr.junos import Device
import getpass
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
feed_location='/var/www/'
temp_location='/var/tmp/'
def prettify(elem):
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
def modify_file(file_name,pattern,value=""):
fh=fileinput.input(file_name,inplace=True)
for line in fh:
replacement=line + value
line=re.sub(pattern,replacement,line)
sys.stdout.write(line)
fh.close()
def delete_line(pattern):
readFile = open(tempFeed,'r')
lines = readFile.readlines()
readFile.close()
writeFile = open(tempFeed,'w')
for line in lines:
if line != pattern+"\n":
#print "Not found--->" + line
writeFile.write(line)
writeFile.close()
def update_manifest(feedname):
ts = int(time.time())
print "Modifying total number of objects for -> " + feedname
with open(tempFeed,'r') as feed:
count = sum(1 for line in feed) - 5
print "Revised address count of -> " + str(count) + "\n"
feed.close()
tree = ET.parse(tempManifest)
root = tree.getroot()
for feed in root.iter('feed'):
name = feed.get('name')
#print name
if name == str(feedname):
feed.set('data_ts',str(ts))
feed.set('objects',str(count))
tree.write(tempManifest)
def create_manifest_entry(feedname):
ts = str(int(time.time()))
print "Inserting new feed into manifest file located at " + feed_location
tree = ET.parse(tempManifest)
root = tree.getroot()
category = root.find('category')
feed = ET.SubElement(category,'feed',dict(data_ts=ts, name=feedname, objects="0", options="", types="ip_addr ip_range", version=feedname))
data = ET.SubElement(feed,'data')
url = ET.SubElement(data,'url')
url.text='/'
text=(prettify(root))
cleantext= "".join([s for s in text.strip().splitlines(True) if s.strip()])
with open(tempManifest,'w') as file:
file.write(cleantext)
def copy_feed_to_tempFeed():
shutil.copyfile(feed,tempFeed)
readFile = open(tempFeed)
lines = readFile.readlines()
readFile.close()
writeFile = open(tempFeed,'w')
writeFile.writelines([item for item in lines[:-1]])
writeFile.close()
def copy_tempFeed_to_feed():
shutil.copyfile(tempFeed,feed)
def copy_tempManifest_to_Manifest():
shutil.copyfile(tempManifest,manifest)
def copy_Manifest_to_tempManifest():
shutil.copyfile(manifest,tempManifest)
def create_newFeed(name):
shutil.copyfile('Feed',name)
def calculate_md5():
with open(tempFeed) as file:
data = file.read()
md5_returned = hashlib.md5(data).hexdigest()
file.close()
writeFile = open(tempFeed,'a')
writeFile.write(md5_returned)
writeFile.close()
if (sys.argv[1]=='add'):
feed=feed_location + str(sys.argv[2])
tempFeed=temp_location + str(sys.argv[2])
manifest=feed_location+'manifest.xml'
tempManifest=temp_location+'manifest.xml'
copy_feed_to_tempFeed()
copy_Manifest_to_tempManifest()
ip = netaddr.IPNetwork(sys.argv[3])
feedname = sys.argv[2]
address = ip.ip
size = ip.size
adj_size = size -1
value = ip.value
print "\nAdding address of -> " + str(sys.argv[3]) +" (including " + str(adj_size) + " subequent hosts)"
if adj_size == 0:
newentry = '{"1":' + str(value) +'}'
else:
newentry = '{"2":[' + str(value) + ',' + str(adj_size) +']}'
#print newentry
modify_file(tempFeed,'#add',newentry)
calculate_md5()
update_manifest(feedname)
copy_tempFeed_to_feed()
copy_tempManifest_to_Manifest()
if sys.argv[1]=='del':
feed=feed_location + str(sys.argv[2])
tempFeed=temp_location + str(sys.argv[2])
manifest=feed_location+'manifest.xml'
tempManifest=temp_location+'manifest.xml'
copy_feed_to_tempFeed()
copy_Manifest_to_tempManifest()
ip = netaddr.IPNetwork(sys.argv[3])
feedname = sys.argv[2]
address = ip.ip
size = ip.size
adj_size = size -1
value = ip.value
print "\nRemoving address of -> " + str(sys.argv[3]) +" (including " + str(adj_size) + " subequent hosts)"
if adj_size == 0:
oldline = '{"1":' + str(value) +'}'
else:
oldline = '{"2":[' + str(value) + ',' + str(adj_size) +']}'
delete_line(oldline)
modify_file(tempFeed,'#del',oldline)
calculate_md5()
update_manifest(feedname)
copy_tempFeed_to_feed()
copy_tempManifest_to_Manifest()
if sys.argv[1]=='list':
feed=feed_location + str(sys.argv[2])
pattern_network = '{"(\d+)":\[\d+,\d+\]}'
pattern_host = '{"(\d+)":\d+}'
pattern_ip_network = '{"\d+":\[(\d+),\d+]}'
pattern_ip_host = '{"\d+":(\d+)}'
pattern_range = '\d+":\[\d+,(\d+)]}'
with open(feed,'r') as file:
lines = file.readlines()
for line in lines:
host = re.search(pattern_host,line)
network = re.search(pattern_network,line)
if host:
ip = str(netaddr.IPAddress(re.findall(pattern_ip_host,line)[0]))
print "Host entry: " + ip
elif network:
#ip = re.findall(pattern_ip_network,line)[0]
ip = str(netaddr.IPAddress(re.findall(pattern_ip_network,line)[0]))
range = re.findall(pattern_range,line)[0]
print "Network Entry: " + ip + " (+" + range + " hosts)"
if sys.argv[1]=='new':
name = str(sys.argv[2])
feed=feed_location + str(sys.argv[2])
manifest=feed_location+'manifest.xml'
tempManifest=temp_location+'manifest.xml'
copy_Manifest_to_tempManifest()
print name
create_newFeed(feed)
create_manifest_entry(name)
copy_tempManifest_to_Manifest()
#print "Completed, add the following line to your SRX to accept feed:\n set security dynamic-address address-name "+name+ " profile category IPFilter feed "+name
username = raw_input("Please enter your SRX Username:")
password = getpass.getpass()
srx_list = 'srx-list'
srxs = open(srx_list,'r')
for srx in srxs:
print "Logging into SRX "+srx
login=str(srx)
dev = Device(host=login,user=username,password=<PASSWORD>)
dev.open()
dev.timeout = 300
cu = Config(dev)
set_cmd = 'set security dynamic-address address-name '+name+' profile category IPFilter feed '+name
cu.load(set_cmd, format='set')
print "Applying changes, please wait...."
cu.commit()
dev.close()
if sys.argv[1]=='drop':
name = feed_location + str(sys.argv[2])
print name
print "do this next...."
if sys.argv[1]=='setup':
print "Kick off initial setup process, copy files to target directories etc"
<file_sep># dynamic-policy - Dynamic creation of SRX address entries
The SRX firewall can be configured to monitor a central web server for a list of IP Addresses to create a dynamic address book using the```security-intelligence```feature-set.
This software will need to be installed on an existing web-server and the python file modified to point to the correct base directory of the web-server. Clone all files and copy the schema.xml and manifest.xml file to the base of the web server.
Configure the SRX security-intelligence module to point to you web server - the auth-token is required to commit (32 ascii chars), but is only used by Junos Space to authenticate the device:
```
set services security-intelligence url http://192.168.1.1/manifest.xml
set services security-intelligence authentication auth-token <PASSWORD>
```
The```manifest.xml```file provides a list of available "feeds" of IP addresses eg:
```
<manifest version="3540642feac48e76af183a6e79d55404">
<category description="Customer category IPFilter" name="IPFilter" options="" ttl="2592000" update_interval="1">
<config version="398490f188">
<url>/schema.xml</url>
</config>
<feed data_ts="1428558808" name="BADSITES" objects="36" options="" types="ip_addr ip_range" version="BADSITES">
<data>
<url>/</url>
</data>
</feed>
</category>
</manifest>
```
The SRX will refresh```manifest.xml``` every```update_interval```seconds, as specified in the manifest.
A feed is essentially a list of IPs that have some common purpose eg: a blacklist, whitelist, prefixes that identify a cloud provider etc.
Addresses are grouped into feeds and stored in independent feed files.
Within the SRX, a dynamic-address is created as follows:
```set security dynamic-address address-name MY-BLACKLIST profile category IPFilter feed BADSITES```
The SRX then consults the```manifest.xml```file for a feed named BADSITES, downloads it from the web server and then installs it into the dynamic-address entry.
The SRX will now consult the feed every update interval and dynamically add or remove addresses as they are available, all without requiring a configuration change.
**NOTE:** As of this writing this has been tested on Junos 12.3X48D10 and 15.1X49-D110 code releases, dynamic-address entries can only be used in security policies; NAT rules only consult the global and zone-based address-books for address entries.
# Usage
**Create a new feed**
```
dynamic-policy.py new MYFEED
```
**Add an address to a feed**
```
dynamic-policy.py add MYFEED 192.168.88.0/24
```
**Remove an address from a feed**
```
dynamic-policy.py del MYFEED 192.168.88.0/24
```
| db7cd0486eaf60890499393529529661a32c25f1 | [
"Markdown",
"Python"
] | 2 | Python | kenokelly/dynamic-address | 23b56cd7e5d15756feddc281ddd451ec3f546f57 | 015ee1121db89e2ee92f3b2980aeac776789b668 |
refs/heads/main | <repo_name>B-Kwapisz/Flowershop<file_sep>/setup/tables/basket-sqlite.sql
create table basket (
id integer primary key not null,
member_id integer not null,
made_on datetime not null,
foreign key(member_id) references member(id)
)
<file_sep>/include/smarty.php
<?php
require_once(__DIR__ . "/libs/Smarty.class.php");
$smarty = new Smarty();
$smarty->template_dir = realpath(__DIR__ . "/../templates");
$smarty->compile_dir = realpath(__DIR__ . "/../app/cache");
$smarty->addPluginsDir(__DIR__ . '/myplugins');
require_once __DIR__ . "/session.php";
$smarty->assign('session', new Session());
<file_sep>/setOrderField.php
<?php
/*
* <NAME>
* <EMAIL>
*/
require_once "include/session.php";
$table = filter_input(INPUT_GET, 'field');
$session->order[$session->display] = $field;
header("location: .");
<file_sep>/setup/createTables.php
<?php
chdir(__DIR__);
require_once '../include/db.php';
echo "\n---- database = ", DBProps::which, "\n\n";
foreach (["item", "basket", "member", "flower"] as $table) {
$sql = "drop table if exists $table";
echo "$sql\n";
R::exec($sql);
}
foreach (["flower", "member", "basket", "item"] as $table) {
$filename = sprintf("%s-%s.sql", $table, DBProps::which);
$sql = file_get_contents("tables/$filename");
echo "$sql\n";
R::exec($sql);
}
<file_sep>/setup/makeTables.php
<pre>
<?php
echo "\n============= createTables\n";
require_once "createTables.php";
echo "\n============= populateTables\n";
require_once "populateTables.php";
<file_sep>/setDisplayTable.php
<?php
/*
* <NAME>
* <EMAIL>
*/
require_once "include/session.php";
$table = filter_input(INPUT_GET, 'table');
$session->display = $table;
header("location: .");<file_sep>/flower-page.php
<?php
/*
* <NAME>
* <EMAIL>
*/
require_once "include/smarty.php";
require_once "include/db.php";
$orderField = filter_input(INPUT_GET, 'orderField');
if (is_null($orderField)) {
$orderField = "name";
}
$flowers_per_page = 10;
$page = filter_input(INPUT_GET, 'page');
if (is_null($page)) {
$page = 1;
}
$offset = ($page-1) * $flowers_per_page;
$flower = R::findAll('flower',
"order by {$session->order['flower']} limit $offset,$flowers_per_page"
);
$num_pages = ceil( R::count('flower')/$flower_per_page );
$data = [
'flower' => $flower,
'page' => $page,
'num_pages' => $num_pages,
];
$smarty->assign($data);
$smarty->display("flower-page.tpl");<file_sep>/flowers.php
<?php
/*
* <NAME>
* <EMAIL>
*/
require_once "include/smarty.php";
require_once "include/db.php";
$books = R::findAll('flower', "order by {$session->order['name']}");
$data = [
'flower' => $flower,
];
$smarty->assign($data);
$smarty->display("flower.tpl");<file_sep>/setup/tables/item-mysql.sql
create table item (
id integer auto_increment primary key not null,
flower_id integer not null,
basket_id integer not null,
quantity integer not null default 0,
price real not null default 0,
foreign key(flower_id) references flower(id),
foreign key(basket_id) references basket(id),
unique(basket_id,flower_id)
)
<file_sep>/setup/tables/flower-sqlite.sql
create table flower (
id integer primary key not null,
name text unique not null collate nocase,
price real,
description text,
imagefile text,
instock integer not null
)
<file_sep>/index.php
<?php
require_once "include/session.php";
require_once "include/smarty.php";
require_once "include/db.php";
if(is_null($session->order) || is_null($session->display)){
$session->order = ['flower'=>'name'];
$session->display = 'flower';
}
$view_script = [
"flower" => "flower-page.php",
"member" => "member.php",
];
$target_script = $view_script[$session->display];
require_once($target_script);
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
$flower = R::find('flower');
$data = [
'page_title' => 'Home',
'flower' => $flower,
];
$smarty->assign($data);
$smarty->display("index.tpl");
<file_sep>/include/myplugins/function.flash_get.php
<?php
/*
retrieve and clear the value of a session key.
only works if the value is scalar
*/
function smarty_function_flash_get($params, &$smarty) {
require_once __DIR__ . "/../session.php";
$session = new Session();
$key = $params['key'];
$value = $session->$key;
unset($session->$key);
return $value;
}
<file_sep>/cart.php
<?php
require_once "include/smarty.php";
require_once "include/db.php";
require_once "include/session.php";
if (!isset($session->cart)) {
$session->cart = [];
}
$cart_data = [];
$total_price = 0;
/*
process $session->cart, storing information into $cart_data
*/
// here's some fake data to give you an idea
$cart_data = [
1 => [ 'name' => '<NAME>', 'price' => 8.00, 'quantity' => 50],
];
$data = [
'cart_data' => $cart_data,
'total_price' => $total_price,
];
$smarty->assign($data);
$smarty->display("cart.tpl");
<file_sep>/setup/tables/basket-mysql.sql
create table basket (
id integer auto_increment primary key not null,
member_id int not null,
made_on datetime not null,
foreign key(member_id) references member(id)
)
<file_sep>/showFlower.php
<?php
require_once "include/session.php";
require_once "include/db.php";
require_once "include/smarty.php";
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
$flower_id = filter_input(INPUT_GET, 'flower_id');
$flower = R::load('flower', $flower_id);
$data = [
'flower' => $flower,
];
$smarty->assign($data);
$smarty->display("showFlower.tpl");
<file_sep>/include/helper.php
<?php
class Helper {
static function reformat($time) {
return implode("@", explode(' ',$time));
}
}<file_sep>/sample.php
<?php
require_once "include/smarty.php";
$data = [
];
$smarty->assign($data);
$smarty->display("sample.tpl");
<file_sep>/setup/tables/flower-mysql.sql
create table flower (
id int auto_increment primary key not null,
name varchar(255) unique not null,
price real,
description text,
imagefile varchar(255),
instock int not null
)
<file_sep>/setup/populateTables.php
<?php
chdir(__DIR__);
require_once "../include/db.php";
echo "\n---- database = ", DBProps::which, "\n";
define('USER', 'member');
// name, email, password, for simplicity password = name
$user_data = [
["john", "<EMAIL>", "john"],
["kirsten", "<EMAIL>", "kirsten"],
["bill", "<EMAIL>", "bill"],
["mary", "<EMAIL>", "mary"],
["joan", "<EMAIL>", "joan"],
["alice", "<EMAIL>", "alice"],
["carla", "<EMAIL>", "carla"],
["dave", "<EMAIL>", "dave"],
];
R::begin(); // begin transaction
echo "\n---- " . USER . "s\n";
foreach ($user_data as $data) {
list($username, $email, $password) = $data;
$user = R::dispense(USER);
$user->name = $username;
$user->email = $email;
$user->password = <PASSWORD>('<PASSWORD>', $<PASSWORD>);
try {
$id = R::store($user);
echo USER . " $id: $username\n";
}
catch (Exception $ex) {
echo $ex->getMessage(), "\n";
}
}
// Admins: choose a few selected ones
echo "\n---- admins\n";
foreach (['dave', 'carla'] as $name) {
$user = R::findOne(USER, 'name = ?', [$name]);
$user->is_admin = true;
R::store($user);
echo "admin: $name\n";
}
R::commit(); // commit transaction
echo "\n---- flowers\n";
R::begin();
$flower = R::dispense('flower');
$flower->name = "Missouri Evening Primrose";
$flower->imagefile = "MissouriEveningPrimrose.jpg";
//$flower->price = 7.99;
$flower->price = 8.00;
$flower->instock = 70;
$flower->description = <<<END
Let the sweet scent of Missouri Evening Primrose grace your garden,
while you enjoy its bright yellow blooms all summer long!
Very resilient. Will perform even in poor soil and drought conditions.
END;
$id = R::store($flower);
echo "flower #$id: $flower->name\n";
$flower = R::dispense('flower');
$flower->name = "Mixed Liatris";
$flower->imagefile = "MixedLiatris.jpg";
$flower->price = 1.19;
$flower->instock = 80;
$flower->description = <<<END
Unique perennial adds interest to sun areas with stunning, stiff bottlebrush
of dense white and purple flowers and fine, grasslike foliage! An excellent
addition to cut flower arrangements, Mixed Liatris has a long vase life
and captivates passersby when grown out in the garden.
END;
$id = R::store($flower);
echo "flower #$id: $flower->name\n";
$flower = R::dispense('flower');
$flower->name = "Commander in Chief Lily";
$flower->imagefile = "CommanderInChiefLily.jpg";
$flower->price = 2.65;
$flower->instock = 90;
$flower->description = <<<END
This Asiatic lily produces an abundance of large, 6-8" blooms of shimmering,
scarlet-red atop 3-4' tall plants. This stunner grows almost anywhere in
zones 3 to 9 in full sun to partial shade. You'll adore these blooms,
but deer won't; they tend to avoid it.
END;
$id = R::store($flower);
echo "flower #$id: $flower->name\n";
$flower = R::dispense('flower');
$flower->name = "<NAME>";
$flower->imagefile = "AlaskaShastaDaisy.jpg";
$flower->price = 3.33;
$flower->instock = 60;
$flower->description = <<<END
No garden should be without this classic flower! This longlived perennial requires
little care and delivers masses of frilly, double blooms with yellow centers.
Butterflies love them!
END;
$id = R::store($flower);
echo "flower #$id: $flower->name\n";
$flower = R::dispense('flower');
$flower->name = "Orange Glory Flower";
$flower->imagefile = "OrangeGloryFlower.jpg";
$flower->price = 4.69;
$flower->instock = 85;
$flower->description = <<<END
If you like to watch beautiful butterflies, then you'll love Orange Glory Flower.
It's one of their favorites! These eye-catching blooms look like a fiery floral
sunset in the garden, creating a lasting statement all season long.
END;
$id = R::store($flower);
echo "flower #$id: $flower->name\n";
$flower = R::dispense('flower');
$flower->name = "Peruvian Daffodil";
$flower->imagefile = "PeruvianDaffodil.jpg";
$flower->price = 4.15;
$flower->instock = 75;
$flower->description = <<<END
Large, trumpet-shaped flower heads unfurl to show off their exotic look and
intense fragrance. A delicately fringed trumpet atop amaryllis-like foliage
provides an attractive accent for this daffodil look-alike.
END;
$id = R::store($flower);
echo "flower #$id: $flower->name\n";
$flower = R::dispense('flower');
$flower->name = "Red Spider Lily";
$flower->imagefile = "RedSpiderLily.jpg";
$flower->price = 4.25;
$flower->instock = 120;
$flower->description = <<<END
Multi-flowering, bright red flowers make a dramatic statement! Strap-shaped
green foliage disappears in July in preparation for the flower spike bursting
forth in August. Grow in cool greenhouses or outdoors in warmer areas where
little or no frost is experienced. Apply winter cover in zones lower than 7.
END;
$id = R::store($flower);
echo "flower #$id: $flower->name\n";
$flower = R::dispense('flower');
$flower->name = "<NAME>";
$flower->imagefile = "SweetWilliam.jpg";
$flower->price = 3.33;
$flower->instock = 85;
$flower->description = <<<END
One sniff of its clusters of small blooms will tell you why this perennial
is so popular! An old-fashioned favorite, it grows fast and brings early-season
color and fragrance to your borders and rock gardens.
END;
$id = R::store($flower);
echo "flower #$id: $flower->name\n";
R::commit(); // commit transaction
function NdaysBefore($n) {
return time() - 24 * 3600 * $n - rand(0,3*3600);
}
foreach (range(1,8) as $i) {
$flower[$i] = R::load('flower', $i);
}
echo "\n---- orders\n";
R::begin();
$basket = R::dispense('basket');
$basket->member_id = 5;
$basket->made_on = date("Y-m-d H:i:s", NdaysBefore(8));
$basket->link('item', ['quantity' => 22, 'price' => $flower[4]->price ]
)->flower = $flower[4];
$basket->link('item', ['quantity' => 33, 'price' => $flower[7]->price ]
)->flower = $flower[7];
$basket->link('item', ['quantity' => 11, 'price' => $flower[2]->price ]
)->flower = $flower[2];
$order_id = R::store($basket);
echo "order #$order_id made by {$basket->member->name} on {$basket->made_on}\n";
$basket = R::dispense('basket');
$basket->member_id = 6;
$basket->made_on = date("Y-m-d H:i:s", NdaysBefore(4));
$basket->link('item', ['quantity' => 22, 'price' => $flower[3]->price ]
)->flower = $flower[3];
$basket->link('item', ['quantity' => 33, 'price' => $flower[2]->price ]
)->flower = $flower[2];
$basket->link('item', ['quantity' => 11, 'price' => $flower[5]->price ]
)->flower = $flower[5];
$order_id = R::store($basket);
echo "order #$order_id made by {$basket->member->name} on {$basket->made_on}\n";
$basket = R::dispense('basket');
$basket->member_id = 5;
$basket->made_on = date("Y-m-d H:i:s", time()); // now
$basket->link('item', ['quantity' => 15, 'price' => $flower[1]->price ]
)->flower = $flower[1];
$basket->link('item', ['quantity' => 70, 'price' => $flower[8]->price ]
)->flower = $flower[8];
$order_id = R::store($basket);
echo "order #$order_id made by {$basket->member->name} on {$basket->made_on}\n";
R::commit(); // commit transaction
<file_sep>/README.md
"# Flowershop"
| c57de6f1cbf011c56820f30bb97de28df5c3e516 | [
"Markdown",
"SQL",
"PHP"
] | 20 | SQL | B-Kwapisz/Flowershop | c1dd4300c3aa3f34305658820bfda0ca45fded67 | 41ed149647707b5547cb00e3015d2e997f57e455 |
refs/heads/master | <file_sep># Drivers for JavaScript Gremlin Language library
This module contains additional drivers for [official gremlin library](https://www.npmjs.com/package/gremlin)
Implemented drivers:
| Name | Description |
|--------|---------------|
| WsJsDriverRemoteConnection | Websocket connection for Web applications |
### How to use it
Install package using npm
```shell script
npm install gremlin-js-driver --save
```
or yarn
```shell script
yarn add gremlin-js-driver
```
Use it in your application:
```javascript
const gremlin = require('gremlin');
const gremlin_drivers = require('gremlin-js-driver');
const traversal = gremlin.process.AnonymousTraversalSource.traversal;
const WsJsDriverRemoteConnection = gremlin_drivers.WsJsDriverRemoteConnection;
const g = traversal().withRemote(new WsJsDriverRemoteConnection('ws://localhost:8182/gremlin'));
```
Please see the [documentation for `gremlin` library](https://www.npmjs.com/package/gremlin) for more information.<file_sep>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* @author <NAME>
*/
'use strict';
const Connection = require('./connection');
const Client = require('gremlin/lib/driver/client');
/**
* A {@link Client} contains methods to send messages to a Gremlin Server.
*/
class WsJsClient extends Client {
constructor(url, options) {
options = options || {};
let isConnectOnStartUp = options.connectOnStartup || true;
options.connectOnStartup = false;
super(url, options);
options.connectOnStartup = isConnectOnStartUp;
this._connection = new Connection(url, options);
}
}
module.exports = WsJsClient;
<file_sep>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* @author <NAME>
*/
'use strict';
const DriverRemoteConnection = require('gremlin/lib/driver/driver-remote-connection');
const WsJsClient = require('./client');
/**
* Represents the default {@link RemoteConnection} implementation.
*/
class WsJsDriverRemoteConnection extends DriverRemoteConnection {
/**
* Creates a new instance of {@link DriverRemoteConnection}.
* @param {String} url The resource uri.
* @param {Object} [options] The connection options.
* @param {GraphSONReader} [options.reader] The reader to use.
* @param {String} [options.traversalSource] The traversal source. Defaults to: 'g'.
* @param {GraphSONWriter} [options.writer] The writer to use.
* @param {Authenticator} [options.authenticator] The authentication handler to use.
* @param {Array} [options.protocols] List of sub-protocols for websocket
* @constructor
*/
constructor(url, options) {
options = options || {};
let isConnectOnStartUp = options.connectOnStartup || true;
options.connectOnStartup = false;
super(url, options);
options.connectOnStartup = isConnectOnStartUp;
this._client = new WsJsClient(url, options);
}
}
module.exports = WsJsDriverRemoteConnection;
| e8cfe0d8e0a85f1f26553d17918aaca8d5504b4d | [
"Markdown",
"JavaScript"
] | 3 | Markdown | bdhl/gremlin-js-driver | 977074ed8341cc8fcfd7dc16fd9c7a0e82aaa226 | 0baf7f1fda15902066e02c83083fa4891de80782 |
refs/heads/master | <file_sep>Python-Cardano
==============
Python implementation of Cardano project, including network protocol, crypto primitives, wallet logic, and more.
Why This Project
----------------
* We want to explore alternate design decisions to support lightweight wallet, and start developing the mobile wallet for Cardano. Current official wallet node is not enough yet.
* Explore the design space of clustered wallet node.
* Provide alternative implementation of Cardano protocols and specifications in another programming language.
* In the future, it could be an alternative foundation for projects in Cardano ecosystem: wallets, side-chains, MPCs.
Why Python
----------
Python is still one of the most cleanly designed, developer friendly programming language out there, has a reputation of
executable pseudocode. And lightweight thread provided by gevent makes it suitable to write networking software, and easy
interoperability with C thanks to Cython enables us to improve performance incrementally.
With python, we can develop clean prototype very fast, with good performance. And in the future we can always move the CPU intensive code to C
after we indentified the hotspot.
Build & Test
------------
.. code-block:: shell
$ virtualenv -p python3 .env
$ source .env/bin/activate
$ pip install -r requirements.txt
$ python setup.py build_ext --inplace
$ mkdir ./test_db
$ python scripts/pycardano.py run
sync block data from mainnet and subscribing for new blocks automatically.
$ python scripts/pycardano.py wallet create default
generate wallet
Features
--------
* Store block data of different epochs in seperate rocksdb database, provides better disk usage(fully synchronized mainchain takes 1.3G disk space), and allows faster synchronization in the future.
* ``pycardano.py sign`` sign a message with wallet, prove an wallet address belongs to you.
* ``pycardano.py verify`` verify a signed message.
* ``pycardano.py utxo stat`` Some statistics of global UTxOs.
Modules
-------
* ``cardano.address``
Implement Cardano HD address derivation and encoding, and wallet recovering for lagacy address format.
* ``cardano.transport``
Implement Haskell's network-transport-tcp, multiplex multiple lightweight unidirectional connections on a single tcp connection.
* ``cardano.node``
Implement cardano-sl's ``Node``, allow bidirectional conversation between endpoints.
* ``cardano.storage``
Storage api of block and wallet's data.
* ``cardano.block``
Block data structures.
* ``cardano.logic``
Workers and listeners of default node.
* ``cardano.retrieve``
Retrieve block data with cardano-sl mainnet.
* ``cardano.wallet``
Implement wallet logic according to formal specification.
TODOs
-----
* wallet state storage, a simple solution first, hopefully something like Haskell's acid-state in the end.
* block verification.
* relay block data with stream api.
* wallet cli app.
* wallet V1 api and api for SPV light client.
* clustered wallet storage.
<file_sep>'''
Implement wallet logic following the formal wallet specification.
'''
from collections import namedtuple, deque
from recordclass import recordclass
# Basic Model.
Tx = namedtuple('Tx', 'txid inputs outputs')
TxIn = namedtuple('TxIn', 'txid ix')
TxOut = namedtuple('TxOut', 'addr c')
# UTxO :: Map TxIn TxOut
# Txs :: List Tx
def constraint_txins(txins, utxo):
# More efficient than filter_ins
return {txin: utxo[txin] for txin in txins if txin in utxo}
def exclude_txins_inplace(txins, utxo):
# More efficient than filter_ins
for txin in txins:
utxo.pop(txin, None)
return utxo
def balance(utxo):
return sum(txout.c for txout in utxo.values())
def dom(utxo):
return set(utxo.keys())
def txins(txs):
'set of inputs spent by transactions'
result = set()
for tx in txs:
result |= tx.inputs
return result
def ours_txouts(txs, is_our_addr):
'utxo generated by transactions which belongs to addresses.'
return {TxIn(tx.txid, ix): txout
for tx in txs
for ix, txout in enumerate(tx.outputs)
if is_our_addr(txout.addr)}
# Comment out current unused operations.
def txouts(txs):
return {TxIn(tx.txid, ix): txout
for tx in txs
for ix, txout in enumerate(tx.outputs)}
def new_utxo(txs, is_our_addr):
'new utxo added by these transactions and owned by addrs.'
return exclude_txins_inplace(txins(txs), ours_txouts(txs, is_our_addr))
def dependent_on(tx2, tx1):
'Check if tx2 is dependent on tx1'
return any(lambda txin: txin.txid == tx1.txid, tx2.inputs)
Checkpoint = recordclass(
'Checkpoint',
'utxo expected_utxo pending utxo_balance')
class Wallet(object):
def __init__(self, addrs):
self.addrs = set(addrs)
self.checkpoints = deque([Checkpoint({}, {}, [], 0)], maxlen=2160)
def is_our_addr(self, addr):
'check is our address'
return addr in self.addrs
def change(self, txs):
'return change UTxOs from transactions.'
return ours_txouts(txs, self.is_our_addr)
def available_utxo(self):
'available utxo'
state = self.checkpoints[-1]
utxo = state.utxo.copy()
return exclude_txins_inplace(txins(state.pending), utxo)
def total_utxo(self):
'total utxo'
change_utxo = self.change(self.checkpoints[-1].pending)
return {**self.available_utxo(), **change_utxo}
def available_balance(self):
state = self.checkpoints[-1]
spent_utxo = constraint_txins(txins(state.pending), state.utxo)
return state.utxo_balance - balance(spent_utxo)
def total_balance(self):
change_utxo = self.change(self.checkpoints[-1].pending)
return self.available_balance() + balance(change_utxo)
def apply_block(self, txs):
state = self.checkpoints[-1]
txouts_ = ours_txouts(txs, self.is_our_addr)
assert dom(txouts_) & dom(state.utxo) == set(), 'precondition doesn\'t meet'
txins_ = txins(txs) & (dom(state.utxo) | dom(txouts_))
self.apply_filtered_block(txins_, txouts_)
def apply_filtered_block(self, txins_, txouts_):
# add new utxo.
state = self.checkpoints[-1]
utxo = state.utxo.copy()
utxo.update(txouts_)
utxo_spent = constraint_txins(txins_, utxo)
# remove spent utxo inplace.
exclude_txins_inplace(txins_, utxo)
utxo_balance = state.utxo_balance + balance(txouts_) - balance(utxo_spent)
pending = filter(lambda tx: tx.inputs & txins_ == set, state.pending)
new_utxo = exclude_txins_inplace(txins_, txouts_)
expected_utxo = exclude_txins_inplace(dom(new_utxo), state.expected_utxo.copy())
self.checkpoints.append(Checkpoint(utxo, expected_utxo, pending, utxo_balance))
def new_pending(self, tx):
assert tx.inputs.issubset(dom(self.available_utxo())), \
'precondition doesn\'t meet.'
self.checkpoints[-1].pending.append(tx)
def rollback(self):
assert self.checkpoints, 'no checkpoints, impossible.'
if len(self.checkpoints) == 1:
state = self.checkpoints[0]
assert not state.pending and not state.utxo, 'impossible'
else:
old = self.checkpoints.pop()
new = self.checkpoints[-1]
new.pending += old.pending
new.expected_utxo.update(old.expected_utxo)
new.expected_utxo.update(exclude_txins_inplace(dom(new.utxo), old.utxo))
# Invariants
def invariant_3_4(self):
state = self.checkpoints[-1]
assert txins(state.pending).issubset(dom(state.utxo)), 'invariant broken'
def invariant_3_5(self):
result = all(self.is_our_addr(txout.addr)
for txout in self.checkpoints[-1].utxo.values())
assert result, 'invariant broken'
def invariant_3_6(self):
change_utxo = self.change(self.checkpoints[-1].pending)
assert dom(change_utxo) & dom(self.available_utxo()) == set(), 'invariant broken'
def invariant_balance_cache(self):
state = self.checkpoints[-1]
assert state.utxo_balance == balance(state.utxo), \
'balance cache broken.'
assert self.available_balance() == balance(self.available_utxo()), \
'balance is wrong'
assert self.total_balance() == balance(self.total_utxo()), \
'balance is wrong'
def invariant_7_6(self):
state = self.checkpoints[-1]
assert dom(state.utxo) & dom(state.expected_utxo) == set(), 'invariant broken'
def invariant_7_7(self):
result = all(self.is_our_addr(txout.addr)
for txout in self.checkpoints[-1].expected_utxo.values())
assert result, 'invariant broken'
def invariant_7_8(self):
state = self.checkpoints[-1]
utxo = {**state.utxo, **state.expected_utxo}
assert txins(state.pending).issubset(dom(utxo)), 'invariant broken'
def check_invariants(self):
invariants = [
self.invariant_3_4,
self.invariant_3_5,
self.invariant_3_6,
self.invariant_balance_cache,
self.invariant_7_6,
self.invariant_7_7,
self.invariant_7_8,
]
for inv in invariants:
inv()
if __name__ == '__main__':
# Test with local database.
import random
from .storage import Storage
store = Storage('test_db', readonly=True)
def random_addresses(threshold):
addrs = set()
for blk in store.blocks():
for tx in blk.txs():
for txout in tx.outputs:
if random.random() < 0.1:
addrs.add(txout.addr)
if len(addrs) > threshold:
return addrs
print('Collect random addresses to test.')
w = Wallet(random_addresses(10000))
print('Apply blocks')
b = w.available_balance()
for blk in store.blocks():
w.apply_block(blk.txs())
w.check_invariants()
n = w.available_balance()
if n != b:
b = n
print('balance changed', b)
<file_sep>import gevent
from gevent import socket
from .transport import make_endpoint_addr, parse_endpoint_addr
from . import config
gevent.config.resolver = 'dnspython'
def resolve(domains):
addrs = []
for domain in domains:
host, port, id = parse_endpoint_addr(domain)
items = socket.getaddrinfo(host, port,
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
for _, _, _, _, (ip, port) in items:
addrs.append((ip.encode(), port, id))
return addrs
def resolve_loop(domains):
while True:
addrs = resolve(domains)
if not addrs:
gevent.sleep(config.SLOT_DURATION / 1000)
continue
for ip, port, id in addrs:
yield make_endpoint_addr(ip, port, id)
if __name__ == '__main__':
for addr in resolve_loop([config.CLUSTER_ADDR]):
print(addr)
gevent.sleep(1)
<file_sep>'''
Support bidirectional conversation on unidirectional lightweight connections.
'''
import sys
import random
import struct
import enum
import cbor
import gevent
import gevent.event
from .transport import Event, RemoteEndPoint
from . import config
class Message(enum.IntEnum):
Void = 0
GetHeaders = 4
Headers = 5
GetBlocks = 6
Block = 7
Subscribe1 = 13
Subscribe = 14
Stream = 15
StreamBlock = 16
TxInvData = 37 # InvOrData (Tagged TxMsgContents TxId) TxMsgContents
TxReqRes = 94 # ReqOrRes (Tagged TxMsgContents TxId)
MessageSndRcv = {
Message.GetHeaders: Message.Headers,
Message.Headers: Message.GetHeaders,
Message.GetBlocks: Message.Block,
Message.Stream: Message.StreamBlock,
Message.TxInvData: Message.TxReqRes,
Message.TxReqRes: Message.TxInvData,
Message.Subscribe: Message.Void,
Message.Subscribe1: Message.Void,
}
def make_peer_data(workers, listeners):
peer_data = [config.PROTOCOL_MAGIC, [0, 1, 0], {}, {}]
for cls in workers:
peer_data[3][cls.message_type] = [
0,
cbor.Tag(24, cbor.dumps(MessageSndRcv[cls.message_type]))]
for msgtype in listeners.keys():
peer_data[2][msgtype] = [0, cbor.Tag(24, cbor.dumps(MessageSndRcv[msgtype]))]
return peer_data
class Conversation(object):
'Bidirectional connection.'
def __init__(self, node, conn, queue, addr):
self._node = node
self._conn = conn # sending side.
self._queue = queue # receive message.
self._addr = addr # remote address.
def __gc__(self):
self.close()
@property
def peer_data(self):
return self._node._peer_received[self._addr][0]
@property
def addr(self):
return self._addr
def send(self, data):
self._conn.send(data)
def receive(self, *args, **kwargs):
o = self._queue.get(*args, **kwargs)
if o == StopIteration:
# closed by remote
if self._conn.alive:
self.close()
self._queue = None
else:
return o
def closed(self):
return not self._conn.alive
def close(self):
'close our end.'
if self.closed():
return
self._conn.close()
remote = self._node._endpoint.valid_state._remotes[self._addr]
if isinstance(remote.state, RemoteEndPoint.Closing) or \
remote.valid_state.outgoing == 0:
self._node._peer_sending.pop(self._addr)
class Node(object):
def __init__(self, ep, workers, listeners):
self._endpoint = ep
self._workers = {cls.message_type: cls for cls in workers}
self._listeners = listeners
self._peer_data = make_peer_data(workers, listeners)
# The first connect request send peer data, other concurrent requests need to wait
# addr -> state (None | 'done' | Event)
self._peer_sending = {}
# Received peer_data, addr -> (peer_data, set of connid)
self._peer_received = {}
# Address of incoming connections, connid -> addr
self._incoming_addr = {}
# Incoming connections in handshaking, connid -> nonce
self._incoming_nonce = {}
# All incoming message queues, connid -> Queue
self._incoming_queues = {}
# Connector wait for message receive queue, (nonce, addr) -> AsyncResult
self._wait_for_queue = {}
self._next_nonce = random.randint(0, sys.maxsize)
self._dispatcher_thread = gevent.spawn(self.dispatcher)
@property
def endpoint(self):
return self._endpoint
def gen_next_nonce(self):
n = self._next_nonce
self._next_nonce = (self._next_nonce + 1) % sys.maxsize
return n
def _connect_peer(self, addr):
conn = self._endpoint.connect(addr)
# Waiting for peer data to be transmitted.
st = self._peer_sending.get(addr)
if st == 'done':
pass # already done.
elif st is None:
# transmit and notify pending connections.
print('sending our peer data')
evt = gevent.event.Event()
self._peer_sending[addr] = evt
conn.send(cbor.dumps(self._peer_data, sort_keys=True))
self._peer_sending[addr] = 'done'
evt.set()
else:
assert isinstance(st, gevent.event.Event), 'invalid state: ' + str(st)
st.wait() # wait for peer data transmiting.
return conn
def connect(self, addr):
conn = self._connect_peer(addr)
# start handshake
nonce = self.gen_next_nonce()
conn.send(b'S' + struct.pack('>Q', nonce))
# wait for ack and receiving queue.
evt = gevent.event.AsyncResult()
self._wait_for_queue[(nonce, addr)] = evt
queue = evt.get()
return Conversation(self, conn, queue, addr)
def dispatcher(self):
ep = self._endpoint
while True:
ev = ep.receive()
tp = type(ev)
if tp == Event.ConnectionOpened:
assert ev.connid not in self._incoming_addr, 'duplicate connection id.'
self._incoming_addr[ev.connid] = ev.addr
if ev.addr in self._peer_received:
self._peer_received[ev.addr][1].add(ev.connid)
elif tp == Event.Received:
addr = self._incoming_addr[ev.connid]
if addr not in self._peer_received:
# not received peerdata yet, assuming this is it.
print('received remote peer data')
self._peer_received[addr] = (cbor.loads(ev.data), set([ev.connid]))
continue
nonce = self._incoming_nonce.get(ev.connid)
if nonce is None:
direction = ev.data[:1]
nonce = struct.unpack('>Q', ev.data[1:])[0]
self._incoming_nonce[ev.connid] = nonce
queue = gevent.queue.Queue(32)
self._incoming_queues[ev.connid] = queue
if direction == b'A':
self._wait_for_queue.pop((nonce, addr)).set(queue)
elif direction == b'S':
gevent.spawn(self._handle_incoming, addr, nonce, queue)
else:
assert False, 'invalid request message.'
else:
# normal data.
self._incoming_queues[ev.connid].put(ev.data)
elif tp == Event.ConnectionClosed:
addr = self._incoming_addr.pop(ev.connid)
_, connset = self._peer_received[addr]
connset.remove(ev.connid)
if not connset:
self._peer_received.pop(addr)
self._incoming_nonce.pop(ev.connid, None)
queue = self._incoming_queues.pop(ev.connid, None)
if queue:
# close the queue.
queue.put(StopIteration)
else:
print('unhandled event', ev)
def _handle_incoming(self, addr, nonce, queue):
# Will use the exist tcp connection.
conn = self._connect_peer(addr)
conn.send(b'A' + struct.pack('>Q', nonce))
conv = Conversation(self, conn, queue, addr)
# run listener.
try:
result = queue.get()
if result != StopIteration:
msgcode = cbor.loads(result)
self._listeners[msgcode](self, conv)
finally:
conv.close()
def worker(self, msgtype, addr):
cls = self._workers[msgtype]
assert cls.message_type == msgtype
conv = self.connect(addr)
if msgtype not in conv.peer_data[2]:
# print('Remote peer don\'t support this message type.')
return
conv.send(cbor.dumps(msgtype))
return cls(conv)
class Worker(object):
def __init__(self, conv):
self.conv = conv
def close(self):
self.conv.close()
def default_node(ep):
from .logic import workers, listeners
return Node(ep, workers, listeners)
if __name__ == '__main__':
config.use('mainnet')
from .transport import Transport
node = default_node(Transport().endpoint())
worker = node.worker(Message.Subscribe, config.CLUSTER_ADDR)
# send subscribe
worker()
# keepalive loop
worker.keepalive()
<file_sep>#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("cardano.cbits", sources=[
"cardano/cbits.pyx",
"cbits/encrypted_sign.c",
"cbits/ed25519/ed25519.c",
"cbits/cryptonite_chacha.c",
"cbits/cryptonite_pbkdf2.c",
"cbits/cryptonite_sha1.c",
"cbits/cryptonite_sha256.c",
"cbits/cryptonite_sha512.c",
"cbits/cryptonite_poly1305.c",
], include_dirs=["cbits", "cbits/ed25519"])]
cmdclass = {'build_ext': build_ext}
setup(
name='cardano-utils',
version='1.0.0',
packages=['cardano'],
ext_modules=ext_modules,
cmdclass=cmdclass,
author='huangyi',
author_email='<EMAIL>',
url='https://github.com/yihuang/cardano-utils',
description='Python library for Cardano crypto primitives.',
long_description=open('README.rst').read(),
)
<file_sep>'''
Logic includes workers and listeners.
'''
import binascii
import random
import time
import math
import traceback
import gevent
import cbor
from orderedset import OrderedSet
from .block import DecodedBlockHeader, DecodedBlock
from .node import Node, Worker, Message
from .utils import get_current_slot, flatten_slotid
from .storage import fetch_raw_blocks, stream_raw_blocks
from . import config
# Workers
class GetHeaders(Worker):
message_type = Message.GetHeaders
def __call__(self, from_, to):
self.conv.send(cbor.dumps([cbor.VarList(from_), [to] if to else []]))
tag, data = cbor.loads(self.conv.receive()) # sum type MsgHeaders
if tag == 1: # NoHeaders
print('no headers', data)
return []
return [DecodedBlockHeader(item) for item in data]
def tip(self):
data = self([], None)
return data[0] if data else None
class GetBlocks(Worker):
message_type = Message.GetBlocks
def __call__(self, from_, to):
self.conv.send(cbor.dumps([from_, to]))
while True:
buf = self.conv.receive()
if not buf:
# closed by remote.
break
tag, data = cbor.loads(buf) # \x82, \x00, block_raw_data
if tag == 0: # MsgBlock
yield DecodedBlock(data, buf[2:])
def one(self, h):
return next(self(h, h))
class StreamBlocks(Worker):
message_type = Message.Stream
def __init__(self, *args, **kwargs):
super(StreamBlocks, self).__init__(*args, **kwargs)
self._ended = False
@property
def ended(self):
return self._ended
def start(self, from_, to, n):
self._ended = False
self.conv.send(cbor.dumps([
0,
[cbor.VarList(from_), to, n]
]))
yield from self._receive_stream(n)
def update(self, n):
assert not self._ended
self.conv.send(cbor.dumps([
1,
[n]
]))
yield from self._receive_stream(n)
def _receive_stream(self, n):
for i in range(n):
buf = self.conv.receive()
if not buf:
# closed by remote.
self._ended = True
print('connection closed')
break
tag, data = cbor.loads(buf) # \x82, \x00, block_raw_data
if tag != 0:
self._ended = True
print('stream ended', tag, data)
break
yield DecodedBlock(data, buf[2:])
class Subscribe(Worker):
message_type = Message.Subscribe
def __call__(self):
# instance Bi MsgSubscribe
self.conv.send(cbor.dumps(42))
def keepalive(self):
while True:
gevent.sleep(config.SLOT_DURATION / 1000)
# keep alive
self.conv.send(cbor.dumps(43))
class Subscribe1(Worker):
message_type = Message.Subscribe1
def __call__(self):
# instance Bi MsgSubscribe1
self.conv.send(cbor.dumps(42))
# Listeners
def handle_get_headers(node, conv):
'Peer wants some block headers from us.'
store = node.store
limit = config.CHAIN['block']['recoveryHeadersMessage']
while True:
checkpoints, tip = cbor.loads(conv.receive())
tip = tip[0] if tip else None
if node.retriever.recovering():
conv.send(cbor.dumps((1, b'server node is in recovery mode')))
continue
headers = None
if not checkpoints:
# return single header
headers = [store.blockheader(tip) if tip else store.tip()]
else:
# TODO filter in mainchain.
# get most recent checkpoint
checkpoint = max(checkpoints, key=lambda k: store.blockheader(k).slot())
count = 0
headers = []
for h in store.iter_header_hash(checkpoint):
count += 1
if count > limit:
break
headers.append(store.blockheader(h))
if headers:
conv.send(cbor.dumps((0, cbor.VarList(hdr.data for hdr in headers))))
else:
conv.send(cbor.dumps((1, b'loaded empty headers')))
def handle_get_blocks(node, conv):
'Peer wants some blocks from us.'
hstart, hstop = cbor.loads(conv.receive())
for rawblk in fetch_raw_blocks(node.store, hstart, hstop):
if not rawblk:
conv.send(cbor.dumps([1, 0])) # NoBlock
break
conv.send(b"\x82\x00" + rawblk)
def handle_stream_start(node, conv):
'Peer wants to stream some blocks from us.'
store = node.store
tag, v = cbor.loads(conv.receive())
assert tag == 0 # MsgStart
checkpoints, tip, window = v
assert window > 0
# TODO filter in mainchain
checkpoint = max(checkpoints, key=lambda k: store.blockheader(k).slot())
for rawblk in stream_raw_blocks(store, checkpoint):
if not rawblk:
break
conv.send(b"\x82\x00" + rawblk)
window -= 1
if window <= 0:
# expect MsgUpdate
tag, v = cbor.loads(conv.receive())
assert tag == 1 # MsgUpdate
window = v[0]
assert window > 0
conv.send((2, 0)) # MsgStreamEnd
def handle_headers(node, conv):
'Peer has a block header for us (yes, singular only).'
data = conv.receive()
if not data:
print('remote closed')
return
tag, headers = cbor.loads(data)
assert tag == 0 and len(headers) == 1, 'invalid header message'
header = DecodedBlockHeader(headers[0])
print('got new block header', binascii.hexlify(header.hash()).decode())
if not getattr(node, 'retriever', None):
# it's just a demo node.
return
node.retriever.add_retrieval_task(conv.addr, header)
# broadcast out.
node.broadcast(Message.Headers, data)
def handle_subscribe(node, conv):
tag = cbor.loads(conv.receive())
assert tag == 42 # MsgSubscribe
# add peer
if conv.addr in node.subscribers:
print('subscriber already exists')
return
print('add subscriber', conv.addr)
node.subscribers.add(conv.addr)
try:
while True:
tag = cbor.loads(conv.receive(timeout=config.SLOT_DURATION * 2 / 1000))
assert tag == 43 # MsgKeepalive
finally:
print('remove subscriber', conv.addr)
node.subscribers.remove(conv.addr)
def inv_worker(conv, key, value):
'''
Inv/Req/Data/Res
send (Left (InvMsg key)) listener (Either InvMsg DataMsg)
Either ReqMsg ResMsg <- recv
case
(ReqMsg (Just key)) ->
send (Right (DataMsg data))
Either ReqMsg ResMsg <- recv
case
ResMsg -> return ResMsg
ReqMsg -> error
(ReqMsg Nothing) -> pass
ResMsg -> error
'''
print('send inv key', key)
conv.send(cbor.dumps([0, key])) # Left (InvMsg key)
(tag, req) = cbor.loads(conv.receive())
assert tag == 0, 'should be ReqMsg'
if req:
assert cbor.dumps(req[0]) == cbor.dumps(key)
conv.send(cbor.dumps([1, value])) # Right (DataMsg value)
(tag, res) = cbor.loads(conv.receive())
assert tag == 1, 'should be ResMsg'
return res
class TxInvWorker(Worker):
message_type = Message.TxInvData
def __call__(self, key, value):
return inv_worker(self.conv, key, value)
workers = [
GetHeaders,
GetBlocks,
StreamBlocks,
Subscribe,
Subscribe1,
TxInvWorker,
]
listeners = {
Message.GetHeaders: handle_get_headers,
Message.GetBlocks: handle_get_blocks,
Message.Stream: handle_stream_start,
Message.Headers: handle_headers,
Message.Subscribe: handle_subscribe,
}
def retry_duration(duration):
slot = config.SLOT_DURATION / 1000
return math.floor(slot / (2 ** (duration / slot)))
class LogicNode(Node):
def __init__(self, ep, store):
super(LogicNode, self).__init__(ep, workers, listeners)
self.store = store
# start worker threads
self._parent_thread = gevent.getcurrent()
# block retriever
from .retrieve import BlockRetriever
self.retriever = BlockRetriever(self.store, self)
self.retriever_thread = gevent.spawn(self.retriever)
self.retriever_thread.link(self._handle_worker_exit)
# recover trigger
self.trigger_recovery_thread = gevent.spawn(
self._trigger_recovery_worker,
config.SECURITY_PARAMETER_K * 2
)
self.trigger_recovery_thread.link(self._handle_worker_exit)
# dns subscribe worker
self._peers = gevent.event.AsyncResult() # set of peer addresses
self.subscribe_thread = gevent.spawn(self._subscribe, [config.CLUSTER_ADDR])
self.subscribe_thread.link(self._handle_worker_exit)
self.subscribers = set() # set of addresses of subscribers
def broadcast(self, code, msg):
for addr in self.subscribers:
try:
conv = self.connect(addr)
conv.send(cbor.dumps(code) + msg)
except Exception as e:
traceback.print_exc()
print('broadcast failed:' + str(e))
self.subscribers.remove(addr)
def _handle_worker_exit(self, t):
print('worker thread exit unexpected')
gevent.kill(self._parent_thread)
def _trigger_recovery(self):
'trigger recovery actively by requesting tip'
print('recovery triggered.')
for addr in list(self._peers.get()): # use list to iterating a copy.
try:
header = self.worker(Message.GetHeaders, addr).tip()
except Exception as e:
traceback.print_exc()
print('get tip failed', str(e))
else:
if header:
self.retriever.add_retrieval_task(addr, header)
def _trigger_recovery_worker(self, lag_behind):
while True:
triggered = False
slot_diff = 0
if not self.retriever.recovering():
cur_slot = get_current_slot()
tip = self.store.tip()
tip_slot = tip.slot() if tip else (0, 0)
slot_diff = flatten_slotid(cur_slot) - flatten_slotid(tip_slot)
if slot_diff >= lag_behind:
# need to recovery.
self._trigger_recovery()
triggered = True
elif slot_diff < 0:
print('tip slot is in future.')
if not triggered:
# random
if random.random() < 0.004 and slot_diff >= 5:
self._trigger_recovery()
triggered = True
gevent.sleep(20 if triggered else 1, True)
def _subscribe(self, domains):
from .peers import resolve_loop
for addr in resolve_loop(domains):
start = time.time()
if not self._peers.ready():
self._peers.set(OrderedSet([addr]))
else:
self._peers.get().add(addr)
try:
print('subscribing to', addr.decode())
w = self.worker(Message.Subscribe, addr)
w()
w.keepalive()
except Exception as e:
traceback.print_exc()
print('subscribtion failed:' + str(e))
# remove peers
self._peers.get().remove(addr)
gevent.sleep(retry_duration(time.time() - start))
if __name__ == '__main__':
config.use('mainnet')
from .transport import Transport
from .storage import Storage
from .utils import hash_data
from .address import AddressContent
from .block import DecodedTransaction, DecodedTxAux
txid = hash_data(b'')
pk = bytes(64)
sig = bytes(64)
addr = AddressContent.pubkey(pk).address().encode_base58()
tx = DecodedTransaction.build(
[(txid, 0)],
[(addr, 100)],
)
txaux = DecodedTxAux.build(tx, [(pk, sig)])
node = LogicNode(Transport().endpoint(), Storage('./test_db'))
peer = node._peers.get()[0]
worker = node.worker(Message.TxInvData, peer)
key, success = worker(tx.hash(), txaux.data)
assert key == tx.hash()
print('success', success)
<file_sep>'''
Crypto primitives of Cardano HD wallet and addresses.
All secret keys in memory are encrypted by passphase.
sk: secret key 32bit
pk: public key 32bit
chaincode: 32bit
xpub: pk + chaincode 64bit
xpriv: 64bit + xpub
hdpassphase: passphase derive from root xpub used to encrypt address payload
'''
import binascii
import hashlib # Python >= 3.6
import hmac
import struct
from collections import namedtuple
from mnemonic import Mnemonic
import cbor
import pbkdf2
import base58
from . import cbits
from .utils import hash_data
from .constants import FIRST_HARDEN_INDEX
def mnemonic_to_seed(words, lang='english'):
return hash_data(bytes(Mnemonic(lang).to_entropy(words)))
def gen_root_xpriv(seed, passphase):
seed = cbor.dumps(seed)
for i in range(1, 1000):
buf = hmac.new(seed, b'Root Seed Chain %d' % i, hashlib.sha512).digest()
buf_l, buf_r = buf[:32], buf[32:]
result = cbits.encrypted_from_secret(passphase, buf_l, buf_r)
if result:
return result
def xpriv_to_xpub(xpriv):
return xpriv[64:]
def derive_hdpassphase(xpub):
return pbkdf2.PBKDF2(xpub, 'address-hashing',
iterations=500, digestmodule=hashlib.sha512).read(32)
def pack_addr_payload(path, hdpass):
'packHDAddressAttr'
plaintext = cbor.dumps(cbor.VarList(path))
return cbits.encrypt_chachapoly(b'serokellfore', hdpass, b'', plaintext)
def unpack_addr_payload(ciphertext, hdpass):
plaintext = cbits.decrypt_chachapoly(b'serokellfore', hdpass, b'', ciphertext)
if plaintext:
return cbor.loads(plaintext)
def addr_hash(addr):
'hash method for address is different.'
return hashlib.blake2b(hashlib.sha3_256(cbor.dumps(addr, sort_keys=True)).digest(),
digest_size=28).digest()
def encode_with_crc(v):
s = cbor.dumps(v, sort_keys=True)
return cbor.dumps([
cbor.Tag(24, s),
binascii.crc32(s)
])
def addr_hash_short(addr):
'Shorten hash result to 20 bytes.'
return hashlib.blake2b(hashlib.sha3_256(cbor.dumps(addr, sort_keys=True)).digest(),
digest_size=20).digest()
def encode_with_crc_short(v):
'Remove a level of cbor overhead.'
s = cbor.dumps(v, sort_keys=True)
# the prefix byte is for backward compatibility, old address always start with 0x82.
return b'\x00' + s + struct.pack('<I', binascii.crc32(s))
def encode_addr_short(addr):
return encode_with_crc_short([
addr_hash_short(addr),
addr.attrs,
addr.type
])
RawAddressContent = namedtuple('RawAddressContent', 'type spending attrs')
RawAddress = namedtuple('RawAddress', 'hash attrs type')
class Address(RawAddress):
def encode(self):
return encode_with_crc(self)
def encode_base58(self):
return base58.b58encode(self.encode())
@classmethod
def decode(cls, s):
if s[0] == 0:
# version byte for new encoding.
crc32, = struct.unpack('<I', s[-4:])
s = s[1:-4]
else:
# old normal address.
tag, crc32 = cbor.loads(s)
s = tag.value
assert binascii.crc32(s) == crc32, 'crc32 checksum don\'t match.'
return cls(*cbor.loads(s))
@classmethod
def decode_base58(cls, s):
return cls.decode(base58.b58decode(s))
def verify_pubkey(self, xpub):
if self.type != 0:
return False
confirm = AddressContent(0, [0, xpub], self.attrs)
return confirm.address().hash == self.hash
def verify_script(self, script):
# TODO
pass
def get_derive_path(self, hdpass):
'Get derive path from lagacy address.'
payload = self.attrs.get(1)
if payload:
return unpack_addr_payload(cbor.loads(payload), hdpass)
class AddressContent(RawAddressContent):
@staticmethod
def pubkey(xpub, attrs=None):
return AddressContent(
0, [0, xpub], attrs or {}
)
@staticmethod
def pubkey_lagacy(xpub, derive_path, hdpass, attrs=None):
return AddressContent(
0, # addrType
[0, xpub], # addrSpendingData
{1: cbor.dumps(pack_addr_payload(derive_path, hdpass)), **(attrs or {})}
)
@staticmethod
def redeem(pk):
return AddressContent(
2, # RedeemASD
[2, pk],
{}
)
@staticmethod
def script(s):
# TODO
pass
def address(self):
return Address(
addr_hash(self),
self.attrs,
self.type
)
def derive_key(xpriv, passphase, path, derivation_schema):
for idx in path:
xpriv = cbits.encrypted_derive_private(
xpriv, passphase, idx, derivation_schema
)
return xpriv
def derive_key_public(xpub, path, derivation_schema):
for idx in path:
xpub = cbits.encrypted_derive_public(xpub, idx, derivation_schema)
return xpub
def derive_address_lagacy(xpriv, passphase, path, derivation_schema):
hdpass = derive_hdpassphase(xpriv_to_xpub(xpriv))
xpriv = derive_key(xpriv, passphase, path, derivation_schema)
return AddressContent.pubkey_lagacy(xpriv_to_xpub(xpriv), path, hdpass)
def recover_addresses_lagacy(store, hdpass):
result = set()
for addr in store.iter_addresses():
if Address.decode(addr).get_derive_path(hdpass):
result.add(addr)
return result
def test_encode_address(root_xpriv, passphase):
addr = AddressContent.pubkey(xpriv_to_xpub(root_xpriv))
print('wallet id', addr.address().encode_base58().decode())
# print('wallet id[short]', base58.b58encode(encode_addr_short(addr)).decode())
path = [FIRST_HARDEN_INDEX, FIRST_HARDEN_INDEX]
addr = derive_address_lagacy(root_xpriv, passphase, path, cbits.DERIVATION_V1)
print('first address', addr.address().encode_base58().decode())
addr = derive_address_lagacy(root_xpriv, passphase, path, cbits.DERIVATION_V1)
# print('first address[short]', base58.b58encode(encode_addr_short(addr)).decode())
print('decode', Address.decode(addr.address().encode()))
# print('decode[short]', Address.decode(encode_addr_short(addr)))
hdpass = derive_hdpassphase(xpriv_to_xpub(root_xpriv))
print('decrypte derive path', addr.address().get_derive_path(hdpass))
if __name__ == '__main__':
from .utils import input_passphase
passphase = input_passphase()
words = 'ring crime symptom enough erupt lady behave ramp apart settle citizen junk'
root_xpriv = gen_root_xpriv(mnemonic_to_seed(words), passphase)
# test_encode_address(root_xpriv, passphase)
from .storage import Storage
hdpass = derive_hdpassphase(xpriv_to_xpub(root_xpriv))
for addr in recover_addresses_lagacy(Storage('test_db'), hdpass):
print(base58.b58encode(addr).decode())
<file_sep>Crossed Connection
-------------------
Assuming A's address < B's address
* A.1 A send connect request to B, create RemoteEndPointB object
* B.1 B send connect request to A, create RemoteEndPointA object
* B.2 B get connect request from A, but find RemoteEndPointA object already exists,
check local_addr(B) > remote_addr(A), should accept the request,
wait for crossed Event which would be fired in step B.3,
reply with Accepted,
re-use the RemoteEndPoint object, and change state to Valid
start processing messages.
* A.2 A get connect request from B, find out RemoteEndPointB object exists,
and local_addr(A) < remote_addr(B), should reject the request,
just reply with Crossed message.
* B.3 B's connect request get Crossed reply,
(should we remove the RemoteEndPoint object, or just leave in Init state?),
fire the crossed Event,
close the socket,
end with failure.
(better if B can wait for step B.2 finish, and reuse the connection)
* A.3 A's connect request get Accepted reply,
start processing messages.
Concurrently Connect
--------------------
* Thread 1 try to connect to A, create RemoteEndPoint object.
* Thread 2 try to connect to A, find RemoteEndPoint exists, wait for evt_resolve Event.
* Thread 1 finish connecting, notify evt_resolve Event.
* Thread 2 retry, reuse the established connection.
Closing Connection
------------------
* B send CreateConnection to A [1]
* increase last_sent
* increase outgoing
* A close last connection to B [2]
* RemoteEndPoint enter Closing state.
* send CloseSocket msg to B
* A create connection to B [3]
* state = RemoteEndPointB (Closing)
* wait for closing Event and retry.
* A received CreateConnection from B [4]
* A is in Closing state, recover to valid state.
* increase last_incoming
* B received CloseSocket from A
* A.last_incoming != B.last_sent
* just ignore it.
Closing Connection
------------------
* A send create connection
* increase outgoing and last_sent
* A send close connection
* decrease outgoing
* A send CloseSocket to B
* enter Closing state.
* B send CloseSocket to A
* A receive CloseSocket
* last_received != last_sent
Closing Connection
------------------
* A connect B
A.next_lid = 1025
A.outgoing = 1
* B connect A
B.next_lid = 1025
B.outgoing = 1
* A close connect
send close connection to B
A.outgoing = 0
send CloseSocket to B (last_incoming=1024)
enter Closing
* B close connect
send close connection to A
B.outgoing = 0
send CloseSocket to A (last_incoming=1024)
enter Closing
* B got connect from A
recover from Closing state.
incomings.add(1024)
* B got close connect from A
incomings.remove(1024)
* A got connect from B
recover from Closing state.
<file_sep>'''
Multiplex lightweight unidirectional connections onto single tcp connection.
https://cardanodocs.com/technical/protocols/network-transport/
'''
# TODO all the evt.wait need to has timeout.
import struct
import enum
import uuid
import cbor
from recordclass import recordclass
import gevent.socket
import gevent.queue
import gevent.event
import gevent.server
from .constants import LIGHT_ID_MIN, HEAVY_ID_MIN
PROTOCOL_VERSION = 0
# Utils
class ControlHeader(enum.IntEnum):
CreatedNewConnection = 0
CloseConnection = 1
CloseSocket = 2
CloseEndPoint = 3
ProbeSocket = 4
ProbeSocketAck = 5
class HandshakeResponse(enum.IntEnum):
UnsupportedVersion = 0xFFFFFFFF
Accepted = 0x00000000
InvalidRequest = 0x00000001
Crossed = 0x00000002
HostMismatch = 0x00000003
def pack_u32(n):
return struct.pack('>I', n)
def unpack_u32(s):
return struct.unpack('>I', s)[0]
def prepend_length(s):
return struct.pack('>I', len(s)) + s
def random_endpoint_address():
return uuid.uuid4().hex
def make_endpoint_addr(host, port, id):
return b'%s:%d:%d' % (host, port, id)
def parse_endpoint_addr(addr):
parts = addr.rsplit(b':', 2)
if len(parts) == 3:
return parts[0], int(parts[1]), int(parts[2])
elif len(parts) == 2:
return parts[0], int(parts[1]), 0
elif len(parts) == 1:
return parts[0], 80, 0
else:
assert False, 'impossible'
def normalize_endpoint_addr(addr):
return make_endpoint_addr(*parse_endpoint_addr(addr))
def endpoint_connect(addr, local_addr):
host, port, id = parse_endpoint_addr(addr)
print('create heavyweight connection to %s:%d' % (host.decode(), port))
id = int(id)
sock = gevent.socket.create_connection((host, port))
msg = struct.pack('>I', PROTOCOL_VERSION) + prepend_length(
struct.pack('>I', id) +
(prepend_length(local_addr) if local_addr else struct.pack('>I', 0))
)
sock.sendall(msg)
result = HandshakeResponse(unpack_u32(recv_exact(sock, 4)))
return sock, result
def connection_id(hid, lid):
'ConnectionId is unique within all incoming lightweight connections LocalEndPoint.'
return (hid << 32) | lid
def recv_exact(sock, n):
buf = b''
while len(buf) < n:
s = sock.recv(n - len(buf))
assert s, 'connection closed'
buf += s
return buf
def send_many(o, *args):
o.sendall(b''.join(args))
class Event(object):
Received = recordclass('EventReceived', 'connid data')
ConnectionOpened = recordclass('EventConnectionOpened', 'connid addr')
ConnectionClosed = recordclass('EventConnectionClosed', 'connid')
EndpointClosed = recordclass('EventEndpointClosed', '')
Error = recordclass('EventError', 'error')
ReceivedMulticast = recordclass('EventReceivedMulticast', '')
class RemoteEndPoint(object):
'''
Represent a heavyweight connection (incoming or outgoing) associated with a
LocalEndPoint.
id: unique index in associated LocalEndPoint
addr: address of remote end of connection, "host:port:id"
local: associated LocalEndPoint object
state: current state object, one of RemoteEndPoint.State.
'''
# Different states
Error = recordclass('Error', 'error')
Init = recordclass('Init', 'evt_resolve origin') # origin: us | them
Closing = recordclass('Closing', 'evt_resolve valid_state')
Closed = recordclass('Closed', '')
class Valid(object):
def __init__(self, sock, origin):
self.socket = sock
self.origin = origin
self.outgoing = 0 # number of lightweight connections.
self.incomings = set()
self.last_incoming = 0
self.next_light_id = LIGHT_ID_MIN
self.probing_thread = None
def __str__(self):
return '<RemoteEndPoint.Valid ' \
'outgoing:%d ' \
'next_light_id:%d ' \
'last_incoming:%d ' \
'len(incomings):%d>' % (
self.outgoing,
self.next_light_id,
self.last_incoming,
len(self.incomings)
)
def gen_next_light_id(self):
n = self.next_light_id
self.next_light_id += 1
return n
def do_probing(self):
self.socket.sendall(pack_u32(ControlHeader.ProbeSocket))
gevent.sleep(10)
# close socket
self.socket.close()
def start_probing(self):
self.probing_thread = gevent.spawn(self.do_probing)
def stop_probing(self):
if self.probing_thread:
gevent.kill(self.probing_thread)
self.probing_thread = None
def __init__(self, local, addr, id, origin):
self._id = id
self._addr = addr
self._state = RemoteEndPoint.Init(gevent.event.Event(), origin)
self._local = local
@property
def addr(self):
return self._addr
@property
def id(self):
return self._id
@property
def state(self):
return self._state
@property
def local(self):
return self._local
@property
def valid_state(self):
if isinstance(self._state, RemoteEndPoint.Valid):
return self._state
def resolve(self, st):
'Leaving init/closing state, notify other listeners.'
assert isinstance(self._state, (RemoteEndPoint.Init, RemoteEndPoint.Closing)), \
'invalid state' + str(self._state)
evt = self._state.evt_resolve
if isinstance(st, RemoteEndPoint.Closed):
del self.local.valid_state._remotes[self._addr]
self._state = st
evt.set()
def closing(self):
'from Valid to Closing'
assert isinstance(self._state, RemoteEndPoint.Valid)
self._state = RemoteEndPoint.Closing(gevent.event.Event(), self._state)
def closed(self):
'from Valid to Closed'
assert isinstance(self._state, RemoteEndPoint.Valid)
del self.local.valid_state._remotes[self._addr]
self._state = RemoteEndPoint.Closed()
class LocalEndPoint(object):
'''
Represent an endpoint in current transport.
transport: current associated transport.
id: unique id in associated transport.
addr: address of current endpoint, host:port:id.
state: Closed | Valid
'''
Closed = recordclass('Closed', '')
class Valid(object):
'''
Valid state of LocalEndPoint
remotes: Current connected RemoteEndPoints.
queue: Message queue of all incoming events.
'''
def __init__(self):
# incoming unaddressable connection use random addr.
# addr -> RemoteEndPoint
self._remotes = {}
self._next_remote_id = HEAVY_ID_MIN
self._queue = gevent.queue.Queue(maxsize=128)
@property
def queue(self):
return self._queue
def gen_next_remote_id(self):
n = self._next_remote_id
self._next_remote_id += 1
return n
def remove_if_invalid(self, addr):
ep = self._remotes.get(addr)
if ep and isinstance(ep.state, RemoteEndPoint.Error):
del self._remotes[addr]
def __init__(self, transport, addr, id):
self._transport = transport
self._addr = addr
self._id = id
self._state = LocalEndPoint.Valid()
@property
def addr(self):
return self._addr
@property
def id(self):
return self._id
@property
def state(self):
return self._state
@property
def valid_state(self):
if isinstance(self._state, LocalEndPoint.Valid):
return self._state
def get_remote_endpoint(self, addr, origin):
'''
get or create shared RemoteEndPoint instance.
origin: 'us' means outgoing connection, 'them' means incoming connection.
'''
lst = self.valid_state
assert lst is not None, 'local endpoint is closed.'
addr = addr or random_endpoint_address()
while True:
remote = lst._remotes.get(addr)
if not remote:
id = lst.gen_next_remote_id()
remote = RemoteEndPoint(self, addr, id, origin)
lst._remotes[addr] = remote
return remote, True
else:
st = remote.state
if isinstance(st, RemoteEndPoint.Valid):
return remote, False
elif isinstance(st, RemoteEndPoint.Init):
if origin == 'us':
# wait for ongoing init finish, no need to set timeout here,
# dependent on another connect request.
st.evt_resolve.wait()
continue # retry
elif st.origin == 'us':
if self.addr > addr:
return remote, True
else:
# Reject the connection request.
return remote, False
else:
assert False, 'already connected [impossible]'
elif isinstance(st, RemoteEndPoint.Closing):
# Waiting for closing finish and retry.
st.evt_resolve.wait()
continue
elif isinstance(st, RemoteEndPoint.Closed):
# Closed RemoteEndPoint should not in _remotes map.
assert False, 'impossible'
else:
assert False, 'Invalid RemoteEndPoint state: ' + st.error
def process_messages_loop(self, sock, remote):
'''
Process incoming messages in standalone thread,
change RemoteEndPoint's state, put Event into LocalEndPoint's queue.
'''
q = self.valid_state.queue
stream = sock.makefile('rb')
while True:
n = unpack_u32(stream.read(4))
if n < LIGHT_ID_MIN:
# command
cmd = ControlHeader(n)
if cmd == ControlHeader.CreatedNewConnection:
lid = unpack_u32(stream.read(4))
st = remote.valid_state
if st:
st.incomings.add(lid)
st.last_incoming = lid
else:
assert isinstance(remote.state, RemoteEndPoint.Closing), \
'invalid state'
# recover closing state.
st = remote.state.valid_state
st.incomings.add(lid)
st.last_incoming = lid
remote.resolve(st)
q.put(Event.ConnectionOpened(connection_id(remote.id, lid),
remote.addr))
elif cmd == ControlHeader.CloseConnection:
lid = unpack_u32(stream.read(4))
st = remote.valid_state
st.incomings.remove(lid)
q.put(Event.ConnectionClosed(connection_id(remote.id, lid)))
# if not st.incomings and st.outgoing == 0:
# # TODO should CloseSocket again?
# print('hanging connection?')
elif cmd == ControlHeader.CloseSocket:
last_received = unpack_u32(stream.read(4))
st = remote.state
if isinstance(st, RemoteEndPoint.Valid):
last_sent = st.next_light_id - 1 \
if st.next_light_id > LIGHT_ID_MIN \
else 0
assert not bool(st.incomings)
if st.outgoing == 0 and last_received == last_sent:
# send back CloseSocket.
st.socket.sendall(
pack_u32(ControlHeader.CloseSocket) +
pack_u32(st.last_incoming)
)
st.socket.close()
remote.closed()
else:
assert isinstance(st, RemoteEndPoint.Closing)
st.valid_state.socket.close()
remote.resolve(RemoteEndPoint.Closed())
elif cmd == ControlHeader.CloseEndPoint:
q.put(Event.EndpointClosed())
elif cmd == ControlHeader.ProbeSocket:
sock.sendall(pack_u32(ControlHeader.ProbeSocketAck))
elif cmd == ControlHeader.ProbeSocketAck:
remote.stop_probing()
else:
# data
q.put(Event.Received(
connection_id(remote.id, n),
stream.read(unpack_u32(stream.read(4)))
))
def connect(self, addr):
'create new connection from local endpoint to remote endpoint address'
st = self.state
assert isinstance(st, LocalEndPoint.Valid), \
'LocalEndPoint state is invalid: ' + str(st)
st.remove_if_invalid(addr)
remote, new = self.get_remote_endpoint(addr, 'us')
if new:
# Setup outgoing heavyweight connection,
# don't send unaddressable local address.
local_addr = self._transport.addr and self._addr or None
try:
sock, result = endpoint_connect(addr, local_addr)
except gevent.socket.error as e:
remote.resolve(RemoteEndPoint.Error('connect error: ' + str(e)))
else:
if result == HandshakeResponse.Accepted:
gevent.spawn(self.process_messages_loop, sock, remote)
remote.resolve(RemoteEndPoint.Valid(sock, 'us'))
elif result == HandshakeResponse.Crossed:
print('connection crossed, close our connection to', addr.decode())
if isinstance(remote.state, RemoteEndPoint.Init):
# Remote connection request has not came yet, remove the endpoint.
remote.resolve(RemoteEndPoint.Closed())
sock.close()
else:
# Remote connection already arrived, then re-use the connection.
assert isinstance(remote.state, RemoteEndPoint.Valid)
sock.close()
else:
remote.resolve(RemoteEndPoint.Closed())
sock.close()
# create lightweight connection.
st = remote.state
assert isinstance(st, RemoteEndPoint.Valid), \
'RemoteEndPoint state is invalid: ' + str(st)
st.outgoing += 1
lid = st.gen_next_light_id()
st.socket.sendall(pack_u32(ControlHeader.CreatedNewConnection) + pack_u32(lid))
return Connection(self, remote, lid)
def receive(self, *args):
return self.valid_state.queue.get(*args)
class Connection(object):
'A lightweight connection.'
def __init__(self, local, remote, lid):
self._local = local
self._remote = remote
self._lid = lid
self._alive = True
@property
def local(self):
return self._local
@property
def remote(self):
return self._remote
@property
def id(self):
return self._lid
@property
def alive(self):
return self._alive
def close(self):
assert self._alive, 'close an inactive connection.'
self._alive = False
remote_st = self._remote.valid_state
if not remote_st:
print('invalid RemoteEndPoint state', self._remote.state)
return
remote_st.socket.sendall(
pack_u32(ControlHeader.CloseConnection) + pack_u32(self._lid)
)
# garbbage collection.
remote_st.outgoing -= 1
if remote_st.outgoing == 0 and not remote_st.incomings:
remote_st.socket.sendall(
pack_u32(ControlHeader.CloseSocket) + pack_u32(remote_st.last_incoming)
)
# enter closing state, maybe there is incoming connection on the way.
self._remote.closing()
def send(self, buf):
assert self._alive, 'send to an inactive connection.'
self._remote.valid_state.socket.sendall(
pack_u32(self._lid) + prepend_length(buf)
)
class Transport(object):
def __init__(self, addr=None):
'''
addr: (host, port).
None means unaddressable.
'''
if isinstance(addr, str):
ip, port = addr.rsplit(':', 1)
addr = (ip, int(port))
self._bind_addr = addr
self._addr = None
self._local_endpoints = {}
self._next_endpoint_id = 0
if addr:
# Start listening server.
self._server = gevent.server.StreamServer(addr, self.handle_connection)
self._server.start()
# Use read binded port.
#self._addr = (addr[0], self._server.address[1])
def close(self):
# TODO close all the endpoints and connections.
self._server.stop()
@property
def addr(self):
return self._addr
def gen_next_endpoint_id(self):
n = self._next_endpoint_id
self._next_endpoint_id += 1
return n
def endpoint(self):
'Create new local endpoint.'
id = self.gen_next_endpoint_id()
if self._addr:
addr = make_endpoint_addr(self._addr[0].encode(), self._addr[1], id)
else:
addr = random_endpoint_address()
local = LocalEndPoint(self, addr, id)
self._local_endpoints[id] = local
return local
def handle_connection(self, sock, addr):
while True:
protocol_version = unpack_u32(recv_exact(sock, 4))
handshake_len = unpack_u32(recv_exact(sock, 4))
if protocol_version != 0:
sock.sendall(pack_u32(HandshakeResponse.UnsupportedVersion) + pack_u32(0))
recv_exact(sock, handshake_len)
continue
# endpoint id
local = self._local_endpoints.get(unpack_u32(recv_exact(sock, 4)))
if not local:
sock.sendall(pack_u32(HandshakeResponse.InvalidRequest))
break
# remote address
size = unpack_u32(recv_exact(sock, 4))
remote_addr = None
if size > 0:
remote_addr = recv_exact(sock, size)
(host, _, _) = parse_endpoint_addr(remote_addr)
# check their host TODO getnameinfo
num_host = addr[0].encode()
if host != num_host:
# address mismatch
send_many(
sock,
pack_u32(HandshakeResponse.HostMismatch),
prepend_length(host),
prepend_length(num_host)
)
break
if remote_addr:
# local state has to be valid.
local.valid_state.remove_if_invalid(remote_addr)
remote, new = local.get_remote_endpoint(remote_addr, 'them')
if not new:
sock.sendall(pack_u32(HandshakeResponse.Crossed))
# Maybe the connection is already closed at remote end, prob it.
st = remote.valid_state
if st:
st.start_probing()
else:
remote.resolve(RemoteEndPoint.Valid(sock, 'them'))
# send success response
sock.sendall(pack_u32(HandshakeResponse.Accepted))
local.process_messages_loop(sock, remote)
break
if __name__ == '__main__':
from . import config
ep = Transport().endpoint() # Unaddressable transport.
# ep = Transport(('127.0.0.1', 3000)).endpoint()
print('connect')
conn = ep.connect(config.CLUSTER_ADDR)
# cardano node handshake.
# send peer data.
DEFAULT_PEER_DATA = [
764824073, # protocol magic.
[0, 1, 0], # version
{
0x04: [0, cbor.Tag(24, cbor.dumps(0x05))],
0x05: [0, cbor.Tag(24, cbor.dumps(0x04))],
0x06: [0, cbor.Tag(24, cbor.dumps(0x07))],
0x22: [0, cbor.Tag(24, cbor.dumps(0x5e))],
0x25: [0, cbor.Tag(24, cbor.dumps(0x5e))],
0x2b: [0, cbor.Tag(24, cbor.dumps(0x5d))],
0x31: [0, cbor.Tag(24, cbor.dumps(0x5c))],
0x37: [0, cbor.Tag(24, cbor.dumps(0x62))],
0x3d: [0, cbor.Tag(24, cbor.dumps(0x61))],
0x43: [0, cbor.Tag(24, cbor.dumps(0x60))],
0x49: [0, cbor.Tag(24, cbor.dumps(0x5f))],
0x53: [0, cbor.Tag(24, cbor.dumps(0x00))],
0x5c: [0, cbor.Tag(24, cbor.dumps(0x31))],
0x5d: [0, cbor.Tag(24, cbor.dumps(0x2b))],
0x5e: [0, cbor.Tag(24, cbor.dumps(0x25))],
0x5f: [0, cbor.Tag(24, cbor.dumps(0x49))],
0x60: [0, cbor.Tag(24, cbor.dumps(0x43))],
0x61: [0, cbor.Tag(24, cbor.dumps(0x3d))],
0x62: [0, cbor.Tag(24, cbor.dumps(0x37))],
},
{
0x04: [0, cbor.Tag(24, cbor.dumps(0x05))],
0x05: [0, cbor.Tag(24, cbor.dumps(0x04))],
0x06: [0, cbor.Tag(24, cbor.dumps(0x07))],
0x0d: [0, cbor.Tag(24, cbor.dumps(0x00))],
0x0e: [0, cbor.Tag(24, cbor.dumps(0x00))],
0x25: [0, cbor.Tag(24, cbor.dumps(0x5e))],
0x2b: [0, cbor.Tag(24, cbor.dumps(0x5d))],
0x31: [0, cbor.Tag(24, cbor.dumps(0x5c))],
0x37: [0, cbor.Tag(24, cbor.dumps(0x62))],
0x3d: [0, cbor.Tag(24, cbor.dumps(0x61))],
0x43: [0, cbor.Tag(24, cbor.dumps(0x60))],
0x49: [0, cbor.Tag(24, cbor.dumps(0x5f))],
0x53: [0, cbor.Tag(24, cbor.dumps(0x00))],
},
]
conn.send(cbor.dumps(DEFAULT_PEER_DATA, True))
nonce = 1
conn.send(b'S' + struct.pack('>Q', nonce))
cmd = ep.receive() # create new connection
assert isinstance(cmd, Event.ConnectionOpened), 'invalid response'
connid = cmd.connid
cmd = ep.receive() # peerdata
assert isinstance(cmd, Event.Received) and connid == cmd.connid, 'invalid response'
print('peer data response', cbor.loads(cmd.data))
cmd = ep.receive() # nodeid
assert isinstance(cmd, Event.Received) and \
connid == cmd.connid and \
cmd.data[:1] == b'A' and \
struct.unpack('>Q', cmd.data[1:])[0] == nonce, 'invalid response'
print(ep.receive())
<file_sep>FIRST_HARDEN_INDEX = 2147483648
LIGHT_ID_MIN = 1024
HEAVY_ID_MIN = 1
WAIT_TIMEOUT = 60 # Maximum wait timeout on Events.
BIP44_PURPOSE = 0x8000002C
BIP44_COIN_TYPE = 0x80000717 # ada
STREAM_WINDOW = 2048
<file_sep>import gevent
from cardano.transport import Transport, Event, RemoteEndPoint
def test_simple():
server = Transport(('127.0.0.1', 3000))
ep1 = server.endpoint()
client = Transport()
ep2 = client.endpoint()
conn = ep2.connect(ep1.addr)
assert conn.remote.state.outgoing == 1
assert isinstance(ep1.receive(), Event.ConnectionOpened)
conn.send(b'test')
cmd = ep1.receive()
assert isinstance(cmd, Event.Received) and cmd.data == b'test'
conn.close()
assert isinstance(conn.remote.state, RemoteEndPoint.Closing)
assert isinstance(ep1.receive(), Event.ConnectionClosed)
server.close()
def test_cross_connection():
t1 = Transport(('127.0.0.1', 3000))
t2 = Transport(('127.0.0.1', 3001))
ep1 = t1.endpoint()
ep2 = t2.endpoint()
def connect(ep, addr):
conn = ep.connect(addr)
assert conn is not None, 'connect failed.'
assert conn.remote.valid_state.outgoing == 1
# Verify underlying tcp connection is reused.
assert conn.remote.valid_state.origin == ('us' if ep.addr < addr else 'them')
conn.close()
thread1 = gevent.spawn(connect, ep1, ep2.addr)
thread2 = gevent.spawn(connect, ep2, ep1.addr)
thread1.join()
thread2.join()
t1.close()
t2.close()
def test_closing():
t1 = Transport(('127.0.0.1', 3000))
t2 = Transport(('127.0.0.1', 3001))
ep1 = t1.endpoint()
ep2 = t2.endpoint()
print('ep1 connect ep2')
conn1 = ep1.connect(ep2.addr)
print('ep1 connect ep2')
conn2 = ep1.connect(ep2.addr)
print('ep2 connect ep1')
conn3 = ep2.connect(ep1.addr)
print('close conn1')
conn1.close()
print('close conn2')
conn2.close()
print('close conn3')
conn3.close()
gevent.sleep(0.1)
print(ep1.valid_state._remotes[ep2.addr].state,
ep2.valid_state._remotes[ep1.addr].state)
if __name__ == '__main__':
test_simple()
test_cross_connection()
test_closing()
<file_sep>from collections import OrderedDict
import os.path
import json
import binascii
import cbor
import yaml
CONF_DIR = os.path.join(os.path.dirname(__file__), '../conf')
def load_conf():
# try cache yaml result with cbor.
conf_path = os.path.join(CONF_DIR, 'configuration.yaml')
cache_path = os.path.join(CONF_DIR, 'cached_configuration.cbor')
if os.path.exists(cache_path) and \
os.path.getmtime(cache_path) > os.path.getmtime(conf_path):
# cache is good.
return cbor.load(open(cache_path, 'rb'))
with open(conf_path) as fp:
conf = yaml.load(fp)
fp = open(cache_path, 'wb')
try:
fp.write(cbor.dumps(conf))
except: # noqa[W291]
fp.close()
os.remove(cache_path)
raise
else:
fp.close()
return conf
g_config = load_conf()
def hash_json(d):
from .utils import hash_serialized
dumped = json.dumps(d, separators=(',', ':'), sort_keys=True).encode()
return binascii.hexlify(hash_serialized(dumped))
def use(key):
g = globals()
g['CLUSTER_ADDR'] = {
'mainnet': b'relays.cardano-mainnet.iohk.io:3000:0',
'mainnet-staging': b'relays.awstest.iohkdev.io',
'testnet': b'relays.cardano-testnet.iohkdev.io',
}[key]
confkey = {
'mainnet': 'mainnet_full',
'mainnet-staging': 'mainnet_dryrun_full',
'testnet': 'testnet_full',
}[key]
genesis_block_hash = {
'mainnet': binascii.unhexlify(
'89d9b5a5b8ddc8d7e5a6795e9774d97faf1efea59b2caf7eaf9f8c5b32059df4')
}[key]
cfg = g_config[confkey]
g['CHAIN'] = cfg
genesis_cfg = cfg['core']['genesis']['src']
genesis = json.load(open(os.path.join(CONF_DIR, genesis_cfg['file'])),
object_pairs_hook=OrderedDict)
genesis_hash = hash_json(genesis)
assert genesis_hash == genesis_cfg['hash'].encode()
g['GENESIS'] = genesis
g['GENESIS_HASH'] = genesis_hash # genesis block's prev_header
g['GENESIS_BLOCK_HASH'] = genesis_block_hash # FIXME generate genesis block ourself
g['PROTOCOL_MAGIC'] = genesis['protocolConsts']['protocolMagic']
g['SECURITY_PARAMETER_K'] = genesis['protocolConsts']['k']
g['SLOT_DURATION'] = int(genesis['blockVersionData']['slotDuration'])
g['START_TIME'] = genesis['startTime']
g['MAX_BLOCK_SIZE'] = genesis['blockVersionData']['maxBlockSize']
g['MAX_HEADER_SIZE'] = genesis['blockVersionData']['maxHeaderSize']
if __name__ == '__main__':
use('mainnet')
<file_sep>'''
* Use rocksdb as cardano-sl did.
* Store each epoch in seperate db.
'b/' + hash -> block data
'u/' + hash -> undo data
g -> hash of genesis block of epoch.
* Main database:
* 'c/tip' -> hash
* 'b/' + hash -> BlockHeader
* 'e/fl/' + hash -> hash of next block.
* 'ut/t/' + txIn -> TxOut
* 's/' + stake holder id
* 's/ftssum'
* 'a/' + addr -> 1 # address discovery.
Sync
----
* get headers from storage current tip to network tip.
* download blocks and save to db.
'''
import os
import cbor
import rocksdb
from .block import DecodedBlock, DecodedBlockHeader
from . import config
def iter_prefix(db, prefix):
it = db.iteritems()
it.seek(prefix)
for k, v in it:
if not k.startswith(prefix):
break
yield k, v
def remove_prefix(db, prefix):
batch = rocksdb.WriteBatch()
for k, _ in iter_prefix(db, prefix):
batch.delete(k)
db.write(batch)
class Storage(object):
def __init__(self, root_path, readonly=False):
if not os.path.exists(root_path):
os.makedirs(root_path)
self._root_path = root_path
opt = rocksdb.Options(create_if_missing=True)
self.db = rocksdb.DB(os.path.join(self._root_path, 'db'), opt, readonly)
self._tip = None # cache current tip header in memory.
# cache recent used epoch db.
self._current_epoch_db = None
self._current_epoch = None
def epoch_db_path(self, epoch):
return os.path.join(self._root_path, 'epoch%d' % epoch)
def open_epoch_db(self, epoch, readonly=False):
if epoch != self._current_epoch:
self._current_epoch = epoch
self._current_epoch_db = rocksdb.DB(
self.epoch_db_path(epoch),
rocksdb.Options(create_if_missing=True),
readonly
)
return self._current_epoch_db
def tip(self):
if not self._tip:
h = self.db.get(b'c/tip')
if h:
self._tip = self.blockheader(h)
return self._tip
def set_tip(self, hdr, batch=None):
self._tip = hdr
(batch or self.db).put(b'c/tip', hdr.hash())
def blockheader(self, h):
buf = self.db.get(b'b/' + h)
if buf:
return DecodedBlockHeader.from_raw(buf, h)
def raw_block(self, hdr):
db = self.open_epoch_db(hdr.slot()[0], readonly=True)
buf = db.get(b'b/' + hdr.hash())
if buf:
return buf
def block(self, hdr):
raw = self.raw_block(hdr)
if raw:
return DecodedBlock.from_raw(raw)
def undos(self, hdr):
db = self.open_epoch_db(hdr.slot()[0], readonly=True)
buf = db.get(b'u/' + hdr.hash())
if buf:
return cbor.loads(buf)
def genesis_block(self, epoch):
db = self.open_epoch_db(epoch, readonly=True)
h = db.get(b'g')
assert h, 'epoch not exist: %d' % epoch
return DecodedBlock.from_raw(db.get(h))
def blocks_rev(self, start_hash=None):
'Iterate blocks backwardly.'
current_hash = start_hash or self.tip().hash()
current_epoch = self.blockheader(current_hash).slot()[0]
current_epoch_db = self.open_epoch_db(current_epoch, readonly=True)
while True:
raw = current_epoch_db.get(b'b/' + current_hash)
if not raw:
# try decrease epoch id.
current_epoch -= 1
if current_epoch < 0:
break
current_epoch_db = self.open_epoch_db(current_epoch, readonly=True)
continue
blk = DecodedBlock(cbor.loads(raw), raw)
yield blk
current_hash = blk.header().prev_header()
def blocks(self, start_hash=None):
'Iterate blocks forwardly.'
if start_hash:
current_epoch, _ = DecodedBlockHeader(
cbor.loads(self.db.get(b'b/' + start_hash))
).slot()
else:
start_hash = config.GENESIS_BLOCK_HASH
current_epoch = 0
current_epoch_db = self.open_epoch_db(current_epoch, readonly=True)
current_hash = start_hash
raw = current_epoch_db.get(b'b/' + current_hash)
yield DecodedBlock(cbor.loads(raw), raw)
while True:
current_hash = self.db.get(b'e/fl/' + current_hash)
if not current_hash:
return
raw = current_epoch_db.get(b'b/' + current_hash)
if raw:
yield DecodedBlock(cbor.loads(raw), raw)
continue
# try increase epoch number.
current_epoch += 1
current_epoch_db = self.open_epoch_db(current_epoch, readonly=True)
if not current_epoch_db:
return
raw = current_epoch_db.get(b'b/' + current_hash)
if not raw:
return
yield DecodedBlock(cbor.loads(raw), raw)
def blockheaders_rev(self, start=None):
'Iterate block header backwardly.'
current_hash = start or self.tip().hash()
while True:
raw = self.db.get(b'b/' + current_hash)
if not raw:
break
hdr = DecodedBlockHeader(cbor.loads(raw), raw)
yield hdr
current_hash = hdr.prev_header()
def blockheaders(self, start=None):
current_hash = start or config.GENESIS_BLOCK_HASH
while True:
raw = self.db.get(b'b/' + current_hash)
yield DecodedBlockHeader.from_raw(raw, current_hash)
current_hash = self.db.get(b'e/fl/' + current_hash)
if not current_hash:
break
def iter_header_hash(self, start=None):
current_hash = start or config.GENESIS_BLOCK_HASH
while True:
yield current_hash
current_hash = self.db.get(b'e/fl/' + current_hash)
if not current_hash:
break
def blockheaders_noorder(self):
'Iterate block header in rocksdb order, fastest.'
return map(
lambda t: DecodedBlockHeader.from_raw(t[1], t[0][2:]),
iter_prefix(self.db, b'b/')
)
def append_block(self, block):
hdr = block.header()
batch = rocksdb.WriteBatch()
# check prev_hash
tip = self.tip()
if tip:
assert hdr.prev_header() == tip.hash(), 'invalid block.'
h = hdr.hash()
batch.put(b'b/' + h, hdr.raw())
batch.put(b'e/fl/' + hdr.prev_header(), h)
undos = None
if not block.is_genesis():
undos = self._get_block_undos(block)
self.utxo_apply_block(block, batch)
for tx in block.transactions():
for out in tx.outputs():
batch.put(b'a/' + out.addr, b'')
self.set_tip(hdr, batch)
self.db.write(batch)
# write body
epoch, _ = hdr.slot()
db = self.open_epoch_db(epoch, readonly=False)
batch = rocksdb.WriteBatch()
if hdr.is_genesis():
assert not db.get(b'g')
batch.put(b'g', h)
else:
batch.put(b'u/' + h, cbor.dumps(undos))
batch.put(b'b/' + h, block.raw())
db.write(batch)
def _get_block_undos(self, block):
return [[self.get_output(txin) for txin in tx.inputs()]
for tx in block.transactions()]
def utxo_apply_block(self, block, batch):
txins, utxo = block.utxos()
for txin in txins:
batch.delete(b'ut/t/' + cbor.dumps(txin))
for txin, txout in utxo.items():
batch.put(b'ut/t/' + cbor.dumps(txin), cbor.dumps(txout))
def iter_utxo(self):
from .wallet import TxIn, TxOut
prefix = b'ut/t/'
for k, v in iter_prefix(self.db, prefix):
yield TxIn(*cbor.loads(k[len(prefix):])), TxOut(*cbor.loads(v))
def iter_addresses(self):
it = self.db.iterkeys()
it.seek(b'a/')
for k in it:
if not k.startswith(b'a/'):
break
yield k[2:]
def get_output(self, txin):
data = self.db.get(b'ut/t/' + cbor.dumps(txin))
if data:
return cbor.loads(data)
def hash_range(store, hstart, hstop, depth_limit):
if hstart == hstop:
assert depth_limit > 0
yield hstart
return
start = store.blockheader(hstart)
stop = store.blockheader(hstop)
assert start and stop
assert stop.diffculty() > start.diffculty()
assert stop.diffculty() - start.diffculty() < depth_limit
for h in store.iter_header_hash(start):
yield h
if h == stop:
break
def fetch_raw_blocks(store, hstart, hstop):
'''
'''
for h in hash_range(store,
hstart,
hstop,
config.CHAIN['block']['recoveryHeadersMessage']):
yield store.raw_block(store.blockheader(h))
def stream_raw_blocks(store, hstart):
for h in store.iter_header_hash(hstart):
yield store.raw_block(store.blockheader(h))
<file_sep>import hashlib
import time
import cbor
import getpass
from . import config
from . import cbits
def hash_serialized(s):
return hashlib.blake2b(s, digest_size=32).digest()
def hash_data(v):
return hash_serialized(cbor.dumps(v))
def flatten_slotid(slot):
epoch, idx = slot
return epoch * config.SECURITY_PARAMETER_K * 10 + (idx or 0)
def unflatten_slotid(n):
return divmod(n, config.SECURITY_PARAMETER_K * 10)
def get_current_slot():
n = (int(time.time()) - config.START_TIME) // (config.SLOT_DURATION / 1000)
return unflatten_slotid(n)
def input_passphase():
passphase = getpass.getpass('Input passphase:').encode()
if passphase:
return hashlib.blake2b(passphase, digest_size=32).digest()
return passphase
SIGN_TAGS = {
'test': b'\x00',
'tx': b'\x01',
'redeem_tx': b'\x02',
'vss_cert': b'\x03',
'us_proposal': b'\x04',
'commitment': b'\x05',
'us_vote': b'\x06',
'mainblock': b'\x07',
'mainblock_light': b'\x08',
'mainblock_heavy': b'\x09',
'proxy_sk': b'\x0a',
}
def sign_tag(tag):
if tag is None:
return b''
elif tag == 'test':
return b'\x00'
else:
return SIGN_TAGS[tag] + cbor.dumps(config.PROTOCOL_MAGIC)
def sign(tag, sk, data):
msg = sign_tag(tag) + cbor.dumps(data)
return cbits.encrypted_sign(sk, b'', msg)
def verify(tag, pk, sig, data):
msg = sign_tag(tag) + cbor.dumps(data)
return cbits.verify(pk, msg, sig)
<file_sep>Cython==0.28.4
base58==1.0.0
#cbor==1.0.0
gevent==1.3.5
mnemonic==0.18
pbkdf2==1.3
recordclass==0.5
-e git+https://github.com/yihuang/cbor_py.git@e93277397ef8f9336e4f0c97fb30ecc872d31861#egg=cbor
python-rocksdb==0.6.9
dnspython==1.15.0
PyYAML==3.13
appdirs==1.4.3
orderedset==2.0.1
<file_sep>import gevent
from cardano.transport import Transport
from cardano.node import default_node, Message
def test_simple():
t1 = Transport(('127.0.0.1', 3000))
t2 = Transport(('127.0.0.1', 3001))
n1 = default_node(t1.endpoint())
n2 = default_node(t2.endpoint())
worker = n1.worker(Message.GetBlocks, n2.endpoint.addr)
print(list(worker(b'test', b'test')))
worker.close()
print('second try')
worker = n1.worker(Message.GetBlocks, n2.endpoint.addr)
print(list(worker(b'test', b'test')))
worker.close()
t1.close()
t2.close()
if __name__ == '__main__':
test_simple()
gevent.sleep(0.1)
<file_sep>import gevent.queue
import gevent.event
from .node import Message
from .utils import get_current_slot
from .constants import STREAM_WINDOW
from .integrity import verify_header
from . import config
def classify_new_header(tip_header, header):
current_slot = get_current_slot()
hdr_slot = header.slot()
# if hdr_slot[1] == None:
# # genesis block
# print('new header is genesis block')
# return # useless
if hdr_slot > current_slot:
print('new header is for future slot')
return # future slot
if tip_header and hdr_slot <= tip_header.slot():
print('new header slot not advanced than tip')
return
tip_hash = tip_header.hash() if tip_header else config.GENESIS_BLOCK_HASH
if header.prev_header() == tip_hash:
verify_header(header, config.PROTOCOL_MAGIC,
prev_header=tip_header, current_slot=current_slot)
return True # is's a continuation
else:
# check difficulty
if not tip_header or header.difficulty() > tip_header.difficulty():
# longer alternative chain.
return False
class BlockRetriever(object):
def __init__(self, store, node):
self.store = store
self.node = node
# retrieval task queue
self.queue = gevent.queue.Queue(16)
# recovery signal
self._recovery = None
self.event = gevent.event.Event()
self.last_known_header = None
def __call__(self):
while True:
self.event.wait()
self.event.clear()
while not self.queue.empty():
addr, header = self.queue.get(False)
self._handle_retrieval_task(addr, header)
if self._recovery:
self._handle_recovery_task(*self._recovery)
def add_retrieval_task(self, addr, header):
print('add retrieval task', header.difficulty())
self._update_last_known_header(header)
self.queue.put((addr, header))
self.event.set()
def recovering(self):
return bool(self._recovery)
def status(self):
'syncing: return sync progress; not syncing: return None'
if self._recovery:
local = self.store.tip().difficulty()
net = self.last_known_header.difficulty()
return local / net
def _set_recovery_task(self, addr, header):
if self._recovery:
_, old_hdr = self._recovery
if header.difficulty() <= old_hdr.difficulty():
# no need to update
return
if not self._recovery:
print('start recovery', header.difficulty())
else:
print('update recovery target', header.difficulty())
self._recovery = (addr, header)
self.event.set()
def _handle_recovery_task(self, addr, header):
tip_header = self.store.tip()
checkpoints = [tip_header.hash() if tip_header else config.GENESIS_BLOCK_HASH]
# TODO proper checkpoints
self._stream_blocks(addr, checkpoints, header.hash())
def _handle_retrieval_task(self, addr, header):
tip_header = self.store.tip()
if not tip_header:
print('retrieve genesis block')
b = self.node.worker(Message.GetBlocks, addr).one(config.GENESIS_BLOCK_HASH)
self._handle_blocks([b])
tip_header = self.store.tip()
result = classify_new_header(tip_header, header)
if result is True:
# continuation, get a single block.
self._single_block(addr, header.hash())
elif result is False:
# alternative, enter recovery mode.
self._set_recovery_task(addr, header)
else:
print('ignore header', header.difficulty())
def _handle_blocks(self, blocks):
header = None
if self._recovery:
_, header = self._recovery
for blk in blocks:
self.store.append_block(blk)
if header is not None:
# print progress
progress = blk.header().difficulty() / header.difficulty()
print('Syncing... %f%%' % (progress * 100), end='\r')
if progress >= 1:
print('exit recovering')
self._recovery = None
header = None
def _batch_blocks(self, addr, checkpoints, head):
# TODO classify headers
print('request batch blocks')
w_headers = self.node.worker(Message.GetHeaders, addr)
headers = w_headers(checkpoints, head)
if not headers:
return
assert headers[-1].prev_header() == self.store.tip().hash(), \
'Don\'t support forks yet.'
w_blocks = self.node.worker(Message.GetBlocks, addr)
blocks = list(w_blocks(headers[-1].hash(), headers[0].hash()))
self._handle_blocks(blocks)
def _stream_blocks(self, addr, checkpoints, head):
# get blocks [tip] header
worker = self.node.worker(Message.Stream, addr)
if worker:
print('request stream blocks')
self._handle_blocks(worker.start(checkpoints, head, STREAM_WINDOW))
while not worker.ended:
self._handle_blocks(worker.update(STREAM_WINDOW))
else:
self._batch_blocks(addr, checkpoints, head)
def _single_block(self, addr, h):
print('request single block')
w = self.node.worker(Message.GetBlocks, addr)
self._handle_blocks([w.one(h)])
def _update_last_known_header(self, header):
# update last known header
if not self.last_known_header or \
header.difficulty() > self.last_known_header.difficulty():
self.last_known_header = header
<file_sep>header size
-----------
::
protocol magic : n
hash(prev header): 32
body proof
tx proof
number : n
tx root: 32
hash(witnesses): 32
mpc proof
hash(data): 32
hash(vss certificate): 32
hash(delegate payload): 32
hash(update payload): 32
consensus data
slotid: (n, n)
leader public key: 64
difficulty: n
signature: 64 * 4
extra block data: 0
<file_sep>import os
import binascii
import json
from collections import defaultdict
import argparse
import itertools
import base58
import rocksdb
import mnemonic
import gevent
from cardano.transport import Transport, normalize_endpoint_addr
from cardano.storage import Storage, remove_prefix
from cardano.logic import LogicNode
from cardano.constants import FIRST_HARDEN_INDEX
from cardano.address import (
Address, AddressContent,
derive_hdpassphase, xpriv_to_xpub,
derive_key, mnemonic_to_seed, gen_root_xpriv,
derive_address_lagacy
)
from cardano.cbits import encrypted_sign, verify, DERIVATION_V1
from cardano.utils import input_passphase
from cardano import config
def load_wallet_config(args):
cfg_path = os.path.join(args.root, 'wallets', args.name + '.json')
if not os.path.exists(cfg_path):
print('wallet config is not exists:', args.name)
return
return json.load(open(cfg_path))
def handle_run(args):
store = Storage(args.root)
transport = Transport(args.listen)
node = LogicNode(transport.endpoint(), store)
if args.backdoor:
from gevent.backdoor import BackdoorServer
BackdoorServer(
('127.0.0.1', args.backdoor),
banner="Hello from gevent backdoor!",
locals={'node': node}
).start()
gevent.wait()
def handle_sign(args):
passphase = input_passphase()
cfg = load_wallet_config(args)
root_xpriv = binascii.unhexlify(cfg['root_key'])
root_xpub = xpriv_to_xpub(root_xpriv)
hdpass = derive_hdpassphase(root_xpub)
addr = Address.decode_base58(args.addr)
path = addr.get_derive_path(hdpass)
if path is None:
print('the address don\'t belong to this wallet')
return
xpriv = derive_key(root_xpriv, passphase, path, DERIVATION_V1)
xpub = xpriv_to_xpub(xpriv)
if not addr.verify_pubkey(xpub):
print('the passphase is wrong')
return
sig = encrypted_sign(xpriv, passphase, args.message.encode('utf-8'))
print(json.dumps({
'xpub': binascii.hexlify(xpub).decode(),
'addr': args.addr,
'msg': args.message,
'sig': binascii.hexlify(sig).decode(),
}))
def handle_verify(args):
data = json.loads(args.json)
addr = Address.decode_base58(data['addr'])
xpub = binascii.unhexlify(data['xpub'])
pub = xpub[:32]
msg = data['msg'].encode('utf-8')
sig = binascii.unhexlify(data['sig'])
# verify address and pubkey
if not addr.verify_pubkey(xpub):
print('address and xpub is mismatched')
return
# verify signature and pubkey
result = verify(pub, msg, sig)
print('signature is right' if result else 'signature is wrong')
def handle_recache_utxo(args):
store = Storage(args.root)
print('Removing all cached utxo')
remove_prefix(store.db, b'ut/t/')
print('Iterating blocks')
count = 0
for block in store.blocks():
batch = rocksdb.WriteBatch()
store.utxo_apply_block(block, batch)
store.db.write(batch)
count += 1
print('%d' % count, end='\r')
def handle_stat_utxo(args):
store = Storage(args.root)
total_coin = 0
balances = defaultdict(int)
print('Start iterating utxos')
for txin, txout in store.iter_utxo():
total_coin += txout.c
balances[txout.addr] += txout.c
top_balances = itertools.islice(
sorted(balances.items(), key=lambda t: t[1], reverse=True),
10
)
print('total_coin', total_coin / (10**6))
print('top addresses:')
for addr, c in top_balances:
print(' ', base58.b58encode(addr).decode(), c / (10**6))
def create_wallet_with_xpriv(args, name, xpriv):
wallets_root = os.path.join(args.root, 'wallets')
if not os.path.exists(wallets_root):
os.mkdir(wallets_root)
cfg_path = os.path.join(wallets_root, name + '.json')
if os.path.exists(cfg_path):
print('wallet config %s already exists.' % cfg_path)
return False
wallet_config = {
'name': name,
'root_key': binascii.hexlify(xpriv).decode(),
}
s = json.dumps(wallet_config)
open(cfg_path, 'w').write(s)
return True
def create_wallet_with_mnemonic(args, words, recover):
# generate seed and mnemonic.
passphase = input_passphase()
xpriv = gen_root_xpriv(mnemonic_to_seed(words, args.language), passphase)
return create_wallet_with_xpriv(args, args.name, xpriv)
def handle_wallet_create(args):
words = mnemonic.Mnemonic(args.language).generate()
if create_wallet_with_mnemonic(args, words, False):
print('wallet', args.name, 'created,'
' please write down follwing mnemonic words in paper:')
print(words)
def handle_wallet_recover(args):
return create_wallet_with_mnemonic(args, args.mnemonic, True)
def handle_wallet_import(args):
'interactive'
import urllib.request
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
rsp = urllib.request.urlopen('https://127.0.0.1:8090/api/v1/wallets', context=ctx)
except urllib.error.URLError:
print('Please open Daedalus wallet.')
return
data = json.loads(rsp.read())
# load secrets
import cbor
import appdirs
root = appdirs.user_data_dir('Daedalus')
path = os.path.join(root, 'Secrets-1.0', 'secret.key')
secrets = {}
for item in cbor.load(open(path, 'rb'))[2]:
xpriv = item[0]
wid = AddressContent.pubkey(xpriv_to_xpub(xpriv)) \
.address() \
.encode_base58() \
.decode()
secrets[wid] = xpriv
candidates = []
for item in data['data']:
if item['id'] in secrets:
candidates.append((item['id'], item['name']))
for i, (wid, name) in enumerate(candidates):
print('[%d] %s' % (i + 1, name))
index = int(input('Select wallet [1]:') or 1) - 1
if create_wallet_with_xpriv(args,
candidates[index][1],
secrets[candidates[index][0]]):
print('imported', candidates[index][1])
def handle_genaddress(args):
cfg = load_wallet_config(args)
root_key = binascii.unhexlify(cfg['root_key'])
path = [FIRST_HARDEN_INDEX, FIRST_HARDEN_INDEX + args.index]
passphase = input_passphase()
addr = derive_address_lagacy(root_key, passphase, path, DERIVATION_V1)
print(addr.address().encode_base58().decode())
def handle_wallet_balance(args):
cfg = load_wallet_config(args)
root_key = binascii.unhexlify(cfg['root_key'])
hdpass = derive_hdpassphase(xpriv_to_xpub(root_key))
# iterate utxo.
print('Searching for utxo...')
store = Storage(args.root)
txouts = []
for txin, txout in store.iter_utxo():
if Address.decode(txout.addr).get_derive_path(hdpass):
txouts.append(txout)
balance = sum(out.c for out in txouts)
print('balance:', balance)
print('details:')
for out in txouts:
print(base58.b58encode(out.addr), out.c)
def handle_wallet_list(args):
wallet_dir = os.path.join(args.root, 'wallets')
if not os.path.exists(wallet_dir):
return
for f in os.listdir(wallet_dir):
if f.endswith('.json'):
print(f[:-5])
def cli_parser():
common = argparse.ArgumentParser(add_help=False)
common.add_argument(
'--chain',
dest='chain',
default='mainnet',
help='choose chain to use, default mainnet, available options:'
' mainnet, testnet, mainnet-staging'
)
common.add_argument(
'--root',
dest='root',
default='./test_db',
help='root directory for storage, default ./test_db'
)
common.add_argument(
'--listen',
dest='listen',
default=None,
help='ip:port to listen, act as relay node'
)
common.add_argument(
'--connect',
dest='connect',
type=os.fsencode,
default=None,
help='connect to alternate relay server'
)
wallet = argparse.ArgumentParser(add_help=False)
wallet.add_argument(
'--name',
metavar='NAME',
required=True,
help='name of wallet',
)
p_root = argparse.ArgumentParser(description='Python cardano cli.', parents=[common])
sp_root = p_root.add_subparsers(help='actions')
sp_root.add_parser('help', help='Print this help.')
p_run = sp_root.add_parser(
'run',
parents=[common],
help='Run main node, sync and subscribe for new block automatically'
)
p_run.set_defaults(handler=handle_run)
p_run.add_argument(
'--backdoor',
dest='backdoor',
type=int,
help='Port of backdoor server, when not specified, don\'t start backdoor server.'
)
p_utxo = sp_root.add_parser(
'utxo',
parents=[common],
help='UTxO commands.'
)
sp_utxo = p_utxo.add_subparsers(help='Choose wallet sub-command to execute')
p = sp_utxo.add_parser(
're-cache',
parents=[common],
help='Re-create UTxO cache, with block data in local storage.'
)
p.set_defaults(handler=handle_recache_utxo)
p = sp_utxo.add_parser(
'stat',
parents=[common],
help='View statistics of current UTxO cache.'
)
p.set_defaults(handler=handle_stat_utxo)
p = sp_root.add_parser(
'sign',
parents=[wallet],
help='sign message with your secret key'
)
p.set_defaults(handler=handle_sign)
p.add_argument('message', metavar='MESSAGE', help='message to sign')
p.add_argument(
'--addr',
metavar='ADDR',
required=True,
help='ada address belongs to the wallet',
)
p = sp_root.add_parser(
'verify',
help='verify signed message'
)
p.set_defaults(handler=handle_verify)
p.add_argument('json', metavar='JSON', help='json encoded information for verify')
p = sp_root.add_parser(
'create',
parents=[common],
help='create wallet'
)
p.set_defaults(handler=handle_wallet_create)
p.add_argument(
'name',
metavar='NAME',
help='the name of the new wallet',
)
p.add_argument(
'--language',
dest='language',
default='english',
help='use the given language for the mnemonic',
)
p = sp_root.add_parser(
'recover',
parents=[common],
help='recover wallet with mnemonic words'
)
p.set_defaults(handler=handle_wallet_recover)
p.add_argument(
'name',
metavar='NAME',
help='the name of the new wallet',
)
p.add_argument(
'--language',
dest='language',
default='english',
help='use the given language for the mnemonic',
)
p.add_argument(
'--mnemonic',
dest='mnemonic',
required=True,
help='mnemonic words for recovering the wallet',
)
p = sp_root.add_parser(
'import',
help='import wallet from Daedalus'
)
p.set_defaults(handler=handle_wallet_import)
p = sp_root.add_parser(
'genaddress',
parents=[common, wallet],
help='gen address of specified wallet'
)
p.set_defaults(handler=handle_genaddress)
p.add_argument(
'--index',
dest='index',
default=0,
type=int,
help='index of address.'
)
p = sp_root.add_parser(
'balance',
parents=[common, wallet],
help='get wallet balance'
)
p.set_defaults(handler=handle_wallet_balance)
p = sp_root.add_parser(
'list',
parents=[common],
help='list wallets'
)
p.set_defaults(handler=handle_wallet_list)
return p_root
if __name__ == '__main__':
p = cli_parser()
args = p.parse_args()
if 'handler' in args:
config.use(args.chain)
if args.connect:
config.CLUSTER_ADDR = normalize_endpoint_addr(args.connect)
args.handler(args)
else:
p.print_help()
<file_sep>from .address import addr_hash
from .utils import hash_data, verify
from . import config
class VerifyException(Exception):
pass
def body_proof(blk):
if blk.is_genesis():
return hash_data(blk.leaders())
else:
()
def verify_header(
hdr,
header_no_unknown=False,
prev_header=None,
current_slot=None,
leaders=None,
max_header_size=None):
if hdr.protocol_magic() != config.PROTOCOL_MAGIC:
raise VerifyException('protocol magic')
if prev_header is not None:
if hdr.prev_header() != prev_header.hash():
raise VerifyException('prev header hash')
if hdr.difficulty() != prev_header.difficulty() + (0 if hdr.is_genesis() else 1):
raise VerifyException('prev header difficulty')
if hdr.slot() <= prev_header.slot():
raise VerifyException('prev header slot')
if not hdr.is_genesis() and hdr.slot()[0] != prev_header.slot()[0]:
raise VerifyException('prev header epoch')
if current_slot is not None and hdr.slot() > current_slot:
raise VerifyException('slot in future')
if leaders is not None and not hdr.is_genesis() and \
leaders[hdr.slot()[1]] != addr_hash(hdr.leader_key()):
raise VerifyException('leader')
if header_no_unknown and hdr.unknowns():
raise VerifyException('extra header data')
def verify_block_do(blk):
if not blk.is_genesis():
pass
def verify_block(
blk,
max_block_size=None,
body_no_unknown=False,
**kwargs):
verify_block_do(blk)
verify_header(blk.header(), **kwargs)
if max_block_size is not None and len(blk.raw()) > max_block_size:
raise VerifyException('block size')
if body_no_unknown and blk.unknowns():
raise VerifyException('extra block data')
def verify_blocks(blks):
pass
<file_sep>'''
Main data structures of blockchain.
Rather than fully decode the data into python object,
we access the required fields from cbor data.
It's more efficient this way at most scenario.
We also try to cache raw data, to prevent re-serialization.
'''
import cbor
import base64
import binascii
import itertools
from collections import defaultdict
from .utils import hash_serialized, hash_data, verify
from .address import Address, AddressContent
from .random import Random
from . import config
class DecodedBase(object):
def __init__(self, data, raw=None, hash=None):
self.data = data
self._raw = raw
self._hash = hash
@classmethod
def from_raw(cls, raw, hash=None):
return cls(cbor.loads(raw), raw, hash)
def raw(self):
if not self._raw:
self._raw = cbor.dumps(self.data)
return self._raw
def hash(self):
if not self._hash:
self._hash = hash_serialized(self.raw())
return self._hash
class DecodedBlockHeader(DecodedBase):
def prev_header(self):
return self.data[1][1]
def slot(self):
'''
(epoch, slotid)
slotid: None means genesis block.
'''
if self.is_genesis():
epoch = self.data[1][3][0]
slotid = None
else:
epoch, slotid = self.data[1][3][0]
return epoch, slotid
def is_genesis(self):
return self.data[0] == 0
def difficulty(self):
if self.is_genesis():
n, = self.data[1][3][1]
else:
n, = self.data[1][3][2]
return n
def tx_count(self):
if not self.is_genesis():
return self.data[1][2][0][0]
def protocol_magic(self):
return self.data[1][0]
def leader_key(self):
assert not self.is_genesis()
return self.data[1][3][1]
def unknowns(self):
return self.data[1][4][2]
class DecodedTransaction(DecodedBase):
@classmethod
def build(cls, inputs, outputs, attrs=None):
'''
inputs: [(txid, ix)]
outputs: [(address, n)]
'''
data = (
cbor.VarList([ # inputs
(0, cbor.Tag(24, cbor.dumps((txid, ix))))
for txid, ix in inputs
]),
cbor.VarList([ # outputs
(cbor.loads(Address.decode_base58(addr).encode()), c)
for addr, c in outputs
]),
attrs or {} # attrs
)
return cls(data)
def tx(self):
from .wallet import Tx
return Tx(self.hash(), self.inputs(), self.outputs())
def inputs(self):
from .wallet import TxIn
return set(TxIn(*cbor.loads(item.value))
for tag, item in self.data[0]
if tag == 0)
def outputs(self):
from .wallet import TxOut
return [TxOut(cbor.dumps(addr), c)
for addr, c in self.data[1]]
class DecodedTxAux(DecodedBase):
'(Tx, TxWitness)'
@classmethod
def build(cls, tx, witnesses):
'''
witnesses: [(pubkey, signature)]
'''
assert len(tx.inputs()) == len(witnesses)
return cls((
tx.data,
[(0, cbor.Tag(24, cbor.dumps((pk, sig))))
for pk, sig in witnesses]
))
def transaction(self):
return DecodedTransaction(self.data[0])
def verify(self, undo):
'''
undo: [TxOut]
'''
for txin, wit, out in itertools.zip_longest(
self.transaction().inputs(),
self.data[1],
undo):
if wit[0] != 0:
print('only support pubkey witness')
return False
pk, sig = cbor.loads(wit[1].value)
if not out:
return False
addr = Address.decode(out.addr)
if not addr.verify_pubkey(pk):
return False
if not verify('tx', pk, sig, hash_data(self.data[0])):
print('sig verify fail')
return False
return True
class DecodedBlock(DecodedBase):
def header(self):
return DecodedBlockHeader([self.data[0], self.data[1][0]])
def is_genesis(self):
return self.data[0] == 0
def transactions(self):
assert not self.is_genesis()
# GenericBlock -> MainBody -> [(Tx, TxWitness)]
return [DecodedTransaction(tx) for tx, _ in self.data[1][1][0]]
def txaux(self):
assert not self.is_genesis()
# GenericBlock -> MainBody -> [(Tx, TxWitness)]
return [DecodedTxAux(data) for data in self.data[1][1][0]]
def txs(self):
'Transaction list in wallet format.'
return map(lambda t: t.tx(), self.transactions())
def utxos(self):
'Set of inputs spent, and UTxO created.'
from .wallet import TxIn
txins = set()
utxo = {}
# Process in reversed order, so we can remove inputs spent by current block.
for t in reversed(self.transactions()):
tx = t.tx()
for idx, txout in enumerate(tx.outputs):
# new utxo
txin = TxIn(tx.txid, idx)
if txin not in txins:
utxo[txin] = txout
for txin in tx.inputs:
txins.add(txin)
return txins, utxo
def unknowns(self):
return self.data[1][2][0]
def leaders(self):
assert self.is_genesis()
return self.data[1][1]
def genesis_block(prev_header, epoch, leaders):
'create genesis block'
return DecodedBlock([
0,
[[
config.PROTOCOL_MAGIC,
prev_header.hash(),
hash_data(leaders),
[epoch, prev_header.difficulty()],
{}
], leaders],
{}
])
def avvm_pk(s):
s = s.replace('_', '/').replace('-', '+')
s = base64.b64decode(s)
assert len(s) == 32
return s
def genesis_balances():
return [(AddressContent.redeem(avvm_pk(k)).address(), int(v))
for k, v in config.GENESIS['avvmDistr'].items()] + \
[(Address.decode_base58(k), int(v))
for k, v in config.GENESIS['nonAvvmBalances'].items()]
def bootstrap_distr(c):
# bootstrap
stakeholders = config.GENESIS['bootStakeholders']
sum_weight = sum(stakeholders.values())
result = []
if c < sum_weight:
for holder, weight in stakeholders.items():
result.append((binascii.unhexlify(holder), min(c, weight)))
c -= weight
if c < 0:
break
else:
d, m = divmod(c, sum_weight)
stakes = [weight * d for _, weight in stakeholders.items()]
if m > 0:
ix = Random(hash_data(m)).number(len(stakeholders))
stakes[ix] += m
result = zip(map(binascii.unhexlify, stakeholders.keys()), stakes)
return result
def addr_stakes(addr, c):
dist = addr.attrs.get(0)
if dist is None:
return bootstrap_distr(c)
else:
# TODO
assert False
def genesis_stakes():
stakes = defaultdict(int)
for addr, c in genesis_balances():
for holder, n in addr_stakes(addr, c):
stakes[holder] += n
return stakes
def fts(slotcount, seed, coinsum, stakelist):
'if stakelist is consistant with coinsum, no exception'
assert coinsum > 0
# generate coin indexes.
rnd = Random(seed)
indices = [(slot, rnd.number(coinsum)) for slot in range(slotcount)]
indices.sort(key=lambda t: t[1]) # sort by coin index
leaders = []
it = iter(stakelist)
current_holder, upper_range = next(it)
for slot, idx in indices:
while True:
if idx <= upper_range:
leaders.append((slot, current_holder))
break
current_holder, c = next(it)
upper_range += c
assert len(leaders) == slotcount
leaders.sort(key=lambda t: t[0]) # sort by slot index
return [leader for _, leader in leaders]
def genesis_block0():
'create the first genesis block from config.'
stakes = genesis_stakes().items()
# TODO cardano-sl used HM.toList to sort genesis stakes, so...
leaders = fts(
config.GENESIS['protocolConsts']['k'] * 10,
config.GENESIS['ftsSeed'].encode(),
sum(n for _, n in stakes),
stakes,
)
return DecodedBlock([
0,
[[
config.PROTOCOL_MAGIC,
config.GENESIS_HASH,
hash_data(leaders),
[0, 0],
{}
], leaders],
{}
])
if __name__ == '__main__':
config.use('mainnet')
blk = genesis_block0()
leaders = blk.leaders()
from cardano.storage import Storage
store = Storage('test_db')
db_leaders = store.genesis_block(0).leaders()
# compare with official result.
for i in range(10):
print(leaders[i], db_leaders[i])
<file_sep>'''
chacha deterministic random.
seed:
drgNewSeed . seedFromInteger . os2ip $ bytes
gen_bytes:
chacha_generate(ctx, n)
'''
from . import cbits
SEED_LENGTH = 40
class Random(object):
__slots__ = ('_ctx',)
def __init__(self, bs):
n = int.from_bytes(bs, 'big')
n %= 2 ** (SEED_LENGTH * 8)
bs = n.to_bytes(SEED_LENGTH, 'big')
self._ctx = cbits.chacha_random_init(bs)
def bytes(self, n):
return cbits.chacha_random_generate(self._ctx, n)
def number(self, n):
assert n > 0
size = max(4, (n.bit_length() + 7) // 8)
start = (2 ** (size * 8)) % n
while True:
x = int.from_bytes(self.bytes(size), 'big')
if x >= start:
return x % n
def range(self, start, stop):
assert stop >= start
return start + self.number(stop - start + 1)
if __name__ == '__main__':
# seed
from .utils import hash_data
for i in range(10):
rnd = Random(hash_data(i))
for _ in range(10):
print(rnd.number(10), end=' ')
print()
<file_sep>A typical process
-----------------
A worker of C want to have a conversation with a listener in S.
* C calls ``connect(S)``
> create lightweight connection ``conn`` to S with transport api, see `transport.rst`_.
> find peer data is not yet sent, send it. (Other concurrently connecting request will wait for it to finish), see ``Node._peer_sending``.
> C generate locally unique nonce, and send handshake message: ``(SYN, nonce)``.
> Register an ``AsyncResult`` and wait for a ``Queue`` to arrive,
will fired when S connects back, see ``Node._wait_ack``.
> success, ``Conversation(conn, queue)``
* S server side.
- new connection ``connid`` opened, record remote address, see ``Node._incoming_addr``.
- receive the peer data if not exist, see ``Node._peer_received``.
- if not handshaked, receive handshake and check, see ``Node._incoming_nonce``.
* if it's ``(SYN, nonce)``, spawn a thread:
> connect back to C, send peer data if necessary.
> send handshake ``(ACK, nonce)``.
> create ``Queue`` to receive message, associate it with ``connid``, see ``Node._incoming_queues``.
> receive next message from the ``Queue``, decode it as message code.
> index an listener with it and call it.
- Normal messages is put to ``Node._incoming_queues[connid]``.
* C server side.
- new connection ``connid`` opened, record remote address, see ``Node._incoming_addr``.
- receive the peer data if not exist, see ``Node._peer_received``.
- if not handshaked, receive handshake and check, see ``Node._incoming_nonce``.
* if it's ``(ACK, nonce)``, then:
> create ``Queue`` to receive message, associate it with ``connid``, see ``Node._incoming_queues``.
> Put the ``Queue`` to ``AsyncResult`` registered above.
- Normal message is put to ``Node._incoming_queues[connid]``.
| a0e6e19a5b12177b30d20852c1eea2ae90503b3c | [
"Python",
"Text",
"reStructuredText"
] | 23 | reStructuredText | yihuang/python-cardano | fb6758e977c063a4429b2d18c705f9e20a3fc680 | a3638d5e723cbe7fa89a8361d9d1ce3f2285a632 |
refs/heads/master | <file_sep>[run]
source = profiler, tests
<file_sep>from unittest import TestCase
from profiler import install_profiler
def add(x, y):
return x + y
class ProfilerTestCase(TestCase):
def test_profiler(self):
install_profiler()
z = add(1, 2)
self.assertEqual(z, 3)
<file_sep># sys.setprofile and coverage
This is a minimal example of coverage not reporting the lines run in a `sys.setprofile` callback.
To replicate:
* Create a virtualenv
* `pip install -r requirements.txt`
* `coverage run -m unittest`
* `coverage report -m`
```
(profiling-sandbox) ian@ian:~/dev/profiling-sandbox$ coverage run -m unittest
<frame at 0x7f232427fd40, file '/home/ian/dev/profiling-sandbox/tests.py', line 6, code add>
<frame at 0x7f232427fd40, file '/home/ian/dev/profiling-sandbox/tests.py', line 7, code add>
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
(profiling-sandbox) ian@ian:~/dev/profiling-sandbox$ coverage report -m
Name Stmts Miss Cover Missing
-------------------------------------------
profiler.py 6 2 67% 6-7
tests.py 9 0 100%
-------------------------------------------
TOTAL 15 2 87%
```
<file_sep>import sys
def install_profiler():
def profiler(frame, event, arg):
if frame.f_code.co_name == "add":
print(frame)
sys.setprofile(profiler)
| 7e67fff0ba7ba5be1dd2f5448a52fa86fdda89ba | [
"Markdown",
"Python",
"INI"
] | 4 | INI | LilyFoote/profiling-sandbox | 04d0ec5eaf6c01e92405297c47b22fba8ba4b2c9 | 5cf36e50c501832ecf7ec84c1af44fcbee2e9634 |
refs/heads/master | <file_sep>package main
import (
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"math/rand"
"net/http"
"os"
"sync"
"time"
)
const saveQueueLength = 1000
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
const AddForm = `
<form method="POST" action="/add">
URL: <input type="text" name="url">
<input type="submit" value="Add">
</form>
`
var src = rand.NewSource(time.Now().UnixNano())
var store = NewURLStore("store.json")
//var templates = template.Must(template.ParseFiles("edit.html"))
type URLStore struct {
urls map[string]string
mu sync.RWMutex
save chan record
}
type record struct {
Key, URL string
}
func (urlStore *URLStore) Get(key string) string {
urlStore.mu.RLock()
defer urlStore.mu.RUnlock()
return urlStore.urls[key]
}
func (urlStore *URLStore) Set(key, url string) bool {
urlStore.mu.Lock()
defer urlStore.mu.Unlock()
_, exists := urlStore.urls[key]
if exists {
return false
}
urlStore.urls[key] = url
return true
}
func (urlStore *URLStore) Put(url string) string {
for {
key := genKey(5)
if urlStore.Set(key, url) {
urlStore.save <- record{key, url}
return key
}
}
panic("could not set key for the url ")
}
func genKey(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func NewURLStore(filename string) *URLStore {
u := &URLStore{
urls: make(map[string]string),
save: make(chan record, saveQueueLength),
}
if err := u.load(filename); err != nil {
log.Println("URLStore", err)
}
go u.saveLoop(filename)
return u
}
func addHandler(w http.ResponseWriter, r *http.Request) {
url := r.FormValue("url")
if url == "" {
t, _ := template.ParseFiles("edit.html")
t.Execute(w, nil)
return
}
key := store.Put(url)
fmt.Fprintf(w, "http://localhost:8080/%s", key)
}
func redirectHandler(w http.ResponseWriter, r *http.Request) {
key := r.URL.Path[1:]
url := store.Get(key)
if url == "" {
http.NotFound(w, r)
return
}
http.Redirect(w, r, url, http.StatusFound)
}
func (urlStore *URLStore) saveLoop(filename string) {
f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal("URLStore", err)
}
e := json.NewEncoder(f)
for {
r := <-urlStore.save
if err := e.Encode(r); err != nil {
log.Println("URLStore:", err)
}
}
}
func (urlStore *URLStore) load(filename string) error {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
d := json.NewDecoder(f)
for err == nil {
var r record
if err = d.Decode(&r); err == nil {
urlStore.Set(r.Key, r.URL)
}
}
if err == io.EOF {
return nil
}
return err
}
func main() {
http.HandleFunc("/add", addHandler)
http.HandleFunc("/", redirectHandler)
http.ListenAndServe(":8080", nil)
}
<file_sep>package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type Job struct {
id int
randomNum int
}
type Result struct {
job Job
res int
}
//channel to store input
var inputStore = make(chan Job, 10)
//channel to store result after processing each input
var results = make(chan Result, 10)
//work to be done on the input
func work(num int) int{
sum := 0
for num != 0 {
digit := num%10
sum += digit
num = num/10;
}
time.Sleep(2*time.Second)
return sum
}
//worker will results of the work and puts the output in results channel
func worker(wg *sync.WaitGroup) {
for input := range inputStore {
output := Result{input, work(input.randomNum)}
results <- output
}
//If no jobs are availabe in the inputStore, worker will mark itself done
wg.Done()
}
//Create the worker pool with the number of workers required
func createWorkerPool(numOfWorkers int) {
var wg sync.WaitGroup
for i:=0; i < numOfWorkers; i++ {
wg.Add(1)
//worker will need to be created in a seperate thread,
//else it will be blocking worker creation
go worker(&wg)
}
wg.Wait()
//unless we close results "for range" on results resultswill never end
close(results)
}
//simulation function to add inputs to the inputStore channel
func addInputsToStore(numOfInputs int) {
for i:=0; i<numOfInputs; i++ {
randomNum := rand.Intn(10000)
input := Job{i, randomNum}
inputStore <- input
}
//unless we close jobs "for range" on inputStore channel will never end
close(inputStore)
}
//function to check results in the results channel
func readResult(done chan bool) {
for result := range results {
fmt.Printf("Job id %d, input random no %d , sum of digits %d\n",
result.job.id, result.job.randomNum, result.res)
}
done <- true
}
//test func to trigger
func main() {
startTime := time.Now()
noOfInputs := 100
go addInputsToStore(noOfInputs)
done := make(chan bool)
go readResult(done)
noOfWorkers := 100
createWorkerPool(noOfWorkers)
<-done
endTime := time.Now()
diff := endTime.Sub(startTime)
fmt.Println("total time taken ", diff.Seconds(), "seconds")
}
| f4959da0d366fae41a83329a809ae88c697e01cb | [
"Go"
] | 2 | Go | sandeepsambidi/goProjects | f7774b16162cf0725b476cd80622e1eacdd05efc | 636ed7fd3e32cb206383250def583c10fd0adc1d |
refs/heads/master | <file_sep>module.exports = {
"jwtSecret": "spanikopitafridarita",
"database": "mongodb://llmaddox:<EMAIL>:53400/voice-your-vote"
};<file_sep>import React from 'react';
import {
Link
} from 'react-router-dom';
import { NotFoundPage } from './NotFoundPage';
import { Chart } from './PieChart';
import axios from 'axios';
import Auth from '../modules/Auth';
import PropTypes from 'prop-types';
class PollPage extends React.Component {
constructor(props) {
super(props);
this.state = {
poll: { "name": "Placeholder Poll", "options": []},
selection: "",
message: "",
id: this.props.id,
loaded: false,
showButtons: false
};
}
componentDidMount(){
this.loadPollFromServer(this.setLoadedTrue.bind(this));
this.checkCorrectUser();
}
componentWillReceiveProps(nextProps){
if(nextProps.message != this.state.message){
this.setState({
message: nextProps.message
});
}
}
setLoadedTrue(){
this.setState({
loaded: true
});
}
loadPollFromServer(callback){
let id = this.state.id;
axios.get('/api/base/polls/' + id)
.then(res => {
if(res.data.length != 0){
this.setState({ poll: res.data[0] });
}
callback();
})
.catch(err => {
console.log(err);
});
}
checkCorrectUser(){
let id = this.state.id;
let token = Auth.getToken();
let headers = { 'Authorization': 'bearer: ' + token };
axios.get('/api/restricted/polls/' + id, { headers: headers })
.then(res => {
this.setState({ showButtons: true });
})
.catch(err => {
if (err) throw err;
});
}
postPollVoteToServer(){
let id = this.state.id;
let selection = this.state.selection;
axios.post('/api/base/polls/' + id, {
"name": selection
})
.then(res => {
this.setState({ message: res.data.message });
this.loadPollFromServer();
})
.catch(err => {
console.log(err);
});
}
handleChange(event) {
this.setState({selection: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
var pollChoice = { name: this.state.selection };
this.postPollVoteToServer();
}
handleDelete(){
if(confirm("Are you sure you want to delete this poll?")){
let id = this.state.id;
let token = Auth.getToken();
axios.delete('/api/restricted/polls/' + id, {
headers: { "Authorization": "bearer: " + token }
})
.then(res => {
this.context.router.history.push('/');
this.props.updateActionStatusMessage('poll deleted');
})
.catch(err => {
console.log(err);
});
}
}
render(){
const poll = this.state.poll;
let id = this.state.id;
let message = this.state.message;
let loaded = this.state.loaded;
if(!loaded) {
return <h2> Loading data </h2>;
}
if (loaded && poll.name == "Placeholder Poll"){
return <NotFoundPage />;
}
let chart = ""; //only show chart if votes exist
if(loaded){
for(i = 0; i < poll.options.length; i++){
for(var prop in poll.options[i]){
if(prop == "votes" && poll.options[i][prop] > 0){
chart = <Chart data={poll} />;
}
}
}
}
var options = [];
for(var i = 0; i < poll.options.length; i++){
options.push(poll.options[i]["name"]);
}
let deleteAndEditButtons;
let editPath = id + '/edit';
if(this.state.showButtons){
deleteAndEditButtons =
<div className="col-10 offset-1 col-md-4 offset-md-2">
<button id="add-poll-options-button" className="btn btn-default">
<Link to={editPath}> Add Poll Options</Link>
</button>
<button className="btn btn-default" onClick={this.handleDelete.bind(this)}>
Delete Poll
</button>
</div>;
}
let messageDiv;
if(message != ""){
messageDiv= <div className="row">
<div className="col-10 offset-1 col-md-8 offset-md-1 success-message-wrapper">
<div className="row">
<h4 className="success-message">{message}</h4>
</div>
</div>
</div>;
}
return (
<div>
<div>
{messageDiv}
</div>
<div className="poll poll-top row">
<div className="col-10 offset-1 col-md-4 offset-md-2">
<div className="row">
<h2 className="poll-name">Poll: {poll.name}</h2>
</div>
<section className="description">
<div className="row">
<h4 className="poll-description">{poll.description}</h4>
</div>
</section>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className="form-group">
<label htmlFor="option-select">Vote for your favorite</label>
<select id="option-select" className="form-control" value={this.state.selection} onChange={this.handleChange.bind(this)}>
<option defaultValue>Pick your favorite...</option>
{options.map(option => (
<option key={option} value={option}>{option}</option>
))}
</select>
</div>
<button type="submit" id="vote-button" className="btn btn-primary">Vote!</button>
</form>
</div>
<div className="col-10 offset-1 col-md-3 offset-md-1">
<div className="row">
{chart}
</div>
</div>
</div>
<div className="poll row">
{deleteAndEditButtons}
</div>
<div className="row">
<div className="col-10 offset-1 col-md-4 offset-md-2">
<div className="navigateBack">
<Link to="/">« Back to the index</Link>
</div>
</div>
</div>
</div>
);
}
}
PollPage.contextTypes = {
router: React.PropTypes.object
};
export default PollPage;<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import Auth from '../modules/Auth';
import PropTypes from 'prop-types';
class Logout extends React.Component {
componentWillMount() {
Auth.deauthenticateUser();
this.context.router.history.replace('/');
this.props.handleLogout();
}
render() {
return null;
}
}
Logout.contextTypes = {
router: React.PropTypes.object
};
export default Logout;<file_sep>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
// Import routing components
import {BrowserRouter as Router, Route, Switch, Link} from 'react-router-dom';
import { browserHistory } from 'react-router';
import IndexPage from './components/IndexPage';
import PollPage from './components/PollPage';
import Login from './components/Login';
import Logout from './components/Logout';
import Account from './components/Account';
import Signup from './components/Signup';
import AddPoll from './components/AddPoll';
import CheckCorrectUser from './components/CheckCorrectUser';
import Auth from './modules/Auth';
const handleAddLinkFollow = ( ) => {
if(Auth.isUserAuthenticated()){
return <AddPoll />;
} else {
alert("You are not authorized to add new polls");
return null;
}
};
class Index extends React.Component {
constructor() {
super();
this.state = {
loggedIN: false,
actionStatus: ""
};
}
componentDidMount(){
if(Auth.isUserAuthenticated()){
this.setState({
loggedIN: true
})
}
}
updateActionStatusMessage(status){
let message;
if(status == "poll deleted"){
message = "Successfully deleted poll";
} else if(status == "poll added"){
message = "Successfully created poll";
} else if (status == "poll options added"){
message = "Added new options to poll";
} else {
//do nothing
}
this.setState({
actionStatus: message
});
setTimeout(this.clearMessage.bind(this), 3000);
}
clearMessage(){
this.setState({actionStatus: ""});
}
handleCorrectLogin(){
this.setState({
loggedIN: true
});
}
handleLogout(){
this.setState({
loggedIN: false
});
}
render() {
let navLinks;
if(this.state.loggedIN){
navLinks =
<div>
<ul className="nav navbar-nav">
<li className="nav-item"><Link to="/">Home</Link></li>
<li className="nav-item"><Link to="/account">Account</Link></li>
<li className="nav-item"><Link to="/polls/new">Add Poll</Link></li>
<li className="nav-item"><Link to="/logout">Logout</Link></li>
</ul>
</div>;
} else {
navLinks =
<div>
<ul className="nav navbar-nav">
<li className="nav-item"><Link to="/">Home</Link></li>
<li className="nav-item"><Link to="/signup">Signup</Link></li>
<li className="nav-item"><Link to="/login">Login</Link></li>
</ul>
</div>
}
return (
<Router history={browserHistory}>
<div>
<nav className="navbar navbar-toggleable-sm navbar-light">
<button className="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="navbar-header">
<a className="navbar-brand" href="#">Voice your Vote</a>
</div>
<div className="collapse navbar-collapse justify-content-end" id="navbarContent">
{navLinks}
</div>
</nav>
<Switch>
<Route path="/" exact={true} render={()=><IndexPage message={this.state.actionStatus} clearMessage={this.clearMessage.bind(this)} />} />
<Route path="/polls/new" exact={true} component={handleAddLinkFollow} />
<Route path="/polls/:id/edit" render={( { match } )=> <CheckCorrectUser id ={match.params.id} updateActionStatusMessage={this.updateActionStatusMessage.bind(this)} clearMessage={this.clearMessage.bind(this)} /> } />
<Route path="/polls/:id" render={({ match })=><PollPage message={this.state.actionStatus} updateActionStatusMessage={this.updateActionStatusMessage.bind(this)} clearMessage={this.clearMessage.bind(this)} id={match.params.id} />} />
<Route path="/login" render={()=><Login handleCorrectLogin={this.handleCorrectLogin.bind(this)} />} />
<Route path='/logout' render={()=><Logout handleLogout={this.handleLogout.bind(this)} />} />
<Route path="/signup" component={Signup} />
<Route path="/account" component={Account} />
</Switch>
</div>
</Router>
);
}
}
ReactDOM.render(<Index />, document.getElementById("container"));
<file_sep># Voice Your Vote
A simple poll voting app using Node, Express, React, MongoDB, and D3. Authenticated users can add, edit, and delete polls.
Any visitor can vote on polls.
## Upcoming features
Limit number of polls initially returned on home page.
See live at [voice-your-vote.herokuapp.com](http://voice-your-vote.herokuapp.com)<file_sep>const express = require('express');
const app = express();
module.exports = (req, res, next) => {
const MongoClient = require('mongodb').MongoClient;
const config = require('../../config');
//first allow routes that don't require authorization
var ObjectId = require('mongodb').ObjectId;
var mongoUrl = config.database
return MongoClient.connect(mongoUrl, (err, db) => {
if (err) throw err;
var db = db;
var id = req.params.id;
var userEmail = req.user.email;
db.collection('polls').find( { _id: ObjectId(id), user: userEmail } ).toArray(function(err, userInfo) {
if(err) throw err;
if(userInfo.length == 0){
return res.status(401).end();
}
return next();
});
}); // end of connection
};<file_sep>"use strict";
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const config = require('../../config');
const router = new express.Router();
var ObjectId = require('mongodb').ObjectId;
var mongoUrl = config.database;
MongoClient.connect(mongoUrl, (err, db) => {
if (err) throw err;
var db = db;
router.post('/polls/create', function (req,res){
//validate form before adding
if(req.body.name == "" || req.body.options.length == 0){
return res.status(400).json( { errors:
{ name: "Poll must contain a name.", options: "Poll must contain at least one option."}});
} else if(req.body.name == ""){
return res.status(400).json( { errors:
{ name: "Poll must contain a name." }});
} else if(req.body.options.length == 0){
return res.status(400).json( { errors: { options: "Poll must contain at least one option."} });
} else {
addNewPoll(req.body,req.user.email, function(poll){
var path = "/polls/" + poll.ops[0]["_id"];
res.status(201).json({ location: path, message: 'Poll added'});
});
}
});
function addNewPoll(record, userEmail, callback){
var item = { "name": record["name"], "description": record["description"], options: record["options"],user: userEmail };
db.collection('polls').insert( item , function(err,result){
if(err) throw err;
console.log("just added the following record to the database: " + JSON.stringify(result.ops));
callback(result);
});
}
const authorizationCheckMiddleware = require('../middleware/user-authorization');
router.use('/polls/:id', authorizationCheckMiddleware);
//this is to assess whether to include edit/delete buttons
router.get('/polls/:id', function(req,res){
res.status(200).end();
});
router.post('/polls/:id/edit', function (req, res){
var id = req.params.id;
var options = req.body.options;
updatePollInfo(id, options, respondToUpdate);
function respondToUpdate(record){
res.json({ message: 'Poll updated'});
};
});
function updatePollInfo(id,options,callback){
db.collection('polls').update({ _id: ObjectId(id) },{ $set: { "options": options } }, function(err,record){
if (err) throw err;
callback(record);
});
}
router.delete('/polls/:id', function (req, res){
var id = req.params.id;
deletePoll(id, respondToDeletion);
function respondToDeletion(){
res.json( {"message": "successfully deleted poll"});
}
});
function deletePoll(id, callback){
db.collection('polls').remove( { "_id": ObjectId(id) }, function(err,result){
if(err) throw err;
callback();
});
}
//user info
router.get('/account', function (req, res){
//this should be returned by auth check
var user = req.user;
getPollInfoForUser(user, sumVotesForEachRecord);
var account_summary = [];
function sumVotesForEachRecord(records){
records.forEach(function(el){
var votes = 0;
var temp_hash = {};
el.options.forEach(function(option){
votes += option["votes"];
});
temp_hash["id"] = el["_id"];
temp_hash["name"] = el["name"];
temp_hash["votes"] = votes;
account_summary.push(temp_hash);
});
res.json( { "vote summary": account_summary });
}
});
function getPollInfoForUser(user, callback){
// db.collection('polls').aggregate.match({ user: user.email}).unwind('options').group({'_id':'$_id','': {'$push': '$players'}})
db.collection('polls').find({ user: user.email }, {"name": 1, "options.votes": 1 }).sort( { "name": 1 } ).toArray(function(err, record) {
if(err) throw err;
callback(record);
});
}
}); //end of connection
module.exports = router;<file_sep>import React from 'react';
import axios from 'axios';
import Auth from '../modules/Auth';
import AcctChart from './AcctChart';
import { Link } from 'react-router-dom';
class Account extends React.Component {
constructor(props) {
super(props);
this.state = {
polls: [{ "name": "", "votes": 0, "showActiveTooltip": false, "showDeleteTooltip": false }],
loaded: false
};
}
componentDidMount(){
this.loadPollsFromServer(this.setLoadedTrue.bind(this));
}
loadPollsFromServer(callback){
let token = Auth.getToken();
let headers = { 'Authorization': 'bearer: ' + token };
axios.get('api/restricted/account', { headers: headers})
.then(res => {
let polls = res.data["vote summary"];
polls.forEach(function(val){
val["showEditTooltip"] = false;
val["showDeleteTooltip"] = false;
});
this.setState({ polls: res.data["vote summary"] });
callback();
})
.catch(err => {
console.log(err);
});
}
setLoadedTrue(){
this.setState({
loaded:true
});
}
handleDelete(id, event){
if(confirm("Are you sure you want to delete this poll?")){
let token = Auth.getToken();
axios.delete('/api/restricted/polls/' + id, {
headers: { "Authorization": "bearer: " + token }
})
.then(res => {
this.loadPollsFromServer(this.setLoadedTrue.bind(this));
})
.catch(err => {
console.log(err);
});
}
}
showTooltip(action, event){
let polls = this.state.polls.slice();
var index = event.target.id.match(/\d+/);
if(action == "edit"){
polls[index].showEditTooltip = true;
}
if(action == "delete"){
polls[index].showDeleteTooltip = true;
}
this.setState({
polls: polls
});
}
hideTooltip(action, event){
let polls = this.state.polls.slice();
let index = event.target.id.match(/\d+/)[0];
if(action == "edit"){
polls[index].showEditTooltip = false;
}
if(action == "delete"){
polls[index].showDeleteTooltip = false;
}
this.setState({
polls: polls
});
}
showPoll(poll, index){
let deleteTooltip;
let editTooltip;
let deleteIconClass = "fa fa-trash-o fa-lg";
let editIconClass = "fa fa-pencil fa-fw";
if(poll.showDeleteTooltip){
deleteTooltip = <div className="icon-tooltip">Delete Poll</div>;
deleteIconClass += " tooltip-parent";
}
if(poll.showEditTooltip){
editTooltip = <div className="icon-tooltip">Edit Poll</div>;
editIconClass += " tooltip-parent";
}
return (<div>
<Link to={'/polls/' + poll["id"]}><span>{poll.name}</span></Link>
<Link to={'/polls/' + poll["id"] + '/edit'}><i className={editIconClass} id={"edit-icon-" + index} onMouseOver={this.showTooltip.bind(this, "edit")} onMouseOut=
{this.hideTooltip.bind(this, "edit")}>{editTooltip}</i></Link>
<Link to="/account/#"><i className={deleteIconClass} id={"delete-icon-" + index} onMouseOver={this.showTooltip.bind(this, "delete")} onMouseOut=
{this.hideTooltip.bind(this, "delete")}
onClick={this.handleDelete.bind(this, poll["id"])}>{deleteTooltip}</i></Link>
</div> );
}
render() {
let acctChart;
if(this.state.loaded){
acctChart = <AcctChart polls={this.state.polls} />;
}
return (
<div className="row">
<div className="col-10 offset-1 col-md-6 offset-md-2 graph-header"><h3>Your Polls</h3></div>
<div className="col-10 offset-1 col-md-6 offset-md-2">
<div className="row">
{acctChart}
</div>
</div>
<div className="col-10 offset-1 col-md-3 offset-md-1">
<div className="summary row">
<div className="polls-list" >{this.state.polls.map((poll,index) => this.showPoll(poll, index)) }
</div>
</div>
</div>
</div>
);
}
}
export default Account;<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Auth from '../modules/Auth';
import { browserHistory } from 'react-router';
import PropTypes from 'prop-types';
import IndexPage from './IndexPage';
class EditPoll extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
pollName: "",
description: "",
originalOptionsList: [{"name": ""}],
additionalOptionsList: [{"name": ""}]
};
}
componentDidMount(){
this.loadPollFromServer();
}
loadPollFromServer(){
let id = this.props.id;
let token = Auth.getToken();
let headers = { 'Authorization': 'bearer: ' + token };
axios.get('/api/base/polls/' + id, { headers: headers })
.then(res => {
this.setState({
pollName: res.data[0].name,
description: res.data[0].description,
originalOptionsList: res.data[0].options
});
})
.catch(err => {
console.log(err);
});
}
handleChange(event) {
const id = event.target.id;
const index = id.match(/\d+/)[0];
const options = this.state.additionalOptionsList;
options[index] = {"name": event.target.value, "votes": 0 };
this.setState({
options: options
});
}
handleAddOptions(event){
event.preventDefault();
const options = this.state.additionalOptionsList;
options.push({"name": ""});
this.setState({
additionalOptionsList: options,
});
}
handleRemoveOption(event){
event.preventDefault();
const options = this.state.additionalOptionsList;
var index = event.target.id.match(/\d+/)[0];
console.log("test for index, it's " + index);
if(options.length == 1){
alert("Cannot delete option. You must add at least one item to edit a poll");
} else {
options.splice(index,1);
this.setState({
additionalOptionsList: options
});
}
}
handleSubmit(event){
event.preventDefault();
this.removeEmptyOptions(this.postPollToServer.bind(this));
}
removeEmptyOptions(callback){
let newOptions = this.state.additionalOptionsList;
let originalOptions = this.state.originalOptionsList;
let filteredList = originalOptions;
for(var i =0; i < newOptions.length; i++){
if(newOptions[i].name != ""){
filteredList.push(newOptions[i]);
}
}
callback(filteredList, this.props.id);
}
postPollToServer(filteredOptionsList, id){
let token = Auth.getToken();
let headers = { 'Authorization': 'bearer: ' + token };
var that = this;
axios.post('/api/restricted/polls/' + id + '/edit', {
'options': filteredOptionsList },{ headers: headers })
.then(function (response) {
let pollPath = '/polls/' + id;
that.context.router.history.push(pollPath);
that.props.handleSuccessfulEdit();
})
.catch(function (error) {
console.log(error);
});
}
render() {
let newOptions = [];
let optionBlock;
for(var i = 0; i < this.state.additionalOptionsList.length; i++){
optionBlock =
<div className="form-group" id={"form-group-" + i}>
<label htmlFor={"poll-options-" + i}> New Option</label>
<input type="text" className="form-control new-poll-options" placeholder="Option" id={"poll-options-" + i}
onChange={this.handleChange.bind(this)} value={this.state.additionalOptionsList[i].name}></input>
<a href="#"><i className="fa fa-times" id={"poll-remove-options-icon-" +i} aria-hidden="true" onClick={this.handleRemoveOption.bind(this)}></i></a>
</div>;
newOptions.push(optionBlock);
}
let pollName = this.state.pollName;
let description = this.state.description;
let originalOptions = [];
for(i = 0; i < this.state.originalOptionsList.length; i++){
for(var prop in this.state.originalOptionsList[i]){
if(prop == "name"){
originalOptions.push(this.state.originalOptionsList[i][prop]);
}
}
}
return (
<div className="home">
<div className="row">
<div className="col-10 offset-1 col-md-8 offset-md-2">
<h2>{pollName}</h2>
</div>
</div>
<div className="row">
<div className="col-10 offset-1 col-md-8 offset-md-2">
<h4 className="poll-description">{description}</h4>
</div>
</div>
<div className="row">
<div className="col-10 offset-1 col-md-6 offset-md-2 col-lg-4">
<form onSubmit={this.handleSubmit.bind(this)}>
<h3 className="edit-form-header">Add New Options</h3>
<div className="new-options-list">
{newOptions.map(option => ( <div>{option}</div>))}
</div>
<div className="row">
<button className="btn btn-default btn-sm add-option-button" onClick={this.handleAddOptions.bind(this)}>Add Another Option</button>
</div>
<div className="row">Existing Options</div>
<ul className="original-options-list">
{originalOptions.map(option => ( <li>{option}</li>))}
</ul>
<div className="row submit-button-row">
<button type="submit" id="add-options-submit-button" className="btn btn-primary">Add Options to Poll</button>
</div>
</form>
</div>
</div>
</div>
);
}
}
EditPoll.contextTypes = {
router: React.PropTypes.object
};
export default EditPoll;<file_sep>import React from 'react';
import { Pie } from './Pie';
export class Chart extends React.Component {
constructor(props){
super(props);
this.state = {
data: this.props.data,
};
}
componentWillReceiveProps(nextProps){
if(this.props != nextProps){
this.setState({
data: nextProps.data
});
}
}
render() {
let data = this.state.data.options;
const width = "450";
const height = "300";
const radius = Math.min(width, height) / 2;
let chart = "Chart loading";
if(data.length > 0){
chart = <Pie data={data} radius={radius} width={width} height={height} />;
}
return (
<div>
{chart}
</div>
);
}
}
<file_sep> import React from 'react';
import * as d3 from 'd3';
export default class AccountDataSeries extends React.Component {
componentDidMount(){
this.renderAxes();
}
renderAxes(){
var xNode = this.refs.xAxis;
var xAxis = d3.axisBottom(this.props.xScale).tickSizeOuter(0);
d3.select(xNode).call(xAxis);
var tickText = d3.selectAll(".tick text");
tickText.call(this.wrap, this.props.xScale.bandwidth());
var yNode = this.refs.yAxis;
var yAxis = d3.axisRight(this.props.yScale).ticks(6).tickSizeOuter(0);
d3.select(yNode).call(yAxis);
d3.selectAll(".tick")
.each(function (d) {
if ( d === 0 ) {
this.remove();
}
});
}
wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
showTooltip (d,x,y, barHeight){
const width = 125;
const tooltipHeight = 30;
let rectX = x - 10;
rectX = rectX.toString();
let rectY = y + barHeight/2;
rectY = rectY.toString();
console.log("test for name length, it's " + d.name.length);
let charFromDefault = d.name.length - 15;
if(charFromDefault > 0){
console.log("test for name length inside if clause, it's " + d.name.length);
d.name = d.name.substring(0,15) + "...";
}
let textX = x + 5;
textX.toString();
let textY = y + 20 +barHeight/2;
textY.toString();
let tooltip = d3.select("#account-tooltip");
tooltip.transition().duration(200).style("opacity", .9);
tooltip.html("<rect x='" +rectX + "' y='" + rectY + "' width='" + width + "' height='" + tooltipHeight + "'></rect><text x='" + textX + "'y='"+
textY + "' >" + d.name + ": " + d.votes + "</text>");
}
hideTooltip(){
let tooltip = d3.select("#account-tooltip");
tooltip.transition().duration(1000).style("opacity", 0);
}
render() {
let bars;
let data = this.props.data;
let chartHeight = this.props.height - this.props.margins.marginTop - this.props.margins.marginBottom;
let chartWidth = this.props.width - this.props.margins.marginLeft - this.props.margins.marginRight;
let xScale = this.props.xScale;
let yScale = this.props.yScale;
bars = data.map((d, i) => {
let y = yScale(d.votes);
let x = xScale(d.name);
let height = chartHeight - yScale(d.votes);
return (
<g key={'g-rect' + i}>
<rect className="bar-chart-rectangle" key = {'rect' + i} x={x} height={height}
y={y}
width={xScale.bandwidth()} onMouseOver={this.showTooltip.bind(this, d,x,y,height, this.wrapTooltipText)} onMouseOut={this.hideTooltip.bind(this)} />
</g>
);
});
return (
<g transform="translate(50,40)">
<g>{bars}</g>
<g className="x-axis" ref="xAxis" transform={"translate(0," + chartHeight + ")"}></g>
<g className="y-axis" ref="yAxis"></g>
<text className="chart-title" textAnchor="middle" x="220" y="-20">Number of Votes per Poll</text>
<text className="y-label" textAnchor="end" y="-20" x ="-50" transform="rotate(-90)">Number of Votes</text>
<text className="x-label" textAnchor="end" y="330" x ={chartWidth/2}>Poll Name</text>
<g id="account-tooltip"></g>
</g>
);
}
} | ad7385fe586af12b3b54b9463f718756e8962efc | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | LindseyMaddox/Voice-your-vote | ddebde2bdbbd610dcc7f356cc8cbc796dcb7e1d7 | b4829f306e5e6427bc2f10503ddb8df6b5004224 |
refs/heads/master | <file_sep>var influx = require('influx');
var AWS = require('aws-sdk');
var request = require('request');
var parse = require('parse-duration');
var _ = require('lodash');
require('required_env')([
'NAGGER_INFLUX_HOST',
{
var: 'NAGGER_INFLUX_PORT',
default: '8086'
},
{
var: 'NAGGER_INFLUX_PROTOCOL',
default: 'http'
},
'NAGGER_INFLUX_USER',
'NAGGER_INFLUX_PASS',
{
var: 'NAGGER_INTERVAL',
default: '1m'
},
'NAGGER_SNS_TOPIC',
'NAGGER_AWS_ACCESS_KEY',
'NAGGER_AWS_SECRET',
{
var: 'NAGGER_SNS_REGION',
default: 'ap-southeast-2'
},
'NAGGER_WATCHER_URL'
]);
var sns = new AWS.SNS({
accessKeyId: process.env.NAGGER_AWS_ACCESS_KEY,
secretAccessKey: process.env.NAGGER_AWS_SECRET,
region: process.env.NAGGER_SNS_REGION
});
var createInfluxClients = function(databases) {
var clients = {};
databases.forEach(function(database) {
clients[database] = influx({
host: process.env.NAGGER_INFLUX_HOST,
port: process.env.NAGGER_INFLUX_PORT,
protocol: process.env.NAGGER_INFLUX_PROTOCOL,
username: process.env.NAGGER_INFLUX_USER,
password: <PASSWORD>.<PASSWORD>,
database: database
});
});
return clients;
};
var buildQueryString = function(selector, set, limit) {
return 'SELECT ' + selector + ' AS value FROM ' + set + ' WHERE time > now() - ' + process.env.NAGGER_INTERVAL + ' AND value ' + limit + ' GROUP BY time(1s)';
};
var send_alert = function(watcher, row, point) {
var alert = [watcher.name, 'alert!', row.name, 'measured', point[1], 'at', new Date(point[0])].join(' ');
console.log(alert);
var params = {
Message: alert,
Subject: alert,
TopicArn: process.env.NAGGER_SNS_TOPIC
};
sns.publish(params, function(err, data) {
if (err) throw err;
});
};
var getWatchers = function(watcher_url, cb) {
request.get(watcher_url, function(err, res, body) {
if (err) throw err;
cb(JSON.parse(body));
});
};
var main_loop = function() {
getWatchers(process.env.NAGGER_WATCHER_URL, function(watchers) {
var clients = createInfluxClients(_.pluck(watchers, 'database'));
watchers.forEach(function(watcher) {
clients[watcher.database].query(buildQueryString(watcher.selector, watcher.set, watcher.limit), function(err, res) {
if (err) console.error(err);
res.forEach(function(row) {
row.points.forEach(function(point) {
send_alert(watcher, row, point);
});
});
});
});
});
};
setInterval(main_loop, parse(process.env.NAGGER_INTERVAL));
main_loop();
| 51b3b49459e93c98cb3e43b953679f67172dd5e0 | [
"JavaScript"
] | 1 | JavaScript | Prismatik/nagger | 18e4c6b534df33b985d85a7b9dc406d676a13ea1 | b697ad6d64ee6bd630f17b308447fa52331b0952 |
refs/heads/master | <file_sep>#define EOF '.'
#define YES 1
#define NO 0
#define WORDLEN 20
main() /* print word length histogram */
{
int c, i, j, inword, cc = 0;
int wl[WORDLEN];
for (i = 0; i < WORDLEN; ++i)
wl[i] = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
inword = NO;
++wl[cc];
cc = 0;
} else if (inword == NO) {
inword = YES;
++cc;
} else if (inword == YES) {
++cc;
}
}
printf("Word Length Histogram\n");
printf("---------------------\n");
for (i = 1; i < WORDLEN; ++i) {
printf("%d | ", i);
for (j = 0; j < wl[i]; ++j)
printf("*");
putchar('\n');
}
}<file_sep>#define EOF '.'
#define YES 1
#define NO 0
main()
{
int c, inspaces = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' && inspaces == NO) {
putchar(c);
inspaces = YES;
} else {
putchar(c);
inspaces = NO;
}
}
}<file_sep>main()
{
printf("Hello\x World\n");
printf("Hello Wo\xrld\n");
}<file_sep>#define EOF '.'
#define YES 1
#define NO 0
main() /* print one word per line */
{
int c, inword = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
inword = NO;
} else if (inword == NO) {
putchar('\n');
putchar(c);
inword = YES;
} else if (inword == YES) {
putchar(c);
}
}
}<file_sep>/* print Celsius-Fahrenheit table
for c = 0, 20, ..., 300 */
main()
{
int lower, upper, step;
float fahr, celsius;
lower = 0; /* lower limit of temperature table */
upper = 300; /* upper limit */
step = 20; /* step size */
printf("cel fahr\n");
celsius = lower;
while (celsius <= upper) {
fahr = celsius/(5.0/9.0) + 32.0;
printf("%4.0f %6.1f\n", celsius, fahr);
celsius = celsius + step;
}
}<file_sep>#define EOF '.'
main() /* count blanks, tabs, and new lines in input */
{
int c, nb, nt, nl = 0;
while ((c = getchar()) != EOF)
if (c == ' ')
++nb;
else if (c == '\t')
++nt;
else if (c == '\n')
++nl;
printf("blanks = %d\n", nb);
printf("tabs = %d\n", nt);
printf("lines = %d\n", nl);
} | 69748868d2f3d8fb88bd02fa457ab13606fed081 | [
"C"
] | 6 | C | rennis250/math_sci_comp | ed2f94b69068eaec6a3ebe6856112227ed40997e | c6f4c6d5de3b9cad9ddb1a3e663ec0e47474605a |
refs/heads/master | <file_sep>datb <- read.csv("/Users/KaetheWalther/Desktop/a04/beaver_dam.csv")
plot(datb$dams.n, datb$area.ha, pch = 19)
dam.mod <- lm(datb$area.ha ~ datb$dams.n)
dam.res <- rstandard(dam.mod)
qqnorm(dam.res)
qqline(dam.res)
shapiro.test(dam.res)
#consensusthedataisnormallydistributed
plot(datb$dams.n, dam.res, pch=19)
head(datb)
plot(datb$dams.n, datb$area.h,
pch = 19,
col = "royalblue4",
ylab = "Surface water area (ha)",
xlab = "Number of beaver dams")
#set up regression
dam.mod <- lm(datb$area.ha ~ datb$dams.n)
#get standardized residuals
dam.res <- rstandard(dam.mod)
#set up qqplot
qqnorm(dam.res)
#add qq line
qqline(dam.res)
abline(h= 0)
dev.off()
#set up qq plot part 2
qqnorm(dam.res)
#addline
qqline(dam.res)
#now the SW test
shapiro.test(dam.res)
#make residual plot
plot(datb$dams.n, dam.res,
xlab = "beaver damns",
ylab = "standardized residual")
#add horizantal line
abline(h=0)
summary(dam.mod)
#start interpreting at the intercept
#look at slope of line
#look at R squared to tell us the linear relationship bw x and y
#are beavers flooding the arctic?
#Yes!
plot(datb$dams.n, datb$area.h,
pch = 19,
col = "royalblue4",
ylab = "Surface water area (ha)",
xlab = "Number of beaver dams")
abline(dam.mod, lwd=2)
#phenotime
pheno <- read.csv("/Users/KaetheWalther/Desktop/a04/red_maple_pheno.csv")
#set up panel plots
par(mfrow=c(1,2))
plot(pheno$Tmax,pheno$doy,
pch = 19,
col = "royalblue4",
ylab = "Day of leaf out",
xlab = "Maximum temperature (C)")
plot(pheno$Prcp,pheno$doy,
pch = 19,
col = "royalblue4",
ylab = "Day of leaf out",
xlab = "Precipitation (mm)")
plot(pheno$Lat,pheno$doy,
pch = 19,
col = "purple",
ylab = "Day of leaf out",
xlab = "Latitude (degrees)")
plot(pheno$elev,pheno$doy,
pch = 19,
col = "red",
ylab = "Day of leaf out",
xlab = "Elevation (m)")
#box plot to show rural/urb
sitefactor <- as.factor(pheno$siteDesc)
plot(sitefactor,pheno$doy,
pch = 19,
col = "dark green",
ylab = "Day of leaf out",
xlab = "")
plot( ~ pheno$Lat + pheno$Tmax+ pheno$Tmin +pheno$Prcp + pheno$elev + pheno$siteDesc)
#ifelse
pheno$urID <- ifelse(pheno$siteDesc == "Urban",1,0)
mlr <- lm(pheno$doy ~ pheno$Tmax + pheno$Prcp + pheno$elev + pheno$urID)
mlFitted <- fitted(mlr)
#qqnorm
pheno.res <- rstandard(mlr)
qqnorm(pheno.res)
qqline(pheno.res)
plot(mlFitted,pheno.res)
summary(mlr)
<file_sep>datW <- read.csv("/Users/KaetheWalther/Desktop/a05/noaa2011124.csv")
datW$NAME<- as.factor(datW$NAME)
#create vector
nameS <- levels(datW$NAME)
nameS
nameS[2]
#make data frame
datP <- na.omit (data.frame(PRCP = datW$PRCP, NAME = datW$NAME, year = datW$year ) )
#total annual precipitation for each site
pr <- aggregate(datP$PRCP, by=list(datP$NAME, datP$year), FUN="sum")
View(pr)
colnames(precip) <- c("NAME","year","totalP")
colnames(pr) <- c("NAME","year","totalP")
pr$ncount <- aggregate(datP$PRCP, by=list(datP$NAME,datP$year), FUN="length")$x
pr <- pr[pr$ncount >=364, ]
ca <- pr[pr$NAME == nameS[2], ]
ny <- pr[pr$NAME == nameS[5], ]
install.packages("ggplot2")
library(ggplot2)
plot(pr$year, pr$totalP)
ggplot(data = pr, aes(x = year, y = totalP, color = NAME))+
geom_point()+
geom_path()
ggplot(data = pr, aes(x = year, y=totalP, color=NAME ) )+ #data for plot
geom_point()+ #make points at data point
geom_path()+ #use lines to connect data points
labs(x="year", y="Annual Precipitation")+ #make axis labels
theme_classic() #change plot theme
ggplot(data = pr, aes(x = year, y=totalP, color=NAME ) )+
geom_point(alpha=0.5)+
geom_path(alpha=0.5)+
labs(x="year", y="Annual Precipitation")+
theme_classic()+
scale_color_manual(values = c("#7FB3D5","#34495E", "#E7B800", "#FC4E07","#26A69A"))
#starting over bc i got confused what I have already done
datW <- read.csv("/Users/KaetheWalther/Desktop/a05/noaa2011124.csv")
datW$NAME<- as.factor(datW$NAME)
nameS <- levels(datW$NAME)
nameS
datP <- na.omit(data.frame(NAME=datW$NAME,
year=datW$year,
PRCP=datW$PRCP))
precip <- aggregate(datW$PRCP, by=list(datW$NAME,datW$year), FUN="sum", na.rm=TRUE)
precip <- aggregate(datP$PRCP, by=list(datP$NAME,datP$year), FUN="sum", na.rm=TRUE)
colnames(precip) <- c("NAME","year","totalP")
precip$ncount <- aggregate(datP$PRCP, by=list(datP$NAME,datP$year), FUN="length")$x
pr <- precip[precip$ncount >=364, ]
ca <- pr[pr$NAME == nameS[2], ]
ny <- pr[pr$NAME == nameS[5], ]
#cali plot
plot(ca$year, ca$totalP)
#make a better plot
plot(ca$year, ca$totalP,
type = "b",
pch = 19,
ylab = "Annual precipitation (mm)",
xlab = "Year")
#fix some things
plot(ca$year, ca$totalP,
type = "b",
pch = 19,
ylab = "Annual precipitation (mm)",
xlab = "Year",
yaxt = "n")
axis(2, seq(200,800, by=200), las=2 )
plot(ca$year, ca$totalP,
type = "b",
pch = 19,
ylab = "Annual precipitation (mm)",
xlab = "Year",
yaxt = "n")
axis(2, seq(200,800, by=200), las=2 )
#add NY
points(ny$year, ny$totalP,
type = "b",
pch = 19,
col="tomato3")
plot(ca$year, ca$totalP,
type = "b",
pch = 19,
ylab = "Annual precipitation (mm)",
xlab = "Year",
yaxt = "n",
ylim =c(0, 1600))
axis(2, seq(0,1600, by=400), las=2 )
#fix the scope of the graph
points(ny$year, ny$totalP,
type = "b",
pch = 19,
col="tomato3")
plot(ca$year, ca$totalP,
type = "b",
pch = 19,
ylab = "Annual precipitation (mm)",
xlab = "Year",
yaxt = "n",
ylim =c(0, 1600))
axis(2, seq(0,1600, by=400), las=2 )
points(ny$year, ny$totalP,
type = "b",
pch = 19,
col="tomato3")
legend("topleft", #position
c("California", "New York"),
col= c("black", "tomato3"),
pch=19,
lwd=1,
bty="n")
#plot of annual mean max temp for morrisville and Mandan
datT <- na.omit(data.frame(NAME=datW$NAME,
year=datW$year,
TMAX=datW$TMAX))
TMAX <- aggregate(datW$TMAX, by=list(datW$NAME,datW$year), FUN="mean", na.rm=TRUE)
colnames(TMAX) <- c("NAME","year","Max Temp")
TMAX$ncount <- aggregate(datT$TMAX, by=list(datT$NAME,datT$year), FUN="length")$x
TMAX
TMAX <- na.omit(TMAX)
TMAX$ncount <- aggregate(datT$TMAX, by=list(datT$NAME,datT$year), FUN="length")$x
#ran some things in the wrong order, one column had omitted values and the other didnt
Temp <- TMAX[TMAX$ncount >=364, ]
Mo <- Temp[Temp$NAME == nameS[5], ]
Mandan <- Temp[Temp$NAME == nameS[3], ]
nameS
plot( Mo$year, Mo$`Max Temp`)
#make plot
plot(Mo$year, Mo$`Max Temp`,
type = "b",
pch = 19,
ylab = "Annual Temperature (Celcius)",
xlab = "Year")
points(Mandan$year, Mandan$`Max Temp`,
type = "b",
pch = 19,
col="tomato3")
#make axis nicer
plot(Mo$year, Mo$`Max Temp`,
type = "b",
pch = 19,
ylab = "Annual Temperature (Celcius)",
xlab = "Year",
xaxt = "n",
yaxt = "n" ,
ylim = c(8,16),
xlim = c(1930,2020))
points(Mandan$year, Mandan$`Max Temp`,
type = "b",
pch = 19,
col="tomato3")
axis(2, seq(8,16, by=1),las=2)
axis(1, seq(1930,2020, by=5), las=1)
install.packages("ggplot2")
library(ggplot2)
plot(pr$year, pr$totalP)
ggplot(data = pr, aes(x = year, y = totalP, color = NAME))+
geom_point()+
geom_path()
ggplot(data = pr, aes(x = year, y=totalP, color=NAME ) )+ #data for plot
geom_point()+ #make points at data point
geom_path()+ #use lines to connect data points
labs(x="year", y="Annual Precipitation")+ #make axis labels
theme_classic() #change plot theme
ggplot(data = pr, aes(x = year, y=totalP, color=NAME ) )+
geom_point(alpha=0.5)+
geom_path(alpha=0.5)+
labs(x="year", y="Annual Precipitation")+
theme_classic()+
scale_color_manual(values = c("firebrick4","limegreen", "goldenrod3", "navyblue","chocolate3"))
ggplot(data = datW, aes(x=NAME, y=TMIN))+ #look at daily tmin
geom_violin(fill=rgb(0.933,0.953,0.98))+ #add a violin plot with blue color
geom_boxplot(width=0.2,size=0.25, fill="grey90")+ #add grey boxplots and make them about 20% smaller than normal with 25% thinner lines than normal
theme_classic() #git rid of ugly gridlines
sub <- datW[datW$NAME == nameS[4] & datW$ year == 1974,]
sub$DATE <- as.Date(sub$DATE,"%Y-%m-%d")
ggplot(data=sub, aes(x=DATE, y=TMAX))+
geom_point()+
geom_path()+
theme_classic()+
labs(x="year", y="Maximimum temperature (C)")
ggplot(data=sub, aes(x=DATE, y=PRCP))+
geom_col(fill="royalblue3")+
theme_classic()+
labs(x="year", y="Daily precipitation (mm)")
#ARIZONA
#make a dataframe with just precipitation, year, and site name
#remove NA using na.omit
datP <- na.omit(data.frame(NAME=datW$NAME,
year=datW$year,
PRCP=datW$PRCP))
#total annual precipitation (mm)
precip <- aggregate(datW$PRCP, by=list(datW$NAME,datW$year), FUN="sum", na.rm=TRUE)
#use aggregate to get total annual precipitation
precip <- aggregate(datP$PRCP, by=list(datP$NAME,datP$year), FUN="sum", na.rm=TRUE)
#rename columns
colnames(precip) <- c("NAME","year","totalP")
#add the x column from aggregate looking at the length of observations in each year
precip$ncount <- aggregate(datP$PRCP, by=list(datP$NAME,datP$year), FUN="length")$x
pr <- precip[precip$ncount >=364, ]
AZ <- pr[pr$NAME == nameS[4], ]
nameS
plot(AZ$year, AZ$totalP)
plot(AZ$year, AZ$totalP,
type = "b",
pch = 19,
ylab = "Annual precipitation (mm)",
xlab = "Year")
datT <- na.omit(data.frame(NAME=datW$NAME,
year=datW$year,
TMAX=datW$TMAX))
TMAX <- aggregate(datW$TMAX, by=list(datW$NAME,datW$year), FUN="mean", na.rm=TRUE)
colnames(TMAX) <- c("NAME","year","Max Temp")
TMAX$ncount <- aggregate(datT$TMAX, by=list(datT$NAME,datT$year), FUN="length")$x
TMAX
TMAX <- na.omit(TMAX)
TMAX$ncount <- aggregate(datT$TMAX, by=list(datT$NAME,datT$year), FUN="length")$x
Temp <- TMAX[TMAX$ncount >=364, ]
AZ <- Temp[Temp$NAME == nameS[4], ]
plot( AZ$year, AZ$`Max Temp`)
#make plot
plot(AZ$year, AZ$`Max Temp`,
type = "b",
pch = 19,
ylab = "Annual Temperature (Celcius)",
xlab = "Year")
#REDO 1974 LOL
sub <- datW[datW$NAME == nameS[1] & datW$ year == 1974,]
sub$DATE <- as.Date(sub$DATE,"%Y-%m-%d")
ggplot(data=sub, aes(x=DATE, y=PRCP))+
geom_col(fill="royalblue3")+
theme_classic()+
labs(x="year", y="Daily precipitation (mm)")
sub <- datW[datW$NAME == nameS[1] & datW$ year == 1974,]
sub$DATE <- as.Date(sub$DATE,"%Y-%m-%d")
ggplot(data=sub, aes(x=DATE, y=TMAX))+
geom_point()+
geom_path()+
theme_classic()+
labs(x="year", y="Maximimum temperature (C)")
#Violin plot
ggplot(data = datW, aes(x=NAME, y=TMIN))+ #look at daily tmin
geom_violin(fill=rgb(0.933,0.953,0.98))+ #add a violin plot with blue color
geom_boxplot(width=0.2,size=0.25, fill="grey90")+ #add grey boxplots and make them about 20% smaller than normal with 25% thinner lines than normal
theme_classic() #git rid of ugly gridlines
dev.off()
sub <- datW[datW$NAME == nameS[1] & datW$ year > 1999,]
sub$year <- as.factor(sub$year)
#make violin plot
ggplot(data = sub, aes(x=year, y=TMIN))+ #look at daily tmin
geom_violin(fill=rgb(0.933,0.953,0.98))+ #add a violin plot with blue color
geom_boxplot(width=0.2,size=0.25, fill="grey90")+ #add grey boxplots and make them about 20% smaller than normal with 25% thinner lines than normal
theme_classic()+ #git rid of ugly gridlines
labs(x="year", y="TMIN (degrees celcius)")
<file_sep>NSLR <- read.csv("/Users/KaetheWalther/Desktop/ENVST206/NJnorthernSLR/NJ_Northern_slr_final_dist.gdb")
ACslr <- read.csv("/Users/KaetheWalther/Desktop/ENVST 206/AC_meantrend.csv")
read.table("/Users/KaetheWalther/Desktop/ENVST 206/AC_meantrend.csv", sep = ",", row.names=TRUE)
#fixed the period problem in the table heading
ACslr <- read.csv("/Users/KaetheWalther/Desktop/ENVST 206/Course Project/AC_meantrend.csv")
SandyHslr <- read.csv("/Users/KaetheWalther/Desktop/ENVST 206/Course Project/SandyHook_meantrend.csv")
CapeMayslr <- read.csv("/Users/KaetheWalther/Desktop/ENVST 206/Course Project/CapeMay_meantrend.csv")
mean(ACslr$Monthly_MSL)
datAC <- na.omit(data.frame(Monthly_MSL=ACslr$Monthly_MSL,
year=ACslr$Year,
month=ACslr$Month))
mean(datAC$Monthly_MSL)
sd(datAC$Monthly_MSL)
plot(datAC$year,datAC$Monthly_MSL, pch =19)
#make it look prettier
plot(datAC$year,datAC$Monthly_MSL, pch =19)
install.packages("ggplot2")
library(ggplot2)
ggplot(data = datAC, aes(x = year, y= Monthly_MSL, color= "red"))+ #data for plot
geom_point()+ #make points at data point
geom_path()+ #use lines to connect data points
labs(x="year", y="Monthly Sea Level (m)")+
theme_classic()+
ggtitle("Sea Level (m) in Atlantic City, NJ")
<file_sep>NSLR <- read.csv("/Users/KaetheWalther/Desktop/ENVST206/NJnorthernSLR/NJ_Northern_slr_final_dist.gdb")
ACslr <- read.csv("/Users/KaetheWalther/Desktop/ENVST 206/AC_meantrend.csv")
read.table("/Users/KaetheWalther/Desktop/ENVST 206/AC_meantrend.csv", sep = ",", row.names=TRUE)
#fixed the period problem in the table heading
ACslr <- read.csv("/Users/KaetheWalther/Desktop/ENVST 206/Course Project/AC_meantrend.csv")
SandyHslr <- read.csv("/Users/KaetheWalther/Desktop/ENVST 206/Course Project/SandyHook_meantrend.csv")
CapeMayslr <- read.csv("/Users/KaetheWalther/Desktop/ENVST 206/Course Project/CapeMay_meantrend.csv")
mean(ACslr$Monthly_MSL)
datAC <- na.omit(data.frame(Monthly_MSL=ACslr$Monthly_MSL,
year=ACslr$Year,
month=ACslr$Month))
mean(datAC$Monthly_MSL)
sd(datAC$Monthly_MSL)
plot(datAC$year,datAC$Monthly_MSL, pch =19)
#make it look prettier
plot(datAC$year,datAC$Monthly_MSL, pch =19)
install.packages("ggplot2")
library(ggplot2)
ggplot(data = datAC, aes(x = year, y= Monthly_MSL, color= "red"))+ #data for plot
geom_point()+ #make points at data point
geom_path()+ #use lines to connect data points
labs(x="year", y="Monthly Sea Level (m)")+
theme_classic()+
ggtitle("Sea Level (m) in Atlantic City, NJ")
#Same thing with Cape May
mean(CapeMayslr$Monthly_MSL)
datCapeMay <- na.omit(data.frame(Monthly_MSL=CapeMayslr$Monthly_MSL,
year=CapeMayslr$Year,
month=CapeMayslr$Month))
mean(datCapeMay$Monthly_MSL)
sd(CapeMayslr$Monthly_MSL)
plot(datCapeMay$year,datCapeMay$Monthly_MSL, pch =19)
#make nice looking
plot(datCapeMay$year,datCapeMay$Monthly_MSL, pch =19, col=c("Blue"))
library(ggplot2)
ggplot(data = datCapeMay, aes(x = year, y= Monthly_MSL, color= "Blue"))+ #data for plot
geom_point(color="royalblue3")+ #make points at data point
geom_path(color="royalblue")+ #use lines to connect data points
labs(x="year", y="Monthly Sea Level (m)")+
theme_classic()+
ggtitle("Sea Level (m) in Cape May, NJ")
#Same thing with Sandy Hook
mean(SandyHslr$Monthly_MSL)
datSandyH <- na.omit(data.frame(Monthly_MSL=SandyHslr$Monthly_MSL,
year=SandyHslr$Year,
month=SandyHslr$Month))
mean(datSandyH$Monthly_MSL)
sd(SandyHslr$Monthly_MSL)
plot(datSandyH$year,datSandyH$Monthly_MSL, pch =19)
#make nice looking
plot(datSandyH$year,datSandyH$Monthly_MSL, pch =19, col=c("Green"))
library(ggplot2)
ggplot(data = datSandyH, aes(x = year, y= Monthly_MSL, color= "Green"))+ #data for plot
geom_point(color="green")+ #make points at data point
geom_path(color="green")+ #use lines to connect data points
labs(x="year", y="Monthly Sea Level (m)")+
theme_classic()+
ggtitle("Sea Level (m) in Sandy Hook, NJ")
#question for class--> how to plot all of these on one plot.
#make new data frame with the three data sets
plot(datSandyH$year, datSandyH$Monthly_MSL, main= "Sea Level Rise in New Jersey Shore Towns",
type = "b",
pch = 19,
ylab = "Monthly Sea Level (m)",
xlab = "Year",
yaxt = "n")
points(datAC$year,datAC$Monthly_MSL,
type = "b",
pch = 19,
col="tomato3")
points(datCapeMay$year,datCapeMay$Monthly_MSL,
type = "b",
pch = 19,
col="green")
legend("topleft",
c("Sandy Hook", "Atlantic City", "Cape May"),
col= c("black", "tomato3", "green"),
pch=19,
lwd=1,
bty="n")
axis(2, seq(-4,4, by=.25), las=1 )
#add title
main
#lets try a regression assessment
SLR.mod <- lm(datAC$year ~ datAC$Monthly_MSL)
SLR.res <- rstandard(SLR.mod)
#set up qqplot
qqnorm(SLR.res)
#set up qq line
qqline(SLR.res)
#shapriowilks normality test
shapiro.test(SLR.res)
#make residual plot
plot(datAC$Monthly_MSL, SLR.res,
xlab = "Sea Level Rise (m)",
ylab = "standardized residual")
#add a horizontal line at zero
abline(h=0)
#interpret results
summary(SLR.mod)
#make plot of year and SLR
plot(datAC$year, datAC$Monthly_MSL,
pch = 19,
col = "royalblue4",
ylab = "Monthly Sea Level Rise (m)",
xlab = "Year")
#add regression line
#make line width thicker
abline(SLR.mod, lwd=2)
<file_sep>ch4 <-read.csv("/Users/KaetheWalther/Desktop/ao3/lemming_herbivory.csv")
ch4$herbivory <- as.factor(ch4$herbivory)
plot(ch4$CH4_Flux ~ ch4$herbivory, xlab ="Treatment",
ylab="CH4 fluxes (mgC m –2 day–1) ")
shapiro.test(ch4$CH4_Flux[ch4$herbivory == "Ctl"])
shapiro.test(ch4$CH4_Flux[ch4$herbivory == "Ex"])
bartlett.test(ch4$CH4_Flux ~ ch4$herbivory)
t.test(ch4$CH4_Flux ~ ch4$herbivory)
#insect data time!
datI <- read.csv("/Users/KaetheWalther/Desktop/ao3/insect_richness.csv")
#ANOVA
datI$urbanName <- as.factor(datI$urbanName)
#Shapiro Wilk Normality Test
shapiro.test(datI$Richness[datI$urbanName == "Developed"])
shapiro.test(datI$Richness[datI$urbanName == "Dense"])
shapiro.test(datI$Richness[datI$urbanName == "Suburban"])
shapiro.test(datI$Richness[datI$urbanName == "Natural"])
#Bartlett Test
in.mod <- lm(datI$Richness ~ datI$urbanName)
in.aov <- aov(in.mod)
summary(in.aov)
tukeyT <- TukeyHSD(in.aov)
tukeyT
plot(tukeyT, cex.axis=0.75)
tapply(datI$Richness, datI$urbanName, "mean")
species <- matrix(c(18,8,15,32), ncol=2, byrow = TRUE)
colnames(species) <- c("Not protected", "Protected")
rownames(species) <- c("Declining", "Stable/Increase")
mosaicplot(species, xlab="population status", ylab="legal protection",
main="Legal protection impacts on populations")
chisq.test(species)
species<file_sep>#activity 2
heights <- c(3,2,3)
datW <-read.csv ("/Users/KaetheWalther/Documents/ES DATA /a02/noaa2011124.csv")
datW$PRCP_cm <- datW$PRCP/10
mean(datW$PRCP_cm, na.rm=TRUE)
str (datW)
datW$NAME <- as.factor(datW$NAME)
myvector <- c(1,4,7,9,11)
numericvector <- c(-1.5,.25,.75,1.25,1.5)
charactervector <- c("hello","R","world","what","up")
factordatavector <- c("coffee","latte","coffee","cappucchino","mocha")
myfactor <- as.factor(factordatavector)
#find out all unique site names
levels(datW$NAME)
mean(datW$TMAX[datW$NAME == "ABERDEEN, WA US"])
mean(datW$TMAX[datW$NAME == "ABERDEEN, WA US"], na.rm=TRUE)
sd(datW$TMAX[datW$NAME == "ABERDEEN, WA US"], na.rm=TRUE)
datW$TAVE <- datW$TMIN + ((datW$TMAX-datW$TMIN)/2)
averageTemp <- aggregate(datW$TAVE, by=list(datW$NAME), FUN="mean",na.rm=TRUE)
averageTemp
colnames(averageTemp) <- c("NAME","MAAT")
averageTemp
datW$siteN <- as.numeric(datW$NAME)
hist(datW$TAVE[datW$siteN == 3],
freq=FALSE,
main = paste(levels(datW$NAME)[3]),
xlab = "Average daily temperature (degrees C)",
ylab="Relative frequency",
col="grey75",
border="white")
AberdeenMean <-mean(datW$TMAX[datW$NAME == "ABERDEEN, WA US"])
qnorm(0.95,
mean(datW$TAVE[datW$siteN == 1],na.rm=TRUE),
sd(datW$TAVE[datW$siteN == 1],na.rm=TRUE))
1-pnorm(18.51026,4+mean(datW$TAVE[datW$siteN == 1],na.rm=TRUE),
sd(datW$TAVE[datW$siteN == 1],na.rm=TRUE))
hist(datW$PRCP[datW$siteN == 1],
freq=FALSE,
main = paste(levels(datW$NAME)[1]),
xlab = "Precipitation (mm)",
ylab="Relative frequency",
col="grey75",
border="white")
averagePRCP <- aggregate(datW$PRCP, by=list(datW$NAME,datW$year), FUN="sum",na.rm=TRUE)
averagePRCP
averagePRCP$Group.1 <- as.factor(averagePRCP$Group.1)
averagePRCP$Group.1 <- as.numeric(averagePRCP$Group.1)
hist(averagePRCP$x[averagePRCP$Group.1 == 1],
freq=FALSE,
main = paste(levels(datW$NAME)[1]),
xlab = "Annual Precipitation (mm)",
ylab="Relative frequency",
col="grey75",
border="white")
hist(averagePRCP$x[averagePRCP$Group.1 == 3],
freq=FALSE,
main = paste(levels(datW$NAME)[3]),
xlab = "Annual Precipitation (mm)",
ylab="Relative frequency",
col="grey75",
border="white")
pnorm(700,mean(averagePRCP$x[averagePRCP$Group.1 == 1],na.rm=TRUE),
sd(averagePRCP$x[averagePRCP$Group.1 == 1],na.rm=TRUE))
pnorm(700,mean(averagePRCP$x[averagePRCP$Group.1 == 3],na.rm=TRUE),
sd(averagePRCP$x[averagePRCP$Group.1 == 3],na.rm=TRUE))<file_sep>print("hello R world")
2*2
6^6
#bananaland
a <- 2446
b <- 2
a*b
c <- c(2,4,6,8)
d <- c(3,5,7,9)
c*d
a+c
b*d
c-b<file_sep>install.packages(c("sp","rgdal","dplyr"))
#package for vector data
library(sp)
#package for reading in spatial data
library(rgdal)
#data manangement package
library(dplyr)
g1966 <- readOGR ("/Users/KaetheWalther/Desktop/a06/GNPglaciers/GNPglaciers_1966.shp")
g2015 <- readOGR ("/Users/KaetheWalther/Desktop/a06/GNPglaciers/GNPglaciers_2015.shp")
#investigating format of this data
str(g2015)
#map the glaciers filling in the polygons with light blue and making the borders grey
plot(g1966, col = "lightblue2", border="grey50")
#data stores all accompanying info/measurements for each spatial object
head(g2015@data)
g1966@proj4string
#check glacier names
g1966@data$GLACNAME
g2015@data$GLACNAME
#fix glacier name so that it is consistent with the entire time period
g2015@data$GLACNAME <- ifelse(g2015@data$GLACNAME == "North Swiftcurrent Glacier",
"N. Swiftcurrent Glacier",
ifelse( g2015@data$GLACNAME == "<NAME>",
"<NAME> Glacier",
as.character(g2015@data$GLACNAME)))
#lets combine area, first work with a smaller data frame
gdf66 <- data.frame(GLACNAME = g1966@data$GLACNAME,
area66 = g1966@data$Area1966)
gdf15 <- data.frame(GLACNAME = g2015@data$GLACNAME,
area15 = g2015@data$Area2015)
#join all data tables by glacier name
gAll <- full_join(gdf66,gdf15, by="GLACNAME")
#calculate the % change in area from 1966 to 2015
gAll$gdiff <- ((gAll$area66-gAll$area15)/gAll$area66)*100
plot(gAll$area66,gAll$gdiff,xlab="area of glaciers in 1966 (Km squared)",ylab="percent glacial loss")
#calculate mean
mean(gAll$gdiff)
sd(gAll$gdiff)
#find the glacier with largest and smallest percent loss
max(gAll$gdiff)
maxglacier <- max(gAll$gdiff)
maxindex <- which(gAll$gdiff==maxglacier)
maxindex
gAll$GLACNAME
min(gAll$gdiff)
minglacier <- min(gAll$gdiff)
minindex <- which(gAll$gdiff==minglacier)
minindex
#max and min area time!
max(gAll$area66)
maxglacierarea <- max(gAll$area66)
maxindexarea <- which(gAll$area66==maxglacierarea)
maxindexarea
#percent change
maxindexareapercent <- gAll$gdiff[maxindexarea]
maxindexareapercent
min(gAll$area66)
minglacierarea <- min(gAll$area66)
minindexarea <- which(gAll$area66==minglacierarea)
minindexarea
minindexareapercent <- gAll$gdiff[minindexarea]
minindexareapercent
g1966@data <- left_join(g1966@data, gAll, by="GLACNAME")
spplot(g1966, "gdiff", main="% change in area", col="transparent")
vulture66 <- g1966[g1966@data$GLACNAME == "Vulture Glacier",]
plot(vulture66, main = "Vulture Glacier in 1966", col="slategray")
Boulder66 <- g1966[g<EMAIL>$GLAC<EMAIL> == "Boulder Glacier",]
plot(Boulder66, main = "Boulder Glacier Loss", col="slategray")
Boulder15 <- g2015[<EMAIL> == "Boulder Glacier",]
plot(Boulder15, col="orange", add=TRUE)
legend("bottomleft",c("1966","2015"), fill = c("slategray", "orange"))
Pumpelly66 <- g1966[g<EMAIL>$GLAC<EMAIL> == "Pumpelly Glacier",]
plot(Pumpelly66, main = "Pumpelly Glacier Loss", col="purple")
Pumpelly15 <- g2015[<EMAIL>$<EMAIL> == "Pumpelly Glacier",]
plot(Pumpelly15, col="yellow", add=TRUE)
legend("bottomleft",c("1966","2015"), fill = c("purple", "yellow"))
| b9e5225ef039523aaa0d9de9abe375786f76a969 | [
"R"
] | 8 | R | emilywalther/ENVST206 | 7a3cbe5b04d8a25f246fb1bb1d1b095e8900cdfb | 3267a49fe5181338c3220d00c0d3588f5f9583a2 |
refs/heads/master | <repo_name>estefatapias99/Curso-js<file_sep>/README.md
# Curso-js
JavaScript and Angular
<file_sep>/test.js
document.write('Mi profesor es muy bueno y algo más')
<file_sep>/index.js
console.log('hola')
console.log('javascript is awesome') | 4d037d45744c0439a87c4a94edba500aef899b8b | [
"Markdown",
"JavaScript"
] | 3 | Markdown | estefatapias99/Curso-js | b4940781e03980b675211b58226a31a17a6f293c | 3bc8ee54538575f0932928606bec09cd809537c0 |
refs/heads/main | <repo_name>adrianferenc/bball-half-misses<file_sep>/README.md
# bball-half-misses
Analysis of shots that lead to offensive rebounds in basketball
<file_sep>/data-collection.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 16:54:04 2021
@author: adrianferenc
"""
import requests
from bs4 import BeautifulSoup
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import os
import lxml
'''
This function creates a list of links of every game's play-by-play from basketball-reference.com from the iput season.
'''
def link_lister(year):
months = ['october', 'november', 'december', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september']
list_of_links = []
prefix = 'https://www.basketball-reference.com/boxscores/pbp/'
suffix = '.html'
for month in months:
url = 'https://www.basketball-reference.com/leagues/NBA_'+ year +'_games-' + month + '.html'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
table = [td for td in soup.findAll('td', {'data-stat': 'box_score_text'})]
rows = len(table)
for line in range(rows):
if len(str(table[line])) > 60:
list_of_links.append(prefix+str(table[line])[66:78]+suffix)
return list_of_links
'''
This creates a class for each player and adds categories for each player's stats
'''
class Player_stats:
def __init__(self, name, team):
self.name = name
self.team = team
self.assists = 0 #
self.fts = 0 #
self.ftas = 0#
self.twops = 0#
self.threeps = 0#
self.twoas = 0#
self.threeas = 0#
self.games = 0#
self.drebounds = 0
self.orebounds = 0
self.turnovers = 0
self.halfmisses = 0
def addassist(self):
self.assists+=1
def addft(self):
self.fts+=1
def addfta(self):
self.ftas+=1
def addtwop(self):
self.twops+=1
def addtwoa(self):
self.twoas+=1
def addthreep(self):
self.threeps+=1
def addthreea(self):
self.threeas+=1
def addgame(self):
self.games+=1
def adddrebound(self):
self.drebounds+=1
def addorebound(self):
self.orebounds+=1
def addturnover(self):
self.turnovers+=1
def addhalfmiss(self):
self.halfmisses+=1
def ppg(self):
if self.games > 0:
return (self.fts + 2*self.twops + 3*self.threeps)/self.games
else:
return 0
def apg(self):
if self.games > 0:
return (self.assists)/self.games
else:
return 0
def bpg(self):
if self.games > 0:
return (self.blocks)/self.games
else:
return 0
def ftpg(self):
if self.games > 0:
return (self.fts)/self.games
else:
return 0
def twospg(self):
if self.games > 0:
return (self.twops)/self.games
else:
return 0
def threespg(self):
if self.games > 0:
return (self.threeps)/self.games
else:
return 0
def drpg(self):
if self.games > 0:
return (self.drebounds)/self.games
else:
return 0
def orpg(self):
if self.games > 0:
return (self.orebounds)/self.games
else:
return 0
def rpg(self):
return self.orpg + self.drpg
def tvpg(self):
if self.games > 0:
return (self.turnovers)/self.games
else:
return 0
'''
This gives each player a unique id in a list, where a player is defined by their name and their team.
This is done so as not to confuse multiple players with the same first initial and last name.
***A current issue with this is if a player is traded they are identified multiple times***
'''
list_of_all_players = []
def player_id(name,team):
answer = -1
for player in list_of_all_players:
if player.name == name and player.team == team:
answer = list_of_all_players.index(player)
break
if answer != -1:
return answer
else:
list_of_all_players.append(Player_stats(name,team))
return len(list_of_all_players)-1
'''
This parses the data from a game and adds all the stats to each player's class.
'''
def stat_adder(plays,team):
players = []
line_number = 0
for line in plays:
line = line.split(' ')
length = len(line)
if length >=5:
if line[-4] == '(assist':
name = line[-2] + ' ' + line[-1][:-1]
list_of_all_players[player_id(name,team)].addassist()
players.append(name)
if line[2] == 'misses':
name = line[0]+' ' +line[1]
if line[3][0] == 'f':
list_of_all_players[player_id(name,team)].addfta()
players.append(name)
if line[3][0] == '2':
list_of_all_players[player_id(name,team)].addtwoa()
players.append(name)
if line[3][0] == '3':
list_of_all_players[player_id(name,team)].addthreea()
players.append(name)
if line[2] == 'makes':
name = line[0]+' ' +line[1]
if line[3][0] == 'f':
list_of_all_players[player_id(name,team)].addft()
list_of_all_players[player_id(name,team)].addfta()
players.append(name)
if line[3][0] == '2':
list_of_all_players[player_id(name,team)].addtwop()
list_of_all_players[player_id(name,team)].addtwoa()
players.append(name)
if line[3][0] == '3':
list_of_all_players[player_id(name,team)].addthreep()
list_of_all_players[player_id(name,team)].addthreea()
players.append(name)
if line[1] == 'rebound':
name = line[3] + ' ' + line[4]
if line[0] == 'Offensive':
list_of_all_players[player_id(name,team)].addorebound()
players.append(name)
hm_line = plays[line_number-1].split(' ')
if len(hm_line)>=4:
if hm_line[2] == 'misses' and hm_line[3] != 'free':
half_misser = hm_line[0] + ' ' + hm_line[1]
list_of_all_players[player_id(half_misser,team)].addhalfmiss()
if line[0] == 'Defensive':
list_of_all_players[player_id(name,team)].adddrebound()
players.append(name)
if line[0] == 'Turnover':
if line[2] != 'Team':
name = line[2] + ' ' + line[3]
list_of_all_players[player_id(name,team)].addturnover()
players.append(name)
line_number+=1
players = np.unique(players)
for name in players:
list_of_all_players[player_id(name,team)].addgame()
'''
This begins to compile the data for each year desired.
'''
start_year =2012
end_year = 2021
years = [str(x) for x in range(start_year,end_year+1)]
for year in years:
print('starting year {}'.format(year))
list_of_all_players = []
game_number = 1
list_of_links = link_lister(year)
total_games = len(list_of_links)
for url in list_of_links:
print(url)
game = pd.read_html(url)[0]
home_team = str(game.columns[5][1])
away_team = str(game.columns[1][1])
table_home = pd.read_html(url)[0].dropna(subset=[game.columns[5]]).reset_index()
home_plays = table_home[table_home.columns[6]]
table_away = pd.read_html(url)[0].dropna(subset=[game.columns[1]]).reset_index()
away_plays = table_away[table_away.columns[2]]
stat_adder(home_plays,home_team)
stat_adder(away_plays,away_team)
print('Game '+ str(game_number) + ' out of '+ str(total_games) + ' complete.')
game_number+=1
Complete_Stats = pd.DataFrame(data = {'Name': [x.name for x in list_of_all_players], 'Team': [x.team for x in list_of_all_players], 'Assists': [x.assists for x in list_of_all_players], 'Free Throws': [x.fts for x in list_of_all_players], 'Free Throw Attempts': [x.ftas for x in list_of_all_players], 'Two Pointers': [x.twops for x in list_of_all_players], 'Three Pointers': [x.threeps for x in list_of_all_players], 'Two Point Attempts': [x.twoas for x in list_of_all_players], 'Three Point Attempts': [x.threeas for x in list_of_all_players], 'Games Played': [x.games for x in list_of_all_players], 'Defensive Rebounds': [x.drebounds for x in list_of_all_players], 'Offensive Rebounds': [x.orebounds for x in list_of_all_players], 'Turnovers': [x.turnovers for x in list_of_all_players], 'Half Misses': [x.halfmisses for x in list_of_all_players]})
Complete_Stats.to_csv('/data/Complete_Stats_{}.csv'.format(year))
print('Finished with year {}'.format(year))
'''
Lastly, this combines all individual years into one complete set of statistics.
'''
years_for_csv = [str(x) for x in range(start_year,end_year)]
CompleteSTATSTEST = pd.DataFrame()
for year in years_for_csv:
print(year)
df = pd.read_csv('/data/Complete_Stats_{}.csv'.format(year), header = 0)
CompleteSTATSTEST = CompleteSTATSTEST.append(df, ignore_index=True)
CompleteSTATSTEST = CompleteSTATSTEST.groupby(['Name','Team'])[CompleteSTATSTEST.columns[3:]].sum()
CompleteSTATSTEST.to_csv('/data/Complete_Stats_{}-{}.csv'.format(start_year,end_year))
| 2247231f9f07b9be51b82fe29e26e22ef7fd4fde | [
"Markdown",
"Python"
] | 2 | Markdown | adrianferenc/bball-half-misses | 4c449c0086a58e4582cb0fdf0a6d313925e47ce4 | e1be47d9f31eec0d4984af012bdab805896c0713 |
refs/heads/master | <repo_name>Nanshan/CMPE235ADtracking<file_sep>/src/com/lifangmoler/lab2/db/TrackingDatabaseUtil.java
package com.lifangmoler.lab2.db;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.net.http.AndroidHttpClient;
import android.telephony.TelephonyManager;
import android.text.format.Time;
/**
* Utility class for adding event tracking records to the database.
*
* @author Leah
*
*/
public final class TrackingDatabaseUtil {
/**
* Add an advertisement to the database.
* @param c AS the context
* @param name AS the ad name
* @param url AS the ad URL
* @return advert_id AS id in the database. -1 if failed
*/
public static long addAdvert(Context c, String name, String url) {
SQLiteDatabase db = getDbFromContext(c);
ContentValues values = new ContentValues();
values.put("advert_name", name);
values.put("advert_url", url);
return db.insert("advert", null, values);
}
/**
* Add an impression tracking event to the database.
* @param c the context
* @param advertName name of the ad having the impression
* @param loc location of the user
* @return event_id in the database. -1 if failed
*/
public static long addImpressionEvent(Context c, String advertName, Location loc) {
try {
HttpPost post = new HttpPost("http://cmpe235project.herokuapp.com/events/impression");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
//pairs.add(new BasicNameValuePair("ad_name", advertName));
post.setEntity(new UrlEncodedFormEntity(pairs));
new PostEventTask().execute(post);
//return addEvent(c, advertName, 0, loc);
}
catch (Exception e) {
e.printStackTrace();
}
return -1;
}
/**
* Add a click tracking event to the database.
* @param c the context
* @param advertName name of the ad having the click
* @param loc location of the user
* @return event_id in the database. -1 if failed
*/
public static long addClickEvent(Context c, String advertName, Location loc) {
return addEvent(c, advertName, 1, loc);
}
/**
* Add a click-through tracking event to the database.
* @param c the context
* @param advertName name of the ad having the click-through
* @param loc location of the user
* @return event_id in the database. -1 if failed
*/
public static long addClickThroughEvent(Context c, String advertName, Location loc) {
return addEvent(c, advertName, 2, loc);
}
/**
* Add an SMS tracking event to the database.
* @param c the context
* @param advertName name of the ad having the SMS sent
* @param receiver receiver of the SMS
* @param message SMS message that was sent
* @param loc location of the user
* @return event_id in the database. -1 if failed
*/
public static long addSMSEvent(Context c, String advertName,
String receiver, String message, Location loc) {
long eventId = addEvent(c, advertName, 3, loc);
addSMSEventData(c, eventId, receiver, message);
return eventId;
}
/**
* Add a call tracking event to the database.
* @param c the context
* @param advertName name of the ad having the call
* @param receiver receiver of the call
* @param loc location of the user
* @return event_id in the database. -1 if failed
*/
public static long addCallEvent(Context c, String advertName,
String receiver, Location loc) {
long eventId = addEvent(c, advertName, 4, loc);
addCallEventData(c, eventId, receiver);
return eventId;
}
/**
* Add a map tracking event to the database.
* @param c the context
* @param advertName name of the ad having the map event
* @param address address found on the map
* @param loc location of the user
* @return event_id in the database. -1 if failed
*/
public static long addMapEvent(Context c, String advertName,
String address, Location loc) {
long eventId = addEvent(c, advertName, 5, loc);
addMapEventData(c, eventId, address);
return eventId;
}
/**
* Helper method to add an event to the database.
* @param c the context
* @param advertName the ad name
* @param eventType the event type ID
* @param loc the location of the user
* @return event_id in the database. -1 if failed
*/
private static long addEvent(Context c, String advertName,
int eventType, Location loc) {
SQLiteDatabase db = getDbFromContext(c);
TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId = tm.getDeviceId();
ContentValues values = new ContentValues();
values.put("event_type_id", eventType);
values.put("advert_id", getAdvertIdByName(db, advertName));
values.put("timestamp", getTimeStamp());
values.put("user_phone_id", deviceId);
putUserLocationIfAvailable(values, loc);
long result = db.insert("event", null, values);
db.close();
return result;
}
/**
* Helper method to add the user location if it is available (not null).
* @param values the DB values object
* @param loc the user location; may be null
*/
private static void putUserLocationIfAvailable(ContentValues values,
Location loc) {
if (loc != null) {
values.put("user_location", loc.getLatitude()+ " "+loc.getLongitude());
}
else {
values.put("user_location", "n/a");
}
}
/**
* Helper method to add SMS-specific event data to the sms_event table.
*/
private static void addSMSEventData(Context c, long eventId,
String receiver, String message) {
SQLiteDatabase db = getDbFromContext(c);
ContentValues values = new ContentValues();
values.put("event_id", eventId);
values.put("receiver", receiver);
values.put("message", message);
db.insert("sms_event", null, values);
db.close();
//return result;
}
/**
* Helper method to add call-specific event data to the call_event table.
*/
private static void addCallEventData(Context c, long eventId, String receiver) {
SQLiteDatabase db = getDbFromContext(c);
ContentValues values = new ContentValues();
values.put("event_id", eventId);
values.put("receiver", receiver);
db.insert("call_event", null, values);
db.close();
//return result;
}
/**
* Helper method to add map-specific event data to the map_event table.
*/
private static void addMapEventData(Context c, long eventId, String address) {
SQLiteDatabase db = getDbFromContext(c);
ContentValues values = new ContentValues();
values.put("event_id", eventId);
values.put("address", address);
db.insert("map_event", null, values);
db.close();
// return result;
}
/**
* Helper method to query the db and fetch the ad ID for the given ad name.
* @param db the database
* @param advertName the ad name
* @return the ad ID for the given name
*/
private static long getAdvertIdByName(SQLiteDatabase db, String advertName) {
String[] projection = {"advert_id"};
String[] selectionArgs = {advertName};
Cursor c = db.query("advert", projection, "advert_name = ?", selectionArgs, null, null, null);
c.moveToFirst();
long result = c.getLong(c.getColumnIndex("advert_id"));
c.close();
return result;
}
/**
* Helper method to get a writeable database handle from the context.
* @param c the context
* @return a writeable SQLite DB handle
*/
private static SQLiteDatabase getDbFromContext(Context c) {
LocalTrackingOpenHelper mDbHelper = new LocalTrackingOpenHelper(c);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
return db;
}
/**
* Helper method to get a timestamp for the current time.
* @return current time as a formatted string
*/
private static String getTimeStamp() {
Time t = new Time();
t.setToNow();
return t.format2445();
}
}
<file_sep>/src/com/lifangmoler/adtracker/tracking/HttpPostTrackingEventTask.java
package com.lifangmoler.adtracker.tracking;
import org.apache.http.client.methods.HttpPost;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
/**
* Task for asynchronous HTTP requests, since Android will not allow
* synchronous requests on the UI thread.
*
* @author Leah
*
*/
class HttpPostTrackingEventTask extends AsyncTask<HttpPost, Void, Void> {
protected Void doInBackground(HttpPost... posts) {
AndroidHttpClient client = AndroidHttpClient.newInstance("remote_app");
try {
for (HttpPost post : posts) {
client.execute(post);
}
} catch (Exception e) {
e.printStackTrace();
}
client.close();
return null;
}
}<file_sep>/src/com/lifangmoler/lab2/db/LocalTrackingOpenHelper.java
package com.lifangmoler.lab2.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Helper class for creating, upgrading, opening or closing the local tracking
* database, which is an instance of SQLiteDatabase.
*
* @author Leah
*
*/
public class LocalTrackingOpenHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "adtracking.db";
private static final String[] TABLES = new String[6];
private static final ContentValues[] EVENT_TYPES = new ContentValues[6];
/**
* Populate this helper class with the table schemas and event types.
* @param context the context
*/
public LocalTrackingOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
populateTableSchemas();
populateEventTypes();
}
@Override
public void onCreate(SQLiteDatabase db) {
// create tables
for (String table : TABLES) {
db.execSQL(table);
}
// insert event types
for (ContentValues values : EVENT_TYPES) {
db.insert("event_type", null, values);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// do nothing... no need to upgrade
}
/**
* Populate the schemas for creating the different tables.
*/
private void populateTableSchemas() {
TABLES[0] = "CREATE TABLE advert (advert_id INTEGER PRIMARY KEY, advert_name TEXT, advert_url TEXT )";
TABLES[1] = "CREATE TABLE event (event_id INTEGER PRIMARY KEY, event_type_id INTEGER, advert_id INTEGER, " +
"timestamp TEXT, user_phone_id TEXT, user_location TEXT )";
TABLES[2] = "CREATE TABLE event_type (event_type_id INTEGER PRIMARY KEY, event_type_desc TEXT )";
TABLES[3] = "CREATE TABLE sms_event (event_id INTEGER PRIMARY KEY, receiver TEXT, message TEXT )";
TABLES[4] = "CREATE TABLE call_event (event_id INTEGER PRIMARY KEY, receiver TEXT )";
TABLES[5] = "CREATE TABLE map_event (event_id INTEGER PRIMARY KEY, address TEXT )";
}
/**
* Populate the six different tracking event types.
*/
private void populateEventTypes() {
putEventType(0, "impression");
putEventType(1, "click");
putEventType(2, "clickThrough");
putEventType(3, "sms");
putEventType(4, "call");
putEventType(5, "map");
}
/**
* Put an event type into the event type array.
*/
private void putEventType(int id, String desc) {
ContentValues values = new ContentValues();
values.put("event_type_id", id);
values.put("event_type_desc", desc);
EVENT_TYPES[id] = values;
}
}
<file_sep>/src/com/lifangmoler/adtracker/fragment/BannerFragment.java
package com.lifangmoler.adtracker.fragment;
import com.lifangmoler.lab1.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
/**
* Fragment to hold a banner ad image and its arguments and behavior.
*
* @author Leah
*
*/
public class BannerFragment extends Fragment {
public static final String ARG_NAME = "name";
public static final String ARG_IMAGE = "image";
public static final String ARG_IMAGE2 = "image2";
public static final String ARG_SHARETEXT = "shareText";
public static final String ARG_ADDRESS = "address";
public static final String ARG_VIDEO = "video";
public static final String ARG_PHONE = "phone";
public static final String ARG_URL = "url";
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated properly.
View rootView = inflater.inflate(
R.layout.banner_view, container, false);
Bundle args = getArguments();
// get the int ID in R, corresponding to the name of the image we want
int resourceId = this.getResources().getIdentifier("com.lifangmoler.lab1:drawable/"+args.getString(ARG_IMAGE), null, null);
// set the image resource in the view equal to the image we want (android:src in XML)
((ImageView) rootView.findViewById(R.id.ad_image)).setImageResource(resourceId);
return rootView;
}
}
| d69212712f34707c6dfe825763c58611a34ece7b | [
"Java"
] | 4 | Java | Nanshan/CMPE235ADtracking | 8c5df69be722de12c101dc88d59a2278b12bb142 | 21f8a01bf5b930f5b31c195055382682659eaf6b |
refs/heads/master | <file_sep>'use strict';
const findAdjacentVetrtex = matr => {
const adjecent = [];
for (let i = 0; i < matr.length; i++) {
adjecent[i] = [];
for (let j = 0; j < matr[i].length; j++) {
if (matr[i][j]) adjecent[i].push(j);
}
}
return adjecent;
};
const DFS = (start, visited, prev, g) => {
visited[start] = true;
for (const el of g[start]) {
if (!visited[el]) {
prev.push([start, el]);
let back = DFS(el, visited, prev, g);
prev.push([start, back, true])
}
}
return start;
};
const DepthFirstSearch = (matr, start) => {
const g = findAdjacentVetrtex(matr);
const visited = [];
const prev = [];
DFS(start, visited, prev, g)
return prev;
};
const getDFSWithoutBack = path => {
const res = [];
for (const el of path) {
if (!el[2]) res.push(el);
}
return res;
}
const getNumericArray = (matr, start) => {
const path = DepthFirstSearch(matr, start);
const pathWB = getDFSWithoutBack(path);
const res = [start];
for (let i = 1; i < matr.length; i++) {
const index = pathWB[i - 1][1];
res[i] = index;
}
return res;
};
const findOpenVertices = (matr, start) => {
const path = DepthFirstSearch(matr, start);
const pathWB = getDFSWithoutBack(path);
const res = [[start]];
const pathWBLastV = pathWB[pathWB.length - 1][1];
for (let i = 0; i < path.length; i++) {
const vertice = path[i][1];
const lastIndex = res.length - 1;
if (!res[lastIndex].includes(vertice)) {
const nextStep = res[lastIndex].slice();
nextStep.push(vertice);
res.push(nextStep);
const resLastVertice = res[lastIndex + 1][res[lastIndex + 1].length - 1];
if (resLastVertice === pathWBLastV) return res;
}
else {
const len = res[lastIndex].length;
res[lastIndex] = res[lastIndex].slice(0, len - 1);
}
}
};
const findOpenVerticesA = (matr, start) => {
const path = DepthFirstSearch(matr, start);
const res = [[start]];
for (let i = 0; i < path.length; i++) {
const vertice = path[i][1];
const lastIndex = res.length - 1;
if (!res[lastIndex].includes(vertice)) {
const nextStep = res[lastIndex].slice()
nextStep.push(vertice);
res.push(nextStep);
}
else {
const prevStep = res[lastIndex].slice();
const len = prevStep.length;
const nextStep = prevStep.slice(0, len - 1);
res.push(nextStep)
}
}
return res
};
const getNumericMatrix = (matr, start) => {
const path = DepthFirstSearch(matr, start);
const pathWB = getDFSWithoutBack(path);
const res = [];
for (let i = 0; i < matr.length; i++) {
res[i] = Array(matr[i].length).fill(0);
}
res[0][start] = 1
for (let i = 1; i < matr.length; i++) {
const index = pathWB[i - 1][1];
res[i][index] = 1;
}
return res;
}
const getTreeMatrix = (matr, path) => {
const res = [];
for (let i = 0; i < matr.length; i++) {
res[i] = Array(matr[i].length).fill(0);
}
for (const [x, y] of path) {
res[x][y] = 1;
}
return res;
};<file_sep>const canvas1 = document.getElementById('lay01');
const canvas2 = document.getElementById('lay02');
const ctx1 = canvas1.getContext('2d');
const ctx2 = canvas2.getContext('2d');
const nonSym = document.getElementById('nonSym');
const tree = document.getElementById('tree');
const nextG = document.getElementById('nextG');
const nextT = document.getElementById('nextT');
const select = document.getElementById('select');
const deg = document.getElementById('degree');
const matr = makeSymMatrix(Lab5);
const weigth = LabW5;
let start = 0;
let num = 0;
const vertices = makeVertices(matr);
searchReletions(matr, vertices);
const edges = makeEdges(matr, vertices);
const ourData = data(matr, LabW5, edges)
const result = findOstTree(matr, ourData);
const zeroDMatr = zeroDiagonal(matr);
const backboneMatr = makeBackboneMatr(matr, edges, result);
addWeigth(edges, weigth);
deg.innerText = 'The Weigth:\n' + matrixToText(weigth);
const drawWeigth = (edge, ctx, color) => {
const xCentr = edge.centreX;
const yCentr = edge.centreY;
ctx.font = ('15px serif');
const angle = countRightAngl(edge);
let x = 0;
let r = edge.r;
if (r === 0) {
x = vectorLength(edge.v) / 8;
};
ctx.translate(xCentr, yCentr);
ctx.rotate(angle);
ctx.translate(x, -r);
ctx.rotate(-angle);
if (color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(6, -3, 10, 0, Math.PI * 2);
ctx.fill();
};
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.fillText(edge.w, 0, 0);
ctx.fill();
ctx.rotate(angle);
ctx.translate(-x, r);
ctx.rotate(-angle);
ctx.translate(-xCentr, -yCentr);
}
const graphButton = () => {
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx2.strokeStyle = 'black';
const m = matr;
for (const key in edges) {
const edge = edges[key];
if (edge.loop) continue;
drawWeigth(edge, ctx2)
}
drawSymGrWithoutClean(zeroDMatr, ctx1, ctx2);
deg.innerText = 'The Symetric Matrix:\n' + matrixToText(Lab5)
num = 0;
};
const treeButton = () => {
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx2.strokeStyle = 'black';
for (const el of result) {
const edge = edges[el[0]];
makeEdge(edge, ctx1, ctx2);
drawWeigth(edge, ctx2)
}
drawVertices(vertices, ctx1, ctx2)
num = 0;
deg.innerText = 'The backbone of the graph:\n' + matrixToText(backboneMatr)
}
const nextClickG = (matr) => {
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
for (const key in edges) {
const edge = edges[key];
if (edge.loop) continue;
drawWeigth(edge, ctx2)
}
ctx1.lineWidth = 4.0;
ctx2.lineWidth = 3.0;
ctx1.strokeStyle = "rgba(255,0,0,0.8)"
const res = result.slice(0, num + 1);
for (const el of res) {
const edge = edges[el[0]];
makeEdge(edge, ctx1, ctx2);
drawWeigth(edge, ctx2, 'red')
}
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx1.lineWidth = 1.0;
drawSymGrWithoutClean(matr, ctx1, ctx2);
num++;
if (num === result.length) {
num = 0;
alert('Кістяк сформовано');
}
};
const selectButton = () => {
res = prompt("Enter the vertices from and to for edge:\n Input like from_to",'4_7');
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
for (const key in edges) {
const edge = edges[key];
if (edge.loop) continue;
drawWeigth(edge, ctx2)
}
ctx1.lineWidth = 4.0;
ctx2.lineWidth = 3.0;
ctx1.strokeStyle = "rgba(255,0,0,0.8)"
const edge = edges[res];
makeEdge(edge, ctx1, ctx2);
drawWeigth(edge, ctx2, 'red')
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx1.lineWidth = 1.0;
drawSymGrWithoutClean(matr, ctx1, ctx2);
num++;
if (num === result.length) {
num = 0;
alert('Кістяк сформовано');
}
};
const nextClickT = (matr) => {
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
for (const el of result) {
const edge = edges[el[0]];
makeEdge(edge, ctx1, ctx2);
drawWeigth(edge, ctx2)
}
ctx1.lineWidth = 4.0;
ctx2.lineWidth = 3.0;
ctx1.strokeStyle = "rgba(255,0,0,0.8)"
const res = result.slice(0, num + 1);
for (const el of res) {
const edge = edges[el[0]];
makeEdge(edge, ctx1, ctx2);
drawWeigth(edge, ctx2, 'red')
}
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx1.lineWidth = 1.0;
drawSymGrWithoutClean(matr, ctx1, ctx2);
num++;
if (num === result.length) {
num = 0;
alert('Кістяк сформовано');
}
};
// enabledBox.addEventListener("click", isFullpath);
nonSym.addEventListener('click', graphButton);
tree.addEventListener('click', treeButton);
nextG.addEventListener('click', () => nextClickG(zeroDMatr));
nextT.addEventListener('click', () => nextClickT(backboneMatr));
select.addEventListener('click', selectButton);
<file_sep>'use strict';
const weigthToText = weight => {
let text = 'Weigth\n';
for (let i = 0; i < weight.length; i++) {
text += `${i + 1} : ${weight[i]}\n`
}
return text;
};
const pathToText = path => {
let text = 'Route\n';
for (let i = 0; i < path.length; i++) {
const p = path[i];
const textPath = p ? p.map(el => el + 1).join('->') : p;
text += textPath + '\n';
}
return text;
};
const pathToEdgeStyle = path => {
const res = [];
if (path.length < 2) return [];
for (let i = 1; i < path.length; i++) {
const fromV = path[i-1] + 1;
const toV = path[i] + 1;
const edge = fromV > toV ? `${toV}_${fromV}` : `${fromV}_${toV}`;
res.push(edge);
}
return res;
}
const markToText = valid => {
let text = 'Mark\n';
for (let i = 0; i < valid.length; i++) {
text += valid[i] ? `${i + 1} : T\n` : `${i + 1} : P\n`;
}
return text;
};
const zeroDiagonal = matr => {
const res = [];
for (let i = 0; i < matr.length; i++) {
res[i] = matr[i].slice();
res[i][i] = 0;
}
return res;
};
const addWeigth = (edges, weigth) => {
for (const key in edges) {
const edge = edges[key];
const fromEl = edge.fromEl;
const toEl = edge.toEl;
edge.w = weigth[fromEl][toEl];
}
};
const zeroToInf = (matr, weigthMatr) => {
const inf = Infinity;
const res = []
for (let i = 0; i < matr.length; i++) {
res[i] = weigthMatr[i].slice();
for (let j = 0; j < matr[i].length; j++){
if(!matr[i][j]) res[i][j] = inf;
}
}
return res;
};
const dejkstraAlg = (weigthMatr, start) => {
const len = weigthMatr.length;
const inf = Infinity;
const valid = Array(len).fill(true);
const weight = Array(len).fill(inf);
const nodes = [start];
const path = Array(len).fill(undefined);
path[start] = [start]
weight[start] = 0;
const steps = [];
for (let i = 0; i < len; i++) {
let minWeight = inf + 1;
let IdMinWeight = -1;
for (let j = 0; j < len; j++) {
if (valid[j] && weight[j] < minWeight) {
minWeight = weight[j];
IdMinWeight = j;
}
}
const pathToMin = path[IdMinWeight];
for(let z = 0; z < len; z++) {
if (weight[IdMinWeight] + weigthMatr[IdMinWeight][z] < weight[z]) {
weight[z] = weight[IdMinWeight] + weigthMatr[IdMinWeight][z];
const pathToVertex = pathToMin.slice();
pathToVertex.push(z);
path[z] = pathToVertex;
}
valid[IdMinWeight] = false;
}
steps.push({
openVert: IdMinWeight,
valid: valid.slice(),
weight: weight.slice(),
path: path.slice(),
})
}
return steps;
};
<file_sep>'use strict';
class Vertix {
constructor(name, x, y) {
this.name = name;
this.fromEl = [];
this.toEl = [];
this.x = x;
this.y = y;
this.haveLoop = false;
}
}
class Edge {
constructor(name, from, to) {
this.name = name;
this.fromEl = from;
this.toEl = to;
this.startPoint = [];
this.endPoint = [];
this.r = 0;
this.loop = false;
this.angle = 0;
}
get centreX() {
return (this.startPoint[0] + this.endPoint[0]) / 2;
}
get centreY() {
return (this.startPoint[1] + this.endPoint[1]) / 2;
}
get v() {
this.startPoint[0] + this.endPoint[0]
const [x1, y1] = this.startPoint;
const [x2, y2] = this.endPoint
return [x2 - x1, y2 - y1];
}
}
let centre = [];
const makeSymMatrix = matr => {
const sym = [];
for (let i = 0; i < matr.length; i++) {
for (let j = 0; j < matr.length; j++) {
if (!sym[i]) sym[i] = [];
if (!sym[j]) sym[j] = [];
if (matr[i][j] || sym[i][j]) {
sym[i][j] = 1;
sym[j][i] = 1;
} else sym[i][j] = 0;
}
}
return sym;
};
const makeVertices = matr => {
const vertices = [];
const n = matr.length;
const num = Math.ceil(n / 4) + 1;
const ost = (n - 2 * num) / 2;
const xStart = 70;
const yStart = 70;
const step = 180;
const xEnd = xStart + (num - 1) * step;
const yEnd = xEnd;
centre = [(xEnd + xStart) / 2, (yEnd + yStart) / 2];
const stepOst = Math.floor((xEnd - xStart) / (ost + 1));
let name = 1;
let x = xStart;
let y = yEnd;
for (; name < num + 1; name++) {
const vertix = new Vertix(name.toString(), x, y,);
vertices.push(vertix);
y -= step;
}
x = xStart + stepOst;
y = yStart;
for (; name < num + ost + 1; name++) {
const vertix = new Vertix(name.toString(), x, y,);
vertices.push(vertix);
x += stepOst;
}
x = xEnd;
y = yStart;
for (; name < n - ost + 1; name++) {
const vertix = new Vertix(name.toString(), x, y,);
vertices.push(vertix);
y += step;
}
x = xEnd - stepOst; // x = 160
y = yEnd;
for (; name < n + 1; name++) {
const vertix = new Vertix(name.toString(), x, y,);
vertices.push(vertix);
x -= stepOst;
}
return vertices;
};
const searchReletions = (matr, vertices) => {
for (let i = 0; i < matr.length; i++) {
for (let j = 0; j < matr.length; j++) {
if (matr[i][j]) {
vertices[i].toEl.push(j);
vertices[j].fromEl.push(i);
}
}
}
};
const getVector = (x1, y1, x2, y2) => [x2 - x1, y2 - y1];
const vectorLength = vector => Math.sqrt(vector[0] ** 2 + vector[1] ** 2);
const countAngle = (vector1, vector2) => {
const cosA = (vector1[0] * vector2[0] + vector1[1] * vector2[1]) /
(vectorLength(vector1) * vectorLength(vector2));
const angle = Math.acos(cosA);
return angle;
};
const countRightAngl = (vector) => {
let vector1 = vector.v;
const vector2 = [1, 0];
const angle = vector1[1] < 0 ?
(vector1 = vector1.map(el => -el),
(countAngle(vector1, vector2)) + Math.PI) :
countAngle(vector1, vector2);
return angle;
}
const makeVectors = (matr, vertices) => {
const vectors = [];
for (let i = 0; i < matr.length; i++) {
for (let j = 0; j < matr.length; j++) {
if (matr[i][j]) {
const name = `${i + 1}_${j + 1}`;
vectors[name] = (new Edge(name, i, j));
vectors[name].startPoint = [vertices[i].x, vertices[i].y];
vectors[name].endPoint = [vertices[j].x, vertices[j].y];
if (i === j) {
vectors[name].loop = true;
vertices[i].haveLoop = true;
}
const vector1L = vectorLength(vectors[name].v)
let r = 0;
if (vector1L % 100 === 0) r = 16 * vector1L / 100;
else r = 14; //* Math.floor(vector1L / 100);
vectors[name].r = r;
}
}
}
return vectors;
};
const makeEdges = (matr, vertices) => {
const edges = {};
for (let i = 0; i < matr.length; i++) {
for (let j = i; j < matr.length; j++) {
if (matr[i][j]) {
const name = `${i + 1}_${j + 1}`;
edges[name] = (new Edge(name, i, j));
edges[name].startPoint = [vertices[i].x, vertices[i].y];
edges[name].endPoint = [vertices[j].x, vertices[j].y];
if (i === j) {
edges[name].loop = true;
vertices[i].haveLoop = true;
}
const x = edges[name].startPoint[0];
const y = edges[name].startPoint[1];
const v = edges[name].v;
const vLen = vectorLength(v)
let r = 0;
if (vLen % 180 === 0 && vLen / 180 > 1) r = 10 * vLen / 100;
edges[name].r = r;
}
}
}
return edges;
};
const matrixToText = (matr, del = ' - ') => {
let mat = '';
for (const arr of matr) mat += arr.join(del) + '\n';
return mat;
};
const showName = (x, y, name, ctx1, ctx2, color, fillStyle = 'black', font = ('12px serif')) =>{
ctx1.fillStyle = 'white';
const px = font.split(' ')[0];
const ind = parseInt(px.slice(0, px.length - 2))
let pos = Math.floor(ind / 3);
const radius = Math.floor(ind * 3 / 4)
if (name.length > 1) pos *= name.length;
ctx1.beginPath();
ctx1.arc(x, y, radius, 0, Math.PI * 2);
ctx1.fill();
if (color) {
ctx1.fillStyle = color;
ctx1.beginPath();
ctx1.arc(x, y, radius, 0, Math.PI * 2);
ctx1.fill();
};
ctx1.fillStyle = fillStyle;
ctx1.font = font;
ctx1.fillText(name, x - pos, y + 4);
};
const drawVertix = (x, y, name, ctx1, ctx2, color = 'black') => {
ctx1.fillStyle = 'white';
ctx1.beginPath();
ctx1.arc(x, y, 15, 0, Math.PI * 2);
ctx1.fill();
ctx1.fillStyle = color;
ctx1.beginPath();
ctx1.arc(x, y, 15, 0, Math.PI * 2);
ctx1.fill();
showName(x, y, name, ctx1, ctx2);
ctx1.fillStyle = 'black';
};
const drawVertices = (vertices, ctx1, ctx2) => {
for (const vertix of vertices) {
drawVertix(vertix.x, vertix.y, vertix.name, ctx1, ctx2);
}
};
const drawVector = (edge, ctx1, ctx2) => {
const xCentre = (edge.startPoint[0] + edge.endPoint[0]) / 2;
const yCentre = (edge.startPoint[1] + edge.endPoint[1]) / 2;
let vector1 = getVector(...edge.startPoint, ...edge.endPoint);
const vector2 = [1, 0];
const vector1L = vectorLength(vector1);
const xRadius = vector1L / 2;
let r = 0;
if (vector1L % 100 === 0) r = 16 * vector1L / 100;
else r = 14; //* Math.floor(vector1L / 100);
const yRadius = r;
const angle = vector1[1] < 0 ?
(vector1 = getVector(...edge.endPoint, ...edge.startPoint, ...vector2),
(countAngle(vector1, vector2)) + Math.PI) :
countAngle(vector1, vector2);
ctx1.translate(xCentre, yCentre);
ctx1.rotate(angle);
ctx1.translate(-xCentre, -yCentre);
ctx2.translate(xCentre, yCentre);
ctx2.rotate(angle);
ctx2.translate(-xCentre, -yCentre);
ctx1.beginPath();
ctx1.ellipse(xCentre, yCentre, xRadius, yRadius, 0, 0, Math.PI, true);
ctx1.stroke();
ctx2.beginPath();
ctx2.moveTo(xCentre - 4, yCentre - r);
ctx2.lineTo(xCentre - 12, yCentre - r - 3);
ctx2.stroke();
ctx2.beginPath();
ctx2.moveTo(xCentre - 4, yCentre - r);
ctx2.lineTo(xCentre - 12, yCentre - r + 3);
ctx2.stroke();
ctx1.translate(xCentre, yCentre);
ctx1.rotate(-angle);
ctx1.translate(-xCentre, -yCentre);
ctx2.translate(xCentre, yCentre);
ctx2.rotate(-angle);
ctx2.translate(-xCentre, -yCentre);
};
const makeEdge = (edge, ctx1, ctx2) => {
const x = edge.startPoint[0];
const y = edge.startPoint[1];
const xCentre = (edge.startPoint[0] + edge.endPoint[0]) / 2;
const yCentre = (edge.startPoint[1] + edge.endPoint[1]) / 2;
let vector1 = getVector(...edge.startPoint, ...edge.endPoint);
const vector2 = [1, 0];
const vector1L = vectorLength(vector1);
const xRadius = vector1L / 2;
const r = edge.r;
const angle = vector1[1] < 0 ?
(vector1 = getVector(...edge.endPoint, ...edge.startPoint, ...vector2),
(countAngle(vector1, vector2)) + Math.PI) :
countAngle(vector1, vector2);
ctx1.translate(xCentre, yCentre);
ctx1.rotate(angle);
ctx1.translate(-xCentre, -yCentre);
ctx1.beginPath();
ctx1.ellipse(xCentre, yCentre, xRadius, r, 0, 0, Math.PI, true);
ctx1.stroke();
ctx1.translate(xCentre, yCentre);
ctx1.rotate(-angle);
ctx1.translate(-xCentre, -yCentre);
};
const loop = (edge, ctx1, ctx2) => {
const xCentre = centre[0];
const yCentre = centre[1];
const vector1 = getVector(...edge.startPoint, ...centre);
const vector2 = [1, 0];
const vector1L = vectorLength(vector1);
const r = 13;
const angle = vector1[1] < 0 ?
(countAngle(getVector(...centre, ...edge.startPoint), vector2)) + Math.PI :
countAngle(vector1, vector2);
ctx1.translate(xCentre, yCentre);
ctx1.rotate(angle + Math.PI);
ctx1.translate(-xCentre, -yCentre);
ctx1.beginPath();
ctx2.translate(xCentre, yCentre);
ctx2.rotate(angle + Math.PI);
ctx2.translate(-xCentre, -yCentre);
ctx1.beginPath();
ctx1.arc(xCentre + vector1L + r, yCentre, r, 0, Math.PI * 2);
ctx1.stroke();
ctx2.beginPath();
ctx2.moveTo(xCentre + vector1L + 2 * r, yCentre);
ctx2.lineTo(xCentre + vector1L + 2 * r - 3, yCentre - 5);
ctx2.stroke();
ctx2.beginPath();
ctx2.moveTo(xCentre + vector1L + 2 * r, yCentre);
ctx2.lineTo(xCentre + vector1L + 2 * r + 2, yCentre - 5);
ctx2.stroke();
ctx1.translate(xCentre, yCentre);
ctx1.rotate(-(angle + Math.PI));
ctx1.translate(-xCentre, -yCentre);
ctx2.translate(xCentre, yCentre);
ctx2.rotate(-(angle + Math.PI));
ctx2.translate(-xCentre, -yCentre);
};
const symLoop = (edge, ctx1, ctx2) => {
const xCentre = centre[0];
const yCentre = centre[1];
const vector1 = getVector(...edge.startPoint, ...centre);
const vector2 = [1, 0];
const vector1L = vectorLength(vector1);
const r = 20;
const angle = vector1[1] < 0 ?
(countAngle(getVector(...centre, ...edge.startPoint), vector2)) + Math.PI :
countAngle(vector1, vector2);
ctx1.translate(xCentre, yCentre);
ctx1.rotate(angle + Math.PI);
ctx1.translate(-xCentre, -yCentre);
ctx1.beginPath();
ctx1.arc(xCentre + vector1L + r - 1, yCentre, r, 0, Math.PI * 2);
ctx1.stroke();
ctx1.translate(xCentre, yCentre);
ctx1.rotate(-(angle + Math.PI));
ctx1.translate(-xCentre, -yCentre);
};
const drawVectors = (edges, ctx1, ctx2) => {
for (const name in edges) {
const edge = edges[name];
if (edge.loop) loop(edge, ctx1, ctx2);
else drawVector(edge, ctx1, ctx2);
}
};
const drawEdges = (edges, ctx1, ctx2) => {
for (const name in edges) {
const edge = edges[name];
if (edge.loop) symLoop(edge, ctx1, ctx2);
else makeEdge(edge, ctx1, ctx2);
}
};
//The start of Lab2
const findIsolateVertex = vertices => {
const isolateVertices = [];
for (const vertex of vertices) {
if (vertex.fromEl.length + vertex.toEl.length === 0)
isolateVertices.push(vertex.name);
}
return isolateVertices;
};
const findLeafVertex = vertices => {
const leafVertices = [];
for (const vertex of vertices) {
if (vertex.fromEl.length + vertex.toEl.length === 1)
leafVertices.push(vertex.name);
}
return leafVertices;
};
const findLeafVertexSym = vertices => {
const leafVertices = [];
for (const vertex of vertices) {
if (vertex.toEl.length === 1 && !vertex.haveLoop)
leafVertices.push(vertex.name);
}
return leafVertices;
};
const degreeOfVertexSym = vertex => {
let degree = vertex.toEl.length;
if (vertex.haveLoop) degree += 1;
return [vertex.name, degree];
};
const degreeOfVertex = vertex => {
const degreePlus = vertex.toEl.length;
const degreeMinus = vertex.fromEl.length;
const degree = degreePlus + degreeMinus;
return [vertex.name, degreePlus, degreeMinus, degree];
};
const isRegular = vertices => {
const degree = degreeOfVertex(vertices[0])[3];
for (const vertex of vertices) {
if (degree !== degreeOfVertex(vertex)[3]) return [false];
}
return [true, degree];
};
const isRegularSym = vertices => {
const degree = degreeOfVertexSym(vertices[0])[1];
for (const vertex of vertices) {
if (degree !== degreeOfVertexSym(vertex)[1]) return [false];
}
return [true, degree];
};
// The end of Lab2
const textDegrees = vertices => {
const textD = [];
for (const vertex of vertices) {
const degree = degreeOfVertex(vertex);
let text = `${degree[0]} det+ = ${degree[1]} | det- = ${degree[2]}`;
if (degree[0].length === 1) text = '0' + text;
textD.push(text);
}
return textD;
};
const textDegreesSym = vertices => {
const textD = [];
for (const vertex of vertices) {
const degree = degreeOfVertexSym(vertex);
let text = `${degree[0]} det = ${degree[1]}`;
if (degree[0].length === 1) text = '0' + text;
textD.push(text);
}
return textD;
};
const drawGraph = (matr, ctx1, ctx2, matrixText) => {
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
const vertices = makeVertices(matr);
searchReletions(matr, vertices);
const vectors = makeVectors(matr, vertices);
drawVectors(vectors, ctx1, ctx2);
drawVertices(vertices, ctx1, ctx2);
matrixText.innerText = 'Matrix\n' + matrixToText(matr);
};
const drawGrWithoutClean = (matr, ctx1, ctx2, matrixText) => {
const vertices = makeVertices(matr);
searchReletions(matr, vertices);
const vectors = makeVectors(matr, vertices);
drawVectors(vectors, ctx1, ctx2);
drawVertices(vertices, ctx1, ctx2);
matrixText.innerText = 'Matrix\n' + matrixToText(matr);
};
const printDeegre = (matr, degreeText) => {
const vertices = makeVertices(matr);
searchReletions(matr, vertices);
degreeText.innerText = 'Degrees:\n' + textDegrees(vertices).join('\n');
};
const drawSymGraph = (matr, ctx1, ctx2, matrixText, degreeText) => {
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
const vertices = makeVertices(matr);
searchReletions(matr, vertices);
const edges = makeEdges(matr, vertices);
drawEdges(edges, ctx1, ctx2);
drawVertices(vertices, ctx1, ctx2);
};
const drawSymGrWithoutClean = (matr, ctx1, ctx2, matrixText) => {
const vertices = makeVertices(matr);
searchReletions(matr, vertices);
const edges = makeEdges(matr, vertices);
drawEdges(edges, ctx1, ctx2);
drawVertices(vertices, ctx1, ctx2);
};<file_sep>const canvas1 = document.getElementById('lay01');
const canvas2 = document.getElementById('lay02');
const ctx1 = canvas1.getContext('2d');
const ctx2 = canvas2.getContext('2d');
const nonSym = document.getElementById('nonSym');
const startV = document.getElementById('startV');
const nextG = document.getElementById('nextG');
const selectEdge = document.getElementById('selectEdge');
const deg = document.getElementById('degree');
const markText = document.getElementById('mark');
const pathText = document.getElementById('path');
const matr = makeSymMatrix(Lab6);
const zeroDMatr = zeroDiagonal(matr);
const weigthMatr = LabW6;
let start = 0;
let num = 0;
const infWeigthMatr = zeroToInf(zeroDMatr, weigthMatr)
const vertices = makeVertices(matr);
searchReletions(matr, vertices);
const edges = makeEdges(matr, vertices);
let steps = dejkstraAlg(infWeigthMatr, start);
addWeigth(edges, weigthMatr);
const drawWeigth = (edge, ctx, color) => {
const xCentr = edge.centreX;
const yCentr = edge.centreY;
ctx.font = ('15px serif');
const angle = countRightAngl(edge);
let x = 0;
let r = edge.r;
if (r === 0) {
x = vectorLength(edge.v) / 8;
};
ctx.translate(xCentr, yCentr);
ctx.rotate(angle);
ctx.translate(x, -r);
ctx.rotate(-angle);
if (color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(6, -3, 10, 0, Math.PI * 2);
ctx.fill();
};
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.fillText(edge.w, 0, 0);
ctx.fill();
ctx.rotate(angle);
ctx.translate(-x, r);
ctx.rotate(-angle);
ctx.translate(-xCentr, -yCentr);
}
const graphButton = () => {
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx2.strokeStyle = 'black';
const m = matr;
for (const key in edges) {
const edge = edges[key];
if (edge.loop) continue;
drawWeigth(edge, ctx2)
}
drawSymGrWithoutClean(zeroDMatr, ctx1, ctx2);
deg.innerText = 'The Symetric Matrix:\n' + matrixToText(Lab5)
markText.innerText = '';
pathText.innerText = '';
num = 0;
};
const nextClick = () => {
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
for (const key in edges) {
const edge = edges[key];
if (edge.loop) continue;
drawWeigth(edge, ctx2)
}
ctx1.lineWidth = 4.0;
ctx2.lineWidth = 3.0;
ctx1.strokeStyle = "rgba(255,0,0,0.8)"
const step = steps[num];
const openVert = step.openVert;
const valid = step.valid;
const path = step.path;
const res = pathToEdgeStyle(step.path[openVert]);
for (const name of res) {
const edge = edges[name];
makeEdge(edge, ctx1, ctx2);
drawWeigth(edge, ctx2, 'red')
}
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx1.lineWidth = 1.0;
drawSymGrWithoutClean(zeroDMatr, ctx1, ctx2);
for (let i = 0; i < valid.length; i++) {
if (valid[i]) {
drawVertix(vertices[i].x, vertices[i].y, vertices[i].name, ctx1, ctx2, 'blue');
} else drawVertix(vertices[i].x, vertices[i].y, vertices[i].name, ctx1, ctx2, 'red');
}
drawVertix(vertices[openVert].x, vertices[openVert].y, vertices[openVert].name, ctx1, ctx2, 'yellow')
num++;
deg.innerText = weigthToText(step.weight);
markText.innerText = markToText(step.valid);
pathText.innerText = pathToText(path)
if (num === steps.length) {
num = 0;
alert('Роботу алгоритму завершено');
}
};
const selectEdgeButton = () => {
let res = prompt("Enter the vertices from and to for edge:\n Input like from_to",'4_7');
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
for (const key in edges) {
const edge = edges[key];
if (edge.loop) continue;
drawWeigth(edge, ctx2)
}
ctx1.lineWidth = 4.0;
ctx2.lineWidth = 3.0;
ctx1.strokeStyle = "rgba(255,0,0,0.8)"
const edge = edges[res];
makeEdge(edge, ctx1, ctx2);
drawWeigth(edge, ctx2, 'red')
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx1.lineWidth = 1.0;
drawSymGrWithoutClean(zeroDMatr, ctx1, ctx2);
};
const selectStartButton = () => {
let res = prompt("Enter the start vertex:\n");
start = parseInt(res) - 1;
steps = dejkstraAlg(infWeigthMatr, start);
num = 0;
}
nonSym.addEventListener('click', graphButton);
startV.addEventListener('click', selectStartButton);
nextG.addEventListener('click', () => nextClick(zeroDMatr));
selectEdge.addEventListener('click', selectEdgeButton);
<file_sep># Repository for DS labs
<file_sep>'use strict';
const arr5 = `
1 1 1 1 1 0 0 0 1 0 1 1,
0 1 0 0 0 0 1 0 1 0 1 1,
0 0 0 0 1 1 0 0 0 0 1 0,
0 0 0 0 1 1 1 0 1 1 1 0,
0 1 1 0 0 0 1 1 1 0 1 0,
0 1 1 1 1 0 0 1 0 1 0 1,
0 0 0 0 1 1 0 0 1 1 0 1,
0 0 1 0 0 1 1 0 0 1 0 0,
1 0 0 0 0 1 1 1 0 0 1 0,
1 0 0 0 0 0 1 1 0 1 1 1,
0 0 0 1 0 1 1 1 1 0 0 1,
0 0 0 1 1 0 0 0 0 0 0 1`.split(',');
const Lab5 = arr5.map(el => el.split(' ').map(x => parseInt(x)));
const arrW5 = `
0 64 33 87 38 0 0 0 78 28 12 46,
64 0 0 0 3 89 71 0 68 0 62 64,
33 0 0 0 98 82 0 25 0 0 54 0,
87 0 0 0 87 85 17 0 71 14 98 68,
38 3 98 87 0 61 89 18 32 0 41 99,
0 89 82 85 61 0 50 3 35 55 33 50,
0 71 0 17 89 50 0 94 73 34 22 74,
0 0 25 0 18 3 94 0 0 33 92 0,
78 68 0 71 32 35 73 0 0 0 88 0,
28 0 0 14 0 55 34 33 0 0 70 95,
12 62 54 98 41 33 22 92 88 70 0 99,
46 64 0 68 99 50 74 0 0 95 99 0`.split(',');
const LabW5 = arrW5.map(el => el.split(' ').map(x => parseInt(x)));
const makeSymMatrix = matr => {
const sym = [];
for (let i = 0; i < matr.length; i++) {
for (let j = 0; j < matr.length; j++) {
if (!sym[i]) sym[i] = [];
if (!sym[j]) sym[j] = [];
if (matr[i][j] || sym[i][j]) {
sym[i][j] = 1;
sym[j][i] = 1;
} else sym[i][j] = 0;
}
}
return sym;
};
const zeroDiagonal = matr => {
const res = [];
for (let i = 0; i < matr.length; i++) {
res[i] = matr[i].slice();
res[i][i] = 0;
}
return res;
};
const addWeigth = (edges, weigth) => {
for (const key in edges) {
const edge = edges[key];
const fromEl = edge.fromEl;
const toEl = edge.toEl;
edge.w = weigth[fromEl][toEl];
}
}
const zeroToInf = (matr, weigthMatr) => {
const inf = Infinity;
for (let i = 0; i < matr.length; i++) {
for (let j = 0; j < matr[i].length; j++){
if(!matr[i][j]) weigthMatr[i][j] = inf;
}
}
}
const dejkstraAlg = (weigthMatr, start) => {
const len = weigthMatr.length;
const inf = Infinity;
const valid = Array(len).fill(true);
const weight = Array(len).fill(inf);
const nodes = [start];
const path = Array(len).fill(undefined);
path[start] = [start]
weight[start] = 0;
const steps = [];
for (let i = 0; i < len; i++) {
let minWeight = inf + 1;
let IdMinWeight = -1;
for (let j = 0; j < len; j++) {
if (valid[j] && weight[j] < minWeight) {
minWeight = weight[j];
IdMinWeight = j;
}
}
const pathToMin = path[IdMinWeight];
for(let z = 0; z < len; z++) {
if (weight[IdMinWeight] + weigthMatr[IdMinWeight][z] < weight[z]) {
weight[z] = weight[IdMinWeight] + weigthMatr[IdMinWeight][z];
const pathToVertex = pathToMin.slice();
pathToVertex.push(z);
path[z] = pathToVertex;
}
valid[IdMinWeight] = false;
}
steps.push({
openVert: IdMinWeight,
valid: valid.slice(),
weight: weight.slice(),
path: path.slice(),
})
}
return steps;
};
const pathToText = path => {
let text = 'Route\n';
for (let i = 0; i < path.length; i++) {
const p = path[i];
const textPath = p ? p.join('->') : p;
text += textPath + '\n';
}
return text;
};
console.table(makeSymMatrix(zeroDiagonal(Lab5)))
zeroToInf(makeSymMatrix(zeroDiagonal(Lab5)), LabW5);
console.table(LabW5)
const res = dejkstraAlg(LabW5, 0);
res.forEach(obj => console.log(obj));
<file_sep>const canvas1 = document.getElementById('lay01');
const canvas2 = document.getElementById('lay02');
const ctx1 = canvas1.getContext('2d');
const ctx2 = canvas2.getContext('2d');
const nonSym = document.getElementById('nonSym');
const condGraph = document.getElementById('condGraph');
const ways2 = document.getElementById('ways2');
const ways3 = document.getElementById('ways3');
const matr2and3 = document.getElementById('matr2and3');
const matrix = document.getElementById('matrix');
const deg = document.getElementById('degree');
const components = document.getElementById('components');
ctx1.strokeStyle = 'blue';
ctx2.lineWidth = 2.0;
ctx2.strokeStyle = 'black';
const matr = Lab3;
const condMatr = makeCondMatr(matr);
const comp = getTextComponents(matr);
const reachMatrix = reachabilityMatr(matr);
const strongConMat = makeStrongConnectM(matr);
const ways2Arr = toHumanRead(findAllWays2(matr));
const ways3Arr = toHumanRead(findAllWays3(matr));
const matrPow2 = powerMatrix(matr, 2);
const matrPow3 = powerMatrix(matr, 3);
const condGraphButton = () => {
drawGraph(condMatr, ctx1, ctx2, matrix)
deg.innerText = comp;
};
const graphButton = () => {
drawGraph(matr, ctx1, ctx2, matrix);
printDeegre(matr, deg)
};
const ways3Button = () => {
matrix.innerText = 'Strong Conectivity Matrix\n' + matrixToText(strongConMat);
deg.innerText = 'Reachability Matrix\n' + matrixToText(reachMatrix);
components.innerText = 'Ways3:\n' + getTextWays((ways3Arr));
}
const matr2and3Button = () => {
matrix.innerText = 'Matrix^2\n' + matrixToText(matrPow2);
deg.innerText = 'Matrix^3\n' + matrixToText(matrPow3);
}
const ways2Button = () => {
matrix.innerText = 'Strong Conectivity Matrix\n' + matrixToText(strongConMat);
deg.innerText = 'Reachability Matrix\n' + matrixToText(reachMatrix);
components.innerText = 'Ways2:\n' + getTextWays(ways2Arr);
}
nonSym.addEventListener('click', graphButton);
condGraph.addEventListener('click', condGraphButton);
ways3.addEventListener('click', ways3Button);
ways2.addEventListener('click', ways2Button);
matr2and3.addEventListener('click', matr2and3Button);<file_sep>'use strict';
const zeroDiagonal = matr => {
const res = [];
for (let i = 0; i < matr.length; i++) {
res[i] = matr[i].slice();
res[i][i] = 0;
}
return res;
};
const data = (matr, weigth, edges) => {
const arr = [];
for (let i = 0; i < matr.length; i++) {
for (let j = i; j < matr[i].length; j++) {
if (matr[i][j]) {
const w = weigth[i][j];
const edgName = `${i+1}_${j+1}`;
const edge = edges[edgName];
if (edge.loop) continue;
arr.push([w, i, j, edgName]);
}
}
}
return arr.sort((a, b) => a[0] - b[0]);
};
const countNumberOfEl = (arr, el) => {
let res = 0;
if (arr.length === 0) return res;
for (const e of arr) {
if (e.includes(el)) res++;
}
return res;
};
const isCycle = (vertices, stopEl, find, ind)=> {
let res = false;
for (let i = 0; i < vertices.length; i++) {
if (i === ind) continue;
const arr = vertices[i];
if (arr.includes(find)) {
const index = arr.indexOf(find);
const nextEl = arr[arr.length - (index + 1)];
if (nextEl === stopEl) {
return true;
}
res = isCycle(vertices, stopEl, nextEl, i);
if (res) break;
}
}
return res
};
const findOstTree = (matr, data) => {
const vertices = [];
const res = [];
const len = matr.length - 1;
for (const [w, fromVer, toVer, name] of data) {
if (res.length >= len) break;
const vertCopy = vertices.slice(0,);
vertCopy.push([fromVer, toVer]);
const fromVerNum = countNumberOfEl(vertCopy, fromVer);
const toVerNum = countNumberOfEl(vertCopy, toVer);
if (fromVerNum >= 3 && toVerNum >= 3) continue;
const cycle = isCycle(vertCopy, fromVer, toVer, vertCopy.length - 1);
if (!cycle) {
vertices.push([fromVer, toVer]);
res.push([name, w]);
}
}
return res;
};
const addWeigth = (edges, weigth) => {
for (const key in edges) {
const edge = edges[key];
const fromEl = edge.fromEl;
const toEl = edge.toEl;
edge.w = weigth[fromEl][toEl];
}
}
const makeBackboneMatr = (matr, edges, result) => {
const res = [];
for (let i = 0; i < matr.length; i++) {
res[i] = Array(matr[i].length).fill(0);
}
for (const el of result) {
const edge = edges[el[0]];
const fromEl = edge.fromEl;
const toEl = edge.toEl;
res[fromEl][toEl] = 1;
}
return res;
}<file_sep>'use strict';
const multMatrix = (matr1, matr2) => {
const res = [];
for (let i = 0; i < matr1.length; i++) {
res[i] = [];
for (let j = 0; j < matr1[i].length; j++) {
let sum = 0;
for (let e = 0; e < matr1[i].length; e++) {
sum += matr1[i][e] * matr2[e][j];
}
res[i][j] = sum;
}
}
return res;
};
const elementMultMatr = (matr1, matr2) => {
const res = [];
for (let i = 0; i < matr1.length; i++) {
res[i] = [];
for (let j = 0; j < matr1[i].length; j++) {
res[i][j] = matr1[i][j] * matr2[i][j];
}
}
return res;
};
const sumMatrix = (matr1, matr2) => {
const res = [];
for (let i = 0; i < matr1.length; i++) {
res[i] = [];
for (let j = 0; j < matr1[i].length; j++) {
res[i][j] = matr1[i][j] + matr2[i][j];
}
}
return res;
};
const transposeMatrix = matr => {
const transposed = [];
for (let i = 0; i < matr.length; i++) {
for (let j = 0; j < matr[i].length; j++) {
if (!transposed[i]) transposed[i] = [];
if (!transposed[j]) transposed[j] = [];
transposed[i][j] = matr[j][i];
}
}
return transposed;
};
const toBoolMatrix = matr => {
for (let i = 0; i < matr.length; i++) {
for (let j = 0; j < matr[i].length; j++) {
matr[i][j] = matr[i][j] ? 1 : 0;
}
}
return matr;
};
const powerMatrix = (matr, pow) => {
let res = multMatrix(matr, matr);
if (pow === 2) return res;
for (let i = 3; i <= pow; i++) {
res = multMatrix(res, matr);
}
return res;
};
const zeroDiagonal = matr => {
const res = [];
for (let i = 0; i < matr.length; i++) {
res[i] = matr[i].slice();
res[i][i] = 0;
}
return res;
};
const oneDiagonal = matr => {
const res = [];
for (let i = 0; i < matr.length; i++) {
res[i] = matr[i].slice();
res[i][i] = 1;
}
return res;
};
const reachabilityMatr = matr => {
const len = matr.length;
let res = sumMatrix(matr, powerMatrix(matr, 2));
for (let i = 3; i < len; i++) {
res = sumMatrix(res, powerMatrix(matr, i));
}
return toBoolMatrix(oneDiagonal(res));
};
const nreachabilityMatr = matr => {
const len = matr.length;
let arr = powerMatrix(matr, 2);
let res = matr;
for (let i = 2; i < len; i++) {
res = sumMatrix(res, arr);
arr = multMatrix(arr, matr);
}
return toBoolMatrix(oneDiagonal(res));
};
const showWaysNlength = (matr, len) => {
if (len === 1) return matr;
//const arr = zeroDiagonal(matr);
return powerMatrix(matr, len);
};
const goOut = (matr, vertix) => {
const res = [];
for (let j = 0; j < matr.length; j++) {
if (matr[vertix][j]) res.push(j);
}
return res;
};
const goIn = (matr, vertix) => {
const res = [];
for (let i = 0; i < matr.length; i++) {
if (matr[i][vertix]) res.push(i);
}
return res;
};
const findIntersection = (arr1, arr2) => {
const res = [];
for (const el of arr1) {
if (arr2.includes(el)) res.push(el);
}
return res;
};
const isIndentical = (arr1, arr2) => {
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
};
const findIndenticalArr = matr => {
const groups = [];
const was = [];
for (let i = 0; i < matr.length; i++) {
if (was.includes(i)) continue;
was.push(i);
groups.push([i]);
for (let j = 0; j < matr.length; j++) {
if (j === i) continue;
if (isIndentical(matr[i], matr[j])) {
was.push(j);
groups[groups.length - 1].push(j);
}
}
}
return groups;
};
const findWays2 = (matr, i, j, indexWays3) => {
const res = [];
const outGo = goOut(matr, i);
const inGo = goIn(matr, j);
const inter = findIntersection(inGo, outGo);
if (i === j && inter.includes(i)) {
const index = inter.indexOf(i);
inter.splice(index, 1);
}
if (matr[indexWays3] && inter.includes(indexWays3) && i === indexWays3) {
const index = inter.indexOf(indexWays3);
inter.splice(index, 1);
}
for (const el of inter) res.push([i, el, j]);
return res;
};
const findAllWays2 = (matr, indexWays3) => {
let ways = [];
const len = matr.length;
const waysMatr2 = showWaysNlength(matr, 2);
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (waysMatr2[i][j]) {
ways = ways.concat(findWays2(matr, i, j, indexWays3));
}
}
}
return ways;
};
const findWays3 = (matr, i, j) => {
let ways = [];
const outGo = goOut(matr, i);
for (const el of outGo) {
const ways2 = findWays2(matr, el, j, i).map(arr => [i].concat(arr));
ways = ways.concat(ways2);
}
return ways;
};
const findAllWays3 = matr => {
let ways = [];
const len = matr.length;
const waysMatr3 = showWaysNlength(matr, 3);
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (waysMatr3[i][j]) {
ways = ways.concat(findWays3(matr, i, j));
}
}
}
return ways;
};
const toHumanRead = arr => {
for (const el of arr) {
for (let i = 0; i < el.length; i++) {
el[i] = el[i] + 1;
}
}
return arr;
};
const makeStrongConnectM = matr => {
const reachMatr = reachabilityMatr(matr);
const transReachMatr = transposeMatrix(reachMatr);
return elementMultMatr(reachMatr, transReachMatr);
};
const makeCondMatr = matr => {
const strongConnecM = makeStrongConnectM(matr);
const groups = findIndenticalArr(strongConnecM);
const cond = [];
const len = groups.length;
for (let i = 0; i < len; i++) {
cond[i] = [];
}
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
cond[i][j] = 0;
if (i === j) continue;
for (const fromVer of groups[i]) {
for (const toVer of groups[j]) {
if (matr[fromVer][toVer]) cond[i][j] = 1;
}
}
}
}
return cond;
};
const getTextComponents = matr => {
const strongConnecM = makeStrongConnectM(matr);
const groups = findIndenticalArr(strongConnecM);
const humGroups = toHumanRead(groups);
let text = 'Components:\n';
for (let i = 0; i < humGroups.length; i++) {
text += `${i + 1} - {${humGroups[i].join(', ')}}\n`;
}
return text;
};
const getTextWays = ways => {
console.log(ways);
const arr = ways.map(el => `[${el.join(',')}],`);
for (let i = 7; i < arr.length; i += 8) {
arr[i] += '\n';
}
return arr.join(' ');
}
| 4e35f832365bfa65ad297819d10746edf861ce5c | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | vladyslavry141/DS | 048e389af1dc0a9323ab144fb3fc20538ccd1b57 | ba2042758bd5829e865af3c96fc21cd9831f9ddf |
refs/heads/master | <file_sep>package agency.v3.components.model.core;
/**
* 0-arg Consumer without checked exception, replacement for RxJava 1's Action0
*/
public interface Consumer0 {
void call();
}
<file_sep>package agency.v3.components.model.core;
/**
* 1-arg Consumer, without checked exception, replacement for RxJava 1's Action1
*/
public interface Consumer1<T> {
void call(T value);
}
<file_sep>package agency.v3.components.model.entity;
import agency.v3.components.model.core.Consumer0;
import io.reactivex.annotations.Nullable;
/**
* An class that encapsulates error details as well as options for recovering from it
* */
public class ErrorWithRecovery {
private final Throwable reasonThrowable;
private final String reason;
@Nullable
private final Consumer0 recovery;
@Nullable
private final Consumer0 cancellation;
ErrorWithRecovery(Throwable reasonThrowable, String reason, Consumer0 recovery, Consumer0 cancellation) {
this.reasonThrowable = reasonThrowable;
this.reason = reason;
this.recovery = recovery;
this.cancellation = cancellation;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Throwable reasonThrowable;
private String reason;
@Nullable
private Consumer0 recovery;
@Nullable
private Consumer0 cancellation;
public Builder() {
}
/**
* Actual {@link Throwable} this {@link ErrorWithRecovery} encapsulates
* */
public Builder reasonThrowable(Throwable throwable) {
this.reasonThrowable = throwable;
return this;
}
/**
* Textual representation of a reason of an error
* */
public Builder reason(String reason) {
this.reason = reason;
return this;
}
/**
* An action invoked when user decides to cancel failed operation
* */
public Builder cancellation(Consumer0 cancellation) {
this.cancellation = cancellation;
return this;
}
/**
* An action invoked when user decides to recover from failed operation
* */
public Builder recovery(Consumer0 recovery) {
this.recovery = recovery;
return this;
}
public ErrorWithRecovery build() {
if (reason == null || reasonThrowable == null) {
throw new IllegalArgumentException("Should provide both reason and reason throwable");
}
return new ErrorWithRecovery(reasonThrowable, reason, recovery, cancellation);
}
}
/**
* Actual {@link Throwable} this {@link ErrorWithRecovery} encapsulates
* */
public Throwable reasonThrowable() {
return reasonThrowable;
}
/**
* Textual representation of a reason of an error
* */
public String reason() {
return reason;
}
/**
* An action invoked when user decides to recover from failed operation
* */
@Nullable
public Consumer0 recovery() {
return recovery;
}
/**
* An action invoked when user decides to cancel failed operation
* */
@Nullable
public Consumer0 cancellation() {
return cancellation;
}
}
<file_sep>package agency.v3.components.model.executors;
import io.reactivex.Scheduler;
/**
* Where job is actually done
* */
public interface ExecutionThread {
Scheduler getScheduler();
}
<file_sep>package agency.v3.components.model.helpers;
import io.reactivex.Observable;
/**
* Can get current application state
* */
public interface AppStateMonitor {
Observable<State> monitor();
enum State {
FIRST_LAUNCH,
ENTERS_FOREGROUND,
ENTERS_BACKGROUND
}
}
<file_sep># v3-components-model
Base classes and utilities to implement Android app model layer in a testable MVP fashion
Examples: TBD<file_sep>package agency.v3.components.model.core;
import java.util.HashMap;
import io.reactivex.disposables.Disposable;
/**
* A helper to remember Subscriptions, Destroyable (by name) and dispose them (by name, all)
* when needed.
* <br/>
* <p>
* <b>This class is not thread safe. Please address to it from one thread only.</b>
*
* @author drew
*/
public class DisposeBag {
private final HashMap<String, Disposable> namedDisposables;
private final HashMap<String, Destroyable> namedDestroyables;
public DisposeBag() {
this.namedDisposables = new HashMap<>();
this.namedDestroyables = new HashMap<>();
}
/**
* This method allows to add named operation handle, so that it could be further
* cancelled by name.
* Adding subsequent subscription with the same name will cancel previous ongoing operation
*/
public void addDisposable(String name, Disposable subscription) {
cancel(name);
this.namedDisposables.put(name, subscription);
}
/**
* This method allows to add named operation handle, so that it could be further
* cancelled by name.
* Adding subsequent subscription with the same name will cancel previous ongoing operation
*/
public void addDisposable(String name, Destroyable disposable) {
cancel(name);
this.namedDestroyables.put(name, disposable);
}
/**
* Disposes previously added disposable by name with which it was added.
*/
private void cancelDestroyableByName(String name) {
Destroyable previous = this.namedDestroyables.remove(name);
if (previous != null) {
previous.destroy();
}
}
/**
* Disposes previously added disposable by name with which it was added.
*/
private void cancelDisposableByName(String name) {
Disposable previous = this.namedDisposables.remove(name);
if (previous != null && !previous.isDisposed()) {
previous.dispose();
}
}
/**
* Disposes previously added disposable by name with which it was added.
*/
public void cancel(String name) {
cancelDisposableByName(name);
cancelDestroyableByName(name);
}
/**
* Disposes all disposables contained in this container.
*/
public void disposeAll() {
//dispose from all actions
for (Destroyable d : namedDestroyables.values()) {
d.destroy();
}
namedDestroyables.clear();
//unsubscribe from all subscriptions and get rid from them
for (Disposable s : namedDisposables.values()) {
if (!s.isDisposed()) {
s.dispose();
}
}
namedDisposables.clear();
}
}
<file_sep>package agency.v3.components.model.core;
import java.util.Objects;
import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;
/**
* A variable that holds value and notifies it's consumer about value changes. Only one consumer is supported
*/
public class Variable<T> {
@Nullable
private volatile T value = null;
@Nullable
private Consumer1<T> consumer = null;
private final boolean shouldClearValueAfterConsumption;
private Variable(T value, boolean shouldClearValueAfterConsumption) {
this.value = value;
this.shouldClearValueAfterConsumption = shouldClearValueAfterConsumption;
}
/**
* Get value of this {@link Variable}
* @return value of variable or null, if no value specified
* */
@Nullable
public T getValue(){
synchronized (this) {
return value;
}
}
/**
* Set value of this {@link Variable} and notify registered consumers
* @param value a new value for this variable
* */
public void setValue(T value) {
synchronized (this) {
boolean isDistinct = setValueInternal(value);
if (isDistinct) {
maybeConsume();
}
}
}
private void maybeConsume() {
if (value != null) {
int consumeCount = 0;
// for (Consumer1<T> c : consumers) {
// c.call(value);
// consumeCount++;
// }
if (consumer != null) {
consumeCount++;
consumer.call(value);
}
maybeClearValue(consumeCount != 0);
}
}
/**
* @return whether distinct value was set
*/
private boolean setValueInternal(T value) {
boolean isDistinct = !Objects.equals(this.value, value);
this.value = value;
return isDistinct;
}
private void maybeClearValue(boolean wasConsumed) {
if (wasConsumed && shouldClearValueAfterConsumption) {
this.value = null;
}
}
/**
* Connect observer to that variable. Observer will be notified of only distinct value changes
* @return Disposable that can be disposed thus ending the subscription of observer to this {@link Variable}
* @throws IllegalStateException if you try to resubscribe already subscribed observer, or if this {@link Variable} is already subscribed to by some observer
*/
public Disposable observe(Consumer1<T> observer) {
synchronized (this) {
if (consumer != null) {
if (Objects.equals(observer, consumer)) {
throw new IllegalStateException("Attempt to RE-SUBSCRIBE the same observer");
} else {
throw new IllegalStateException("Attempt to SUBSCRIBE observer while Variable already has observer");
}
} else {
this.consumer = observer;
maybeConsume();
}
}
return new Disposable() {
//TODO: atomic reference, compare and set?
private volatile boolean isDisposed = false;
@Override
public void dispose() {
synchronized (this) {
consumer = null;
isDisposed = true;
}
}
@Override
public boolean isDisposed() {
return isDisposed;
}
};
}
/**
* Constructs an empty Variable that can keep some value
*/
public static <T> Variable<T> empty() {
return new Variable<>(null, /*keep value*/false);
}
/**
* Constructs a Variable that keeps value that's been set into it.
*/
public static <T> Variable<T> value(T value) {
return new Variable<>(value, /*keep value*/false);
}
/**
* Constructs a Variable that keeps value only until it is consumed; after it is consumed, Variable does not hold value
*/
public static <T> Variable<T> signal() {
return new Variable<>(null, /*clear value after it's been consumed */true);
}
}
<file_sep>package agency.v3.components.model.core;
import io.reactivex.observers.DisposableObserver;
/**
* A helper for building {@link DisposableObserver} in a fluent way
*/
public class DisposableBuilder<T> {
private Consumer0 whenStart;
private Consumer0 whenDone;
private Consumer1<T> whenNext;
private Consumer1<Throwable> whenError;
private final boolean allowQuietDisposable;
/**
* @param allowQuietDisposable whether to allow all callbacks to be empty, or throw an
* */
public DisposableBuilder(boolean allowQuietDisposable) {
this.allowQuietDisposable = allowQuietDisposable;
}
/**
* Invoke this callback in {@link DisposableObserver#onNext(T)}
* */
public DisposableBuilder<T> whenNext(Consumer1<T> onNext) {
this.whenNext = onNext;
return this;
}
/**
* Invoke this callback in {@link DisposableObserver#onStart()}
* */
public DisposableBuilder<T> whenStart(Consumer0 onStart) {
this.whenStart = onStart;
return this;
}
/**
* Invoke this callback in {@link DisposableObserver#onError(Throwable)}
* */
public DisposableBuilder<T> whenError(Consumer1<Throwable> onError) {
this.whenError = onError;
return this;
}
/**
* Invoke this callback in {@link DisposableObserver#onComplete()}
* */
public DisposableBuilder<T> whenDone(Consumer0 onDone) {
this.whenDone = onDone;
return this;
}
private void onCompleted() {
if (whenDone != null) {
whenDone.call();
}
}
private void onError(Throwable e) {
if (whenError != null) {
whenError.call(e);
}
}
private void onNext(T t) {
if (whenNext != null) {
whenNext.call(t);
}
}
private void onStart() {
if (whenStart != null) {
whenStart.call();
}
}
/**
* Builds a {@link DisposableObserver}.
* @throws IllegalArgumentException if no callbacks provided AND allowQuietDisposable param is false
* */
public DisposableObserver<T> build() {
if (!allowQuietDisposable && whenStart == null && whenDone == null && whenError == null && whenNext == null) {
throw new IllegalArgumentException("Disposable does not define any callback, and allowQuietDisposable param is FALSE");
}
return new DisposableObserver<T>() {
@Override
public void onComplete() {
DisposableBuilder.this.onCompleted();
}
@Override
public void onError(Throwable e) {
DisposableBuilder.this.onError(e);
}
@Override
public void onNext(T t) {
DisposableBuilder.this.onNext(t);
}
@Override
public void onStart() {
DisposableBuilder.this.onStart();
}
};
}
}
<file_sep>package agency.v3.components.model.resolvers;
/**
* An abstraction for Android string resource resolution
* */
public interface StringResolver {
String getString(int resId);
String getString(int resId, Object... args);
}
<file_sep>apply plugin: 'java-library'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
}
}
allprojects {
repositories {
jcenter()
}
}
if (JavaVersion.current().isJava8Compatible()) {//disable linter for javadoc
allprojects {
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
}
ext {
//For bintray and jcenter distribution
bintrayRepo = 'v3-components-model'
bintrayName = 'v3-components-model'
publishedGroupId = 'agency.v3.components.model'
libraryName = 'v3-components-model'
artifact = 'v3-components-model' //This artifact name should be the same with library module name
libraryDescription = 'Base classes and utilities to implement Android app model layer, in a testable MVP fashion'
siteUrl = 'https://github.com/ousenko/v3-components-model'
gitUrl = '<EMAIL>:ousenko/v3-components-model.git'
libraryVersion = '0.1.1'
developerId = 'ousenko'
developerName = 'Drew'
developerEmail = '<EMAIL>'
// organization = '' // if you push to organization's repository.
licenseName = 'MIT License' //Example for license
licenseUrl = 'https://github.com/ousenko/v3-components-model/blob/master/LICENSE'
allLicenses = ["MIT"]
}
//These two remote files contain Bintray configuration as described above.
//apply from: 'https://raw.githubusercontent.com/quangctkm9207/template-files/master/android/gradle/install.gradle'
//apply from: 'https://raw.githubusercontent.com/quangctkm9207/template-files/master/android/gradle/bintray.gradle'
//Add these lines to publish library to bintray. This is the readymade scripts made by github user nuuneoi to make uploading to bintray easy.
//Place it at the end of the file
apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle'
apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle'
dependencies {
api 'io.reactivex.rxjava2:rxjava:2.1.7'
}
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
<file_sep>package agency.v3.components.model.resolvers;
/**
* An abstraction for Android color resource resolution
* */
public interface ColorResolver {
int getColor(int resId);
}
| 2f6b02c4543067b74c3b9d2c567f0f64dedb11b8 | [
"Markdown",
"Java",
"Gradle"
] | 12 | Java | ousenko/v3-components-model | 41cde8dbecdd86f37dbb72e12d04e78a13774239 | d30d1e6e020013f19a648ac3b9c1cb290869cccc |
refs/heads/master | <repo_name>mice-k/mice-k.github.io<file_sep>/keychain/main.js
function hive_customJSON(urlParams) {
hive_keychain.requestCustomJson(
urlParams.get('username'),
urlParams.get('id'),
urlParams.get('auth'),
urlParams.get('json'),
urlParams.get('message'),
function(response) {
console.log('main js response - custom JSON');
console.log(response);
}
);
};
function hive_sendTokens(urlParams) {
hive_keychain.requestSendToken(
urlParams.get('username'),
urlParams.get('sendTo'),
urlParams.get('amount'),
urlParams.get('memo'),
urlParams.get('symbol'),
function(response) {
console.log("main js response - tokens");
console.log(response);
}
);
};
function hive_transfer(urlParams) {
hive_keychain.requestTransfer(
urlParams.get('username'),
urlParams.get('sendTo'),
urlParams.get('amount'),
urlParams.get('memo'),
urlParams.get('symbol'),
function(response) {
console.log("main js response - transfer");
console.log(response);
},
!(urlParams.get('enforce') === 'false')
);
};
window.addEventListener('load', function () {
if (window.hive_keychain) {
keychains_ready();
} else {
var keychain_check = setInterval(function(){
if (window.hive_keychain) {
clearInterval(keychain_check);
keychains_ready();
}
}, 250);
}
});
function keychains_ready() {
const urlParams = new URLSearchParams(window.location.search);
const chain = urlParams.get('chain');
if (chain === 'hive') {
const type = urlParams.get('type');
console.log(type);
if (type === 'customJSON') {
hive_customJSON(urlParams);
} else if (type === 'transfer') {
hive_transfer(urlParams);
} else if (type === 'sendTokens') {
hive_sendTokens(urlParams);
}
}
}<file_sep>/gen/sketch.js
const speed = 4;
let r;
const w = 500;
const h = 500;
let s;
let x = 0;
let y = 0;
let d;
let hue = 0;
let hs;
let stop;
let sat;
function setup() {
//randomSeed(107);
random();
r = random(2, 20);
console.log(r);
s = random(4, 40);
d = random() * 2 * PI;
stop = random(2000, 9000);
hs = random(1, 1000);
sat = random(50, 100);
createCanvas(w,h);
background(0);
colorMode(HSB);
}
function draw() {
translate(w/2, h/2);
for (let i=0;i<speed;i++) {
noStroke();
fill(hue, sat, 100);
hue = (hue + hs/1000) % 360;
circle(x, y, r * 2);
x += s * cos(d);
y += s * sin(d);
if (x > w/2-r) { // right
d *= -1;
d += PI;
x -= 2 * (x - (w/2-r));
}
else if (x < -w/2+r) { // left
d += PI;
d *= -1;
x += 2 * -(x + (w/2-r));
}
else if (y > h/2-r) { // bottom
d = -d;
y -= 2 * (y - (h/2-r));
}
else if (y < -h/2+r) { // top
d = -d;
y += 2 * -(y + (h/2-r));
}
}
if (frameCount * speed >= stop) noLoop();
} | 201afe094f972f1edccab77daab4fef4e268f929 | [
"JavaScript"
] | 2 | JavaScript | mice-k/mice-k.github.io | f11e60156426697e782958773854cd51de074dc7 | 5ad2eeea53166ee80e0734457ec22265aa0b92b0 |
refs/heads/master | <repo_name>1392794981/ListenMe<file_sep>/app/src/main/java/com/example/x/listenme/MainActivity.java
package com.example.x.listenme;
//My GitHub
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
//import static android.os.Environment.getExternalStorageDirectory;
public class MainActivity extends FragmentActivity {
String strFilePath;
boolean isShowText = false;
float playSpeed = 1.0f;
final int REQUEST_CODE_OPEN_FILE = 6;
static MediaPlayer player = new MediaPlayer();
AudioManager audioManager;
FileDialog fileDialog;
TextView txtFilePath, txtPosition, txtText, txtTemp;//txtVolume,
Button btnOpenFile, btnLRC, btnClear, btnForward, btnBack, btnRePlay, btnPlayOrPause, btnPre, btnNext, btnInsertPoint, btnDelPoint, btnShowText, btnVolumeUp, btnVolumeDown;
Button btnSpeedUp, btnSpeedDown;
Button btnSimple, btnComplex;
TextView txtShowTextInSecond;
Button btnShowTextInSecond, btnNextInSecond, btnAnotherNextInSecond, btnPreInSecond;
ImageView imageViewProgress;
SortedList pointList;
private View complexView, simpleView;
static class HandlerProgress extends Handler {
WeakReference<MainActivity> mActivity;
HandlerProgress(MainActivity activity) {
mActivity = new WeakReference<MainActivity>(activity);
}
@SuppressLint("SetTextI18n")
@Override
public void handleMessage(Message msg) {
MainActivity theActivity = mActivity.get();
super.handleMessage(msg);
switch (msg.what) {
case 1:
ImageView image = theActivity.imageViewProgress;
MediaPlayer player = theActivity.player;
SortedList list = theActivity.pointList;
int width = image.getWidth();
int height = image.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.argb(0xff, 0x11, 0x11, 0x11));
canvas.drawRect(0, 0, width, height, paint);
paint.setColor(Color.argb(0xff, 0x55, 0x55, 0x55));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.argb(0xff, 0x55, 0x55, 0x55));
canvas.drawRect(40, 30, 1040, 90, paint);
//canvas.drawRect(40, 40, 1040, 80, paint);
try {
if (player.getDuration() > 0) {
int duration = player.getDuration();
int position = player.getCurrentPosition();
int value = (position * 1000) / duration;
int startValue = (int) ((Math.round(list.getValueByPosition(list.position) * 1000) / duration) + 40);
paint.setStyle(Paint.Style.FILL);
canvas.drawRect(startValue, 46, value + 40, 74, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
for (int i = 0; i < list.getSize(); i++) {
value = (int) ((Math.round(list.getValueByPosition(i)) * 1000) / duration + 40);
canvas.drawLine(value, 30, value, 90, paint);
}
value = (int) ((Math.round(list.getValueByPosition(list.position) * 1000) / duration) + 40);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(value, 82, 6, paint);
if (player.getCurrentPosition() >= list.getNextPoint())
player.pause();
String str = "#";
for (int i = 0; i < theActivity.pointList.getSize(); i++)
str = str + " " + theActivity.pointList.getValueByPosition(i);
int m = (position / 1000) / 60;
int s = (position / 1000) % 60;
long currentPoint = (long) list.getCurrentPoint();
String currentPointString = String.valueOf((currentPoint / 1000) / 60) + "分" + String.valueOf((currentPoint / 1000) % 60) + "秒";
theActivity.txtPosition.setText(currentPointString + "->" + String.valueOf(m) + "分" + String.valueOf(s) + "秒"+
" ["+"音量:" +String.valueOf(theActivity.getCurrentVolume())+" 速度:" + String.valueOf(theActivity.playSpeed)+ "]");
if (theActivity.isShowText) {
theActivity.btnShowText.setText("隐藏");
theActivity.btnShowTextInSecond.setText("隐");
str = list.getCurrentDataString();
if (str != null) {
theActivity.txtText.setText(str);
theActivity.txtShowTextInSecond.setText(str);
} else {
theActivity.txtText.setText("无");
theActivity.txtShowTextInSecond.setText("");
}
} else {
theActivity.btnShowText.setText("显示");
theActivity.btnShowTextInSecond.setText("显");
theActivity.txtText.setText("");
theActivity.txtShowTextInSecond.setText("");
}
theActivity.txtFilePath.setText(theActivity.strFilePath);
theActivity.showVolume();
}
} catch (Exception e) {
theActivity.txtPosition.setText(e.getMessage());
}
image.setImageBitmap(bitmap);
break;
}
}
}
private final HandlerProgress handlerProgress = new HandlerProgress(this);
class ThreadProgress extends Thread {
@Override
public void run() {
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
txtPosition.setText(e.getMessage());
}
Message message = new Message();
message.what = 1;
handlerProgress.sendMessage(message);
}
}
}
// class KeyBroadcastReceiver extends BroadcastReceiver {
// @Override
// public void onReceive(Context context, Intent intent) {
// if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// txtTemp.setText("好");
// abortBroadcast();
// }
// }
// }
//
// private KeyBroadcastReceiver keyBroadcastReceiver; //= new KeyBroadcastReceiver(this);
// private IntentFilter keyIntentFilter;
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
complexView = getLayoutInflater().inflate(R.layout.activity_main, null);
simpleView = getLayoutInflater().inflate(R.layout.layout_simple, null);
setContentView(complexView);
verifyStoragePermissions(this);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
imageViewProgress = complexView.findViewById(R.id.surfaceViewProgress);
new ThreadProgress().start();
// try {
// keyBroadcastReceiver = new KeyBroadcastReceiver();
// keyIntentFilter = new IntentFilter();
// keyIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
// registerReceiver(keyBroadcastReceiver, keyIntentFilter);
// } catch (Exception e) {
// txtTemp.setText(e.getMessage());
// }
txtFilePath = (TextView) complexView.findViewById(R.id.txtFilePath);
txtPosition = (TextView) complexView.findViewById(R.id.txtPosition);
txtText = complexView.findViewById(R.id.txtText);
// txtVolume = complexView.findViewById(R.id.txtVolume);
txtTemp = complexView.findViewById(R.id.textView2);
btnOpenFile = (Button) complexView.findViewById(R.id.btnOpenFile);
btnLRC = (Button) complexView.findViewById(R.id.btnLRC);
btnClear = (Button) complexView.findViewById(R.id.btnClear);
btnForward = (Button) complexView.findViewById(R.id.btnForward);
btnBack = (Button) complexView.findViewById(R.id.btnBack);
btnRePlay = (Button) complexView.findViewById(R.id.btnRePlay);
btnPlayOrPause = (Button) complexView.findViewById(R.id.btnPlayOrPause);
btnNext = (Button) complexView.findViewById(R.id.btnNext);
btnPre = (Button) complexView.findViewById(R.id.btnPre);
btnDelPoint = (Button) complexView.findViewById(R.id.btnDelPoint);
btnInsertPoint = (Button) complexView.findViewById(R.id.btnInsertPoint);
btnShowText = complexView.findViewById(R.id.btnShowText);
btnVolumeUp = complexView.findViewById(R.id.btnVolumeUp);
btnVolumeDown = complexView.findViewById(R.id.btnVolumeDown);
btnSpeedDown = complexView.findViewById(R.id.btnSpeedDown);
btnSpeedUp = complexView.findViewById(R.id.btnSpeedUp);
btnSimple = complexView.findViewById(R.id.btnSimple);
btnComplex = simpleView.findViewById(R.id.btnComplex);
txtShowTextInSecond = simpleView.findViewById(R.id.txtShowTextInSecond);
btnNextInSecond = simpleView.findViewById(R.id.btnNextInSecond);
btnShowTextInSecond = simpleView.findViewById(R.id.btnShowTextInSecond);
btnPreInSecond = simpleView.findViewById(R.id.btnPreInSecond);
btnAnotherNextInSecond = simpleView.findViewById(R.id.btnAnotherNextInSecond);
initCustomSetting();
String dir = strFilePath.substring(0, strFilePath.lastIndexOf("/"));//"/storage/";//
File dialogDir = new File(dir);
if (!dialogDir.exists())
dialogDir = new File("/storage/");
Log.v("dir", dir);
//txtTemp.setText(strFilePath+"\n"+ dir);
fileDialog = new FileDialog(this, dialogDir, ".mp3");
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
@Override
public void fileSelected(File file) {
strFilePath = file.getAbsolutePath();
loadSound(strFilePath);
}
});
btnOpenFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toOpenFile();
}
});
btnRePlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toRePlay();
}
});
btnPlayOrPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toPlayOrPause();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toNext();
}
});
btnPre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toPre();
}
});
btnInsertPoint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toInsertPoint();
}
});
btnDelPoint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toDelPoint();
}
});
btnLRC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toLRC();
}
});
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toClear();
}
});
btnForward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toForward();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toBack();
}
});
btnShowText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toShowText();
}
});
btnVolumeDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toDownVolume();
}
});
btnVolumeUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toUpVolume();
}
});
btnSimple.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setContentView(simpleView);
}
});
btnComplex.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setContentView(complexView);
}
});
btnShowTextInSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toShowText();
}
});
btnNextInSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toNext();
}
});
btnAnotherNextInSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toNext();
}
});
btnPreInSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toPre();
}
});
btnSpeedUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toSpeedUp();
}
});
btnSpeedDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toSpeedDown();
}
});
}
private void loadSound(String soundFilePath) {
player.reset();
try {
player.setDataSource(soundFilePath);
player.prepare();
initPoint();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
txtTemp.setText(event.toString());
//本函数处理onkeydown无法处理的几个键
String characters = event.getCharacters();//返回全角字符
if (characters != null) {
switch (characters) {
case "+":
toPlayOrPause();
break;
case "-":
toRePlay();
break;
case "*":
toForward();
break;
case "/":
toBack();
break;
}
}
return super.dispatchKeyEvent(event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//txtTemp.setText(txtTemp.getText()+"\n&&&"+String.valueOf(keyCode) + "\n&&&" + event.toString());
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP: //音量键 上
toRePlay();
break;
case KeyEvent.KEYCODE_VOLUME_DOWN: //音量键 下
if ((!player.isPlaying()) && (pointList.getNextPoint() <= player.getCurrentPosition()))
toRePlay();
else
toPlayOrPause();
break;
case KeyEvent.KEYCODE_NUMPAD_9:
toPre();
break;
case KeyEvent.KEYCODE_PAGE_UP:
toPre();
break;
case KeyEvent.KEYCODE_NUMPAD_3:
toNext();
break;
case KeyEvent.KEYCODE_PAGE_DOWN:
toNext();
break;
case KeyEvent.KEYCODE_NUMPAD_0:
toInsertPoint();
break;
case KeyEvent.KEYCODE_INSERT:
toInsertPoint();
break;
case KeyEvent.KEYCODE_NUMPAD_DOT:
toDelPoint();
break;
case KeyEvent.KEYCODE_FORWARD_DEL:
toDelPoint();
break;
case KeyEvent.KEYCODE_NUMPAD_8:
toSpeedUp();
break;
case KeyEvent.KEYCODE_DPAD_UP:
toSpeedUp();
break;
case KeyEvent.KEYCODE_NUMPAD_2:
toSpeedDown();
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
toSpeedDown();
break;
case KeyEvent.KEYCODE_NUMPAD_1:
toSpeedNormal();
break;
case KeyEvent.KEYCODE_MOVE_END:
toSpeedNormal();
break;
case KeyEvent.KEYCODE_MOVE_HOME:
toLRC();
break;
case KeyEvent.KEYCODE_NUMPAD_7:
toLRC();
break;
case KeyEvent.KEYCODE_NUMPAD_5:
toLRC();
break;
case KeyEvent.KEYCODE_BACK: //不屏蔽返回建
super.onKeyDown(keyCode, event);
break;
}
return true;
}
private void toSpeedNormal() {
playSpeed=1;
setPlaySpeed();
}
private void toSpeedDown() {
if (playSpeed > 0.11f)
playSpeed -= 0.1f;
setPlaySpeed();
}
private void setPlaySpeed() {
playSpeed = new BigDecimal(playSpeed).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();//四舍五入,保留一位小数
player.setPlaybackParams(player.getPlaybackParams().setSpeed(playSpeed));
}
private void toSpeedUp() {
if (playSpeed < 2.91)
playSpeed += 0.1f;
setPlaySpeed();
}
private void showVolume() {
//txtVolume.setText(String.valueOf(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)));
}
private int getCurrentVolume() {
return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
private void toUpVolume() {
int oldIndex = getCurrentVolume();
int maxIndex = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
if (oldIndex + 1 < maxIndex)
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, oldIndex + 1, AudioManager.FLAG_PLAY_SOUND);
showVolume();
}
private void toDownVolume() {
int oldIndex = getCurrentVolume();
if (oldIndex - 1 >= 0)
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, oldIndex - 1, AudioManager.FLAG_PLAY_SOUND);
showVolume();
}
private void toClear() {
pointList.clearPoint();
}
private void toLRC() {
loadLRC();
}
private void toShowText() {
isShowText = !isShowText;
}
private void toBack() {
int pos = player.getCurrentPosition();
if (pos - 2000 > 0)
player.seekTo(pos - 2000);
else
player.seekTo(0);
player.start();
}
private void toForward() {
int pos = player.getCurrentPosition();
if (pos + 2000 < player.getDuration())
player.seekTo(pos + 2000);
player.start();
}
private void toDelPoint() {
pointList.deleteCurrentPoint();
toRePlay();
}
private void toInsertPoint() {
pointList.position = pointList.insertByOrder(player.getCurrentPosition());
toRePlay();
}
private void toPre() {
if (pointList.position > 0) {
pointList.position--;
}
toRePlay();
}
private void toNext() {
if (pointList.position < pointList.getSize() - 2) {
pointList.position++;
}
toRePlay();
}
private void toPlayOrPause() {
if (player.isPlaying()) player.pause();
else player.start();
}
private void toRePlay() {
player.seekTo((int) Math.round(pointList.getCurrentPoint()));
player.start();
}
private void toOpenFile() {
fileDialog.showDialog();
// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// intent.setType("audio/MP3");//设置类型,我这里是任意类型,任意后缀的可以这样写。
// intent.addCategory(Intent.CATEGORY_OPENABLE);
// startActivityForResult(intent, REQUEST_CODE_OPEN_FILE);
}
@Override
protected void onStop() {
super.onStop();
stopCustomSettings();
// unregisterReceiver(keyBroadcastReceiver);
}
private void stopCustomSettings() {
String settingFileName = getApplicationContext().getFilesDir() + "/setting.txt";
File file = new File(settingFileName);
if (file.exists())
file.delete();
try {
file.createNewFile();
OutputStream outStream = new FileOutputStream(file);//设置输出流
OutputStreamWriter out = new OutputStreamWriter(outStream);//设置内容输出方式
out.write(strFilePath + "\n");//输出内容到文件中
out.close();
} catch (java.io.IOException e) {
android.util.Log.i("stop", e.getMessage());
}
}
private void initCustomSetting() {
String settingFileName = getApplicationContext().getFilesDir() + "/setting.txt";
File file = new File(settingFileName);
try {
// float speed= (float) 0.5;
// player.setPlaybackParams(player.getPlaybackParams().setSpeed(speed));
if (file.exists()) {
InputStream inputStream = new FileInputStream(file);//读取输入流
InputStreamReader inputReader = new InputStreamReader(inputStream);//设置流读取方式
BufferedReader bufferedReader = new BufferedReader(inputReader);
String line = bufferedReader.readLine();
strFilePath = line;
player.reset();
player.setDataSource(line);
player.prepare();
initPoint();
}
} catch (Exception e) {
txtTemp.setText(e.getMessage());
}
}
protected void initPoint() {
pointList = new SortedList();
pointList.insertByOrder(0);
pointList.insertByOrder(player.getDuration());
}
protected void loadLRC() {
try {
String fileName = strFilePath.substring(0, strFilePath.length() - 4) + ".lrc";
File file = new File(strFilePath);
if (file.exists()) {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
Double value = Double.valueOf(str.substring(1, 3)) * 60 * 1000 + Double.valueOf(str.substring(4, 10)) * 1000;
String string = str.substring(11, str.length());
pointList.insertByOrder(value, string);
}
br.close();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CODE_OPEN_FILE) {
strFilePath = getRealPath(data.getData());
txtFilePath.setText(strFilePath);
try {
player.reset();
player.setDataSource(strFilePath);
player.prepare();
initPoint();
} catch (IOException e) {
txtFilePath.setText(e.getMessage());
}
}
}
}
protected String getRealPath(Uri uri) {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {"_data"};
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
cursor.moveToFirst();
return cursor.getString(column_index);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
} else {
return null;
}
}
//
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"};
public static void verifyStoragePermissions(Activity activity) {
try {
//检测是否有写的权限
int permission = ActivityCompat.checkSelfPermission(activity,
"android.permission.WRITE_EXTERNAL_STORAGE");
if (permission != PackageManager.PERMISSION_GRANTED) {
// 没有写的权限,去申请写的权限,会弹出对话框
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/README.md
# ListenMe
this is my firt app
| 4b10a377c4a0f1f938456dffdf65aac5f06166f8 | [
"Markdown",
"Java"
] | 2 | Java | 1392794981/ListenMe | d68ed354b0b2687ba54dc8b324e6eb8282a633f3 | de5fe09bbba1500e296bebda27e9330c72f85a26 |
refs/heads/master | <file_sep>package com.example.Model;
import javax.persistence.*;
import java.util.Date;
import java.sql.Time;
@Entity
@Table(name = "prosby")
public class Prosby {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
Integer idp;
@Column(nullable = false)
Time godzina;
@Temporal(TemporalType.DATE)
@Column(nullable = false)
Date data;
@Column(nullable = false)
String imie;
@Column(nullable = false)
String nazwisko;
@Column(nullable = true)
Integer lekarzeidl;
public Integer getIdp() {
return idp;
}
public void setIdp(Integer idp) {
this.idp = idp;
}
public Time getGodzina() {
return godzina;
}
public void setGodzina(Time godzina) {
this.godzina = godzina;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public Integer getLekarzeidl() {
return lekarzeidl;
}
public void setLekarzeidl(Integer lekarzeidl) {
this.lekarzeidl = lekarzeidl;
}
}
<file_sep>package com.example.repositories;
import com.example.Model.Uzytkownik;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UzytkownikRepository extends JpaRepository<Uzytkownik,Long> {
}
<file_sep>package com.example.controllers;
import com.example.Model.Harmonogram;
import com.example.Model.Lekarze;
import com.example.Model.Prosby;
import com.example.repositories.HarmonogramRepository;
import com.example.repositories.LekarzeRepository;
import com.example.repositories.ProsbyRepository;
import com.example.repositories.UzytkownikRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.Date;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Controller
public class MappingController {
@Autowired
UzytkownikRepository uzytkownikRepository;
@Autowired
LekarzeRepository lekarzeRepository;
@Autowired
ProsbyRepository prosbyRepository;
@Autowired
HarmonogramRepository harmonogramRepository;
/*@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}*/
@GetMapping("/")
public ModelAndView index(){
List<Lekarze> doctorList = lekarzeRepository.findAll();
ModelAndView mv = new ModelAndView("index");
mv.addObject("doctorList",doctorList);
return mv;
}
@RequestMapping(value = "/returnClicked/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> getClicked(@PathVariable("id") int id){
System.out.println("listExistingUser is called in controller");
Lekarze lekarz = lekarzeRepository.findByIdl(id);
return new ResponseEntity<Object>(lekarz, HttpStatus.OK);
}
@RequestMapping(value = "/returnClickedHarm/{data}/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> getHarm(@PathVariable("id") int id,@PathVariable("data") String data){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
try {
date = new Date(formatter.parse(data).getTime());
}
catch (Exception e){System.out.println(e.getMessage());}
//System.out.println("listExistingHarm is called in controller");
List<Harmonogram> harm = harmonogramRepository.findAllByIdl(id);
Harmonogram result = new Harmonogram();
for(Harmonogram h:harm){
if((h.getDataod().equals(date) || h.getDataod().before(date) )&&(h.getDatado().equals(date) || h.getDatado().after(date)))
result = h;
}
return new ResponseEntity<Object>(result, HttpStatus.OK);
}
@RequestMapping(value ="/returnAvaibility/{data}/{id}",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Object> getAvaibility(@PathVariable("data") String data,@PathVariable("id") int id ){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Pobieram dostepnosc "+ data );
List<Prosby> prosby = new ArrayList<>();
List<Prosby> doprzesl = new ArrayList<>();
for(int i = 0;i<7;i++) {
try {
Date date = new Date(formatter.parse(data).getTime() + TimeUnit.DAYS.toMillis(i));
//System.out.println("Pobieram dostepnosc "+ data +" " + formatter.parse(data).toString() +" "+ new Date(formatter.parse(data).getTime()));
prosby = prosbyRepository.findAllByData(date);
Prosby prosba = prosbyRepository.findByData(date);
//if (prosba != null)
//System.out.println(prosby.size()+ " " + prosba.getNazwisko());
} catch (Exception e) {
System.out.println(e.getMessage());
}
for (Prosby p : prosby) {
if (p.getLekarzeidl() == id) {
doprzesl.add(p);
}
}
}
System.out.println(doprzesl.size());
return new ResponseEntity<Object>(doprzesl.toArray(),HttpStatus.OK);
}
@GetMapping("/lekarz")
public String lekarz(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
Lekarze lekarz = new Lekarze();
//lekarz.setImie("Imie");
//lekarz.setNazwisko("Nazwisko");
//lekarz.setgodzinaspracypocz(Time.valueOf("12:20:19"));
//lekarz.setgodzinaspracykonc(Time.valueOf("12:20:19"));
//lekarzeRepository.save(lekarz);
return "lekarz";
}
@GetMapping("/lekarz2")
public ModelAndView lekarz2() {
ModelAndView mv = new ModelAndView("lekarz2");
List<Lekarze> doctorList = lekarzeRepository.findAll();
Lekarze doctor = null;
for(Lekarze d : doctorList){
if (d.getuzytkownikidu() != null && d.getuzytkownikidu() == 1)
doctor = d;
}
if(doctor!=null){
Harmonogram harmonogram = harmonogramRepository.findHarmonogramByIdl(doctor.getidl());
mv.addObject("harmonogram",harmonogram);
}
mv.addObject("doctor",doctor);
return mv;
}
@PostMapping("/lekarz2")
public ModelAndView modifyHarmonogram(String pp,String pk,String wp,String wk,String sp,String sk,String cp,String ck,String pip,String pik,String sop,String sok,String np,String nk) {
DateFormat formatter = new SimpleDateFormat("HH:mm");
ModelAndView mv = new ModelAndView("lekarz2");
List<Lekarze> doctorList = lekarzeRepository.findAll();
Lekarze doctor = null;
for(Lekarze d : doctorList){
if (d.getuzytkownikidu() != null && d.getuzytkownikidu() == 1)
doctor = d;
}
Harmonogram harm = harmonogramRepository.findHarmonogramByIdl(doctor.getidl());
mv.addObject("harmonogram",harm);
System.out.println("POSTMAPPING");
mv.addObject("doctor",doctor);
try {
harm.setPoniedzialek_p((pp.equals(""))?null:new java.sql.Time(formatter.parse(pp).getTime()));
harm.setPoniedzialek_k((pk.equals(""))?null:new java.sql.Time(formatter.parse(pk).getTime()));
harm.setWtorek_p((wp.equals(""))?null:new java.sql.Time(formatter.parse(wp).getTime()));
harm.setWtorek_k((wk.equals(""))?null:new java.sql.Time(formatter.parse(wk).getTime()));
harm.setSroda_p((sp.equals(""))?null:new java.sql.Time(formatter.parse(sp).getTime()));
harm.setSroda_k((sk.equals(""))?null:new java.sql.Time(formatter.parse(sk).getTime()));
harm.setCzwartek_p((cp.equals(""))?null:new java.sql.Time(formatter.parse(cp).getTime()));
harm.setCzwartek_k((ck.equals(""))?null:new java.sql.Time(formatter.parse(ck).getTime()));
harm.setPiatek_p((pip.equals(""))?null:new java.sql.Time(formatter.parse(pip).getTime()));
harm.setPiatek_k((pik.equals(""))?null:new java.sql.Time(formatter.parse(pik).getTime()));
harm.setSobota_p((sop.equals(""))?null:new java.sql.Time(formatter.parse(sop).getTime()));
harm.setSobota_k((sok.equals(""))?null:new java.sql.Time(formatter.parse(sok).getTime()));
harm.setNiedziela_p((np.equals(""))?null:new java.sql.Time(formatter.parse(np).getTime()));
harm.setNiedziela_k((nk.equals(""))?null:new java.sql.Time(formatter.parse(nk).getTime()));
harmonogramRepository.save(harm);
}
catch (Exception e){System.out.println(e.getMessage());}
mv.addObject("harmonogram", harm);
return mv;
}
@GetMapping("/zarzadca")
public ModelAndView zarzadca(){
List<Lekarze> doctorList = lekarzeRepository.findAll();
List<Prosby> prosbyList = prosbyRepository.findAll();
ModelAndView mv = new ModelAndView("zarzadca");
mv.addObject("prosbyList",prosbyList);
mv.addObject("doctorList",doctorList);
return mv;
}
@PostMapping("/zarzadcaDodLek")
public ModelAndView addLekarz(String imie,String nazwisko) {
Lekarze lek = new Lekarze();
lek.setImie(imie);
lek.setNazwisko(nazwisko);
//lek.setgodzinaspracypocz(new Time(System.currentTimeMillis()));
//lek.setgodzinaspracykonc(new Time(System.currentTimeMillis()));
lekarzeRepository.save(lek);
ModelAndView mv = new ModelAndView();
mv.addObject("lek",lek);
mv.setViewName("zarzadcaDodLek");
return mv;
}
@GetMapping("/zarzadcaDodLek")
public String zarzadcaDodLek(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "zarzadcaDodLek";
}
@GetMapping("/zarzadcaModLek")
public ModelAndView zarzadcaModLek(){
List<Lekarze> doctorList = lekarzeRepository.findAll();
ModelAndView mv = new ModelAndView("zarzadcaModLek");
mv.addObject("doctorList",doctorList);
return mv;
}
}<file_sep>package com.example.repositories;
import com.example.Model.Harmonogram;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface HarmonogramRepository extends JpaRepository<Harmonogram,Long> {
public Harmonogram findHarmonogramByIdl(Integer idl);
public List<Harmonogram> findAllByIdl(Integer idl);
}
<file_sep>package com.example.repositories;
import com.example.Model.Lekarze;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LekarzeRepository extends JpaRepository<Lekarze,Long> {
public Lekarze findByIdl(int i);
}
<file_sep>package com.example.repositories;
import com.example.Model.Wizyty;
import org.springframework.data.jpa.repository.JpaRepository;
public interface WizytyRepository extends JpaRepository<Wizyty,Long> {
}
<file_sep>package com.example.Model;
import org.springframework.lang.Nullable;
import javax.persistence.*;
import java.sql.Time;
@Entity
@Table(name = "lekarze" )
public class Lekarze
{
public Lekarze() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
Integer idl;
@Column(nullable = false)
String imie;
@Column(nullable = false)
String nazwisko;
@Column(nullable = true)
Integer uzytkownikidu;
//@OneToOne
//@Nullable
//@JoinColumn(name = "uzytkownikidu")
//Uzytkownik uzytkownikidu;
public Integer getidl() {
return idl;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public Integer getuzytkownikidu() {
return uzytkownikidu;
}
public void setuzytkownikidu(Integer uzytkownikidu) {
this.uzytkownikidu = uzytkownikidu;
}
}
<file_sep>package com.example.Model;
import javax.persistence.*;
import java.sql.Time;
@Entity
@Table(name = "wizyty")
public class Wizyty {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
Integer idw;
@Column(nullable = false)
Integer prosbyidp;
}
<file_sep>package com.example.repositories;
import com.example.Model.Harmonogram;
import com.example.Model.Prosby;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Date;
import java.util.List;
public interface ProsbyRepository extends JpaRepository<Prosby,Long> {
public List<Prosby> findAllByData(Date data);
public Prosby findByData(Date data);
}
| 84886687d1b83734ae2b37ea5364e8254fbdd064 | [
"Java"
] | 9 | Java | FractialCopper/Przychodnia | a7761334868ec9e9efd910ffa05f51256c6c7f33 | 3074e965c01307c56ba005b70bd9374688ebad20 |
refs/heads/master | <file_sep><div class="form">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'question tilte'); ?>
<?php echo CHtml::activeTextField($model,'question_title', array('class' => 'span4')); ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'description'); ?>
<?php echo CHtml::activeTextarea($model,'description', array('rows' => '4', 'class' => 'span6 text-box')) ?>
</div>
<div class="row rememberMe">
<?php //echo CHtml::activeCheckBox($model,'rememberMe'); ?>
<?php //echo CHtml::activeLabel($model,'rememberMe'); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Submit', array('class' => 'btn btn-info')); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form --><file_sep><?php
class User extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{user}}';
}
/**
* The followings are the available columns in table 'user':
* @var integer $id
* @var string $username
* @var string $password
* @var string $c_password
* @var string $email
* @var string $profile
*/
public $c_password;
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, password, email, c_password', 'required', 'on'=>'insert'),
array('password, <PASSWORD>', 'length', 'min'=>3, 'max'=>40),
array('password', 'compare', 'compareAttribute'=>'<PASSWORD>'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'Id',
'username' => 'Username',
'password' => '<PASSWORD>',
'c_password' => '<PASSWORD>',
'email' => 'Email',
'profile' => 'Profile'
);
}
/**
* @return string the URL that shows the detail of the post
*/
public function getUrl()
{
return Yii::app()->createUrl('user/register', array(
'id'=>$this->id,
//'title'=>$this->title,
));
}
/**
* This is invoked before the record is saved.
* @return boolean whether the record should be saved.
*/
protected function beforeSave()
{
if(parent::beforeSave())
{
if($this->isNewRecord)
{
$this->password = <PASSWORD>($this->password);
$this->group_id = 2;
return true;
}
else
return true;
}
else
return false;
}
public function relations()
{
return array(
'group' => array(self::BELONGS_TO, 'Group', 'group_id', 'together'=>false),
);
}
public function getGroupName() {
if (Yii::app()->user->id) {
$data = $this->findByPk(Yii::app()->user->id);
return $data->group->name;
} else {
return;
}
}//end getGroupName()
}<file_sep><div class="form">
<?php echo CHtml::beginForm(); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'Username'); ?>
<?php echo CHtml::activeTextField($model,'username', array()); ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Password'); ?>
<?php echo CHtml::activePasswordField($model,'password', array()) ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Confirm Password'); ?>
<?php echo CHtml::activePasswordField($model,'c_password', array()) ?>
</div>
<div class="row email">
<?php echo CHtml::activeLabel($model,'Email'); ?>
<?php echo CHtml::activeTextField($model,'email', array()); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Submit', array('class' => 'btn btn-info')); ?>
</div>
<?php echo CHtml::endForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
</div><!-- form --><file_sep><?php /* @var $this Controller */ ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="language" content="en" />
<meta name="description" content="forum">
<meta name="author" content="<NAME>">
<!-- blueprint CSS framework
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/print.css" media="print" />-->
<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" />
<![endif]-->
<!--<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.css" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/form.css" />-->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/fontawesome.css">
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/inconsolata.css">
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/style.css">
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/highlight.css">
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/bootstrap-responsive.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/custom.css">
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/jquery-te-1.3.5.css">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/bootstrap.min.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery-te-1.3.5.min.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/custom.js"></script>
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<body>
<script>
var baseurl="<?php print Yii::app()->request->baseUrl;?>";
</script>
<div class="container1" id="page">
<?php $this->renderPartial('/partial/_header', array());?>
<?php if(Yii::app()->user->hasFlash('success')): ?>
<div class="alert-success alert">
<?php echo Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>
<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="alert alert-' . $key . '"> <button type="button" class="close" data-dismiss="alert">×</button>' . $message . "</div>\n";
}
?>
<div class="container-fluid">
<?php if(isset($this->breadcrumbs)):?>
<?php $this->widget('zii.widgets.CBreadcrumbs', array(
'links'=>$this->breadcrumbs,
)); ?><!-- breadcrumbs -->
<?php endif?>
<div class="row-fluid">
<div class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Index</li>
<li>
<?php echo CHtml::link('<i class="icon-plus"></i>Post Question',array('/question/add/')); ?>
</li>
<li>
<?php echo CHtml::link('<i class="icon-list"></i>All Question',array('/question/')); ?>
</li>
<li>
<?php
if (User::model()->getGroupName() == 'Admin') {
?> <li class="nav-header">Admin Section</li> <?php
echo CHtml::link('<i class="icon-list"></i>All Question',array('/question/admin_index'));
}
?>
</li>
<!--<li><a href="#">Director</a></li>
<li><a href="#">Plates</a></li>
<li><a href="#">Resourceful</a></li>
<li class="active"><a href="#">Union</a></li>
<li><a href="#">Winston</a></li>
<li class="nav-header">Subnav</a></li>
<li><a href="#">Initialization</a></li>
<li class="active"><a href="#">Writing middleware</a></li>
<li><a href="#">Error handling</a></li>
<li><a href="#">Connect compatibility</a></li>-->
</ul>
</div>
</div>
<div class="span1"> </div>
<div class="span7">
<div class="row-fluid">
<div class="span12 document">
<?php echo $content; ?>
</div>
</div>
</div>
</div>
<div class="clear"></div>
<div id="footer">
<footer>
Copyright © 2012, <NAME>
</footer>
</div><!-- footer -->
</div><!-- page -->
<?php if(!empty(Yii::app()->params['debugContent'])):?>
<?php echo Yii::app()->params['debugContent'];?>
<?php endif;?>
<script>
if ($('.text-box').length != 0) {
$('.text-box').jqte();
}
</script>
</body>
</html>
<file_sep><?php
class Answer extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @return CActiveRecord the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{answers}}';
}
/**
* The followings are the available columns in table 'questions':
* @var integer $id
* @var string $answer
* @var string $rate
* @var integer $created
* @var integer $modified
* @var integer $user_id
*/
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('answer', 'required'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'Id',
'answer' => 'Answer',
'rate' => 'Rate',
'user_id' => 'User',
'created' => 'Created',
'modified' => 'Modified'
);
}
/**
* @return string the URL that shows the detail of the post
*/
public function getUrl()
{
return Yii::app()->createUrl('answer/view', array(
'id'=>$this->id,
//'title'=>$this->title,
));
}
/**
* This is invoked before the record is saved.
* @return boolean whether the record should be saved.
*/
protected function beforeSave()
{
if(parent::beforeSave())
{
if($this->isNewRecord)
{
$this->created = $this->modified = date('Y-m-d H:i:s');
$this->user_id=1;
return true;
}
else
// $this->update_time=time();
return true;
}
else
return false;
}
}<file_sep>
<div class="form question-block">
<div class="post highlight">
<div class="title">
<h1>Question:
<?php echo $data->question_title; ?>
</h1>
</div>
<div class="">
<b>Brief:</b>
<?php echo $data->description; ?>
</div>
</div>
</div><!-- form -->
<?php foreach ($data->answers as $answer) { ?>
<div class="form code-block">
<div class="post highlight">
<div class="title">
<b>Answer:</b>
<?php echo $answer->answer; ?>
</div>
<div class="nav">
<?php $answer->rate; ?>
</div>
</div>
</div><!-- form -->
<?php } ?>
<div class="well">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
<div class="">
<?php echo CHtml::activeLabel($model,'Your Answer'); ?>
<?php echo CHtml::activeTextarea($model,'answer', array('class' => 'span7 text-box')); ?>
</div>
<div class="">
<?php echo CHtml::activeLabel($model,'rate'); ?>
<?php
$list = range(-5, 5);
echo CHtml::dropDownList('Answer[rate]', $model, $list, array('options' => array('5'=>array('selected'=>true))));
?>
</div>
<div class="submit">
<?php echo CHtml::submitButton('Submit', array('class' => 'btn btn-info')); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div>
<file_sep><?php
class GroupController extends Controller
{
// Uncomment the following methods and override them if needed
/*
public function filters()
{
// return the filter configuration for this controller, e.g.:
return array(
'inlineFilterName',
array(
'class'=>'path.to.FilterClass',
'propertyName'=>'propertyValue',
),
);
}
public function actions()
{
// return external action classes, e.g.:
return array(
'action1'=>'path.to.ActionClass',
'action2'=>array(
'class'=>'path.to.AnotherActionClass',
'propertyName'=>'propertyValue',
),
);
}
*/
/**
* Lists all models.
*/
public function actionIndex()
{
$this->debug(Yii::app()->authManager->defaultRoles);
$criteria=new CDbCriteria(array(
//'condition' => 'active=1',
'order' => 'created DESC',
//'with'=>'commentCount',
));
//if(isset($_GET['tag']))
//$criteria->addSearchCondition('active', 1);
$dataProvider= new CActiveDataProvider('Group', array('pagination'=>array(
//'pageSize'=>Yii::app()->params['postsPerPage'],
),
'criteria'=>$criteria,
));
//print_r($dataProvider);
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Lists all models.
*/
public function actionCreate()
{
$model = new Group;
//$this->debug($_POST['Group']);
if (isset($_POST['Group']))
{
$model->attributes = $_POST['Group'];
//$model->attributes = array('question_title' => 'hello', 'description' => 'hello world');
// print_r($_POST['Group']);
//$this->debug($model->attributes );
//$model->validate();
//var_dump($model->getErrors());
//$this->debug($model->save());
//exit;
if ($model->save())
$this->redirect(array('view', 'id'=>$model->id));
}
$this->render('create',array(
'model' => $model,
));
}
/**
* Displays a particular model.
*/
public function actionView($id = null)
{
//$model = new Group;
// $data = Group::model()->find('id=:Id', array(':Id'=>$id));
$data=$this->loadModel();
$criteria = new CDbCriteria;
//$criteria->condition = 'active = 1 AND id = '.$id;
$data = Group::model()->with(
array(
//'answers'=>array('together'=>false, 'condition' => 'answers.active = 1')
))->find($criteria);
//$this->debug($data);
$model = new Answer;
if (isset($_POST['Answer'])) {
$model->attributes = $_POST['Answer'];
$model->question_id = $id;
if ($model->save())
$this->redirect(array('view', 'id'=>$id));
// echo "hi";
// exit;
}
//$question = $this->$model->findById($id);
//$this->debug($data);
//exit;
$this->render('view',array(
'model' => $model,
'data' => $data,
));
}
public function loadModel()
{
if($this->_model===null)
{
if(isset($_GET['id']))
$this->_model=Group::model()->findbyPk($_GET['id']);
if($this->_model===null)
throw new CHttpException(404,'The requested page does not exist.');
}
return $this->_model;
}
/**
* Lists all models.
*/
public function actionEdit($id = null)
{
$model=$this->loadModel();
//$this->debug($_POST['Group']);
if(isset($_POST['Group']))
{
$model->attributes = $_POST['Group'];
//$model->attributes = array('question_title' => 'hello', 'description' => 'hello world');
// print_r($_POST['Group']);
//$this->debug($model->attributes );
//$model->validate();
//var_dump($model->getErrors());
//$this->debug($model->save());
//exit;
if ($model->save())
$this->redirect(array('view', 'id'=>$model->id));
}
$this->render('edit', array(
'model' => $model,
//'data' => $data
));
}// end edit
/**
* Lists all models.
*/
public function actionDelete($id = null)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
echo "success";
// if(isset($_POST['type']))
//$this->redirect(array('/question/'));
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
// if(!isset($_GET['ajax']))
// $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}// end delete
}<file_sep><div class="<?php echo 'post question-block question_row_'.$data->id;?>">
<div class="title ">
<b>Question:</b>
<?php echo $data->question_title; ?>
<div class='pull-right'>
<?php
$checked = null;
if ($data->active) {
$checked = 'checked';
}
?>
<?php echo CHtml::link('<i class="icon-eye-open"></i>',array('/question/'.$data->id)); ?>
<?php if (Yii::app()->user->isGuest == false && $data->user_id == Yii::app()->user->id || User::model()->getGroupName() == 'Admin') : ?>
<?php echo CHtml::link('<i class="icon-pencil"></i>',array('/question/edit/'.$data->id)); ?>
<?php
echo CHtml::ajaxLink('<i class="icon-trash"></i>',
Yii::app()->createUrl('/question/delete/'.$data->id),
array(
'type'=>'post',
'data' => array('id' =>$data->id,'type'=>'delete'),
'success' => 'function(response) {
$(".question_row_'.$data->id.'").remove();
}',
),
array( 'confirm'=>'Are you sure to delete this question',)
);
endif;
?>
<div class="question_status">
<?php echo CHtml::CheckBox('active', $data->active, array(
'id' => 'activeCheckbox_'.$data->id,
'class' => 'activeQuestion',
'question_id' => $data->id
/*'ajax' => array(
'url'=>$this->createUrl('/question/activated?id='.$data->id),
//'data'=>'event_status_on=5',
'type'=>'POST',
'beforeSend' => 'js:function() {
}',
'success'=>"js:function(resp) {
if (resp == 1) {
$('#activeCheckbox_".$data->id."').attr('checked', 'checked');
$('#activeCheckbox_".$data->id."').siblings('p').remove();
$('#activeCheckbox_".$data->id."').before('<p class=\"success_ajax\">Activated</p>');
} else {
$('#activeCheckbox_".$data->id."').removeAttr('checked');
$('#activeCheckbox_".$data->id."').siblings('p').remove();
$('#activeCheckbox_".$data->id."').before('<p class=\"failure_ajax\">Deactivated</p>');
}
return true;
}"
),*/
)); ?>
</div>
</div>
</div>
<div class="">
<?php echo $data->description; ?>
</div>
</div><file_sep><div id="header">
<div id="logo"><?php //echo CHtml::encode(Yii::app()->name); ?></div>
</div><!-- header -->
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="brand" href="#">Forum</a>
<div id="mainmenu" class="nav-collapse">
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Home', 'url'=>array('/')),
array('label'=>'About', 'url'=>array('/site/page/view/about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
//array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
), 'htmlOptions'=>array('class'=>'nav')
)); ?>
</div><!-- mainmenu -->
<form class="navbar-search pull-left" action="">
<input type="text" class="search-query span4" placeholder="Search"/>
</form>
<ul class="nav pull-right">
<li class="dropdown">
<?php
if (Yii::app()->user->isGuest) {
echo CHtml::link('Login', array('/user/login/'));?>
</li>
<li> <?php
echo CHtml::link('Signup', array('/user/register/'));
} else {
echo CHtml::link(Yii::app()->user->name.'<b class="caret"></b>', '#', array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown'));
$this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest),
//array('label'=>'Register', 'url'=>array('/site/register')),
array('label'=>'', 'itemOptions' => array('class' => 'divider')),
array('label'=>'MANAGE ACCOUNT', 'itemOptions' => array('class' => 'nav-header')),
array('label'=>'Profile', 'url'=>array('/site/profile')),
array('label'=>'Setting', 'url'=>array('/site/setting')),
), 'htmlOptions'=>array('class'=>'dropdown-menu')
));
}
?>
</li>
<li class="divider-vertical"></li>
</ul>
</div>
</div>
</div>
<file_sep>-- phpMyAdmin SQL Dump
-- version 3.4.5
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 27, 2013 at 11:29 AM
-- Server version: 5.5.16
-- PHP Version: 5.3.8
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
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 utf8 */;
--
-- Database: `yii_blog`
--
-- --------------------------------------------------------
--
-- Table structure for table `aco`
--
CREATE TABLE IF NOT EXISTS `aco` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`collection_id` int(11) NOT NULL,
`path` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `aco_collection_id` (`collection_id`),
KEY `path` (`path`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `aco_collection`
--
CREATE TABLE IF NOT EXISTS `aco_collection` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`alias` varchar(20) NOT NULL,
`model` varchar(15) NOT NULL,
`foreign_key` int(11) NOT NULL,
`created` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `alias` (`alias`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `action`
--
CREATE TABLE IF NOT EXISTS `action` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(15) NOT NULL,
`created` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
--
-- Dumping data for table `action`
--
INSERT INTO `action` (`id`, `name`, `created`) VALUES
(5, 'create', 0),
(6, 'read', 0),
(7, 'update', 0),
(8, 'delete', 0),
(9, 'grant', 0);
-- --------------------------------------------------------
--
-- Table structure for table `answers`
--
CREATE TABLE IF NOT EXISTS `answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`answer` text NOT NULL,
`rate` int(11) NOT NULL,
`active` tinyint(4) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`question_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;
--
-- Dumping data for table `answers`
--
INSERT INTO `answers` (`id`, `user_id`, `answer`, `rate`, `active`, `created`, `modified`, `question_id`) VALUES
(1, 1, 'my answer is ', 0, 0, '2013-04-26 11:51:58', '2013-04-26 11:51:58', 10),
(2, 1, 'pakula', 0, 0, '2013-04-26 11:59:44', '2013-04-26 11:59:44', 10),
(3, 1, 'test', 0, 0, '2013-04-26 14:06:25', '2013-04-26 14:06:25', 10),
(4, 1, 'pata ni kayko', 0, 0, '2013-04-26 14:20:24', '2013-04-26 14:20:24', 10),
(5, 1, 'aur batao kya haal h', 0, 0, '2013-04-26 14:22:55', '2013-04-26 14:22:55', 14),
(6, 1, 'test', 0, 0, '2013-04-26 16:25:53', '2013-04-26 16:25:53', 14),
(7, 1, 'i dont know', 0, 0, '2013-04-26 16:27:31', '2013-04-26 16:27:31', 16),
(8, 1, '<div align="center"><ol><li>to me kya karu karte k<span style="color:rgb(255,0,0);"><i style="color: rgb(255, 0, 0);">yun ho login db se</i></span><i></i></li><li>ma<b>t karo na</b><br></li></ol></div>', 0, 0, '2013-04-26 16:46:30', '2013-04-26 16:46:30', 16),
(9, 1, 'ek kaam kato bata bhi do<br>', 0, 1, '2013-04-29 15:37:58', '2013-04-29 15:37:58', 21),
(10, 1, 'chalo theek h<br>', 0, 0, '2013-04-29 15:38:26', '2013-04-29 15:38:26', 21),
(11, 1, 'ka theek h<br>', 0, 0, '2013-04-30 07:52:46', '2013-04-30 07:52:46', 21),
(12, 1, 'chal to be<br>', 0, 1, '2013-04-30 08:12:03', '2013-04-30 08:12:03', 21),
(13, 1, 'bata na<br>', 0, 0, '2013-05-04 09:49:21', '2013-05-04 09:49:21', 21),
(14, 1, ' <br>', 0, 1, '2013-06-26 16:21:15', '2013-06-26 16:21:15', 10),
(15, 1, ' <br>', 0, 1, '2013-06-26 16:21:57', '2013-06-26 16:21:57', 10),
(16, 1, 'hi dear<br>', 0, 0, '2013-06-27 09:50:02', '2013-06-27 09:50:02', 29),
(17, 1, 'popo', 0, 0, '2013-06-27 09:51:57', '2013-06-27 09:51:57', 29);
-- --------------------------------------------------------
--
-- Table structure for table `aro`
--
CREATE TABLE IF NOT EXISTS `aro` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`collection_id` int(11) NOT NULL,
`path` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `aco_collection_id` (`collection_id`),
KEY `path` (`path`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `aro_collection`
--
CREATE TABLE IF NOT EXISTS `aro_collection` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`alias` varchar(20) NOT NULL,
`model` varchar(15) NOT NULL,
`foreign_key` int(11) NOT NULL,
`created` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `alias` (`alias`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `comment`
--
CREATE TABLE IF NOT EXISTS `comment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`status` int(11) NOT NULL,
`create_time` int(11) DEFAULT NULL,
`author` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`post_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_comment_post` (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ;
--
-- Dumping data for table `comment`
--
INSERT INTO `comment` (`id`, `content`, `status`, `create_time`, `author`, `email`, `url`, `post_id`) VALUES
(1, 'This is a test comment.', 2, 1230952187, 'Tester', '<EMAIL>', NULL, 2);
-- --------------------------------------------------------
--
-- Table structure for table `group`
--
CREATE TABLE IF NOT EXISTS `group` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `group`
--
INSERT INTO `group` (`id`, `name`, `created`, `modified`) VALUES
(1, 'Admin', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(2, 'User', '2013-05-14 13:29:26', '2013-05-14 13:29:26');
-- --------------------------------------------------------
--
-- Table structure for table `lookup`
--
CREATE TABLE IF NOT EXISTS `lookup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`code` int(11) NOT NULL,
`type` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ;
--
-- Dumping data for table `lookup`
--
INSERT INTO `lookup` (`id`, `name`, `code`, `type`, `position`) VALUES
(1, 'Draft', 1, 'PostStatus', 1),
(2, 'Published', 2, 'PostStatus', 2),
(3, 'Archived', 3, 'PostStatus', 3),
(4, 'Pending Approval', 1, 'CommentStatus', 1),
(5, 'Approved', 2, 'CommentStatus', 2);
-- --------------------------------------------------------
--
-- Table structure for table `permission`
--
CREATE TABLE IF NOT EXISTS `permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`aco_id` int(11) NOT NULL,
`aro_id` int(11) NOT NULL,
`aco_path` varchar(11) NOT NULL,
`aro_path` varchar(11) NOT NULL,
`action_id` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `aco_id` (`aco_id`,`aro_id`,`aco_path`,`aro_path`),
KEY `action_id` (`action_id`),
KEY `created` (`created`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `post`
--
CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`tags` text COLLATE utf8_unicode_ci,
`status` int(11) NOT NULL,
`create_time` int(11) DEFAULT NULL,
`update_time` int(11) DEFAULT NULL,
`author_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_post_author` (`author_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;
--
-- Dumping data for table `post`
--
INSERT INTO `post` (`id`, `title`, `content`, `tags`, `status`, `create_time`, `update_time`, `author_id`) VALUES
(1, 'Welcome!', 'This blog system is developed using Yii. It is meant to demonstrate how to use Yii to build a complete real-world application. Complete source code may be found in the Yii releases.\n\nFeel free to try this system by writing new posts and posting comments.', 'yii, blog', 2, 1230952187, 1230952187, 1),
(2, 'A Test Post', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', 'test', 2, 1230952187, 1230952187, 1);
-- --------------------------------------------------------
--
-- Table structure for table `questions`
--
CREATE TABLE IF NOT EXISTS `questions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`question_title` varchar(255) NOT NULL,
`description` text NOT NULL,
`active` tinyint(4) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=37 ;
--
-- Dumping data for table `questions`
--
INSERT INTO `questions` (`id`, `user_id`, `question_title`, `description`, `active`, `created`, `modified`) VALUES
(10, 1, 'why people are showing so much', 'while people can be simple and honest why they are trying to be best than other, why they want that much.', 1, '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(17, 1, 'test', 'tetsgdfhgsdfd <br>', 1, '2013-04-29 15:14:24', '2013-04-29 15:14:24'),
(18, 1, 'mera question ye h', 'tu kayko beech beech me...<br>', 1, '2013-04-29 15:15:12', '2013-04-29 15:15:12'),
(19, 1, 'cis question', 'nice question nice<b><span style="color:rgb(61,133,198);"> question hello heloo</span></b><br>', 1, '2013-04-29 15:19:50', '2013-04-29 15:19:50'),
(21, 20, 'batana be', '<b>ka bataye</b> kachu bhi batao<br>', 1, '2013-04-29 15:28:59', '2013-04-29 15:28:59'),
(22, 0, 'how to create role in yii', 'plz help if any one can suggest in this<br>', 1, '2013-05-13 16:20:23', '2013-05-13 16:20:23'),
(24, 13, 'wamp', 'wamp', 0, '2013-06-15 12:14:03', '2013-06-15 12:14:03'),
(25, 0, 'test', 'test', 1, '2013-06-15 12:14:28', '2013-06-15 12:14:28'),
(26, 1, 'test', 'test<p></p>', 1, '2013-06-26 09:14:09', '2013-06-26 09:14:09'),
(27, 1, 'what is Testing?', '<a href="http://testing.com/">Testing.com</a>', 1, '2013-06-26 16:23:28', '2013-06-26 16:23:28'),
(28, 0, 'hello', 'hello world<br>', 0, '2013-06-27 08:47:14', '2013-06-27 08:47:14'),
(29, 0, 'world', '<span style="color: rgb(153, 0, 0);">hello<span style="color: rgb(255, 0, 0);"><span style="color:rgb(255,0,0);"> </span></span></span>', 1, '2013-06-27 08:55:48', '2013-06-27 08:55:48'),
(30, 0, 'test', 'test', 0, '2013-06-27 08:59:42', '2013-06-27 08:59:42'),
(31, 0, 'wow', 'wow', 0, '2013-06-27 09:00:23', '2013-06-27 09:00:23'),
(32, 0, 'mm', 'mm', 0, '2013-06-27 09:02:31', '2013-06-27 09:02:31'),
(33, 0, 'lal', 'lalala', 0, '2013-06-27 09:05:01', '2013-06-27 09:05:01'),
(34, 0, 'popo', 'po', 0, '2013-06-27 09:08:03', '2013-06-27 09:08:03'),
(35, 0, 'bvcbc', 'vbvcbvc', 0, '2013-06-27 09:09:28', '2013-06-27 09:09:28'),
(36, 0, 'saasdsad', 'asdsa', 0, '2013-06-27 09:30:08', '2013-06-27 09:30:08');
-- --------------------------------------------------------
--
-- Table structure for table `tag`
--
CREATE TABLE IF NOT EXISTS `tag` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`frequency` int(11) DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;
--
-- Dumping data for table `tag`
--
INSERT INTO `tag` (`id`, `name`, `frequency`) VALUES
(1, 'yii', 1),
(2, 'blog', 1),
(3, 'test', 1);
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`group_id` int(11) NOT NULL,
`username` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`profile` text COLLATE utf8_unicode_ci,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=23 ;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id`, `group_id`, `username`, `password`, `email`, `profile`) VALUES
(1, 1, 'admin', '$1$9u6diYDN$<PASSWORD>z6KDc3wrRLa4ZTQ1', '<EMAIL>', NULL),
(13, 2, 'jitz', '$1$fEZr65Dh$wAFo82.dtR50RIkTsoVVL0', '<EMAIL>', NULL),
(14, 2, 'kdjafh', '$1$3Ysy9bwe$EFjzddXi2YOpjjWZmXVEa.', 'djsfklh@jgh', NULL),
(15, 2, 'dfgfdg', '$1$k3QmQBBM$9EGUF8RxMxF56XC/SgDKL/', 'dfgfd@hgffdg', NULL),
(16, 2, 'sdfsdfd', '123456', 'gfgfg@<EMAIL>', NULL),
(17, 2, 'gfdg', '1234567', 'dfgfd@hgffdg', NULL),
(18, 2, 'sfsdfdsf', '123456', '<EMAIL>', NULL),
(19, 2, 'loga', '$1$kdiWmli1$cqHzz5co9uQNCkB4pbK/w.', 'loga@jdsfh', NULL),
(20, 2, 'cis', '$1$1BfhaiBz$kJdoMSDfdHasUHhpSJzHZ1', '<EMAIL>', NULL),
(21, 2, 'vikash', '$1$pZXEwv29$iG9VP8tYU6oY5ZskCEIR2.', '<EMAIL>', NULL),
(22, 2, 'test', '$1$9u6diYDN$kT2CRLz6KDc3wrRLa4ZTQ1', '<EMAIL>', NULL);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `comment`
--
ALTER TABLE `comment`
ADD CONSTRAINT `FK_comment_post` FOREIGN KEY (`post_id`) REFERENCES `post` (`id`) ON DELETE CASCADE;
--
-- Constraints for table `post`
--
ALTER TABLE `post`
ADD CONSTRAINT `FK_post_author` FOREIGN KEY (`author_id`) REFERENCES `user` (`id`) ON DELETE CASCADE;
/*!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
/* @var $this SiteController */
$this->pageTitle=Yii::app()->name;
?>
<!-- Pygments code -->
<div class="highlight">
<pre>
<span class="kd">var</span>
<span class="nx">flatiron</span>
<span class="o">=</span>
<span class="nx">require</span>
<span class="p">(</span>
<span class="s1">'flatiron'</span>
<span class="p">),</span>
<span class="nx">app</span>
<span class="o">=</span>
<span class="nx">flatiron</span>
<span class="p">.</span>
<span class="nx">app</span>
<span class="p">;</span>
<span class="nx">app</span>
<span class="p">.</span>
<span class="nx">use</span>
<span class="p">(</span>
<span class="nx">flatiron</span>
<span class="p">.</span>
<span class="nx">plugins</span>
<span class="p">.</span>
<span class="nx">http</span>
<span class="p">,</span>
<span class="p">{</span>
<span class="c1">//</span>
<span class="c1">// List of middleware to use before dispatching to app.router</span>
<span class="c1">//</span>
<span class="nx">before</span>
<span class="o">:</span>
<span class="p">[],</span>
<span class="c1">//</span>
<span class="c1">// List of Streams to execute on the response pipeline</span>
<span class="c1">//</span>
<span class="nx">after</span>
<span class="o">:</span>
<span class="p">[]</span>
<span class="p">});</span>
<span class="nx">app</span>
<span class="p">.</span>
<span class="nx">listen</span>
<span class="p">(</span>
<span class="mi">8000</span>
<span class="p">,</span>
<span class="kd">function</span>
<span class="p">()</span>
<span class="p">{</span>
<span class="nx">console</span>
<span class="p">.</span>
<span class="nx">log</span>
<span class="p">(</span>
<span class="s1">'Application is now started on port 8000'</span>
<span class="p">);</span>
<span class="p">});</span>
</pre>
</div>
<!-- Pygments code -->
<h3>How does it work?</h3>
<!-- Pygments code -->
<div class="highlight">
<pre>
<span class="c1">//</span>
<span class="c1">// for the sake of this example, lets define a function to represent our</span>
<span class="c1">// middleware. Your middleware would likely be a more complex module.</span>
<span class="c1">//</span>
<span class="kd">function</span>
<span class="nx">middleware1</span>
<span class="p">(</span>
<span class="nx">req</span>
<span class="p">,</span>
<span class="nx">res</span>
<span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span>
<span class="p">(</span>
<span class="o">~</span>
<span class="nx">req</span>
<span class="p">.</span>
<span class="nx">url</span>
<span class="p">.</span>
<span class="nx">indexOf</span>
<span class="p">(</span>
<span class="s1">'foo'</span>
<span class="p">))</span>
<span class="p">{</span>
<span class="k">return</span>
<span class="kc">false</span>
<span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="kd">var</span>
<span class="nx">server</span>
<span class="o">=</span>
<span class="nx">union</span>
<span class="p">.</span>
<span class="nx">createServer</span>
<span class="p">({</span>
<span class="nx">before</span>
<span class="o">:</span>
<span class="p">[</span>
<span class="nx">middleware1</span>
<span class="p">]</span>
<span class="p">});</span>
<span class="nx">router</span>
<span class="p">.</span>
<span class="nx">get</span>
<span class="p">(</span>
<span class="sr">/foo/</span>
<span class="p">,</span>
<span class="kd">function</span>
<span class="p">()</span>
<span class="p">{</span>
<span class="k">this</span>
<span class="p">.</span>
<span class="nx">res</span>
<span class="p">.</span>
<span class="nx">writeHead</span>
<span class="p">(</span>
<span class="mi">200</span>
<span class="p">,</span>
<span class="p">{</span>
<span class="s1">'Content-Type'</span>
<span class="o">:</span>
<span class="s1">'text/plain'</span>
<span class="p">});</span>
<span class="k">this</span>
<span class="p">.</span>
<span class="nx">res</span>
<span class="p">.</span>
<span class="nx">end</span>
<span class="p">(</span>
<span class="s1">'never sent\n'</span>
<span class="p">);</span>
<span class="p">});</span>
</pre>
</div>
<!-- Pygments code -->
<file_sep>yii-forum
=========
A forum in yii framework, user can add question and people can review and can correct it
<file_sep><?php
class QuestionController extends Controller
{
// public $layout='column2';
/**
* @var CActiveRecord the currently loaded data model instance.
*/
private $_model;
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
/*$access = array();
$groupId = null;
if (isset(Yii::app()->user->group_id)) {
$groupId = Yii::app()->user->group_id;
}
if (User::model()->getGroupName() == 'Admin') {
$access = array(
array(
'allow', // allow all users to access 'index' and 'view' actions.
'actions' => array('add'),
'users'=>array('@'),
'expression' => "$groupId === 1"
),
array('deny')
);
} else if (User::model()->getGroupName() == 'User') {
$access = array(
array(
'allow', // allow all users to access 'index' and 'view' actions.
'actions' => array('index','view', 'edit', 'delete', 'add'),
'users'=>array('@'),
'expression' => "$groupId === 2"
),
array('deny')
);
} else {
$access = array(
array(
'allow',
'actions' => array('index', 'add', 'view'),
'users'=>array('*')
),
array('deny')
);
}*/
$params = array(
'Admin' => array('add', 'edit', 'delete', 'admin_index', 'activated'),
'User' => array('add', 'edit', 'delete'),
'Anonymous' => array('index', 'view', 'add')
);
return $this->isGrantAccess($params);
}
/**
* Lists all models.
*/
public function actionIndex()
{
$criteria=new CDbCriteria(array(
'condition' => 'active = 1',
'order' => 'created DESC',
//'with'=>'commentCount',
));
//if(isset($_GET['tag']))
//$criteria->addSearchCondition('active', 1);
$dataProvider= new CActiveDataProvider('Question', array(
'pagination'=>array(
'pageSize' => 8
//'pageSize'=>Yii::app()->params['postsPerPage'],
),
'criteria'=>$criteria,
));
//$this->debug(User::model()->getGroupName());
//$this->debug(Yii::app()->user->group_id);
$this->render('index', array(
'dataProvider'=>$dataProvider,
));
}
/**
* Lists all models.
*/
public function actionAdd()
{
$model = new Question;
if (isset($_POST['Question']))
{
$model->attributes = $_POST['Question'];
if ($model->validate()) {
if (Yii::app()->user->isGuest) {
$model->active = 0;
Yii::app()->user->setFlash('block', "Your question is on under supervision!");
$redirect = array('index');
} else {
$model->active = 1;
$model->user_id = Yii::app()->user->id;
$redirect = array('view', 'id' => $model->id);
}
//$model->attributes = array('question_title' => 'hello', 'description' => 'hello world');
// print_r($_POST['Question']);
//$this->debug($model->attributes );
//$model->validate();
//var_dump($model->getErrors());
//$this->debug($model->save());
//exit;
if ($model->save())
$this->redirect($redirect);
}
}
$this->render('add',array(
'model' => $model,
));
}
/**
* Displays a particular model.
*/
public function actionView($id = null)
{
//$model = new Question;
// $data = Question::model()->find('id=:Id', array(':Id'=>$id));
$data=$this->loadModel();
$criteria = new CDbCriteria;
$criteria->condition = 'active = 1 AND id = '.$id;
$data = Question::model()->with(
array(
'answers'=>array('together'=>false, 'condition' => 'answers.active = 1')
))->find($criteria);
//$this->debug($data);
if (empty($data)) {
$this->redirect(array('index'));
}
//exit;
$model = new Answer;
if (isset($_POST['Answer'])) {
$model->attributes = $_POST['Answer'];
$model->question_id = $id;
if (Yii::app()->user->isGuest) {
$model->active = 0;
Yii::app()->user->setFlash('block', "Your answer is on under supervision!");
} else {
$model->active = 1;
$model->user_id = Yii::app()->user->id;
}
if ($model->save())
$this->redirect(array('view', 'id'=>$id));
// echo "hi";
// exit;
}
//$question = $this->$model->findById($id);
//$this->debug($data);
//exit;
$this->render('view',array(
'model' => $model,
'data' => $data,
));
}
public function loadModel()
{
if($this->_model===null)
{
if(isset($_GET['id']))
$this->_model=Question::model()->findbyPk($_GET['id']);
if($this->_model===null)
throw new CHttpException(404,'The requested page does not exist.');
}
return $this->_model;
}
/**
* Lists all models.
*/
public function actionEdit($id = null)
{
$model=$this->loadModel();
//$this->debug($_POST['Question']);
if(isset($_POST['Question']))
{
$model->attributes = $_POST['Question'];
//$model->attributes = array('question_title' => 'hello', 'description' => 'hello world');
// print_r($_POST['Question']);
//$this->debug($model->attributes );
//$model->validate();
//var_dump($model->getErrors());
//$this->debug($model->save());
//exit;
if ($model->save())
$this->redirect(array('view', 'id'=>$model->id));
}
$this->render('edit', array(
'model' => $model,
//'data' => $data
));
}// end edit
/**
* Lists all models.
*/
public function actionDelete($id = null)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
echo "success";
// if(isset($_POST['type']))
//$this->redirect(array('/question/'));
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
// if(!isset($_GET['ajax']))
// $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}// end delete
/**
* Lists all models.
*/
public function actionAdmin_Index()
{
$criteria=new CDbCriteria(array(
//'condition' => 'active = 1',
'order' => 'active ASC',
//'with'=>'commentCount',
));
//if(isset($_GET['tag']))
//$criteria->addSearchCondition('active', 1);
$dataProvider= new CActiveDataProvider('Question', array(
'pagination'=>array(
'pageSize' => 8
//'pageSize'=>Yii::app()->params['postsPerPage'],
),
'criteria'=>$criteria,
));
//$this->debug(User::model()->getGroupName());
//$this->debug(Yii::app()->user->group_id);
$model = new Question;
$this->render('admin_index', array(
'dataProvider'=>$dataProvider,
'model' => $model
));
}
public function actionActivated($id = null) {
$model=$this->loadModel();
if ($model->attributes['active']) {
$flag = 0;
} else {
$flag = 1;
}
$model->active = $flag;
$model->save();
echo json_encode($flag);
}
}//end class<file_sep><?php
/**
* Controller is the customized base controller class.
* All controller classes for this application should extend from this base class.
*/
class Controller extends CController
{
/**
* @var string the default layout for the controller view. Defaults to '//layouts/column1',
* meaning using a single column layout. See 'protected/views/layouts/column1.php'.
*/
public $layout='//layouts/column1';
/**
* @var array context menu items. This property will be assigned to {@link CMenu::items}.
*/
public $menu=array();
/**
* @var array the breadcrumbs of the current page. The value of this property will
* be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
* for more details on how to specify this property.
*/
public $breadcrumbs=array();
protected function debug($var){
$bt = debug_backtrace();
$dump = new CVarDumper();
$debug = '<div style="display:block;background-color:gold;border-radius:10px;border:solid 1px brown;padding:10px;z-index:10000;"><pre>';
$debug .= '<h4>function: '.$bt[1]['function'].'() line('.$bt[0]['line'].')'.'</h4>';
$debug .= $dump->dumpAsString($var);
$debug .= "</pre></div>\n";
Yii::app()->params['debugContent'] .=$debug;
}
protected function isGrantAccess($params = array()) {
$access = array();
$anonymous = true;
foreach ($params as $role => $action) {
if (User::model()->getGroupName() == $role) {
$action = array_merge($action, $params['Anonymous']);
$access = array(
array(
'allow', // allow all users to access 'index' and 'view' actions.
'actions' => $action,
'users' => array('@'),
//'expression' => "$groupId === 1"
),
array('deny')
);
$anonymous = false;
}
}
if ($anonymous) {
$access = array(
array(
'allow',
'actions' => $params['Anonymous'],
'users'=>array('*')
),
array('deny')
);
}
return $access;
}//end isGrantAccess()
}<file_sep><div class="<?php echo 'post question-block question_row_'.$data->id;?>">
<div class="title ">
<b>Question:</b>
<?php echo $data->question_title; ?>
<div class='pull-right'>
<?php echo CHtml::link('<i class="icon-eye-open"></i>',array('/question/'.$data->id)); ?>
<?php if (Yii::app()->user->isGuest == false && $data->user_id == Yii::app()->user->id) : ?>
<?php echo CHtml::link('<i class="icon-pencil"></i>',array('/question/edit/'.$data->id)); ?>
<?php
echo CHtml::ajaxLink('<i class="icon-trash"></i>',
Yii::app()->createUrl('/question/delete/'.$data->id),
array(
'type'=>'post',
'data' => array('id' =>$data->id,'type'=>'delete'),
'success' => 'function(response) {
$(".question_row_'.$data->id.'").remove();
}',
),
array( 'confirm'=>'Are you sure to delete this question',)
);
endif;
?>
</div>
</div>
<div class="">
<?php echo $data->description; ?>
</div>
</div> | 22ae8b5fb57dbdf08de368a8d3dc04768dc1bb98 | [
"Markdown",
"SQL",
"PHP"
] | 15 | PHP | jitendrathakur/yii-forum | 3d8306b22feebdc3e24f8c25e5af031163de0b73 | 626c88dbe4103559445336b442e4eb3c807781ff |
refs/heads/master | <repo_name>Gainare/WEB501-Playing<file_sep>/scripts/height_width.js
/**
* We can get the height and width of a window by using
the window object built-in properties.
*/
let h = window.outerHeight
let w = window.outerWidth
window.document.write("Height and width of the window are: " + h + " and " + w)
/**
* We can also access the document object using a window object(window.document)
which gives us access to the HTML document, hence we can add new HTML element,
or write any content to the document, like we did in the example above.
*/<file_sep>/scripts/scripts.js
/**
Let's use the JavaScript window object to create a new window,
using the open() method.
This method creates a new window and returns an object which further can be used to manage that window.
*/
function createWindow() {
let url = "https://google.com";
let win = window.open(url, "My New Window", "width=300, height=200");
document.getElementById("result").innerHTML =
win.name + " - " + win.opener.location;
}
/**
* In the code above, we have used the window object of the existing window to create a new window using the open() method.
* In the open() method we can provide the URL to be opened in the new window(we can keep it blank as well), name of the window,
the width and the height of the window to be created.
Following is the syntax for the window object open() method:
* let newWindow = window.open(url, windowName, [windowFeatures]);
* We can provide, as many properties as we want, while creating a new window.
* When the open() method is executed, it returns the reference of the window object for the new window created,
which you can assign to a variable, like we have done in the code above.
* We have assigned the value returned by the window.open() method to the win variable.
* The we have used the win variable to access the new window, like getting the name of the window,
getting location of the window which opened the new window etc.
There are many properties and methods for the window object, which we have listed down below.
*/<file_sep>/scripts/create-window.js
function createWindow() {
var win = window.open("", "My Window", "width=500, height=200,screenX=100,screenY=100");
// window properties
var isclose = win.closed;
var name = win.name;
// writing in the current document
document.write(isclose + "<br>");
document.write(name + "<br>");
document.write(win.screenY + "<br>");
document.write(win.screenX + "<br>");
// we can access the new window document like this
win.document.write("Hello World!");
}
/**
* In the example above, we have created a new window, just to make you familiar with new window creation and also,
to make you understand that when we create a new window, then the current window has a different window object
and the new window will have a separate window object.
* We have then tried to access some properties of the new window created.
*/ | 8b4e83fc5eafabe2502fbdda8205f9943cea8141 | [
"JavaScript"
] | 3 | JavaScript | Gainare/WEB501-Playing | f3876ff86ffa87c0177d4980f27013f78ef59c86 | 3cf07a2cfdd2f280f6d5b65c816bd2be8d57136f |
refs/heads/master | <repo_name>ZaidBarkat/Ideal-Gas-Simulation<file_sep>/src/gas_container.cc
#include "gas_container.h"
namespace idealgas {
using glm::vec2;
GasContainer::GasContainer() {
}
void GasContainer::Display() const {
// This function has a lot of magic numbers; be sure to design your code in a way that avoids this.
ci::gl::color(ci::Color("orange"));
ci::gl::drawSolidCircle(vec2(dummy_variable_, 200), 10);
ci::gl::color(ci::Color("white"));
ci::gl::drawStrokedRect(ci::Rectf(vec2(100, 100), vec2(600, 400)));
}
void GasContainer::AdvanceOneFrame() {
++dummy_variable_;
}
} // namespace idealgas
| 48aa4334602584b440a5207d7f9455b3aeab1377 | [
"C++"
] | 1 | C++ | ZaidBarkat/Ideal-Gas-Simulation | dfd189660d18b980eab048e4f82051dbb029d343 | 84fb45b1f181dc2dab699f3f00bfd3a0a7fa76d0 |
refs/heads/master | <repo_name>ohyeyoye/dictionary<file_sep>/package/naverSearch.py
import urllib.request as req
from bs4 import BeautifulSoup
url = "https://dict.naver.com/search.nhn?dicQuery="
def getSearchResult(vocab):
res = req.urlopen(url + vocab.replace(" ", "+"))
soup = BeautifulSoup(res, "html.parser")
print("{} 검색중...".format(vocab))
searchResult = soup.select_one(".dic_search_result dd")
return searchResult
def getFormattedTextFromResult(searchResult):
lines = []
result = ""
for line in searchResult:
line = formatText(str(line))
if line != '':
lines.append(line)
for i in range(len(lines)):
result += lines[i].replace("{}. ".format(str(i+1)), "") + "\015"
return result
def formatText(text):
text = " ".join(text.split())
text = text.replace("<br/>", "")
return text
def getDefinition(vocab):
searchResult = getSearchResult(vocab)
return getFormattedTextFromResult(searchResult)<file_sep>/dictionary.py
import sys
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
from package import naverSearch
# argv 체크
if len(sys.argv) != 3:
print(sys.argv.count)
print("다음과 같이 실행하세요. $ python dictionary.py \"입력 파일명\" \"출력 파일명\"")
sys.exit()
# 입력 파일명, 출력 파일명 변수 생성
ifile, ofile = sys.argv[1], sys.argv[2]
# DataFrame df 생성 & 입력 파일 읽기
df = pd.read_excel(ifile)
print("검색을 시작합니다.")
# 검색 후 테이블 값 수정
definitions = []
for vocab in df["Vocabulary"]:
definitions.append(naverSearch.getDefinition(str(vocab)))
df["Definition"] = definitions
# DataFrame df를 출력 파일에 쓰기
df.to_excel(ofile)
print("출력 파일에 저장을 완료하였습니다.")
# excel_file = "./crawler/resources/vocab1.xlsx"
# table = pd.read_excel(excel_file)
# vocabularyCol = table["Vocabulary"]
# numOfVocabs = table.shape[0]
# result_dict = {}
# vocab_list = []
# def_list = []
# for i in range(numOfVocabs):
# definition = getDefinitionForVocabulary(vocabularyCol[i])
# result_dict[vocabularyCol[i]] = definition
# vocab_list.append(vocabularyCol[i])
# def_list.append(definition)
# df = pd.DataFrame(data={"Vocabulary": vocab_list, "Definition": def_list})
# df.to_excel("final.xlsx", "w", index="False")
| 4e89df2c72f2d3f8a85af146811d0cff292765e0 | [
"Python"
] | 2 | Python | ohyeyoye/dictionary | 0a65e95431e2e4f77d0d095d5bbd60d4afd8442e | 56eeda069fec18cbee3f5d199d30ed4539d0409f |
refs/heads/master | <file_sep>package modules;
import static org.jibble.pircbot.Colors.*;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import main.Message;
import main.NoiseModule;
import static main.Utilities.*;
/**
* Beer Advocate module
*
* @author <NAME>
* Created Sweetmorn, the 22nd day of Bureaucracy in the YOLD 3178
*/
public class BeerAdvocate extends NoiseModule {
private static final String COLOR_ERROR = RED + REVERSE;
// Yeah, you wanna fight?
public static String extract(Document page, String selector)
{
Element node = page.select(selector).first();
if (node == null)
return "";
return node.text();
}
private Document snarf(String url)
{
final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36";
try {
return Jsoup.connect(url).timeout(10000).userAgent(USER_AGENT).get();
} catch (IOException e) {
e.printStackTrace();
this.bot.sendMessage(COLOR_ERROR + "Error retrieving BA page...");
return null;
}
}
@Command(".*(http://beeradvocate.com/beer/profile/[0-9]+/[0-9]+).*")
public void beer(Message message, String beerUrl)
{
Document page = snarf(beerUrl);
String name = extract(page, ".titleBar");
String score = extract(page, ".BAscore_big");
String style = extract(page, "[href^=/beer/style/]");
this.bot.sendMessage(name + " - " + style + " - " + score);
}
// Runs a search in BA and returns the first search result. Searches beer only.
@Command("\\.beer (.*)")
public void search(Message message, String toSearch)
{
toSearch = toSearch.replaceAll(" ", "\\+");
Document searchResults = snarf("http://beeradvocate.com/search?q=\""+toSearch+"\"&qt=beer");
String rel = searchResults.body().getElementsByTag("li").get(2).getElementsByTag("a").get(0).attr("href");
String url = "http://beeradvocate.com" + rel;
this.beer(null, url);
this.bot.sendMessage(url);
}
@Override
public String getFriendlyName() {
return "BeerAdvocate";
}
@Override
public String getDescription() {
return "Returns information about a beer when a BeerAdvocate link appears...";
}
@Override
public String[] getExamples() {
return new String[] {
"http://beeradvocate.com/beer/profile/192/83920/"
};
}
}
<file_sep>package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import java.io.Serializable;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jibble.pircbot.User;
import static org.jibble.pircbot.Colors.*;
import debugging.Log;
/**
* NoiseModule
*
* @author <NAME>
* Created Jun 13, 2009.
*/
public abstract class NoiseModule implements Comparable<NoiseModule> {
private static final String COLOR_ERROR = RED;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
protected static @interface Command {
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
protected static @interface PM {
String value();
}
protected transient NoiseBot bot;
protected transient Map<Pattern, Method> patterns = new LinkedHashMap<Pattern, Method>();
protected transient Map<Pattern, Method> pmPatterns = new LinkedHashMap<Pattern, Method>();
public void init(NoiseBot bot) {
this.bot = bot;
Log.v(this + " - Init");
for(Method method : this.getClass().getDeclaredMethods()) {
final Command command = method.getAnnotation(Command.class);
if(command != null) {
final Pattern pattern = Pattern.compile(command.value());
Log.i(this + " - Added pattern " + command.value() + " for method " + method);
this.patterns.put(pattern, method);
}
final PM pm = method.getAnnotation(PM.class);
if(pm != null) {
final Pattern pattern = Pattern.compile(pm.value());
Log.i(this + " - Added PM pattern " + pm.value() + " for method " + method);
this.pmPatterns.put(pattern, method);
}
}
}
public void unload() {
Log.v(this + " - Unload");
}
public void onJoin(String sender, String login, String hostname) {this.joined(sender);}
public void onPart(String sender, String login, String hostname) {this.left(sender);}
public void onQuit(String sender, String login, String hostname, String reason) {this.left(sender);}
public void onUserList(User[] users) {
for(User user : users) {
this.joined(user.getNick());
}
}
public void onKick(String kickerNick,String kickerLogin, String kickerHostname, String recipientNick,String reason) {this.left(recipientNick);}
public void onNickChange(String oldNick, String login, String hostname, String newNick) {
this.left(oldNick);
this.joined(newNick);
}
public void onTopic(String topic, String setBy, long date, boolean changed) {}
protected void joined(String nick) {}
protected void left(String nick) {}
public abstract String getFriendlyName();
public abstract String getDescription();
public abstract String[] getExamples();
// Doesn't show in the help listing, and only I can trigger
public boolean isPrivate() {return false;}
public File[] getDependentFiles() {return new File[0];}
public Pattern[] getPatterns() {return this.patterns.keySet().toArray(new Pattern[0]);}
public void processMessage(Message message) {
Log.v(this + " - Processing message: " + message);
for(Pattern pattern : (message.isPM() ? this.pmPatterns : this.patterns).keySet()) {
Log.v("Trying pattern: " + pattern);
final Matcher matcher = pattern.matcher(message.getMessage());
if(matcher.matches()) {
final Method method = (message.isPM() ? this.pmPatterns : this.patterns).get(pattern);
Log.i(this + " - Handling message: " + message + " -- " + method.getDeclaringClass().getName() + "." + method.getName());
final Class[] params = method.getParameterTypes();
if(matcher.groupCount() == params.length - 1) {
Object[] args = new Object[params.length];
args[0] = message;
for(int i = 1; i < args.length; i++) {
if(params[i] == int.class) {
try {
args[i] = Integer.parseInt(matcher.group(i));
} catch(NumberFormatException e) {
throw new ArgumentMismatchException("Argument " + (i - 1) + " should be an integer");
}
} else {
args[i] = matcher.group(i);
}
}
try {
Log.v("Invoking with " + args.length + " args");
method.invoke(this, args);
break;
} catch(Exception e) {
Log.e(e);
}
} else {
throw new ArgumentMismatchException(params.length == 0 ? "Method doesn't take the mandatory Message instance" : "Expected " + (params.length - 1) + " argument" + (params.length - 1 == 1 ? "" : "s") + "; found " + matcher.groupCount());
}
}
}
}
public static <T extends NoiseModule> T load(Class<T> moduleType) {
Log.v(moduleType.getSimpleName() + " - Loading");
if(!Arrays.asList(moduleType.getInterfaces()).contains(Serializable.class)) {return null;}
try {
return Serializer.deserialize(moduleType.getSimpleName(), moduleType);
} catch(FileNotFoundException e) {
Log.v("No store file for " + moduleType.getSimpleName());
} catch(Exception e) { // Should just be IOException
Log.w("Unable to deserialize " + moduleType.getSimpleName());
Log.w(e);
}
return null;
}
public boolean save() {
Log.v(this + " - Saving");
if(!(this instanceof Serializable)) {return true;}
try {
Serializer.serialize(this.getClass().getSimpleName(), this);
return true;
} catch(Exception e) { // Should just be IOException
Log.e(e);
return false;
}
}
@Override public int compareTo(NoiseModule other) {return this.getFriendlyName().compareTo(other.getFriendlyName());}
@Override public String toString() {return this.getFriendlyName();}
protected String encoded(final String s) {
try {
final byte bytes[] = s.getBytes("UTF8");
return new String(bytes, "ISO8859_1");
} catch (UnsupportedEncodingException e) {
this.bot.sendMessage(COLOR_ERROR + "He looks like a fuckin' loser.");
return s;
}
}
}
<file_sep>package modules;
import main.Message;
import main.NoiseModule;
import static panacea.Panacea.*;
import static org.jibble.pircbot.Colors.*;
/**
* Woop Woop Woop
*
* @author <NAME> | sed 's/Mrozek/Auchter/'
* Created Jun 16, 2009. + 1 year, 9 months
*/
public class Woop extends NoiseModule {
@Command("\\.woop ([0-9]+\\.?[0-9]*)")
public void woop(Message message, String woopsArg) {
float requestedWoops = Float.valueOf(woopsArg);
int wholeWoops = (int) Math.floor(requestedWoops);
int boundedWoops = range(wholeWoops, 1, 20);
int woopPart = Math.round((requestedWoops - wholeWoops) * 4);
String woops = new String(new char[boundedWoops]).replace("\0", "WOOP ") + "WOOP".substring(0, woopPart);
this.bot.sendMessage(RED + woops.trim());
}
@Command("\\.woop")
public void woopDefault(Message message) {this.woop(message, "10");}
@Command("\\.woo[o]+p ([0-9]+\\.?[0-9]*)")
public void woopLong(Message message, String woopsArg) {this.woop(message, woopsArg);}
@Command("\\.woo([o]+)p")
public void woopLongDefault(Message message, String numOs) {this.woop(message, "" + (numOs.length() + 2));}
@Override public String getFriendlyName() {return "Woop";}
@Override public String getDescription() {return "Woop it up a bit (to the nearest quarter woop).";}
@Override public String[] getExamples() {
return new String[] {
".woop",
".woop 15",
".woop 4.25",
".woooooop"
};
}
}
<file_sep>package modules;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import debugging.Log;
import main.Message;
import main.NoiseBot;
import main.NoiseModule;
import static org.jibble.pircbot.Colors.*;
import static panacea.Panacea.*;
/**
* Fortune
*
* @author <NAME>
* Created Jun 16, 2009.
*/
public class Fortune extends NoiseModule {
private static File FORTUNE_FILE = new File("fortunes");
private static final String COLOR_ERROR = RED;
private String[] fortunes;
@Override public void init(NoiseBot bot) {
super.init(bot);
try {
final Vector<String> fortunesVec = new Vector<String>();
final BufferedReader r = new BufferedReader(new FileReader(FORTUNE_FILE));
String line;
while((line = r.readLine()) != null) {
fortunesVec.add(line);
}
this.fortunes = fortunesVec.toArray(new String[0]);
Log.i("Loaded fortune file: " + this.fortunes.length + " lines");
} catch(FileNotFoundException e) {
this.bot.sendNotice("No fortune file found");
} catch(IOException e) {
this.bot.sendNotice("Problem reading fortune file: " + e.getMessage());
}
}
@Command("\\.fortune")
public void fortune(Message message) {
this.bot.sendMessage(getRandom(this.fortunes));
}
@Command("\\.fortune (.*)")
public void fortune(Message message, String keyword) {
final String match = getRandomMatch(this.fortunes, ".*" + keyword + ".*");
if(match != null) {
this.bot.sendMessage(match);
} else {
this.bot.reply(message, COLOR_ERROR + "No matches");
}
}
@Override public String getFriendlyName() {return "Fortune";}
@Override public String getDescription() {return "Displays a random fortune from the Plan 9 fortune file";}
@Override public String[] getExamples() {
return new String[] {
".fortune"
};
}
@Override public File[] getDependentFiles() {return new File[] {FORTUNE_FILE};}
}
<file_sep>#!/bin/sh
BRANCH=$(tail -n 1 | cut -d' ' -f3)
MASTER=$(git show-ref -s refs/heads/master)
GIT_DIR=$(readlink -f "$GIT_DIR")
SRC_DIR=$(readlink -f "$GIT_DIR/..")
cd "$SRC_DIR"
# We only care about updating master
if [ "$BRANCH" != "refs/heads/sync" ]; then
echo "** Aborting, push to ':sync' to update **"
git branch -D "${BRANCH/refs\/heads\//}"
exit 1
fi
# Merge sync into master
if git merge --ff-only $BRANCH; then
git branch -d sync
else
git branch -D sync
exit 1
fi
# Rebuild objects
if make all; then
git push origin master
netcat -e 'echo -n sync' localhost 41932
else
git reset --hard $MASTER
make clean
make all
fi
<file_sep>package main;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Scanner;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Utilities
*
* @author <NAME>
* Created Jun 16, 2009.
*/
public class Utilities {
public static String urlEncode(String text) {
try {
return URLEncoder.encode(text, "UTF-8");
} catch(UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 unsupported");
}
}
public static String urlDecode(String text) {
try {
return URLDecoder.decode(text, "UTF-8");
} catch(UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 unsupported");
}
}
public static JSONObject getJSON(String url) throws IOException, JSONException {
return getJSON(new URL(url).openConnection());
}
public static JSONObject getJSON(URLConnection c) throws IOException, JSONException {
final Scanner s = new Scanner(c.getInputStream());
final StringBuffer buffer = new StringBuffer();
while(s.hasNextLine()) {
buffer.append(s.nextLine());
}
return new JSONObject(buffer.toString());
}
}
<file_sep>package modules;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.Vector;
import main.Message;
import main.NoiseBot;
import main.NoiseModule;
import static panacea.Panacea.*;
import static modules.Slap.slapUser;
import static org.jibble.pircbot.Colors.*;
/**
* Spook
*
* @author <NAME>
* Created Jun 16, 2009.
*/
public class Spook extends NoiseModule {
private static final String COLOR_ERROR = RED;
private static File SPOOK_FILE = new File("spook.lines");
private Vector<String> lines;
@Override public void init(NoiseBot bot) {
super.init(bot);
try {
this.lines = new Vector<String>();
final Scanner s = new Scanner(SPOOK_FILE);
while(s.hasNextLine()) {
lines.add(substring(s.nextLine(), 0, -1));
}
} catch(FileNotFoundException e) {
this.bot.sendNotice("No spook lines file found");
}
}
@Command("\\.spook ([0-9]+)")
public void spook(Message message, int num) {
num = range(num, 1, 20);
if(num <= this.lines.size()) {
final Set<String> choices = new LinkedHashSet<String>();
while(choices.size() < num) {
// Yuck..
choices.add(getRandom(this.lines.toArray(new String[0])));
}
this.bot.sendMessage(implode(choices.toArray(new String[0]), " "));
} else {
this.bot.sendMessage("There are only " + this.lines.size() + " entries in the spook lines file");
}
}
@Command("\\.addspook (.*)")
public void addspook(Message message, String spook) {
spook = spook.trim();
if (!spook.matches("^[a-zA-Z0-9][a-zA-Z0-9 _.-]+")) {
this.bot.sendAction(slapUser(message.getSender()));
} else if (this.lines.contains(spook)) {
this.bot.reply(message, COLOR_ERROR + "Message already exists");
} else {
try {
FileWriter writer = new FileWriter(SPOOK_FILE, true);
writer.append(spook + '\u0000' + '\n');
writer.close();
this.lines.add(spook);
this.bot.reply(message, "Added");
} catch (Exception e) {
this.bot.reply(message, COLOR_ERROR + "Error adding to spook file");
}
}
}
@Command("\\.spook")
public void spookDefault(Message message) {this.spook(message, 10);}
@Override public String getFriendlyName() {return "Spook";}
@Override public String getDescription() {return "Displays a random line from the Emacs spook file";}
@Override public String[] getExamples() {
return new String[] {
".spook",
".spook 15"
};
}
@Override public File[] getDependentFiles() {return new File[] {SPOOK_FILE};}
}
<file_sep>package modules;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import main.Message;
import main.ModuleLoadException;
import main.NoiseBot;
import main.NoiseModule;
import static main.Utilities.getJSON;
import static main.Utilities.urlEncode;
import static org.jibble.pircbot.Colors.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import debugging.Log;
/**
* Translate
*
* @author <NAME>
* Created Jun 16, 2009.
*/
public class Translate extends NoiseModule {
private static final String COLOR_ERROR = RED;
private static final String COLOR_RELIABLE = GREEN;
private static final String COLOR_UNRELIABLE = YELLOW;
// http://code.google.com/apis/language/translate/v2/using_rest.html#language-params
private static final Map<String, String> LANGUAGE_KEYS = new HashMap<String, String>() {{
put("af", "Afrikaans");
put("sq", "Albanian");
put("ar", "Arabic");
put("be", "Belarusian");
put("bg", "Bulgarian");
put("ca", "Catalan");
put("zh-CN", "Chinese Simplified");
put("zh-TW", "Chinese Traditional");
put("hr", "Croatian");
put("cs", "Czech");
put("da", "Danish");
put("nl", "Dutch");
put("en", "English");
put("et", "Estonian");
put("tl", "Filipino");
put("fi", "Finnish");
put("fr", "French");
put("gl", "Galician");
put("de", "German");
put("el", "Greek");
put("iw", "Hebrew");
put("hi", "Hindi");
put("hu", "Hungarian");
put("is", "Icelandic");
put("id", "Indonesian");
put("ga", "Irish");
put("it", "Italian");
put("ja", "Japanese");
put("ko", "Korean");
put("lv", "Latvian");
put("lt", "Lithuanian");
put("mk", "Macedonian");
put("ms", "Malay");
put("mt", "Maltese");
put("no", "Norwegian");
put("fa", "Persian");
put("pl", "Polish");
put("pt", "Portuguese");
put("ro", "Romanian");
put("ru", "Russian");
put("sr", "Serbian");
put("sk", "Slovak");
put("sl", "Slovenian");
put("es", "Spanish");
put("sw", "Swahili");
put("sv", "Swedish");
put("th", "Thai");
put("tr", "Turkish");
put("uk", "Ukrainian");
put("vi", "Vietnamese");
put("cy", "Welsh");
put("yi", "Yiddish");
}};
private static final Map<String, String> LANGUAGE_NAMES = new HashMap<String, String>() {{
for(Map.Entry<String, String> entry : LANGUAGE_KEYS.entrySet()) {
put(entry.getValue().toLowerCase(), entry.getKey());
}
}};
private String key;
@Override public void init(NoiseBot bot) {
super.init(bot);
this.key = this.bot.getSecretData("translate-key");
if(this.key == null) {
this.bot.sendNotice("Missing Google Translate key");
}
}
private void translationHelper(String fromCode, String toCode, String phrase) {
try {
fromCode = fromCode == null ? null : interpretCode(fromCode);
toCode = interpretCode(toCode);
} catch(IllegalArgumentException e) {
this.bot.sendMessage(COLOR_ERROR + e.getMessage());
return;
}
try {
final StringBuffer buffer = new StringBuffer();
if(fromCode == null) {
final JSONObject json = getJSON(String.format("https://www.googleapis.com/language/translate/v2/detect?key=%s&format=text&target=%s&q=%s", urlEncode(this.key), urlEncode(toCode), urlEncode(phrase)));
if(json.has("data")) {
final JSONObject data = json.getJSONObject("data");
final JSONArray detections = data.getJSONArray("detections");
final JSONArray inner = detections.getJSONArray(0);
final JSONObject detection = inner.getJSONObject(0);
fromCode = detection.getString("language");
final boolean isReliable = detection.getBoolean("isReliable");
final double confidence = detection.getDouble("confidence") * 100;
buffer.append(LANGUAGE_KEYS.get(fromCode)).append(String.format(" (%s%2.2f%%%s)", isReliable ? COLOR_RELIABLE : COLOR_UNRELIABLE, confidence, NORMAL));
} else if(json.has("error")) {
final JSONObject error = json.getJSONObject("error");
this.bot.sendMessage(COLOR_ERROR + "Google Translate error " + error.getInt("code") + ": " + error.get("message"));
return;
} else {
this.bot.sendMessage(COLOR_ERROR + "Unknown Google Translate error");
return;
}
} else {
buffer.append(LANGUAGE_KEYS.get(fromCode));
}
buffer.append(" -> ").append(LANGUAGE_KEYS.get(toCode)).append(": ");
final JSONObject json = getJSON(String.format("https://www.googleapis.com/language/translate/v2?key=%s&format=text&source=%s&target=%s&q=%s", urlEncode(this.key), urlEncode(fromCode), urlEncode(toCode), urlEncode(phrase)));
if(json.has("data")) {
final JSONObject data = json.getJSONObject("data");
final JSONArray translations = data.getJSONArray("translations");
buffer.append(translations.getJSONObject(0).get("translatedText"));
this.bot.sendMessage(buffer.toString());
} else if(json.has("error")) {
final JSONObject error = json.getJSONObject("error");
this.bot.sendMessage(COLOR_ERROR + "Google Translate error " + error.getInt("code") + ": " + error.get("message"));
} else {
this.bot.sendMessage(COLOR_ERROR + "Unknown Google Translate error");
}
} catch(IOException e) {
Log.e(e);
this.bot.sendMessage(COLOR_ERROR + "Unable to connect to Google Translate");
} catch(JSONException e) {
Log.e(e);
this.bot.sendMessage(COLOR_ERROR + "Problem parsing Google Translate response");
}
}
@Command("\\.translate ([a-z]+) ([a-z]+) \"(.*)\"")
public void translate(Message message, String fromCode, String toCode, String phrase) {
this.translationHelper(fromCode, toCode, phrase);
}
@Command("\\.translate ([a-z]+) \"(.*)\"")
public void detect(Message message, String toCode, String phrase) {
this.translationHelper(null, toCode, phrase);
}
@Command("\\.translate \"(.*)\"")
public void toEnglish(Message message, String phrase) {
this.translationHelper(null, "en", phrase);
}
private static String interpretCode(String code) {
if(LANGUAGE_KEYS.containsKey(code)) {
return code;
} else if(LANGUAGE_NAMES.containsKey(code.toLowerCase())) {
return LANGUAGE_NAMES.get(code.toLowerCase());
} else {
throw new IllegalArgumentException("Unrecognized language code: " + code);
}
}
@Override public String getFriendlyName() {return "Translate";}
@Override public String getDescription() {return "Translates text between languages";}
@Override public String[] getExamples() {
return new String[] {
".translate _from_ _to_ \"_message_\" -- Translate _message_ from language _from_ to _to_ (use language codes)",
".translate _to_ \"_message_\" -- Guess the from language and translate as above",
".translate \"_message_\" -- Guess the from language and translate to English"
};
}
}
<file_sep>package modules;
import static org.jibble.pircbot.Colors.*;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import main.Message;
import main.NoiseModule;
import static main.Utilities.*;
/**
* Urban Dictionary module
*
* @author <NAME>
* Created Nov 5, 2011
*/
public class UrbanDictionary extends NoiseModule {
private static final int MAXIMUM_MESSAGE_LENGTH = 400; // Approximately (512 bytes including IRC data)
private static final String COLOR_WARNING = RED;
private static final String COLOR_ERROR = RED + REVERSE;
private static final String URBAN_URL = "http://www.urbandictionary.com/define.php?term=";
private static final String DEFINITION_SELECTOR = ".meaning";
@Command("\\.(?:ud|urban) (.+)")
public void urban(Message message, String term) {
if (term.isEmpty()) { // Should be impossible
this.bot.sendMessage(COLOR_ERROR + "Missing term");
return;
}
sendDefinition(term);
}
private void sendDefinition(String term) {
// fetch webpage
Document page = null;
try {
page = Jsoup.connect(URBAN_URL + urlEncode(term))
.timeout(10000) // 10 seems like a nice number
.get();
} catch (IOException e) {
e.printStackTrace();
this.bot.sendMessage(COLOR_ERROR + "Error retrieving urban dictionary page");
}
// search page for definition
Element node = page.select(DEFINITION_SELECTOR).first();
if (node == null) {
this.bot.sendMessage(COLOR_WARNING + "Not found");
return;
}
String definition = node.text();
// truncate the definition if it's too long
if (definition.length() > MAXIMUM_MESSAGE_LENGTH)
definition = definition.substring(0, MAXIMUM_MESSAGE_LENGTH);
this.bot.sendMessage(definition);
}
@Override
public String getFriendlyName() {
return "UrbanDictionary";
}
@Override
public String getDescription() {
return "Looks up a term in urbandictionary.com";
}
@Override
public String[] getExamples() {
return new String[] {
".urban _term_ -- Look up a term",
".ud _term_ -- Look up a term"
};
}
}
<file_sep>package modules;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import org.jibble.pircbot.User;
import panacea.MapFunction;
import panacea.ReduceFunction;
import main.Message;
import main.NoiseBot;
import main.NoiseModule;
import static panacea.Panacea.*;
import static modules.Slap.slapUser;
/**
* Wheel
*
* @author <NAME>
* Created Jun 18, 2009.
*/
public class Wheel extends NoiseModule implements Serializable {
private Map<String, Integer> victims = new HashMap<String, Integer>();
@Command("\\.(?:wheel|spin)")
public void wheel(Message message) {
final String[] wheels = new String[] {
"justice", "misfortune", "fire", "blame", "doom", "science", "morality", "fortune", "wheels", "time",
"futility", "utility", "arbitrary choice", "wood", "chrome"
// THIS LIST MUST GROW!
};
this.bot.sendMessage("Spin, Spin, Spin! the wheel of " + getRandom(wheels));
sleep(2);
final User[] users = this.bot.getUsers();
String choice;
do {
choice = getRandom(users).getNick();
} while(choice.equals(this.bot.getNick()));
this.victims.put(choice, (this.victims.containsKey(choice) ? this.victims.get(choice) : 0) + 1);
this.save();
this.bot.sendAction(slapUser(choice));
}
@Command("\\.wheelstats")
public void wheelStats(Message message) {
if(victims.isEmpty()) {
this.bot.sendMessage("No victims yet");
return;
}
final String[] nicks = victims.keySet().toArray(new String[0]);
Arrays.sort(nicks, new Comparator<String>() {
@Override public int compare(String s1, String s2) {
// Reversed to order max->min
return victims.get(s2).compareTo(victims.get(s1));
}
});
final int total = reduce(victims.values().toArray(new Integer[0]), new ReduceFunction<Integer, Integer>() {
@Override public Integer reduce(Integer source, Integer accum) {
return source + accum;
}
}, 0);
this.bot.sendMessage(implode(map(nicks, new MapFunction<String, String>() {
@Override public String map(String nick) {
final int amt = victims.get(nick);
return String.format("(%2.2f%%) %s", ((double)amt/(double)total*100.0), nick);
}
}), ", "));
}
@Override public String getFriendlyName() {return "Wheel";}
@Override public String getDescription() {return "Slaps a random user";}
@Override public String[] getExamples() {
return new String[] {
".wheel -- Choose a random user and slap them",
".wheelstats -- Display statistics"
};
}
}
<file_sep>package debugging;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Log
*
* @author <NAME>
* Created Dec 19, 2010.
*/
public class Log {
// DEBUG, VERBOSE, INFO, WARN, ERROR;
public static void d(String msg) {Debugger.me.log(Level.DEBUG, msg);}
public static void v(String msg) {Debugger.me.log(Level.VERBOSE, msg);}
public static void i(String msg) {Debugger.me.log(Level.INFO, msg);}
public static void w(String msg) {Debugger.me.log(Level.WARN, msg);}
public static void e(String msg) {Debugger.me.log(Level.ERROR, msg);}
public static void d(Throwable e) {d(parseThrowable(e));}
public static void v(Throwable e) {v(parseThrowable(e));}
public static void i(Throwable e) {i(parseThrowable(e));}
public static void w(Throwable e) {w(parseThrowable(e));}
public static void e(Throwable e) {e(parseThrowable(e));}
public static void in(String text) {i(text); Debugger.me.in.add(text);}
public static void out(String text) {i(text); Debugger.me.out.add(text);}
private static String parseThrowable(Throwable e) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}
}
<file_sep>package modules;
import static org.jibble.pircbot.Colors.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.Vector;
import debugging.Log;
import main.Message;
import main.NoiseBot;
import main.NoiseModule;
import org.jibble.pircbot.User;
import static panacea.Panacea.*;
/**
* Commit
*
* @author <NAME>
* Created May 7, 2013.
*/
public class Commit extends NoiseModule {
// https://raw.github.com/ngerakines/commitment/master/commit_messages.txt
private static File MESSAGES_FILE = new File("commit_messages.txt");
private static final String COLOR_QUOTE = CYAN;
private static final String COLOR_ERROR = RED;
private String[] messages;
@Override public void init(NoiseBot bot) {
super.init(bot);
this.messages = new String[0];
try {
final Vector<String> messages = new Vector<String>();
final Scanner s = new Scanner(MESSAGES_FILE);
while(s.hasNextLine()) {
messages.add(s.nextLine());
}
this.messages = messages.toArray(new String[0]);
Log.i("Loaded messages file: " + this.messages.length);
} catch(FileNotFoundException e) {
this.bot.sendNotice("No commit messages file found");
}
}
@Command("\\.commit")
public void commit(Message message) {
if(this.messages.length > 0) {
final User user = getRandom(this.bot.getUsers());
this.bot.sendMessage(getRandom(this.messages).replace("XNAMEX", user.getNick()).replace("XUPPERNAMEX", user.getNick().toUpperCase()));
}
}
@Override public String getFriendlyName() {return "Commit";}
@Override public String getDescription() {return "Outputs random commit messages from http://github.com/ngerakines/commitment";}
@Override public String[] getExamples() {
return new String[] {
".commit"
};
}
@Override public File[] getDependentFiles() {return new File[] {MESSAGES_FILE};}
}
<file_sep>package modules;
import main.Message;
import main.NoiseModule;
/**
* Hug
*
* @author <NAME>
* Created Jun 14, 2009.
*/
public class Hug extends NoiseModule {
@Command("\\.hug (.*)")
public void hug(Message message, String target) {
this.bot.sendAction("hugs " + target);
}
@Command("\\.hug")
public void hugSelf(Message message) {
this.hug(message, message.getSender());
}
@Override public String getFriendlyName() {return "Hug";}
@Override public String getDescription() {return "Hugs the specified user";}
@Override public String[] getExamples() {
return new String[] {
".hug -- Hug the sending user",
".hug _nick_ -- Hug the specified nick"
};
}
}
<file_sep>package modules;
import static org.jibble.pircbot.Colors.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import main.Message;
import main.NoiseModule;
/**
* Seen
*
* @author <NAME>
* Created Jun 14, 2009.
*/
public class Seen extends NoiseModule implements Serializable {
private static final String COLOR_HERE = GREEN;
private static final String COLOR_LAST_SEEN = YELLOW;
private static final String COLOR_NEVER_SEEN = RED;
private Map<String, Date> seenDates = new HashMap<String, Date>();
private Map<String, Date> talkDates = new HashMap<String, Date>();
@Command("\\.seen (.+)")
public void seen(Message message, String target) {
target = target.replaceAll(" +$", "");
this.bot.reply(message, this.bot.isOnline(target)
? COLOR_HERE + target + " is here now" + NORMAL + (this.talkDates.containsKey(target) ? " -- last spoke " + this.talkDates.get(target) : "")
: (this.seenDates.containsKey(target)
? COLOR_LAST_SEEN + target + " was last seen " + this.seenDates.get(target)
: COLOR_NEVER_SEEN + target + " hasn't been seen"));
}
@Command(".*")
public void talked(Message message) {
this.talkDates.put(message.getSender(), new Date());
this.save();
}
/*
@Override protected void joined(String nick) {
this.seenDates.put(nick, new Date());
this.save();
}
*/
@Override protected void left(String nick) {
this.seenDates.put(nick, new Date());
this.save();
}
@Override public String getFriendlyName() {return "Seen";}
@Override public String getDescription() {return "Reports the last time a nick was in-channel";}
@Override public String[] getExamples() {
return new String[] {
".seen _nick_ -- Returns the last time the specified nick was in-channel"
};
}
}
<file_sep>package panacea;
/**
* ReduceFunction
*
* @author <NAME>
* Created Jun 16, 2009.
*/
public interface ReduceFunction <T, U> {
public U reduce(T source, U accum);
}
<file_sep>package main;
/**
* ModuleUnloadException
*
* @author <NAME>
* Created Jun 15, 2009.
*/
public class ModuleUnloadException extends Exception {
public ModuleUnloadException(String message) {super(message);}
public ModuleUnloadException(ModuleLoadException e) {super(e);}
}
<file_sep>package modules;
import static org.jibble.pircbot.Colors.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import java.util.Vector;
import debugging.Log;
import main.Message;
import main.NoiseBot;
import main.NoiseModule;
import static panacea.Panacea.*;
import static modules.Slap.slapUser;
/**
* _____
* __.---'' ''--
* ___..---' \ \"---_
* .-'' - . \ \ \ \
* _.' `,..___.----./ \ \ \
* .' - .-' ( \ \
* .' ,_.-----' | \
* / ' .' \ \ .__ \
* | / . \ \ ""\. \._
* | | / \ \ \ \._
* | | | ___...\ | \ `-.
* / / | _.--'' | \ `.
* | | | _.-//////, | \ '.
* / \ \ | ___...--.==|///////// / || \ \
* | .-///, |-|//////// | || \ \ '.
* | .'////// | \''''' | | || '. '
* | |/////// | \ .| | '\ \ '
* / |'////' / '--.____.--' | \ \ \ |
* | | \ / ' \ | | \ \. |
* | | \_ .// ' - -. \ \ \. \ |
* | | ""----"" ( .--../ \ \ \. \. .^.
* / | | \_.--._/. - _- _ \ "-. \___'
* | | \ \ . -_-_-_-__ - _ . \ \ \ /
* \| | .'_ - ______''-__ ' \ \ \ __/
* \ \ \ .'-.==**""""""**=._' \ \ '\ \\ /
* \ \ \ '=" .- - --. "" / \ '\ \ "" ____/
* \ \ \ / '|.| |'.- / \ ' \ _.'
* | | \ / /| \ . / \ \ |\___ --'/.
* / / \ | / '/ / / ''--' \ \ \ ______.' ___/ \-.
* / / / / / / | \ \ \ \ . '\ __./ \ '-.
* \ \\ / / / / \ \\.' -------''' / | '.
* / \ \ / // / | \ \ \ \ \ \ / | \
* ) ) / / / / \ \ \ \ \ \ / / |__
* // / / / | \| \ \ \ \ \ / / | '-.
* ( (_ ./ / \ ` ` ` / / / '\
* ./ / | ` / / /
* ./ / /| ` / / /
* ./ / / | ` / / /
* ./ / / | .-/ / /
* ./ / / | .' / / /
* ./ / / | .-' / / /
* / / / \ .-' / / /
* / / / \ .-' / / /
* / / / \ ..-' / / /
* / / / \ ..-'' / / /
* / / / \_.-'' / / /
*
* @author <NAME>
* Created Jun 18, 2009.
*/
public class Lebowski extends NoiseModule {
private static class Match {
private String line;
private int lineNum;
private int pos;
public Match(String line, int lineNum, int pos) {
this.line = line;
this.lineNum = lineNum;
this.pos = pos;
}
public String getLine() {return this.line;}
public int getLineNum() {return this.lineNum;}
public int getPos() {return this.pos;}
}
private static class RateLimiter {
private Map<String,List<Long>> users;
public RateLimiter() {
this.users = new HashMap<String,List<Long>>();
}
public boolean isAllowed(String user) {
if(!users.containsKey(user))
users.put(user, new LinkedList());
// Calculate probability of allowing the request
// This could be made configurable..
double prob = 1;
for(Long date : users.get(user)) {
long now = System.nanoTime();
double age = 1E-9*(now - date);
prob *= 1.0 - 1.0/(age/60.0+5.0);
}
// Log the request
users.get(user).add(System.nanoTime());
return Math.random() < prob;
}
}
private static File TRANSCRIPT_FILE = new File("lebowski");
private static final int CHAR_MAX = 127;
private static final int PATTERN_MAX = 31;
private static final int TOLERANCE = 3;
private static final int MIN_MESSAGE = 8;
private static final int MAX_CONSECUTIVE_MATCHES = 3;
private static final int SPACER_LINES = 30;
private static final String COLOR_QUOTE = CYAN;
private static final String COLOR_ERROR = RED;
static {
assert MIN_MESSAGE > TOLERANCE : "Messages must be longer than the number of errors allowed";
}
private String[] lines;
private String lastNick = "";
private int lastNickMatches = 0;
private int lastLineMatched = -1;
private int linesSinceLastQuote = SPACER_LINES;
private RateLimiter limiter = null;
private List<Match> undisplayedMatches = null;
private String lastMatchedUserMessage = null;
@Override public void init(NoiseBot bot) {
super.init(bot);
this.limiter = new RateLimiter();
this.lines = new String[0];
try {
final Vector<String> linesVec = new Vector<String>();
// I'd love to know why Scanner can't read this file...
final BufferedReader r = new BufferedReader(new FileReader(TRANSCRIPT_FILE));
String line;
while((line = r.readLine()) != null) {
if(!line.isEmpty()) {
linesVec.add(line);
}
}
this.lines = linesVec.toArray(new String[0]);
Log.i("Loaded lebowski file: " + this.lines.length);
} catch(FileNotFoundException e) {
this.bot.sendNotice("No lebowski quotes file found");
} catch(IOException e) {
this.bot.sendNotice("Problem reading quotes file: " + e.getMessage());
}
}
@Command(".*fascist.*")
public void fascist(Message message) {
this.lebowski(message, "fucking fascist");
}
@Command(".*shut the fuck up.*")
public void shutTheFuckUp(Message message) {
this.lebowski(message, "shut the fuck up");
}
// Single char at the beginning doesn't allow . to avoid matching commands
// [a-zA-Z0-9,\\'\\\" !-][a-zA-Z0-9,\\'\\\"\\. !-]
@Command("([^\\.].{" + (MIN_MESSAGE - 1) + "," + (PATTERN_MAX - 1) + "})")
public void lebowski(Message message, String userMessage) {
Log.i("Lebowski: Searching for matches for \"" + userMessage + "\"");
this.linesSinceLastQuote++;
final Vector<Match> matches = new Vector<Match>();
for(int lineNum = 0; lineNum < lines.length; lineNum++) {
final String line = lines[lineNum];
final int match = search(line.toLowerCase(), userMessage.toLowerCase(), TOLERANCE);
if(match >= 0) {
matches.add(new Match(line, lineNum, match));
}
}
Log.v("Matches: " + matches.size());
if(!matches.isEmpty()) {
if(this.linesSinceLastQuote < SPACER_LINES) {
return;
} else if(this.lastNick.equalsIgnoreCase(message.getSender())) {
if(++this.lastNickMatches > MAX_CONSECUTIVE_MATCHES) {return;}
} else {
this.lastNick = message.getSender();
this.lastNickMatches = 0;
this.linesSinceLastQuote = 0;
}
final Match match = matches.get(getRandomInt(0, matches.size() - 1));
this.lastLineMatched = match.getLineNum();
this.bot.sendMessage(renderMatch(match, matches.size(), userMessage));
this.undisplayedMatches = matches;
this.undisplayedMatches.remove(match);
this.lastMatchedUserMessage = userMessage;
}
}
@Command("\\.next") public void nextLine(Message message) {
if(this.lastLineMatched < 0) {
this.bot.sendMessage(COLOR_ERROR + "No matches yet");
} else if(this.lastLineMatched+1 == this.lines.length) {
this.bot.sendMessage(COLOR_ERROR + "Out of lines");
} else {
if(this.undisplayedMatches != null) // Should always be true
this.undisplayedMatches.clear();
if(this.limiter.isAllowed(message.getSender()))
this.bot.sendMessage(COLOR_QUOTE + this.lines[++this.lastLineMatched]);
else
this.bot.sendAction(slapUser(message.getSender()));
}
}
@Command("\\.other") public void other(Message message) {
if(this.lastLineMatched < 0 || this.undisplayedMatches == null) {
this.bot.sendMessage(COLOR_ERROR + "No matches yet");
} else if(this.undisplayedMatches.isEmpty()) {
this.bot.sendMessage(COLOR_ERROR + "No other matches to display");
} else {
final Match match = this.undisplayedMatches.get(getRandomInt(0, this.undisplayedMatches.size() - 1));
this.lastLineMatched = match.getLineNum();
this.undisplayedMatches.remove(match);
this.bot.sendMessage(renderMatch(match, 1, this.lastMatchedUserMessage));
}
}
private static String renderMatch(Match match, int matches, String userMessage) {
final StringBuffer b = new StringBuffer();
if(matches > 1) {b.append("(").append(matches).append(") ");}
b.append(COLOR_QUOTE);
if(match.getPos() > 0) {b.append(match.getLine().substring(0, match.getPos()));}
b.append(UNDERLINE);
b.append(substring(match.getLine(), match.getPos(), userMessage.length()));
b.append(NORMAL).append(COLOR_QUOTE);
if(match.getPos() + userMessage.length() < match.getLine().length()) {b.append(match.getLine().substring(match.getPos() + userMessage.length()));}
return b.toString();
}
// http://en.wikipedia.org/wiki/Bitap_algorithm
private static int search(String text, String pattern, int k) {
final int m = pattern.length();
final long[] R = new long[k + 1];
final long[] patternMask = new long[CHAR_MAX + 1];
if(m == 0) {return 0;} // return text
if(m > PATTERN_MAX) {throw new IllegalArgumentException("Pattern is too long");}
for(int i =0; i <= k; i++) {R[i] = ~1;}
for(int i = 0; i <= CHAR_MAX; i++) {patternMask[i] = ~0;}
for(int i = 0; i < m; i++) {patternMask[pattern.charAt(i)] &= ~(1 << i);}
try {
for(int i = 0; i < text.length(); i++) {
long oldRd1 = R[0];
R[0] |= patternMask[text.charAt(i)];
R[0] <<= 1;
for(int d = 1; d <= k; d++) {
long tmp = R[d];
R[d] = (oldRd1 & (R[d] | patternMask[text.charAt(i)])) << 1;
oldRd1 = tmp;
}
if(0 == (R[k] & (1 << m))) {
// result = text.substring(i - m + 1);
return i - m + 1;
}
}
} catch(Exception e) {}
// return result;
return -1;
}
@Override public String getFriendlyName() {return "Lebowski";}
@Override public String getDescription() {return "Outputs Big Lebowski quotes similar to user text";}
@Override public String[] getExamples() {
return new String[] {
"Where's the money, Lebowski?",
"You're entering a world of pain",
".next -- Outputs the next quote after the one most recently said",
".other -- Outputs another quote that matches the last pattern"
};
}
@Override public File[] getDependentFiles() {return new File[] {TRANSCRIPT_FILE};}
}
<file_sep>package modules;
import static main.Utilities.getJSON;
import static org.jibble.pircbot.Colors.*;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import debugging.Log;
import main.Message;
import main.NoiseModule;
import static panacea.Panacea.*;
/**
* Clip
*
* @author <NAME>
* Created Feb 19, 2011.
*/
public class Clip extends NoiseModule {
private static final String COLOR_ERROR = RED;
private static final String COLOR_INFO = PURPLE;
@Command(".*(http://clip.mrozekma.com/[0-9a-fA-F-]{36}).*")
public void clip(Message message, String url) {
try {
final JSONObject json = getJSON(url + "?info");
if(json.has("id") && json.has("title") && json.has("source") && json.has("start") && json.has("end")) {
this.bot.sendMessage(COLOR_INFO + (json.isNull("title") ? "Untitled" : json.get("title")) + " (from " + json.get("source") + ", " + json.get("start") + "-" + json.get("end") + ")");
} else if(json.has("error")) {
this.bot.sendMessage(COLOR_ERROR + json.get("error"));
} else {
this.bot.sendMessage(COLOR_ERROR + "Unknown error");
}
} catch(IOException e) {
Log.w(e);
this.bot.sendMessage(COLOR_ERROR + "Unable to connect to mrozekma server");
} catch(JSONException e) {
Log.w(e);
this.bot.sendMessage(COLOR_ERROR + "Problem parsing response");
}
}
@Override public String getFriendlyName() {return "Clip";}
@Override public String getDescription() {return "Outputs information about any mrozekma.com video clip URLs posted";}
@Override public String[] getExamples() {
return new String[] {
"http://clip.mrozekma.com/c06c0612-349b-4580-b03e-ba8f771c2d0f"
};
}
}
<file_sep>package modules;
import main.Message;
import main.NoiseBot;
import main.NoiseModule;
import static panacea.Panacea.*;
/**
* Ping
*
* @author <NAME>
* Created Jun 13, 2009.
*/
public class Ping extends NoiseModule {
@Command("(.*)!")
public void direct(Message message, String nick) {
if(!nick.equals(this.bot.getNick())) return;
this.bot.sendMessage(message.getSender() + "!");
}
@Command("(?:[hH]i|[hH]ello|[hH]ey) (.*)")
public void indirect(Message message, String nick) {
if(!nick.equals(this.bot.getNick())) return;
this.bot.sendMessage(getRandom(new String[] {"Hi", "Hello", "Hey"}) + " " + message.getSender());
}
@Override public String getFriendlyName() {return "Ping";}
@Override public String getDescription() {return "Greets the user";}
@Override public String[] getExamples() {
return new String[] {
"Hi " + this.bot.getNick(),
this.bot.getNick() + "!"
};
}
}
<file_sep>package panacea;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* RichDialog
*
* @author <NAME>
* Created Jul 16, 2007.
*/
@SuppressWarnings("serial") public class RichDialog extends JDialog {
private static final Font FONT = new Font("Arial", Font.BOLD, 12);
private final JLabel titleLabel;
private final JLabel descriptionLabel;
private JPanel contentPanel;
private JPanel buttonPanel = null;
public RichDialog(Window parent, String title, String description, boolean modal) {
super(parent, title, modal ? Dialog.ModalityType.DOCUMENT_MODAL : Dialog.ModalityType.MODELESS);
this.setSize(400, 200);
JPanel panel = new JPanel(new BorderLayout());
this.add(panel);
JPanel titlePanel = new JPanel(new BorderLayout());
panel.add(titlePanel, BorderLayout.NORTH);
titlePanel.setBackground(Color.WHITE);
titlePanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY));
this.titleLabel = new JLabel(title);
titlePanel.add(this.titleLabel, BorderLayout.NORTH);
this.titleLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 0, 0));
this.titleLabel.setFont(FONT);
this.descriptionLabel = new JLabel(description);
titlePanel.add(this.descriptionLabel, BorderLayout.SOUTH);
this.descriptionLabel.setBorder(BorderFactory.createEmptyBorder(5, 20, 10, 0));
// this.descriptionLabel.setFont(FONT.deriveFont(Font.PLAIN, 10));
panel.add(this.contentPanel = new JPanel());
}
public void setTitle(String title) {this.titleLabel.setText(title);}
public void setDescription(String description) {this.descriptionLabel.setText(description);}
@Override public void setVisible(boolean b) {
if(this.contentPanel.getComponents().length == 0 && this.buttonPanel != null) {this.buttonPanel.setBorder(null);}
super.setVisible(b);
}
public JPanel getContentPanel() {return this.contentPanel;}
public void addButton(JButton button) {
if(this.buttonPanel == null) {
this.add(this.buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 10)),BorderLayout.SOUTH);
this.buttonPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY));
}
this.buttonPanel.add(button);
}
public void addEnterEscapeListener(JButton enterButton, JButton escapeButton) {addEnterEscapeListener(enterButton, escapeButton,new Object[] {});}
public void addEnterEscapeListener(final JButton enterButton, final JButton escapeButton, Object[] exceptions) {
Panacea.addGlobalKeyListener(this, new KeyAdapter() {
private boolean enterPress = false;
@Override public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE && e.getModifiers() == 0) {
escapeButton.doClick();
} else if(e.getKeyCode() == KeyEvent.VK_ENTER && e.getModifiers() == 0) {
this.enterPress = true;
} else {
super.keyPressed(e);
}
}
@Override public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER && e.getModifiers() == 0 && this.enterPress) {
enterButton.doClick();
} else {
super.keyReleased(e);
}
this.enterPress = false;
}
}, exceptions);
this.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
escapeButton.doClick();
}
});
}
public static String showInputDialog(Window parent, String title, String message) {return showInputDialog(parent, title, message, "");}
public static String showInputDialog(Window parent, String title, String message, String defaultValue) {return showInputDialog(parent, title, message, defaultValue, "OK", "Cancel");}
public static String showInputDialog(Window parent, String title, String message, String defaultValue, String okText, String cancelText) {
final String[] rtn = {null};
final RichDialog d = new RichDialog(parent, title, message, true);
final JTextField input = new JTextField(defaultValue);
input.setPreferredSize(new Dimension(380, input.getPreferredSize().height));
d.getContentPanel().add(input);
JButton okButton = new JButton(okText);
d.addButton(okButton);
d.getRootPane().setDefaultButton(okButton);
okButton.setMnemonic(KeyEvent.VK_O);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rtn[0] = input.getText();
d.dispose();
}
});
JButton cancelButton = new JButton(cancelText);
d.addButton(cancelButton);
cancelButton.setMnemonic(KeyEvent.VK_A);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
d.dispose();
}
});
d.addEnterEscapeListener(okButton, cancelButton);
Panacea.smartPack(d);
input.selectAll();
d.setVisible(true);
return rtn[0];
}
public static int showOptionDialog(Window parent, String title, String message, String[] options) {return showOptionDialog(parent, title, message, null, options);}
public static int showOptionDialog(Window parent, String title, String message, String details, String[] options) {
final int[] rtn = {-1};
final RichDialog d = new RichDialog(parent, title, message, true);
final HashMap<Character, JButton> keys = new HashMap<Character, JButton>();
if(details != null) {
d.getContentPanel().setLayout(new BoxLayout(d.getContentPanel(), BoxLayout.LINE_AXIS));
d.getContentPanel().setBorder(Panacea.makeBorder(10));
final JLabel label = new JLabel(details);
label.setAlignmentY(JLabel.TOP_ALIGNMENT);
d.getContentPanel().add(label);
d.getContentPanel().setPreferredSize(new Dimension(400, 150));
}
for(int i = 0; i < options.length; i++) {
final int j = i;
JButton b = new JButton(options[i]);
if(options[i].contains("&")) {
char hotkey=options[i].charAt(options[i].indexOf("&")+1);
keys.put(Character.toLowerCase(hotkey),b);
b.setMnemonic(hotkey);
b.setText(options[i].replaceFirst("&",""));
}
d.addButton(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rtn[0] = j;
d.dispose();
}
});
}
Panacea.addGlobalKeyListener(d, new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) {
if(e.getModifiers() == 0) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {d.dispose();}
for(char k : keys.keySet()) {
if(Character.toLowerCase(e.getKeyChar()) == k) {
keys.get(k).doClick();
}
}
}
}
});
Panacea.smartPack(d);
d.setVisible(true);
return rtn[0];
}
}<file_sep># Suck on it ant. Suck it hard.
PASS := $(shell echo $$RANDOM)
SOURCES := $(shell find src -name '*.java')
OBJECTS := $(subst .java,.class,$(SOURCES))
OBJECTS := $(subst src/,bin/,$(OBJECTS))
CLASSPATH := bin:src:lib/*
all: $(OBJECTS)
run: $(OBJECTS)
ulimit -v 4096000; \
java -cp $(CLASSPATH) -ea -Xms64m -Xmx512m main.NoiseBot
test: $(OBJECTS)
ulimit -v 4096000; \
java -cp $(CLASSPATH) -ea -Xms64m -Xmx512m main.NoiseBot \
cmdline irc.freenode.net 6667 "rh$(USER)bot" "<PASSWORD>$(PASS)" "#rh$(USER)"
clean:
rm -rf bin
$(OBJECTS): $(SOURCES)
ulimit -v 4096000; \
mkdir -p bin; \
javac -cp $(CLASSPATH) -d bin $+
<file_sep>package modules;
import static org.jibble.pircbot.Colors.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import main.Message;
import main.NoiseModule;
/**
* Tell
*
* @author <NAME>
* Created Jun 16, 2009.
*/
public class Tell extends NoiseModule implements Serializable {
private static class CachedMessage implements Serializable {
private String sender;
private Date date;
private String message;
private CachedMessage() {}
public CachedMessage(String sender, String message) {
this.sender = sender;
this.date = new Date();
this.message = message;
}
@Override public String toString() {return this.date + " <" + this.sender + "> " + this.message;}
}
private static final String COLOR_ERROR = RED;
private static final String COLOR_SUCCESS = GREEN;
private Map<String, LinkedList<CachedMessage>> messages = new HashMap<String, LinkedList<CachedMessage>>();
@Command("\\.(?:tell|ask) ([^ ]+) (.+)")
public void tell(Message message, String nick, String userMessage) {
if(nick.equals(message.getSender())) {
this.bot.reply(message, COLOR_ERROR + "That's you");
} else if(this.bot.isOnline(nick)) {
this.bot.reply(message, COLOR_ERROR + "They're here now");
} else {
if(!this.messages.containsKey(nick)) {this.messages.put(nick, new LinkedList<CachedMessage>());}
this.messages.get(nick).add(new CachedMessage(message.getSender(), userMessage));
this.save();
this.bot.reply(message, COLOR_SUCCESS + "Queued");
}
}
@Override protected void joined(String nick) {
if(this.messages.containsKey(nick)) {
for(CachedMessage message : this.messages.get(nick)) {
this.bot.reply(nick, "" + message);
}
this.messages.remove(nick);
this.save();
}
}
@Override public String getFriendlyName() {return "Tell";}
@Override public String getDescription() {return "Queues messages for offline users (in-channel MemoServ)";}
@Override public String[] getExamples() {
return new String[] {
".tell _nick_ _message_ -- Queue _message_ to be sent when _nick_ joins",
".ask _nick_ _question_ -- Same as .tell"
};
}
}
| 7627a685d7705aa9c6651b35f92e35821a664c57 | [
"Java",
"Makefile",
"Shell"
] | 22 | Java | whitelje/NoiseBot | 71c9393f2cd9792cd532fe67cc855527533cb0d4 | 359a0656a85bdcc5c217ab29ce1269c3874b41fc |
refs/heads/master | <file_sep>#ifndef YYMALLOC_H
#define YYMALLOC_H
void *yymalloc(size_t size);
void *yycalloc(size_t size);
void *yyrealloc(void *ptr, size_t size);
void yyfree(void *ptr);
char *yystrdup(const char *s);
size_t yymalloc_used_memory(void);
void yymalloc_set_oom_handler(void (*oom_handler)(size_t));
float yymalloc_get_fragmantation_ratio(size_t rss);
size_t yymalloc_get_rss(void);
size_t yymalloc_get_private_dirty(void);
void zlibc_free(void *ptr);
size_t yymalloc_size(void *ptr);
#endif<file_sep># yubo-kv
sample kv store
<file_sep>#include <stdio.h>
#include <stdlib.h>
void zlibc_free(void *ptr)
{
free(ptr);
}
#include <string.h>
#include <pthread.h>
#include "yymalloc.h"
#define PREFIX_SIZE (sizeof(size_t))
#define update_yymalloc_stat_add(__n) do { \
pthread_mutex_lock(&used_memory_mutex); \
used_memory += (__n); \
pthread_mutex_unlock(&used_memory_mutex); \
} while(0)
#define update_yymalloc_stat_sub(__n) do { \
pthread_mutex_lock(&used_memory_mutex); \
used_memory -= (__n); \
pthread_mutex_unlock(&used_memory_mutex); \
} while(0)
#define update_yymalloc_stat_alloc(__n) do { \
size_t _n = (__n); \
if (_n & (sizeof(long) - 1)) _n += sizeof(long) - (_n & sizeof(long) - 1); \
if (yymalloc_thread_safe) { \
update_yymalloc_stat_add(_n); \
} else { \
used_memory += _n; \
} \
} while(0)
#define update_yymalloc_stat_free(__n) do { \
size_t _n = (__n); \
if (_n & (sizeof(long) - 1)) _n += sizeof(long) - (_n&sizeof(long) - 1); \
if (yymalloc_thread_safe) { \
update_yymalloc_stat_sub(_n) ; \
} else { \
used_memory -= _n; \
} \
} while(0)
static size_t used_memory = 0;
static int yymalloc_thread_safe = 0;
pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER;
static void yymalloc_default_oom(size_t size)
{
fprintf(stderr, "yymalloc : Out of memory trying to allocate %zu bytes\n", size);
fflush(stderr);
abort();
}
static void (*yymalloc_oom_handler)(size_t) = yymalloc_default_oom;
void *yymalloc(size_t size)
{
void *ptr = malloc(size + PREFIX_SIZE);
if (!ptr) yymalloc_oom_handler(size);
update_yymalloc_stat_alloc(size + PREFIX_SIZE);
*((size_t *)ptr) = size;
return (char *)ptr + PREFIX_SIZE;
}
void *yycalloc(size_t size)
{
void *ptr = calloc(1, size + PREFIX_SIZE);
if (!ptr) yymalloc_oom_handler(size);
update_yymalloc_stat_alloc(size + PREFIX_SIZE);
return (char *)ptr + PREFIX_SIZE;
}
void *yyrealloc(void *ptr, size_t size)
{
void *realptr;
size_t oldsize;
void *newptr;
if (ptr == NULL) return yymalloc(size);
realptr = (char *)ptr - PREFIX_SIZE;
oldsize = *((size_t*)realptr);
newptr = realloc(realptr, size + PREFIX_SIZE);
if (!newptr) yymalloc_oom_handler(size);
*((size_t*)newptr) = size;
update_yymalloc_stat_free(oldsize);
update_yymalloc_stat_alloc(size);
return (char *) newptr + PREFIX_SIZE;
}
size_t yymalloc_size(void *ptr)
{
void *realptr = (char*)ptr - PREFIX_SIZE;
size_t size = *((size_t *)realptr);
if (size &(sizeof(long) - 1)) size += sizeof(long) - (size & (sizeof(long) - 1));
return size + PREFIX_SIZE;
}
void yyfree(void *ptr)
{
void *realptr;
size_t oldsize;
if (NULL == ptr) return;
realptr = (char *) ptr - PREFIX_SIZE;
oldsize = *((size_t *) realptr);
update_yymalloc_stat_free(oldsize + PREFIX_SIZE);
free(realptr);
}
char *yystrdup(const char *s)
{
size_t l = strlen(s) + 1;
char *p = yymalloc(l);
memcpy(p, s, l);
return p;
}
size_t yymalloc_used_memory(void)
{
size_t um;
if (yymalloc_thread_safe) {
pthread_mutex_lock(&used_memory_mutex);
um = used_memory;
pthread_mutex_unlock(&used_memory_mutex);
} else {
um = used_memory;
}
return um;
}
size_t yymalloc_enable_thread_safeness(void)
{
yymalloc_thread_safe = 1;
}
void yymalloc_set_oom_handler(void (*oom_handler)(size_t))
{
yymalloc_oom_handler = oom_handler;
}
size_t yymalloc_get_rss(void)
{
return yymalloc_used_memory();
}
/**
* fragmentation = rss / allocated-bytes
*/
float yymalloc_get_fragmentation_ratio (size_t rss)
{
return (float) rss / yymalloc_used_memory();
}
size_t yymalloc_get_private_dirty(void)
{
return 0;
}<file_sep>all: yymalloctest
yymalloctest: yymalloc.o yymalloctest.o
gcc -o yymalloctest yymalloc.o yymalloctest.o
yymalloc.o: yymalloc.c
gcc -c -g yymalloc.c
yymalloctest.o: yymalloctest.c
gcc -c -g yymalloctest.c
clean:
rm -rf yymalloctest *.o<file_sep>
#include <stdio.h>
#include <stdlib.h>
#include "yymalloc.h"
int main(int argc, char *argv[])
{
int *p = (int *) yymalloc(sizeof(int));
size_t alloc_size = yymalloc_used_memory();
printf("Used memory : %zu\n", alloc_size);
printf("Int %zu, long %zu, size_t %zu\n", sizeof(int), sizeof(long), sizeof(size_t));
exit(0);
} | 639703a5e84fd8af99acf2709657a9007e71e7c6 | [
"Markdown",
"C",
"Makefile"
] | 5 | C | yubo-yue/yubo-kv | 670db329c4ccb77f9bc3b23755b67b01f35fb94a | 77735de60bba194506388f39bd6d4a153711b0ef |
refs/heads/master | <repo_name>guojuncheng595/python-learning<file_sep>/linuxShare/ASpider/ASpider/spiders/wy_video.py
# -*- coding: utf-8 -*-
import scrapy
import re
# import sys
class WanYingVideo(scrapy.Spider):
name = 'sodyy'
allowed_domains = ['www.sodyy.com']
start_urls = ['http://www.sodyy.com/vod-type-id-1-pg-1.html']
def parse(self, response):
post_nodes = response.css(".movie-name::text").extract()
for post_node in post_nodes:
print("序号:%s,值:%s" % (post_nodes.index(post_node) + 1,post_node))
pass<file_sep>/my_python_project/mitmdump_code/spider_douguomeishi.py
import json
import requests
from multiprocessing import Queue
from handlermongo import mongo_info
from concurrent.futures import ThreadPoolExecutor
# 创建队列
queue_list = Queue()
def handel_request(url, data):
header = {
"client": "4",
"version": "6935.2",
"device": "MI 5",
"sdk": "22,5.1.1",
"imei": "863064010600213",
"channel": "baidu",
# "mac": "60:02:B4:C4:B2:D6",
"resolution": "1280*720",
"dpi": "1.5",
# "android-id": "6002b4c4b2d64805",
# "pseudo-id": "4c4b2d648056002b",
"brand": "Xiaomi",
"scale": "1.5",
"timezone": "28800",
"language": "zh",
"cns": "3",
"carrier": "CHINA+MOBILE",
# "imsi": "460076002180196",
"user-agent": "Mozilla/5.0 (Linux; Android 5.1.1; MI 5 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36",
"reach": "1",
"newbie": "0",
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
"Accept-Encoding": "gzip, deflate",
"Connection": "Keep-Alive",
# "Cookie": "duid=59624219",
"Host": "api.douguo.net",
# "Content-Length": "68",
}
proxy = {'http': 'http://H076RR7P08B5W86P:D6B83B693<EMAIL>:9010'}
# response1 = requests.get(url=url, proxies=proxy)
#
# print(response1.text)
response = requests.post(url=url, headers=header, data=data)
return response
def handle_index():
url = 'http://api.douguo.net/recipe/flatcatalogs'
data = {
"client": "4",
# "_session": "1557537321152863064010600213",
# "v": "1557405381",
"_vs": "2305",
}
response = handel_request(url=url, data=data)
index_response_dict = json.loads(response.text)
for index_item in index_response_dict['result']['cs']:
# print(index_item)
for index_item_1 in index_item['cs']:
# print(index_item_1)
for item in index_item_1['cs']:
# print(item)
data_2 = {
"client": "4",
# "_session": "1557539422131863064010600213",
"keyword": item['name'],
"order": "0",
"_vs": "400",
}
# print(data_2)
queue_list.put(data_2)
print(response.text)
def handle_caipu_list(data):
print("当前处理的食材:", data['keyword'])
caipu_list_url = 'http://api.douguo.net/recipe/v2/search/0/20'
caipu_list_response = handel_request(url=caipu_list_url, data=data)
# print(caipu_list_response.text)
caipu_list_response_dict = json.loads(caipu_list_response.text)
for item in caipu_list_response_dict['result']['list']:
# print(item)
caipu_info = {}
caipu_info['shicai'] = data['keyword']
if item['type'] == 13:
caipu_info['user_name'] = item['r']['an']
caipu_info['shicai_id'] = item['r']['id']
caipu_info['describe'] = item['r']['cookstory'].replace('\n', '').replace(' ', '')
caipu_info['caipu_name'] = item['r']['n']
caipu_info['zuoliao_list'] = item['r']['major']
detail_url = 'http://api.douguo.net/recipe/detail/' + str(caipu_info['shicai_id'])
detail_data = {
"client": "4",
# "_session": "1557539422131863064010600213",
"author_id": "0",
"_vs": "2801",
"_ext": '{"query":{"kw":'+caipu_info['shicai']+',"src":"2801","idx":"1","type":"13","id":'+str(caipu_info['shicai_id'])+'}}',
}
detail_response = handel_request(url=detail_url, data=detail_data)
detail_response_dict = json.loads(detail_response.text)
caipu_info['tips'] = detail_response_dict['result']['recipe']['tips']
caipu_info['cook_step'] = detail_response_dict['result']['recipe']['cookstep']
print('当前入库菜谱是:', caipu_info['caipu_name'])
mongo_info.insert_item(caipu_info)
else:
continue
handle_index()
pool = ThreadPoolExecutor(max_workers=2)
while queue_list.qsize() > 0:
pool.submit(handle_caipu_list, queue_list.get())
# handle_caipu_list(queue_list.get())
# print(queue_list.qsize())
<file_sep>/linuxShare/ASpider/ASpider/utils/wukongwenda_requests.py
# -*- coding: utf-8 -*-
import requests
try:
import cookielib
except:
import http.cookiejar as cookielib
import json
import bs4
session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename='cookies.txt')
session.cookies.save(ignore_discard=True)
try:
session.cookies.load(ignore_discard=True)
except:
print("Cookie 未能加载")
# def get_csrf():
# # 获取csrf code https://www.jianshu.com/p/887af1ab4200
# response = requests.get("https://www.yunpanjingling.com", headers=header)
# soup = bs4.BeautifulSoup(response.text, "html.parser")
# soup.title.string[3:7]
# for meta in soup.select('meta'):
# if meta.get('name') == 'csrf-token':
# return meta.get('content')
# # print(meta.get('content'))
# # print(response.text) #获取服务器获取的值
# # text = '<meta name="csrf-token" content="<KEY>" />'
# # match_obj = re.match('.*name="csrf-token" content="(.*?)"', response.text)
# # if match_obj:
# # return (match_obj.group(1))
# # else:
# # return "none"
#
#
# def wukongwenda_login(account, password):
# header = {
# "HOST": "www.yunpanjingling.com",
# "User-Agent": agent,
# "Cookie": get_cookies(),
# "X-CSRF-TOKEN": get_csrf()
# }
#
# # 悟空问答 - 登陆 ; 1551623139
# if re.match("[0-9a-zA-Z_]{<EMAIL>", account):
# print("手机号码登陆")
# post_url = "https://www.yunpanjingling.com/user/login"
# post_date = {
# # "test":get_ccid,
# "email": account,
# "password": <PASSWORD>,
# "remember": "true"
# }
# response_text = session.post(post_url, data=post_date)
# print(response_text.text)
# # session.cookies.save()
header = {
"HOST":"www.yunpanjingling.com",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept": "application/json, text/javascript, */*; q=0.01"
}
def is_login():
#通过个人中心页面返回状态码来判断是否为登陆状态
inbox_url = "https://www.yunpanjingling.com/user/dashboard"
response = session.get(inbox_url, allow_redirects=False)
if response.status_code != 200:
return False
else:
return True
def get_csrf_token():
# 获取csrf code https://www.jianshu.com/p/887af1ab4200
response = requests.get("https://www.yunpanjingling.com/user/login", headers=header)
token = ""
ctoken = "none"
if response.cookies:
for key, value in response.cookies.items():
if key == 'XSRF-TOKEN':
token += ("XSRF-TOKEN=" + value + ";")
elif key == '_session':
token += ("_session=" + value + ";")
print(token[:-1])
token = token[:-1]
else:
token = 'none'
soup = bs4.BeautifulSoup(response.text, "html.parser")
soup.title.string[3:7]
for meta in soup.select('meta'):
if meta.get('name') == 'csrf-token':
print(meta.get('content'))
ctoken = meta.get('content')
return [ctoken, token]
def ajaxRequest():
token = get_csrf_token()
headers = {
"X-CSRF-TOKEN": token[0],
"Accept": "application/json, text/javascript, */*; q=0.01",
"Cookie": token[1],
"Content-Type": "application/json; charset=UTF-8"
}
datas = {'email': '<EMAIL>', 'password': '<PASSWORD>', 'remember': 'true'}
url = "https://www.yunpanjingling.com/user/login"
response = session.post(url=url, data=json.dumps(datas), headers=headers)
response.encoding = "utf-8"
if response.status_code == 200:
print("返回码:" + str(response.status_code))
print("返回码:" + str(response.text.encode("utf-8")))
else:
test = str(response.text.encode("utf-8"))
print("返回码:" + test)
session.cookies.save()
# cookie = session.cookies
# print(cookie)
ajaxRequest()
is_login()
<file_sep>/linuxShare/ASpider/ASpider/image_detail_with/down_image.py
#-*-coding:utf-8-*-
import requests
def spider():
url = "https://www.epailive.com/basic/captcha?ran=0.22070346581876787"
for i in range(1, 101):
print("正在下载的张数是:",i)
with open("D:\Desktop\python-learning\linuxShare\ASpider\ASpider\image_detail_with\image\{}.png".format(i), "wb") as f:
f.write(requests.get(url).content)
spider()<file_sep>/linuxShare/ArticleSpider/main.py
# _*_ coding: utf-8 _*_
__author__ = 'bobby'
from scrapy.cmdline import execute
import sys
import os
print (os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(["scrapy","crawl","jobbole"])<file_sep>/my_python_project/WPSourceWebsite/WPSourceWebsite/spiders/yunpanjingling.py
# -*- coding: utf-8 -*-
import re
import scrapy
from WPSourceWebsite.items import WPItemLoader, WPSearchItem
try:
import cookielib
except:
import http.cookiejar as cookielib
header = {
"HOST": "www.yunpanjingling.com",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept": "application/json, text/javascript, */*; q=0.01"
}
class YunpanjinglingSpider(scrapy.Spider):
name = 'yunpanjingling'
allowed_domains = ['https://www.yunpanjingling.com/']
start_urls = ['https://www.yunpanjingling.com/search/python']
def parse(self, response):
item_loader = WPItemLoader(item=WPSearchItem(), response=response)
titles = response.css('div.search-list')
for title in titles:
t_title = title.css("div.name a")
# 获取内容详情的url
title_url = t_title.css("::attr(href)").extract_first("")
print('标题url:title_url:' + title_url)
# 获取内容title
rex = '<a.*?href="(.+)".*?>(.*?)</a>'
match_re = re.match(rex, t_title.extract_first(""))
print('标题title:' + match_re.group(2).strip().replace("<em>", "").replace("</em>", ""))
# 获取内容副标题
s_title = title.css("div.referrer a")
# 获取内容的来源网站 TODO 可能为空
s_title_url = s_title.css("::attr(href)").extract_first("")
print("来源网址url:" + s_title_url)
# 副标题内容
match_re = re.match(rex, s_title.extract_first(""))
print('副标题内容s_title:' + match_re.group(2).strip().replace("<em>", "").replace("</em>", ""))
# item_loader.add_css("title", "div.search-list div.name")
pass
<file_sep>/linuxShare/ASpider/ASpider/spiders/yunpan.py
# -*- coding: utf-8 -*-
import scrapy.http.request
import bs4
import requests
import json
from requests import Request
from scrapy.http.cookies import CookieJar # 该模块继承自内置的http.cookiejar,操作类似
# 实例化一个cookiejar对象
cookie_jar = CookieJar()
try:
import cookielib
except:
import http.cookiejar as cookielib
import re
# import sys
session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename='cookies.txt')
session.cookies.save(ignore_discard=True)
try:
session.cookies.load(ignore_discard=True)
except:
print("Cookie 未能加载")
header = {
"HOST":"www.yunpanjingling.com",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept": "application/json, text/javascript, */*; q=0.01"
}
class YunPan(scrapy.Spider):
name = 'yunpan'
allowed_domains = ['www.yunpanjingling.com']
start_urls = ['https://www.yunpanjingling.com/search/python']
def parse(self, response):
post_nodes = response.css(".search-list a::text").extract()
print(post_nodes)
def start_requests(self):
return [scrapy.http.Request('https://www.yunpanjingling.com/user/login', meta={'cookiejar': 1}, headers=header, callback=self.login)]
def login(self, response):
# 如果有图片验证码
# import time
# t = str(int(time.time()*1000))
# captcha_url = ""
# yield scrapy.Request(captcha_url, headers=self.headers, meta={"post_data":post_data},callback=self.login_after_captcha)
#
# https://www.jianshu.com/p/404e4ac156a6
cookies = response.headers.getlist('Set-Cookie')
print("后台首次写入,相应的Cookies", cookies)
str_cookies = ""
for cookie in cookies:
# https://www.cnblogs.com/timelesszhuang/p/7235798.html
str_cookie = re.findall(r"(.*?) expires", str(cookie, encoding="utf-8"))
str_cookies += str_cookies.join(str_cookie)
print("序号:%s 值:%s"%(cookie.index(cookie)+1, str_cookie))
print("合成后的cookie的值为:", str_cookies[:-1])
# 获取x-csrf-token值
ctoken = "none"
soup = bs4.BeautifulSoup(response.text, "html.parser")
soup.title.string[3:7]
for meta in soup.select('meta'):
if meta.get('name') == 'csrf-token':
print(meta.get('content'))
ctoken = meta.get('content')
# return [ctoken, token]
if ctoken and str_cookies:
headers = {
"X-CSRF-TOKEN": ctoken,
"Accept": "application/json, text/javascript, */*; q=0.01",
"Cookie": str_cookies,
"Content-Type": "application/json; charset=UTF-8"
}
post_data = {
'email': '<EMAIL>',
'password': '<PASSWORD>',
'remember': 'true'
}
post_url = "https://www.yunpanjingling.com/user/login"
response = session.post(url=post_url, data=json.dumps(post_data), headers=headers)
if response.status_code == 200:
print("返回码:" + str(response.status_code))
print("返回码:" + str(response.text.encode("utf-8")))
self.check_login(response)
else:
test = str(response.text.encode("utf-8"))
print("返回码:" + test)
session.cookies.save()
def check_login(self, response):
# 验证服务器的返回数据判断是否成功
pass
# 图形验证码获取
def login_after_captcha(self,response):
with open("captcha.jpg","wb") as f:
f.write(response.body)
f.close()
from PIL import Image
try:
im = Image.open('captcha.jpg')
im.show()
im.close()
except:
pass
captcha = input("输入验证码\n>")
# 登陆URL
post_url = ""
# 登陆请求数据
post_data = response.meta.get("post_data",{})
post_data["captcha"] = captcha
# 验证服务器返回的数据是否成功
text_json = json.load(response.txt)
if "msg" in text_json and text_json["msg"] == "登陆成功":
for url in self.start_urls:
yield scrapy.Request(url,dont_filter=True)
<file_sep>/linuxShare/ASpider/ASpider/image_detail_with/detail_image3.py
#-*-coding:utf-8-*-
import numpy as np
import os
import time
from PIL import Image
from sklearn.externals import joblib
from sklearn.neighbors import KNeighborsClassifier
def load_dataset():
X = []
y = []
for i in "23456789ABVDEFGHKMNPRSTUVWXYZ":
target_path = "fenlei/" + i
print(target_path)
for title in os.listdir(target_path):
pix = np.asarray(Image.open(os.path.join(target_path, title)).convert('L'))
X.append(pix.reshape(25 * 30))
y.append(target_path.split('/')[-1])
X = np.asarray(X)
y = np.asarray(y)
return X, y
def check_everyone(model):
pre_list = []
y_list = []
for i in "23456789ABCDEFGHKMNPRSTUVWXYZ":
part_path = "part/" + i
for title in os.listdir(part_path):
pix = np.asarray(Image.open(os.path.join(part_path, title)).convert('L'))
pix = pix.reshape(25 * 30)
pre_list.append(pix)
y_list.append(part_path.split('/')[-1])
pre_list = np.asarray(pre_list)
y_list = np.asarray(y_list)
result_list = model.predict(pre_list)
acc = 0
for i in result_list == y_list:
print(result_list,y_list,)
if i == np.bool(True):
acc += 1
print(acc, acc / len(result_list))
X, y = load_dataset()
knn = KNeighborsClassifier()
knn.fit(X, y)
joblib.dump(knn, 'yipai.model')
check_everyone(knn)<file_sep>/my_python_project/mitmdump_code/handler_proxy.py
import requests
#{"ip":"192.168.127.12","locale":""}
url = 'http://ip.hahado.cn/ip'
proxy = {'http':'http://H076RR7P08B5W86P:<EMAIL>:9010'}
response = requests.get(url=url, proxies=proxy)
print(response.text) | 9fd285aa7d32a1d18fada2420a04bd6ba58e684d | [
"Python"
] | 9 | Python | guojuncheng595/python-learning | f986f6a5e0ea9dad2a77fe1be345a5df2e1a1eee | 48f032bd2262a339e2a21e210226b820584a5608 |
refs/heads/master | <repo_name>geronimoEKIA/Wazir<file_sep>/hungry.py
hungry==input("are you hungry?")
if hungry=="yes" and hungry=="Y" and hungry=="yy" :
print("eat samosa")
else:
print("do sleep")
<file_sep>/README.md
# Wazir
Project wazir test repository
| db4d375c08e59d229290bbf85054f548220e34b6 | [
"Markdown",
"Python"
] | 2 | Python | geronimoEKIA/Wazir | 5ca93a4f155dcfdb4d92071bd0cbbfa74efc023b | ac9c1bc59e7cb6bb76094b891cbe54afd705d8ef |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace PaylocityBenefitsChallenge.Entities
{
public class BenefitsCostResult
{
public BenefitEmployee EmployeeData { get; set; }
public decimal BenefitCostForEmployeeOnly { get; internal set; }
public decimal BenefitCostForDependentsOnly;
public decimal TotalBenefitsCostPerYear { get; internal set; }
public decimal TotalEmployeeCostPerPayPeriod { get; internal set; }
public decimal TotalEmployeeCostPerYear { get; internal set; }
public string ErrorDetails;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PaylocityBenefitsChallenge;
using PaylocityBenefitsChallenge.Entities;
using PaylocityBenefitsChallengeWeb.Models;
namespace PaylocityBenefitsChallengeWeb.Controllers
{
public class BenefitsController : Controller
{
public Lazy<IBenefitsManager> benefitsMgr = new Lazy<IBenefitsManager>(() => new BenefitsManager());
public ActionResult Calculate()
{
var employee = new BenefitsEmployeeModel();
return View(employee);
}
[HttpPost]
public ActionResult Calculate(BenefitsEmployeeModel model)
{
if (!ModelState.IsValid)
{
return View("Calculate", model);
}
var benefitsEmployee = new BenefitEmployee(model.Employee.FirstName, model.Employee.LastName);
if (model.Dependents != null && model.Dependents.Count > 0)
{
var dependents = new List<PaylocityBenefitsChallenge.Entities.Person>();
foreach (var dependent in model.Dependents)
{
var employeeDependent = new Person(dependent.FirstName, dependent.LastName);
dependents.Add(employeeDependent);
}
benefitsEmployee.Dependents = dependents;
}
var response = benefitsMgr.Value.GetEmployeeCost(benefitsEmployee);
EmployeeCostModel responseModel = new EmployeeCostModel();
responseModel.TotalBenefitCost = response.TotalBenefitsCostPerYear;
responseModel.EmployeeCostPerPayPeriod = response.TotalEmployeeCostPerPayPeriod;
responseModel.EmployeeCostPerYear = response.TotalEmployeeCostPerYear;
return View("ViewEmployeeCost", responseModel);
}
public ActionResult AddNewDependent()
{
var dependent = new PersonModel();
return PartialView("_Dependent", dependent);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PaylocityBenefitsChallengeWeb.Models
{
public class BenefitsEmployeeModel
{
public BenefitsEmployeeModel(string firstName, string lastName)
{
Employee = new PersonModel(){FirstName = firstName, LastName = lastName};
Dependents = new List<PersonModel>();
}
public BenefitsEmployeeModel()
{
Employee = new PersonModel();
Dependents = new List<PersonModel>();
}
[Required]
public PersonModel Employee { get; set; }
public List<PersonModel> Dependents { get; set; }
}
public class PersonModel
{
[Display(Name = "First Name")]
[Required]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required]
public string LastName { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using PaylocityBenefitsChallenge.Entities;
namespace PaylocityBenefitsChallenge
{
public interface IBenefitsManager
{
BenefitsCostResult GetEmployeeCost(BenefitEmployee employee);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace PaylocityBenefitsChallenge.Entities
{
public class BenefitEmployee
{
public BenefitEmployee(string firstName, string lastName)
{
Employee = new Person(firstName, lastName, true);
}
public Person Employee { get; set; }
public List<Person> Dependents { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace PaylocityBenefitsChallenge.Entities
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsEligibleForDiscount { get; private set; }
public bool IsEmployee { get; private set; }
public Person(string firstName, string lastName, bool? isEmployee = false)
{
FirstName = firstName;
LastName = lastName;
IsEmployee = isEmployee ?? false;
// employees and dependents whose first or last name starts with the character A are eligible
IsEligibleForDiscount = FirstName.ToLower().StartsWith("a") ||
LastName.ToLower().StartsWith("a"); ;
}
}
}
| b17fc9638734023da0f5a477924898a39fd292ec | [
"C#"
] | 6 | C# | purkles/paylocity | e2145078fdad2480b22b2fbebe3931c54a682412 | cd760463539b7d02c68a6efbc782bf834d361697 |
refs/heads/master | <file_sep>#!/usr/bin/env ruby
require_relative "../lib/user.rb"
require_relative "../lib/teacher.rb"
require_relative "../lib/student.rb"
steve = Student.new
steve.first_name = "Steve"
steve.last_name = "Jobs"
bill = Student.new
bill.first_name = "Bill"
bill.last_name = "Gates"
avi = Teacher.new
avi.first_name = "Avi"
avi.last_name = "Flombaum"
some_knowledge = avi.teach
2.times do
steve.learn(some_knowledge)
bill.learn(some_knowledge)
end
steve.knowledge.each do |k|
puts k
end
bill.knowledge.each do |k|
puts k
end
#puts "Steve just learned this important knowledge: '#{steve.knowledge.first}' from Avi"
jim = User.new
jim.first_name = "Jim"
jim.last_name = "Morrison"
#jim.learn(some_knowledge) #does not work because User does not have #learn
| 9211504d603bf3b7c79fcc9c8ef0848cd7333b1a | [
"Ruby"
] | 1 | Ruby | sydra08/ruby-inheritance-lab-v-000 | f6127a9b40090afeb29209dd0300d53ed1546e52 | 3b72b52a9a621663c42b06a0891d7f913461ec03 |
refs/heads/master | <file_sep><?php
namespace Henesis\PlatformBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PlatformController extends Controller
{
public function indexAction()
{
//récupere le json de l'api et le stock dans l'array obj
$json = file_get_contents('http://172.16.58.3/api/nightclub/fb_feed.php?id=1');
$obj = json_decode($json, true);
// Affiche la page d'accueil
$content = $this->get('templating')->render('HenesisPlatformBundle:Platform:index.html.twig', array(
'post' => $obj["feed"]
));
return new Response($content);
}
public function eventAction()
{
//récupere le json de l'api et le stock dans l'array obj
$json = file_get_contents('http://172.16.58.3/api/nightclub/fb_feed.php?id=1');
$obj = json_decode($json, true);
// Affiche la page d'accueil
$content = $this->get('templating')->render('HenesisPlatformBundle:Platform:event.html.twig', array(
'event' => $obj["feed"]
));
return new Response($content);
}
public function menuAction()
{
// Affiche la page du menu
//récupération des produits disponibles
$json = file_get_contents('http://172.16.58.3/api/product/product_nightclub.php?id=1');
$obj = json_decode($json, true);
$content = $this->get('templating')->render('HenesisPlatformBundle:Platform:menu.html.twig', array(
'products' => $obj["prod"]
));
return new Response($content);
}
public function aboutAction()
{
// Affiche la page d'info
$content = $this->get('templating')->render('HenesisPlatformBundle:Platform:about.html.twig');
return new Response($content);
}
public function loginAction()
{
// Affiche la page d'accueil
$content = $this->get('templating')->render('HenesisPlatformBundle:Platform:login.html.twig');
return new Response($content);
}
} | ee5ece33d57616d35f239ce1d86fcdae4c16e979 | [
"PHP"
] | 1 | PHP | gonckelb/henesisclub | f4b1d9386df990edbed3217caee4e206a51a1e5c | 65e0f33b48b814679a4a3fd4ad5aa3cf7c4a2c32 |
refs/heads/master | <repo_name>bondom/ts-jest-bug<file_sep>/User.test.ts
import { getUser } from "User";
describe("describe", () => {
test("test", () => {
const user: { name: string; age: number } = getUser();
expect(user.name).toEqual("Uasia");
});
});
<file_sep>/src/components/User.ts
export const getUser = (): { name: string; age: number } => {
return { name: "Uasia", age: 18 };
};
| 23e13ff5dbc0ab0ab021fccb7b404b349a603778 | [
"TypeScript"
] | 2 | TypeScript | bondom/ts-jest-bug | 96709489456eee6a5b88041835f97f8c79adcd75 | ace4c8dae0c9516269c13e4cda1fb4809eeb4451 |
refs/heads/master | <repo_name>hectoram/CopyHelper<file_sep>/CopyPlus/CopyPlus/EntryTypes/FileEntry.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyPlus.EntryTypes
{
class FileEntry : Entry
{
public FileEntry(Entry Previous, object data, DateTime date)
{
SetPrevious(Previous);
Data = (string)data;
Time = date;
EntryType = Enums.EntryType.File;
}
}
}
<file_sep>/CopyPlus/CopyPlus/EntryTypes/RtfStringEntry.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyPlus.EntryTypes
{
class RtfStringEntry : Entry
{
public RtfStringEntry(Entry previous, object data, DateTime date)
{
SetPrevious(previous);
Data = (string)data;
Time = date;
EntryType = Enums.EntryType.RtfText;
}
}
}
<file_sep>/CopyPlus/CopyPlus/ShowAll.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CopyPlus
{
public partial class ShowAll : Form
{
//Ref to my main form
//Use it to get back an forth
Form mainForm;
//displayCopies is the gridView object used to handle output
public ShowAll(Form myForm)
{
InitializeComponent();
mainForm = myForm;
loadCopies();
}
private void loadCopies()
{
displayCopies.AutoGenerateColumns = false;
string[] row = new string[1];
string myDate = DateTime.Now.ToString("MM/dd/yyyy");
//For time stamp as well "MM/dd/yyyy h:mm tt"
for (int i = 0; i < ClipBoardEntries.Instance.size(); i++)
{
row = new string[] { ClipBoardEntries.Instance.getDataAtIndex(i), myDate, getType(i) };
displayCopies.Rows.Add(row);
}
}
private string getType(int i)
{
switch (ClipBoardEntries.Instance.getDataTypeAtIndex(i))
{
case copyType.STRING:
return "Text";
case copyType.RTF:
return "Formatted Text";
case copyType.IMAGE:
return "Image";
case copyType.FILE:
return "File";
}
return "Format not recognized";
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
mainForm.Show();
}
private void displayCopies_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
ClipBoardEntries.Instance.removeEntryAtIndex(e.RowIndex);
}
private void displayCopies_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
ClipBoardEntries.Instance.setCurrentCopyAtIndex(e.RowIndex);
}
}
}
<file_sep>/CopyPlus/CopyPlus/Factory/EntryFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CopyPlus.Enums;
using System.Text.RegularExpressions;
using CopyPlus.EntryTypes;
using System.Windows.Forms;
using System.Collections;
namespace CopyPlus.Factory
{
class EntryFactory
{
private String[] imageTypes = new String[4] {".jpg",".png",".bmp",".gif"};
public Entry getEntry(IDataObject data, DateTime date, Entry previous)
{
switch (getType(data))
{
case EntryType.Text:
return new StringEntry(previous, (object)data, date);
case EntryType.RtfText:
return new RtfStringEntry(previous, (object)data, date);
case EntryType.URL:
return new URLEntry(previous, (object)data, date);
case EntryType.Email:
return new EmailEntry(previous, (object)data, date);
case EntryType.File:
return new FileEntry(previous, (object)data, date);
case EntryType.Image:
return new ImageEntry(previous, (object)data, date);
default:
break;
}
return null;
}
private EntryType getType(IDataObject data)
{
String[] allFormats = data.GetFormats();
if (allFormats.Contains("Text"))
{
if (Regex.IsMatch((string)data.GetData(DataFormats.Text), @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)))
return EntryType.Email;
else if (Uri.IsWellFormedUriString((string)data.GetData(DataFormats.Text), UriKind.RelativeOrAbsolute))
return EntryType.URL;
else if (allFormats.Contains("Rich Text Format"))
return EntryType.RtfText;
}
else if (allFormats.Contains("FileDrop"))
return determineFileType(data);
return EntryType.Text;
}
private EntryType determineFileType(IDataObject toCheck)
{
var temp = toCheck.GetData(DataFormats.FileDrop);
//Unpacks object to get the array inside
string[] arr = ((IEnumerable)temp).Cast<object>().Select(x => x.ToString()).ToArray();
string path = "";
foreach (string a in arr)
path = a;
foreach (string check in imageTypes)
if (path.Contains(check))
return EntryType.Image;
return EntryType.File;
}
}
}
<file_sep>/CopyPlus/CopyPlus/MainMenue.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace CopyPlus
{
public partial class MainMenue : Form
{
private bool hasBeenMinimizedBefore = false;
public bool copyOccured;
IntPtr clipboardViewer;
Hotkey copyNext;
Hotkey copyPrevious;
Hotkey removeFromList;
public static bool manualCopy = false;
private Form showWindow;
//HotKeys
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
// Unregisters the hot key with Windows.
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
public MainMenue()
{
InitializeComponent();
}
private void initHotKeys()
{
copyNext = new Hotkey();
copyPrevious = new Hotkey();
removeFromList = new Hotkey();
//Sets copy next to cntrl + right
copyNext.KeyCode = Keys.Right;
copyNext.Control = true;
copyNext.Pressed += delegate { setNextCopy(); };
copyNext.Register(this);
//Set copy previous to cntrl + left
copyPrevious.KeyCode = Keys.Left;
copyPrevious.Control = true;
copyPrevious.Pressed += delegate { setPreviousCopy(); };
copyPrevious.Register(this);
//Set remove to cntrl + up
removeFromList.KeyCode = Keys.Up;
removeFromList.Control = true;
removeFromList.Pressed += delegate { removeCurrentEntry(); };
removeFromList.Register(this);
}
private void minimize(object sender, EventArgs e)
{
myNotifyIcon.BalloonTipTitle = "CopyPlus minimized to tray";
myNotifyIcon.BalloonTipText = "Restore application from here";
if (FormWindowState.Minimized == this.WindowState)
{
myNotifyIcon.Visible = true;
if (!hasBeenMinimizedBefore)
{
myNotifyIcon.ShowBalloonTip(500);
hasBeenMinimizedBefore = !hasBeenMinimizedBefore;
}
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
myNotifyIcon.Visible = false;
}
}
private void myNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
private void onLoad(object sender, EventArgs e)
{
RegisterClipboardViewer();
initHotKeys();
}
//My methods
//----------------------------------------------------------------------------------------------
private void RegisterClipboardViewer()
{
clipboardViewer = User32.SetClipboardViewer(this.Handle);
}
/// <summary>
/// Remove this form from the Clipboard Viewer list
/// </summary>
private void UnregisterClipboardViewer()
{
User32.ChangeClipboardChain(this.Handle, clipboardViewer);
}
private void addCopyEntry(IDataObject dataToAdd)
{
ClipBoardEntries.Instance.addEntry(dataToAdd);
}
private void GetClipboardData()
{
IDataObject copiedData = new DataObject();
copyOccured = true;
try
{
copiedData = Clipboard.GetDataObject();
}
catch (System.Runtime.InteropServices.ExternalException externEx)
{
return;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return;
}
// Get RTF if it is present
if (copiedData.GetDataPresent(DataFormats.Rtf))
{
string userInput = (string)copiedData.GetData(DataFormats.Rtf);
copyDisplay.Rtf = (string)copiedData.GetData(DataFormats.Rtf);
addCopyEntry(copiedData);
}
else
{
// Get Text if it is present
if (copiedData.GetDataPresent(DataFormats.Text))
{
copyDisplay.Text = (string)copiedData.GetData(DataFormats.Text);
addCopyEntry(copiedData);
}
else
{
addCopyEntry(copiedData);
setDisplay();
}
}
}
protected override void WndProc(ref Message m)
{
if (!ClipBoardEntries.Instance.wasManualCopy())
{
switch ((CopyPlus.Msgs)m.Msg)
{
//
// The WM_DRAWCLIPBOARD message is sent to the first window
// in the clipboard viewer chain when the content of the
// clipboard changes. This enables a clipboard viewer
// window to display the new content of the clipboard.
//
case CopyPlus.Msgs.WM_DRAWCLIPBOARD:
Debug.WriteLine("WindowProc DRAWCLIPBOARD: " + m.Msg, "WndProc");
GetClipboardData();
copyOccured = true;
//
// Each window that receives the WM_DRAWCLIPBOARD message
// must call the SendMessage function to pass the message
// on to the next window in the clipboard viewer chain.
//
CopyPlus.User32.SendMessage(clipboardViewer, m.Msg, m.WParam, m.LParam);
break;
//
// The WM_CHANGECBCHAIN message is sent to the first window
// in the clipboard viewer chain when a window is being
// removed from the chain.
//
case CopyPlus.Msgs.WM_CHANGECBCHAIN:
Debug.WriteLine("WM_CHANGECBCHAIN: lParam: " + m.LParam, "WndProc");
// When a clipboard viewer window receives the WM_CHANGECBCHAIN message,
// it should call the SendMessage function to pass the message to the
// next window in the chain, unless the next window is the window
// being removed. In this case, the clipboard viewer should save
// the handle specified by the lParam parameter as the next window in the chain.
copyOccured = true;
//
// wParam is the Handle to the window being removed from
// the clipboard viewer chain
// lParam is the Handle to the next window in the chain
// following the window being removed.
if (m.WParam == clipboardViewer)
{
//
// If wParam is the next clipboard viewer then it
// is being removed so update pointer to the next
// window in the clipboard chain
//
clipboardViewer = m.LParam;
}
else
{
CopyPlus.User32.SendMessage(clipboardViewer, m.Msg, m.WParam, m.LParam);
copyOccured = true;
}
break;
default:
//
// Let the form process the messages that we are
// not interested in
//
copyOccured = true;
base.WndProc(ref m);
break;
}
}
}
private void setNextCopy()
{
if (ClipBoardEntries.Instance.size() > 0)
{
ClipBoardEntries.Instance.getNext();
setDisplay();
}
else
{
copyDisplay.Text = "No Copy To Display";
}
}
private void setPreviousCopy()
{
if (ClipBoardEntries.Instance.size() > 0)
{
ClipBoardEntries.Instance.getPrevious();
setDisplay();
}
else
{
copyDisplay.Text = "No Copy To Display";
}
}
private void removeCurrentEntry()
{
ClipBoardEntries.Instance.removeEntry();
ClipBoardEntries.Instance.getNext();
setDisplay();
setNextCopy();
}
private void setNextCopy(object sender, EventArgs e)
{
if (ClipBoardEntries.Instance.size() > 0)
{
ClipBoardEntries.Instance.getNext();
setDisplay();
}
else
{
copyDisplay.Text = "No Copy To Display";
}
}
private void setDisplay()
{
copyDisplay.Clear();
if (ClipBoardEntries.Instance.getType() == copyType.STRING)
copyDisplay.Text = ClipBoardEntries.Instance.toStringCurrent();
else if (ClipBoardEntries.Instance.getType() == copyType.RTF)
copyDisplay.Rtf = ClipBoardEntries.Instance.toStringCurrent();
else
copyDisplay.Text = ClipBoardEntries.Instance.toStringCurrent();
if (ClipBoardEntries.Instance.size() > 1)
{
myNotifyIcon.BalloonTipTitle = "Current Copy:";
myNotifyIcon.BalloonTipText = copyDisplay.Text;
myNotifyIcon.Visible = true;
myNotifyIcon.ShowBalloonTip(1);
}
}
private void getPreviousCopy(object sender, EventArgs e)
{
if (ClipBoardEntries.Instance.size() > 0)
{
ClipBoardEntries.Instance.getPrevious();
setDisplay();
}
else
{
copyDisplay.Text = "No Copy To Display";
}
}
private void showAllCopies(object sender, EventArgs e)
{
this.Hide();
showWindow = new ShowAll(this);
showWindow.Show();
}
private void UndoButton_Click(object sender, EventArgs e)
{
ClipBoardEntries.Instance.undoLastRemoveOrListDelete();
}
private void ClearButton_Click(object sender, EventArgs e)
{
ClipBoardEntries.Instance.clearList();
copyDisplay.Clear();
copyDisplay.Text = "List Cleared";
}
}
}
<file_sep>/CopyPlus/CopyPlus/EntryTypes/Entry.cs
using CopyPlus.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyPlus.EntryTypes
{
class Entry
{
public object Data { get; set; }
public DateTime Time { get; set; }
public EntryType EntryType { get; set; }
public Entry Next { get; set; }
public Entry Previous { get; set; }
public Entry GetNext()
{
return Next;
}
Entry GetPrevious()
{
return Previous;
}
public void SetNext(Entry nextEntry)
{
Next = nextEntry;
}
public void SetPrevious(Entry previousEntry)
{
Previous = previousEntry;
}
}
}
<file_sep>/CopyPlus/CopyPlus/ClipBoardEntries.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace CopyPlus
{
class ClipBoardEntries
{
private static ClipBoardEntries instance;
private ClipBoardEntries() { }
public static ClipBoardEntries Instance
{
get
{
if (instance == null)
{
instance = new ClipBoardEntries();
}
return instance;
}
}
public bool addEntry(IDataObject toAdd)
{
currentCounter++;
proccessEntries(toAdd);
return true;
}
public void addEntry(string data, string date)
{
currentCounter++;
copyList.Add(Tuple.Create(data,copyType.STRING,date));
}
//Check to see if the list is empty.
public bool removeEntry()
{
if (copyList.Count != 0)
{
itemRemoved = true;
removePosition = currentCounter;
backupEntry = copyList[currentCounter];
copyList.Remove(copyList[currentCounter]);
return true;
}
else
return false;
}
public bool removeEntryAtIndex(int index)
{
if (index >= 0 && index <= copyList.Count)
{
copyList.Remove(copyList[index]);
return true;
}
else
return false;
}
public bool setCurrentCopyAtIndex(int index)
{
//If problems occur then set to 0
if (index > -1 && index <= copyList.Count)
{
currentCounter = index;
setCopyData();
return true;
}else
return false;
}
public void getNext()
{
currentCounter++;
if (copyList.Count < currentCounter || copyList.Count == currentCounter)
{
currentCounter = 0;
setCopyData();
}
else
{
setCopyData();
}
}
public void getPrevious()
{
currentCounter--;
if (0 > currentCounter)
{
currentCounter = copyList.Count - 1;
setCopyData();
}
else
{
setCopyData();
}
}
public copyType getType()
{
if (copyList.Count > 0)
return copyList[currentCounter].Item2;
else
return copyType.NON;
}
public string getDataAtIndex(int index)
{
if (index >= 0 && index <= copyList.Count)
{
return copyList[index].Item1;
}
return "";
}
public string getDateAtIndex(int index)
{
if (index >= 0 && index <= copyList.Count)
{
return copyList[index].Item3;
}
return "";
}
public int size()
{
return copyList.Count;
}
public copyType getDataTypeAtIndex(int index)
{
if (index >= 0 && index <= copyList.Count)
{
return copyList[index].Item2;
}
return copyType.NON;
}
public string toStringCurrent()
{
if (copyList.Count > 0)
{
switch (copyList[currentCounter].Item2)
{
case copyType.STRING:
return (string)copyList[currentCounter].Item1;
case copyType.RTF:
return (string)copyList[currentCounter].Item1;
case copyType.IMAGE:
return "Image at: " + getFilePath();
case copyType.FILE:
return "File at" + getFilePath();
}
}
return "";
}
public void clearList()
{
listCleared = !listCleared;
backupList = copyList;
copyList = new List<Tuple<string, copyType,string>>();
}
public void undoLastRemoveOrListDelete()
{
if (listCleared)
{
copyList = backupList;
listCleared = false;
} else if (itemRemoved)
{
copyList.Insert(removePosition, backupEntry);
itemRemoved = false;
}
}
public bool wasManualCopy()
{
return manualCopy;
}
private static string stringToRTF(string value)
{
RichTextBox richTextBox = new RichTextBox();
richTextBox.Text = value;
int offset = richTextBox.Rtf.IndexOf(@"\f0\fs17") + 8; // offset = 118;
int len = richTextBox.Rtf.LastIndexOf(@"\par") - offset;
string result = richTextBox.Rtf.Substring(offset, len).Trim();
return result;
}
//Private fields
private List<Tuple<string,copyType,string>> copyList = new List<Tuple<string,copyType,string>>();
Tuple<string, copyType,string> backupEntry;
private List<Tuple<string, copyType,string>> backupList = new List<Tuple<string, copyType,string>>();
private String[] imageTypes = new String[4] {".jpg",".png",".bmp",".gif"};
private int currentCounter = -1;
private int removePosition = 0;
private bool manualCopy = false;
private bool listCleared = false;
private bool itemRemoved = false;
//Helper methods
private void setCopyData()
{
//Need the manual copy bool otherwise the MainMenue will not work because a clear
//Is seeen as a copy event. This flag helps to avoid adding extra empty entries.
if (copyList.Count > 0)
{
manualCopy = true;
Clipboard.Clear();
switch (copyList[currentCounter].Item2)
{
case copyType.STRING:
Clipboard.SetText(copyList[currentCounter].Item1);
break;
case copyType.RTF:
Clipboard.SetText((string)copyList[currentCounter].Item1);
break;
case copyType.IMAGE:
System.Collections.Specialized.StringCollection path = new System.Collections.Specialized.StringCollection();
path.Add(getFilePath());
Clipboard.SetFileDropList(path);
break;
case copyType.FILE:
System.Collections.Specialized.StringCollection path1 = new System.Collections.Specialized.StringCollection();
path1.Add(getFilePath());
Clipboard.SetFileDropList(path1);
break;
}
manualCopy = !manualCopy;
}
}
private string getFilePath()
{
return copyList[currentCounter].Item1;
}
//Add the manual copy = true here
private Tuple<string, copyType,string> determineFileType(IDataObject toCheck)
{
manualCopy = true;
var temp = toCheck.GetData(DataFormats.FileDrop);
//Unpacks object to get the array inside
string[] arr = ((IEnumerable)temp).Cast<object>().Select(x => x.ToString()).ToArray();
string path = "";
foreach(string a in arr)
path = a;
foreach(string check in imageTypes)
{
if(path.Contains(check))
{
manualCopy = !manualCopy;
return new Tuple<string, copyType,string>(path, copyType.IMAGE, DateTime.Now.ToString("MM/dd/yyyy"));
}
}
manualCopy = !manualCopy;
return Tuple.Create(path, copyType.FILE, DateTime.Now.ToString("MM/dd/yyyy"));
}
//Sorts incoming copies into a new tuple with the right data format attached.
private void proccessEntries(IDataObject toProcess)
{
String[] allFormats = toProcess.GetFormats();
if (allFormats.Contains("Text"))
{
if (allFormats.Contains("Rich Text Format"))
copyList.Add(Tuple.Create((string)toProcess.GetData(DataFormats.Rtf), copyType.RTF, DateTime.Now.ToString("MM/dd/yyyy")));
else
copyList.Add(Tuple.Create((string)toProcess.GetData(DataFormats.StringFormat), copyType.STRING, DateTime.Now.ToString("MM/dd/yyyy")));
}
else if (allFormats.Contains("FileDrop"))
copyList.Add(determineFileType(toProcess));
}
}
public enum copyType:int
{
RTF = 0,
STRING = 1,
IMAGE = 2,
FILE = 3,
NON = 4
}
}<file_sep>/CopyPlus/CopyPlus/Options.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CopyPlus
{
public partial class Options : Form
{
Form startForm;
public Options(Form myForm)
{
InitializeComponent();
startForm = myForm;
}
public Options()
{
InitializeComponent();
}
private void Options_Load(object sender, EventArgs e)
{
//Load user options
if (Properties.Settings.Default.startAtCurrentCopy)
startOptionCurrent.Select();
else
startOptionFront.Select();
loadNextSettings();
}
private void loadNextSettings()
{
hotKeyDisplayNext.Text = "+ " + Properties.Settings.Default.nextHotKey;
if (Properties.Settings.Default.ctrlNextEnabled)
ctrlEnabledNext.Select();
if (Properties.Settings.Default.altNextEnabled)
altEnabledNext.Select();
}
private void controlEnable_CheckedChanged(object sender, EventArgs e)
{
}
private void backButton_Click(object sender, EventArgs e)
{
}
private void userHotKey_KeyPress(object sender, KeyPressEventArgs e)
{
userHotKeyNextInput.Clear();
userHotKeyNextInput.Text = e.KeyChar.ToString();
hotKeyDisplayNext.Text = "+ " + e.KeyChar.ToString();
Properties.Settings.Default.nextHotKey = e.KeyChar.ToString();
e.Handled = true;
}
private void currentCopy_CheckedChanged(object sender, EventArgs e)
{
}
//End
}
}
<file_sep>/CopyPlus/CopyPlus/Enums/EntryType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyPlus.Enums
{
enum EntryType
{
Text,
RtfText,
URL,
Email,
File,
Image
}
}
<file_sep>/CopyPlus/CopyPlus/MyMenu.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace CopyPlus
{
public partial class MyMenu : UserControl
{
public MyMenu()
{
InitializeComponent();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog savePath = new SaveFileDialog();
// set a default file name
savePath.FileName = "SaveHistory.txt";
// set filters - this can be done in properties as well
savePath.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
savePath.InitialDirectory = Directory.GetCurrentDirectory();
if (savePath.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(File.Open(savePath.FileName, System.IO.FileMode.Append)))
{
//Start of a new copy list.
//===Date===
string toDisplay = "===" + DateTime.Now.ToString("MM/dd/yyyy") + "===";
sw.WriteLine(toDisplay);
sw.WriteLine();
for (int i = 0; i < ClipBoardEntries.Instance.size(); i++)
{
sw.WriteLine(ClipBoardEntries.Instance.getDataAtIndex(i));
sw.WriteLine();
}
}
}
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
Options myOptions = new Options();
myOptions.Show();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openPath = new OpenFileDialog();
openPath.InitialDirectory = Directory.GetCurrentDirectory();
openPath.Filter = "txt files (*.txt)|*.txt";
openPath.FilterIndex = 2;
openPath.RestoreDirectory = true;
if (openPath.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openPath.OpenFile()) != null)
{
StreamReader reader = new StreamReader(myStream);
ClipBoardEntries.Instance.clearList();
//While it is not the end of stream
//Read in next line
while (!reader.EndOfStream)
parseLine(reader.ReadLine());
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
private void parseLine(string toParse)
{
if (!String.IsNullOrEmpty(toParse))
{
if (toParse.Contains("==="))
{
string[] tokens = toParse.Split(new[] { "===" }, StringSplitOptions.None);
foreach (string myHeader in tokens)
{
//If it isn't === then it's your date
if (!String.IsNullOrEmpty(myHeader) && !myHeader.Contains("==="))
myCurrentDate = myHeader;
}
}
else
{
//Else add to entries
ClipBoardEntries.Instance.addEntry(toParse,myCurrentDate);
}
}
//else if empty do nothing and continue
}
private string myCurrentDate = "";
//End
}
}
<file_sep>/CopyPlus/CopyPlus/EntryTypes/EmailEntry.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyPlus.EntryTypes
{
class EmailEntry : Entry
{
public EmailEntry(Entry previous, object data, DateTime date)
{
SetPrevious(previous);
Data = (string)data;
Time = date;
EntryType = Enums.EntryType.Email;
}
}
}
<file_sep>/CopyPlus/CopyPlus/EntryTypes/URLEntry.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CopyPlus.Enums;
namespace CopyPlus.EntryTypes
{
class URLEntry : Entry
{
public URLEntry(Entry Previous, object data, DateTime date)
{
SetPrevious(Previous);
Data = new Uri((string)data);
Time = date;
EntryType = Enums.EntryType.URL;
}
}
}
| afde392868350859b9d628f33cb1168558fd1e6e | [
"C#"
] | 12 | C# | hectoram/CopyHelper | 39f72a599fe1aba7a8c8aa3919ac578c4a13a48c | ade761c2464fbe3f83679950f23f9f8321461a5d |
refs/heads/master | <repo_name>kokihonda/fpga_road_detect<file_sep>/road_detect.cpp
/*
0~30, 180~150の直線を検出できるように書いてみた。
*/
#include "road_detect.h"
#include "hls_math.h"
#define pai 3.1415926
#define angle 60
#define rho 1000
void adptive_threshold(xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &in, xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &out) {
pixel window[3][3];
pixel line_buffer[2][WIDTH];
#pragma HLS array_partition variable=line_buffer complete dim=1
#pragma HLS array_partition variable=window complete dim=0
row_loop: for(int row=0; row < HEIGHT+1; row++) {
col_loop: for(int col=0; col < WIDTH+1; col++) {
#pragma HLS pipeline II=1
pixel p;
if (row < HEIGHT && col < WIDTH) {
p = in.data[row*WIDTH+col];
}
for(int i = 0; i < 3; i++) {
window[i][0] = window[i][1];
window[i][1] = window[i][2];
}
if (col < WIDTH) {
window[0][2] = (line_buffer[0][col]);
window[1][2] = (line_buffer[0][col] = line_buffer[1][col]);
window[2][2] = (line_buffer[1][col] = p);
}
if (row >= 1 && col >= 1) {
int outrow = row - 1;
int outcol = col -1;
if(outrow == 0 || outcol == 0
|| outrow == (HEIGHT - 1) || outcol == (WIDTH - 1)) {
out.data[outrow*WIDTH+outcol] = 0;
} else {
out.data[outrow*WIDTH+outcol] = mean_threshold(window);
}
}
}
}
}
pixel mean_threshold(pixel window[3][3]) {
ap_uint<32>sum=0;
pixel out;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += window[i][j];
}
}
if ((sum - 3*9) > window[1][1]*9) {
out = 255;
} else {
out = 0;
}
return out;
}
void median_blur(xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &in, xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &out) {
pixel window[3][3];
pixel line_buffer[2][WIDTH];
#pragma HLS array_partition variable=line_buffer complete dim=1
#pragma HLS array_partition variable=window complete dim=0
row_loop: for(int row=0; row < HEIGHT+1; row++) {
col_loop: for(int col=0; col < WIDTH+1; col++) {
#pragma HLS pipeline II=1
pixel p;
if (row < HEIGHT && col < WIDTH) {
p = in.data[row*WIDTH+col];
}
for(int i = 0; i < 3; i++) {
window[i][0] = window[i][1];
window[i][1] = window[i][2];
}
if (col < WIDTH) {
window[0][2] = (line_buffer[0][col]);
window[1][2] = (line_buffer[0][col] = line_buffer[1][col]);
window[2][2] = (line_buffer[1][col] = p);
}
if (row >= 1 && col >= 1) {
int outrow = row - 1;
int outcol = col -1;
if(outrow == 0 || outcol == 0 ||
outrow == (HEIGHT - 1) ||
outcol == (WIDTH - 1)) {
out.data[outrow*WIDTH+outcol] = 0;
} else {
out.data[outrow*WIDTH+outcol] = median_filter(window);
}
}
}
}
}
pixel median_filter(pixel window[3][3]) {
v_pixels tmp[3];
#pragma HLS array_partition variable=tmp complete
pixel t0, t1, t2;
pixel out;
for (int i = 0; i < 3; i++) {
#pragma HLS unroll
tmp[i] = sort3(window[0][i], window[1][i], window[2][i]);
}
#pragma HLS DATAFLOW
t0 = min3(tmp[0].upper, tmp[1].upper, tmp[1].upper);
t1 = med(tmp[0].middle, tmp[1].middle, tmp[2].middle);
t2 = max3(tmp[0].bottom, tmp[1].bottom, tmp[2].bottom);
out = med(t0, t1, t2);
return out;
}
v_pixels sort3 (pixel y0, pixel y1, pixel y2) {
pixel t0, t1;
pixel tt1;
pixel out0, out1, out2;
v_pixels out;
if (y0 > y1) {
t0 = y0;
t1 = y1;
} else {
t0 = y1;
t1 = y0;
}
if (t1 > y2) {
tt1 = t1;
out2 = y2;
} else {
tt1 = y2;
out2 = t1;
}
if (t0 > tt1) {
out0 = t0;
out1 = tt1;
} else {
out0 = tt1;
out1 = t0;
}
out.upper = out0;
out.middle = out1;
out.bottom = out2;
return out;
}
pixel min3(pixel x0, pixel x1, pixel x2) {
pixel t1;
pixel out2;
t1 = (x0 < x1) ? x0 : x1;
out2 = (t1 < x2) ? t1 : x2;
return out2;
}
pixel med(pixel x3, pixel x4, pixel x5) {
pixel t3, t4;
pixel tt4;
pixel out4;
if (x3 > x4) {
t3 = x3;
t4 = x4;
} else {
t3 = x4;
t4 = x3;
}
tt4 = (t4 > x5) ? t4 : x5;
out4 = (t3 < tt4) ? t3 : tt4;
return out4;
}
pixel max3(pixel x6, pixel x7, pixel x8) {
pixel t7;
pixel out6;
t7 = (x7 < x8)? x8 : x7;
out6 = (x6 < t7)? t7 : x6;
return out6;
}
void full_accum(xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &in,acc accum[angle][rho]) {
// accuracy cosval[angle/2] = {1.0, 0.9998476951563913, 0.9993908270190958, 0.9986295347545738, 0.9975640502598242, 0.9961946980917455, 0.9945218953682733, 0.992546151641322, 0.9902680687415704, 0.9876883405951378, 0.984807753012208, 0.981627183447664, 0.9781476007338057, 0.9743700647852352, 0.9702957262759965, 0.9659258262890683, 0.9612616959383189, 0.9563047559630354, 0.9510565162951535, 0.9455185755993168, 0.9396926207859084, 0.9335804264972017, 0.9271838545667874, 0.9205048534524404, 0.9135454576426009, 0.9063077870366499, 0.898794046299167, 0.8910065241883679, 0.882947592858927, 0.8746197071393957};
;
// accuracy sinval[angle/2] = {0.0, 0.01745240643728351, 0.03489949670250097, 0.05233595624294383, 0.0697564737441253, 0.08715574274765817, 0.10452846326765346, 0.12186934340514748, 0.13917310096006544, 0.15643446504023087, 0.17364817766693033, 0.1908089953765448, 0.20791169081775931, 0.224951054343865, 0.24192189559966773, 0.25881904510252074, 0.27563735581699916, 0.29237170472273677, 0.3090169943749474, 0.32556815445715664, 0.3420201433256687, 0.35836794954530027, 0.374606593415912, 0.3907311284892737, 0.40673664307580015, 0.42261826174069944, 0.4383711467890774, 0.45399049973954675, 0.4694715627858908, 0.48480962024633706};
;
accuracy cosval[angle/2];
accuracy sinval[angle/2];
#pragma HLS ARRAY_PARTITION variable=sinval complete dim=0
#pragma HLS ARRAY_PARTITION variable=cosval complete dim=0
accuracy Angle_accuracy=pai/180;
acc addr[angle];
acc accbuf[2][angle];
#pragma HLS ARRAY_PARTITION variable=addr complete dim=0
#pragma HLS ARRAY_PARTITION variable=accbuf complete dim=0
ap_fixed<14,13> t1, t2;
for(int i=0;i<angle/2;i++)
{
sinval[i]=::hls::sinf(i*Angle_accuracy);
cosval[i]=::hls::cosf(i*Angle_accuracy);
}
loop_init_r: for(int r=0;r<rho;r++)
{
loop_init_n: for(int n=0;n<angle;n++)
{
#pragma HLS PIPELINE
accum[n][r]=0;
}
}
loop_init: for(int n = 0; n < angle; n++ )
{
addr[n]=0;
accbuf[0][n]=0;
}
loop_height: for( int i = 0; i < HEIGHT; i++ )
{
loop_width: for( int j = 0; j < WIDTH; j++ )
{
#pragma HLS PIPELINE
#pragma HLS DEPENDENCE array inter false
if(in.data[i*WIDTH+j]!=0)
{
loop_angle: for(int n = 0; n < angle/2; n++ )
{
int n2 = n + angle/2;
accbuf[1][n]=accbuf[0][n];
accbuf[1][n2]=accbuf[0][n2];
t1=j*cosval[n]+i*sinval[n];
t2=-j*cosval[n]+i*sinval[n];
acc r1 = t1.range(13,1);
acc r2 = t2.range(13,1)+700;
accbuf[0][n]=accum[n][r1];
accbuf[0][n2]=accum[n2][r2];
if(r1==addr[n])
accbuf[0][n]=accbuf[0][n]+1;
if(r2==addr[n2])
accbuf[0][n2]=accbuf[0][n2]+1;
accum[n][addr[n]]=accbuf[1][n]+1;
accum[n2][addr[n2]]=accbuf[1][n2]+1;
addr[n]=r1;
addr[n2]=r2;
}
}
}
}
loop_exit: for(int n = 0; n < angle/2; n++ )
{
int n2 = n + angle/2;
accum[n][addr[n]]=accbuf[0][n]+1;
accum[n2][addr[n2]]=accbuf[0][n2]+1;
}
}
void axis2xfMat (xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &_src, axis_t *src, int src_rows, int src_cols) {
#pragma HLS inline off
for (int i=0; i<src_rows; i++) {
for (int j=0; j<src_cols; j++) {
#pragma HLS pipeline
#pragma HLS loop_flatten off
_src.data[i*src_cols+j] = src[i*src_cols+j].data;
}
}
}
void xfMat2axis (xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &_dst, axis_t *dst, int dst_rows, int dst_cols) {
#pragma HLS inline off
for (int i=0; i<dst_rows; i++) {
for (int j=0; j<dst_cols; j++) {
#pragma HLS pipeline
#pragma HLS loop_flatten off
ap_uint<1> tmp = 0;
if ((i==dst_rows-1) && (j== dst_cols-1)) {
tmp = 1;
}
dst[i*dst_cols+j].last = tmp;
dst[i*dst_cols+j].data = _dst.data[i*dst_cols+j];
}
}
}
void P_xfMat2axis (acc accum[angle][rho], out_t *dst, int dst_rows, int dst_cols) {
#pragma HLS inline off
for (int i=0; i<dst_rows; i++) {
for (int j=0; j<dst_cols; j++) {
#pragma HLS pipeline
#pragma HLS loop_flatten off
ap_uint<1> tmp = 0;
if ((i==dst_rows-1) && (j== dst_cols-1)) {
tmp = 1;
}
dst[i*dst_cols+j].last = tmp;
dst[i*dst_cols+j].data = accum[i][j];
}
}
}
void hough(axis_t *src, out_t *dst,int src_rows, int src_cols, int dst_rows, int dst_cols) {
#pragma HLS INTERFACE axis port=src depth=384*288 // Added depth for C/RTL cosimulation
#pragma HLS INTERFACE axis port=dst depth=192*144 // Added depth for C/RTL cosimulation
#pragma HLS INTERFACE s_axilite port=src_rows
#pragma HLS INTERFACE s_axilite port=src_cols
#pragma HLS INTERFACE s_axilite port=dst_rows
#pragma HLS INTERFACE s_axilite port=dst_cols
#pragma HLS INTERFACE s_axilite port=return
xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> _src(HEIGHT, WIDTH);
xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> _img0(HEIGHT, WIDTH);
xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> _img1(HEIGHT, WIDTH);
#pragma HLS stream variable=_src.data depth=150
#pragma HLS stream variable=_img0.data depth=150
#pragma HLS stream variable=_img1.data depth=150
acc _accum[angle][rho];
#pragma HLS ARRAY_PARTITION variable= _accum complete dim=1
#pragma HLS dataflow
axis2xfMat(_src, src, HEIGHT, WIDTH);
median_blur(_src, _img0);
adptive_threshold(_img0, _img1);
full_accum(_img1, _accum);
P_xfMat2axis(_accum, dst, angle, rho);
//xfMat2axis(_dst, dst, dst_rows, dst_cols);
//xfMat2axis(_src, dst, dst_rows, dst_cols);
}
<file_sep>/road_detect.h
#ifndef _ROAD_DETECT_COFIG_
#define _ROAD_DETECT_COFIG_
#include "hls_stream.h"
#include "ap_int.h"
#include "common/xf_common.h"
#define NPC1 XF_NPPC1
#define TYPE XF_8UC1
struct axis_t {
ap_uint<8> data;
ap_int<1> last;
};
struct out_t {
ap_uint<16> data;
ap_int<1> last;
};
#define HEIGHT 480
#define WIDTH 640
#define SIZE 9
#define P_HEIGHT 92
#define P_WIDTH 1601
#define P_TYPE XF_8UC1
typedef ap_uint<8> pixel;
typedef ap_fixed<16,2,AP_RND> accuracy;
typedef ap_uint<13> acc;
struct v_pixels {
pixel upper;
pixel middle;
pixel bottom;
};
pixel mean_threshold(pixel window[3][3]);
void adptive_threshold(xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &in, xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &out);
void hough (axis_t *src, axis_t *dst, int src_rows, int src_cols, int dst_rows, int dst_cols);
void median_blur(xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &in, xf::Mat<TYPE, HEIGHT, WIDTH, NPC1> &out);
pixel median_filter(pixel window[3][3]);
pixel median(pixel in[SIZE]);
v_pixels sort3 (pixel y0, pixel y1, pixel y2);
pixel min3(pixel x0, pixel x1, pixel x2);
pixel med(pixel x3, pixel x4, pixel x5);
pixel max3(pixel x6, pixel x7, pixel x8);
#endif
<file_sep>/README.md
# fpga_road_detect
- toy-level FPGA roal detection code written by Vivado HLS.
- the processing consists of three parts: median blur, adaptive threshold, and Hough transformation. find local maximum and sort in Hough transform are processed by Python
- The work was presented in MCSoC 2019. | a99f91c40ad2d530e0a1b222551cb62bedaafbdf | [
"Markdown",
"C",
"C++"
] | 3 | C++ | kokihonda/fpga_road_detect | 15dde3ec1c508cad9e6ad89c6e524a9beda53242 | d17ad72556ae1af58d8493fbe7979f07b7329589 |
refs/heads/master | <file_sep>package com.zhygr.util;
/**
* @author <NAME>
*/
public interface Consts {
String INTENT_KEY_FINISH_ACTIVITY_ON_SAVE_COMPLETED = "finishActivityOnSaveCompleted";
int ADD_CONTACT_REQUEST_CODE = 1000;
}<file_sep>package com.zhygr.datingmanager;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Pair;
import android.view.View;
import android.widget.TextView;
import com.zhygr.datingmanager.R;
import com.zhygr.util.Consts;
import java.util.ArrayList;
public class HomeActivity extends Activity {
//region Lifecycle Events
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Consts.ADD_CONTACT_REQUEST_CODE && resultCode == RESULT_OK) {
//returns a lookup URI to the contact just inserted
Uri newContact = data.getData();
TextView contactNameTextView = (TextView) findViewById(R.id.contactName);
Long groupId = findGirlFriendGroup();
if (groupId != null) {
addContactToGirlfriendGroup(newContact, groupId);
}
}
}
//endregion
//region Event Handlers
public void addContact(View view) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
intent.putExtra(ContactsContract.Intents.EXTRA_FORCE_CREATE, true);
intent.putExtra(Consts.INTENT_KEY_FINISH_ACTIVITY_ON_SAVE_COMPLETED, true);
startActivityForResult(intent, Consts.ADD_CONTACT_REQUEST_CODE);
}
//endregion
//region Helper
/** Finds target group to which we should add given user. */
protected Long findGirlFriendGroup() {
String[] mProjection = {
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE
};
String mSelectionClause = String.format("%s = ?", ContactsContract.Groups.TITLE);
String[] mSelectionArgs = { getResources().getString(R.string.girlfriend_group_name) };
Cursor cursor = getContentResolver().query(
ContactsContract.Groups.CONTENT_URI,
mProjection,
mSelectionClause,
mSelectionArgs,
""
);
if (cursor == null) {
android.util.Log.e("contacts", "Could not access curson while performing lookup for group contact.");
} else {
android.util.Log.e("contacts", "Could not find a girlfriend group");
if (cursor.getCount() > 1) {
cursor.moveToFirst();
return cursor.getLong(0);
}
}
return null;
}
protected void addContactToGirlfriendGroup(Uri contact, Long groupId) {
//first get contact id that will be used to find the raw contact.
Long contactId = getContactId(contact);
Long rawContactId = getRawContactId(contactId);
//update group membership based on raw contact id and group id.
//first we need to check that we don't have existing group assigned to a given contact
}
protected Pair<Boolean, Long> hasExistedGroupMembership(@Nonnull Long rawContactId) {
Cursor c = getContentResolver()
.query(
ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.Data._ID, ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID },
ContactsContract.Data.RAW_CONTACT_ID+" = ? AND "+ContactsContract.Data.MIMETYPE+" = ?",
new String[] { String.valueOf(), },
null
);
}
private Long getContactId(Uri contact) {
return ContentUris.parseId(contact);
}
private Long getRawContactId(Long contactId) {
String[] mProjection = {
ContactsContract.RawContacts._ID
};
String mSelectionClause = String.format("%s = ?", ContactsContract.RawContacts.CONTACT_ID);
String[] mSelectionArgs = { contactId.toString() };
Cursor cursor = getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
mProjection,
mSelectionClause,
mSelectionArgs,
null
);
if (cursor == null) {
android.util.Log.e("contacts", "Could not fetch the raw contact data data.");
} else {
cursor.moveToFirst();
return cursor.getLong(0);
}
return null;
}
//endregion
} | 4b2c6c5b26229d07df1f3aff9352de4fa46383f6 | [
"Java"
] | 2 | Java | zhygr/dating-manager | 539f05e59126b37fe84d3e9ef5bb9019078a2b30 | fa6135b35263594cea5c35aad1abfb55abe17608 |
refs/heads/master | <repo_name>RedCometLabs/couch-viewer<file_sep>/README.md
## Yowzer
Welcome to *Yowzer*, your Couchdb view app to compliment Futon. I love Couchdb, but found Futon a bit limited in functionality.
So I wrote *Yowzer* to add those features.
## Install
npm install -g grunt
npm install
grunt
By default running `grunt` will install Yowzer into your local Couchdb instance. Edit the grunt.js file and change the db path
## Development
`grunt watch` will watch for changes and re-deploy couchdb for quicker development testing
## License
Copyright (c) 2012 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
<file_sep>/grunt.js
/*global module:false*/
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-couchapp');
couch_config = {
yowzer: {
db: 'http://localhost:5984/yowzer',
app: './app.js',
options: {
okay_if_missing: true
}
}
}
// Project configuration.
grunt.initConfig({
watch: {
//files: '<config:lint.files>',
//tasks: 'lint test'
files: ['**/*.html', '**/*.less', '**/*.js'],
tasks: 'less yowzer'
},
less: {
development: {
options: {
// paths: ["assets/css"]
},
files: {
"_attachments/style/main.css": "_attachments/style/main.less"
}
},
},
mkcouchdb: couch_config,
rmcouchdb: couch_config,
couchapp: couch_config
});
grunt.registerTask('yowzer', 'rmcouchdb:yowzer mkcouchdb:yowzer couchapp:yowzer');
grunt.registerTask('default', 'less yowzer');
};
| 175903b8e454d22cba683ef97ecba976fc8a5a02 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | RedCometLabs/couch-viewer | fdd7eedba1ca4496920129e58f5a0a825062555e | 6a081353c5cc69020a57048229ee2978b49933b7 |
refs/heads/master | <repo_name>kaspernj/github_org_reports<file_sep>/models/commit.rb
class GithubOrgReports::Models::Commit < Baza::Model
has_one :User
has_one :PullRequest
has_many [
[:CommitOrganizationLink, :commit_id]
]
def scan
hash = ob.data[:github_org_reports].scan_for_time_and_orgs(self[:text])
#Parse organizations.
hash[:orgs].each do |org|
link = self.ob.get_or_add(:CommitOrganizationLink, {
:organization_id => org.id,
:commit_id => self.id
})
link[:time] = hash[:orgs_time][org.id][:secs]
end
#Parse time.
self[:time] = hash[:secs]
return nil
end
end<file_sep>/spec/github_org_reports_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require "tmpdir"
require "sqlite3"
require "json"
describe "GithubOrgReports" do
it "should be able to fill the database" do
db_path = "#{Dir.tmpdir}/github_org_reports.sqlite3"
db = Baza::Db.new(:type => :sqlite3, :path => db_path, :index_append_table_name => true)
login_info = JSON.parse(File.read("#{File.dirname(__FILE__)}/spec_info.txt").to_s.strip)
begin
gor = GithubOrgReports.new(:db => db)
gor.add_repo GithubOrgReports::Repo.new(:user => "kaspernj", :name => "php4r", :login => login_info["login"], :password => login_info["password"])
gor.add_repo GithubOrgReports::Repo.new(:user => "kaspernj", :name => "github_org_reports", :login => login_info["login"], :password => login_info["password"])
gor.scan
rescue => e
puts e.inspect
puts e.backtrace
raise e
end
end
it "should be able to parse special json strings" do
str = "!{time: 00:30, orgs: [knjit, gfish]}!\n"
str << "!{time: 00:15, orgs: [knjit]}!"
db_path = "#{Dir.tmpdir}/github_org_reports.sqlite3"
db = Baza::Db.new(:type => :sqlite3, :path => db_path, :index_append_table_name => true)
login_info = JSON.parse(File.read("#{File.dirname(__FILE__)}/spec_info.txt").to_s.strip)
begin
gor = GithubOrgReports.new(:db => db)
res = gor.scan_for_time_and_orgs(str)
org_knjit = gor.ob.get_by(:Organization, :name_short => "knjit")
org_gfish = gor.ob.get_by(:Organization, :name_short => "gfish")
res[:orgs_time][org_knjit.id][:secs].should eql(2700)
res[:orgs_time][org_gfish.id][:secs].should eql(1800)
rescue => e
puts e.inspect
puts e.backtrace
raise e
end
end
it "should be able to convert seconds to time strings" do
GithubOrgReports.secs_to_time(1800).should eql("0:30")
GithubOrgReports.secs_to_time(2700).should eql("0:45")
end
end
<file_sep>/models/organization.rb
class GithubOrgReports::Models::Organization < Baza::Model
def name
name_str = self[:name].to_s.strip
name_str = self[:name_short].to_s.strip if name_str.empty?
name_str = "[no name]" if name_str.empty?
return name_str
end
end<file_sep>/lib/github_org_reports.rb
require "rubygems"
require "github_api"
require "baza"
class GithubOrgReports
attr_reader :db, :ob, :repos
def self.const_missing(name)
require "#{File.dirname(__FILE__)}/../include/github_org_reports_#{name.to_s.downcase}.rb"
raise "Still not defined: '#{name}'." unless GithubOrgReports.const_defined?(name)
return GithubOrgReports.const_get(name)
end
def self.secs_to_time(secs)
return "0:00" if secs <= 0
hours = (secs / 3600).floor
secs -= hours * 3600
mins = (secs / 60).floor
secs -= mins * 60
return "#{hours}:#{sprintf("%02d", mins)}"
end
def initialize(args = {})
@args = args
@repos = []
@db = @args[:db]
raise "No ':db' was given." unless @db
Baza::Revision.new.init_db(:db => @db, :schema => GithubOrgReports::Dbschema::SCHEMA)
@ob = Baza::ModelHandler.new(
:db => @db,
:class_path => "#{File.dirname(__FILE__)}/../models",
:class_pre => "",
:module => GithubOrgReports::Models,
:require_all => true
)
@ob.data[:github_org_reports] = self
end
def add_repo(repo)
raise "Invalid class: '#{repo.class.name}'." unless repo.is_a?(GithubOrgReports::Repo)
@repos << repo
end
def self.scan_hash(str)
str.to_s.scan(/!(\{(.+?)\})!/) do |match|
json_str = match[0]
#Fix missing quotes in 'time' and 'orgs' to make it easier to write.
json_str.gsub!(/time:\s*([\d+:]+)/, "\"time\": \"\\1\"")
if orgs_match = json_str.match(/orgs:\s*\[(.+?)\]/)
orgs_str = orgs_match[1]
orgs_str.gsub!(/\s*(^|\s*,\s*)([A-z_\d]+)/, "\\1\"\\2\"")
json_str.gsub!(orgs_match[0], "\"orgs\": [#{orgs_str}]")
end
#Parse the JSON and yield it.
begin
yield JSON.parse(json_str)
rescue JSON::ParserError => e
$stderr.puts e.inspect
#$stderr.puts e.backtrace
end
end
end
def scan
@repos.each do |repo|
@cur_repo = repo
gh_args = {
:user => repo.user,
:repo => repo.name
}
gh_args[:login] = repo.args[:login] unless repo.args[:login].to_s.strip.empty?
gh_args[:password] = repo.args[:password] unless repo.args[:password].to_s.strip.empty?
gh = ::Github.new(gh_args)
commits = gh.repos.commits.all(gh_args)
commits.each do |commit_data|
commit = init_commit_from_data(commit_data)
end
prs = []
gh.pull_requests.list(gh_args.merge(:state => "closed")).each do |pr|
prs << pr
end
gh.pull_requests.list(gh_args.merge(:state => "open")).each do |pr|
prs << pr
end
prs.each do |pr_data|
text = pr_data.body_text
name = pr_data.user.login
raise "Invalid name: '#{name}' (#{pr_data.to_hash})." if !name.is_a?(String)
user = @ob.get_or_add(:User, {
:name => name
})
#puts "PullRequest: #{pr_data.to_hash}"
github_id = pr_data.id.to_i
raise "Invalid github-ID: '#{github_id}'." if github_id <= 0
number = pr_data.number.to_i
raise "Invalid number: '#{number}'." if number <= 0
pr = @ob.get_or_add(:PullRequest, {
:repository_user => @cur_repo.user,
:repository_name => @cur_repo.name,
:github_id => github_id,
:number => number
})
#puts "PullRequest: #{pr_data.to_hash}"
pr[:user_id] = user.id
pr[:title] = pr_data.title
pr[:text] = pr_data.body_text
pr[:html] = pr_data.body_html
pr[:date] = Time.parse(pr_data.created_at)
pr.scan
commits = gh.pull_requests.commits(gh_args.merge(:number => pr_data.number))
commits.each do |commit_data|
commit = init_commit_from_data(commit_data)
commit[:pull_request_id] = pr.id
end
end
end
end
def scan_for_time_and_orgs(str)
res = {:secs => 0, :orgs => [], :orgs_time => {}}
GithubOrgReports.scan_hash(str) do |hash|
#Parse time.
if hash["time"] and match_time = hash["time"].to_s.match(/^(\d{1,2}):(\d{1,2})$/)
secs = 0
secs += match_time[1].to_i * 3600
secs += match_time[2].to_i * 60
#Parse organizations.
if orgs = hash["orgs"]
orgs = [orgs] if !orgs.is_a?(Array)
orgs.each do |org_name_short|
org_name_short_dc = org_name_short.to_s.downcase
next if org_name_short_dc.strip.empty?
raise "Invalid short-name: '#{org_name_short_dc}'." unless org_name_short_dc.match(/^[A-z\d+_]+$/)
org = self.ob.get_or_add(:Organization, {:name_short => org_name_short_dc})
res[:orgs] << org unless res[:orgs].include?(org)
res[:orgs_time][org.id] = {:secs => 0} unless res[:orgs_time].key?(org.id)
res[:orgs_time][org.id][:secs] += secs
end
else
res[:secs] += secs
end
end
end
return res
end
private
def init_commit_from_data(commit_data)
sha = commit_data.sha
raise "Invalid SHA: '#{sha}' (#{commit_data.to_hash})." if sha.to_s.strip.empty?
commit = @ob.get_or_add(:Commit, {
:repository_user => @cur_repo.user,
:repository_name => @cur_repo.name,
:sha => sha
})
raise "Commit didnt get added right '#{commit[:sha]}', '#{sha}'." if sha != commit[:sha]
text = commit_data.commit.message
raise "Invalid text: '#{text}' (#{commit_data.to_hash})." if !text.is_a?(String)
commit[:text] = text
date = Time.parse(commit_data.commit.committer.date)
raise "Invalid date: '#{date}' (#{commit_data.commit.to_hash})" if !date
commit[:date] = date
if commit_data.author
user = @ob.get_or_add(:User, {
:name => commit_data.author.login
})
commit[:user_id] = user.id
else
commit[:user_id] = 0
end
commit.scan
return commit
end
end<file_sep>/include/github_org_reports_models.rb
class GithubOrgReports::Models
end<file_sep>/include/github_org_reports_repo.rb
class GithubOrgReports::Repo
attr_reader :args
def initialize(args)
@args = args
end
def name
return @args[:name]
end
def user
return @args[:user]
end
end<file_sep>/models/user.rb
class GithubOrgReports::Models::User < Baza::Model
end<file_sep>/include/github_org_reports_dbschema.rb
class GithubOrgReports::Dbschema
SCHEMA = {
:tables => {
:Commit => {
:columns => [
{:name => :id, :type => :int, :autoincr => true, :primarykey => true},
{:name => :repository_name, :type => :varchar},
{:name => :repository_user, :type => :varchar},
{:name => :user_id, :type => :int},
{:name => :pull_request_id, :type => :int},
{:name => :sha, :type => :varchar},
{:name => :date, :type => :datetime},
{:name => :text, :type => :text},
{:name => :time, :type => :int}
],
:indexes => [
:repository_name,
:repository_user,
:user_id
]
},
:CommitOrganizationLink => {
:columns => [
{:name => :id, :type => :int, :autoincr => true, :primarykey => true},
{:name => :commit_id, :type => :int},
{:name => :organization_id, :type => :int},
{:name => :time, :type => :int}
],
:indexes => [
:commit_id,
:organization_id
]
},
:Organization => {
:columns => [
{:name => :id, :type => :int, :autoincr => true, :primarykey => true},
{:name => :name, :type => :varchar},
{:name => :name_short, :type => :varchar, :maxlength => 5}
]
},
:User => {
:columns => [
{:name => :id, :type => :int, :autoincr => true, :primarykey => true},
{:name => :name, :type => :varchar}
]
},
:PullRequest => {
:columns => [
{:name => :id, :type => :int, :autoincr => true, :primarykey => true},
{:name => :repository_name, :type => :varchar},
{:name => :repository_user, :type => :varchar},
{:name => :github_id, :type => :int, :renames => [:pull_request_id]},
{:name => :number, :type => :int},
{:name => :user_id, :type => :int},
{:name => :date, :type => :datetime},
{:name => :title, :type => :varchar},
{:name => :text, :type => :text},
{:name => :html, :type => :text},
{:name => :time, :type => :int}
],
:indexes => [
:repository_name,
:repository_user,
:github_id,
:user_id,
:number
]
},
:PullRequestOrganizationLink => {
:columns => [
{:name => :id, :type => :int, :autoincr => true, :primarykey => true},
{:name => :pull_request_id, :type => :int},
{:name => :organization_id, :type => :int},
{:name => :time, :type => :int}
],
:indexes => [
:pull_request_id,
:organization_id
]
}
}
}
end<file_sep>/README.rdoc
= github_org_reports
A gem able to generate organization based statistics based on information given in commits and pull requests.
Example:
1. Make some commits that contains information like this:
My commit message.
!{time: '00:30', orgs: [org1, org3]}!
2. Run a small scripts that uses the gem:
require "rubygems"
require "github_org_reports"
db = Baza::Db.new(...) #See "baza" for this part.
gor = GithubOrgReports.new(:db => db)
gor.add_repo GithubOrgReports::Repo.new(:user => "username", :name => "reponame", :login => "your_username", :password => "<PASSWORD>")
gor.scan
3. You can now go through the database to get the various time-information.
== Contributing to github_org_reports
* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
* Fork the project.
* Start a feature/bugfix branch.
* Commit and push until you are happy with your contribution.
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
== Copyright
Copyright (c) 2013 kaspernj. See LICENSE.txt for
further details.
<file_sep>/models/pull_request_organization_link.rb
class GithubOrgReports::Models::PullRequestOrganizationLink < Baza::Model
has_one :Organization
has_one :PullRequest
end<file_sep>/models/pull_request.rb
class GithubOrgReports::Models::PullRequest < Baza::Model
has_many [
[:PullRequestOrganizationLink, :pull_request_id],
[:Commit, :pull_request_id]
]
def scan
hash = ob.data[:github_org_reports].scan_for_time_and_orgs(self[:text])
#Parse organizations.
hash[:orgs].each do |org|
link = self.ob.get_or_add(:PullRequestOrganizationLink, {
:organization_id => org.id,
:pull_request_id => self.id,
})
link[:time] = hash[:orgs_time][org.id][:secs]
end
#Parse time.
self[:time] = hash[:secs]
return nil
end
def total_time_for_org(args)
org = args[:org]
raise "No ':org' was given." if !org
#Collect shared time.
secs = self[:time].to_i
#Collect time for the pull-request-organization-links.
self.pull_request_organization_links(:organization_id => org.id) do |prol|
secs += prol[:time].to_i
end
#Collect time from commits.
self.commits do |commit|
secs += commit[:time].to_i
commit.commit_organization_links(:organization_id => org.id) do |col|
secs += col[:time].to_i
end
end
return secs
end
def title(args = nil)
title_str = self[:title].to_s.strip
title_str = self[:text].to_s.lines.first.to_s.strip if title_str.empty?
mlength = (args && args[:maxlength]) ? args[:maxlength] : 15
if title_str.length > mlength
title_str = title_str.slice(0, mlength).strip
title_str << "..."
end
title_str = "[no title]" if title_str.empty?
return title_str
end
end<file_sep>/models/commit_organization_link.rb
class GithubOrgReports::Models::CommitOrganizationLink < Baza::Model
has_one :Organization
has_one :Commit
end | 697809b114a0234237c98d62a29b7e4ea5687f8e | [
"RDoc",
"Ruby"
] | 12 | Ruby | kaspernj/github_org_reports | 35e47529b9131691ddd0bb81a1f654ec42bf07ce | 5df43d5c9b693a159c9e33a53393c6327494b4b8 |
refs/heads/master | <repo_name>summonholmes/hmm-pandas<file_sep>/viterbi_pandas.py
from pandas import DataFrame, IndexSlice
from seaborn import light_palette
# Initialize tuples of conditions. Observations are the input
observations = ( # Modify, add, remove with any key in emit_prob_df
"Wearing Trenchcoat & Fedora", "Browsing Reddit", "Drinking Mountain Dew",
"Eating Doritos", "Eating Pizza")
hidden_states = ("Depressed", "Confident", "Tired", "Hungry",
"Thirsty") # The confounding factors
# Probability of transition
trans_prob_df = DataFrame(
data={ # From depressed to confident, vice-versa, static, etc.
"Depressed": (0.20, 0.25, 0.10, 0.20, 0.20),
"Confident": (0.15, 0.25, 0.10, 0.20, 0.25),
"Tired": (0.25, 0.10, 0.30, 0.10, 0.15),
"Hungry": (0.20, 0.20, 0.25, 0.30, 0.30),
"Thirsty": (0.20, 0.20, 0.25, 0.20, 0.10)
}, # All should vertically sum to 1
columns=("Depressed", "Confident", "Tired", "Hungry", "Thirsty"),
index=hidden_states)
# Probability of observation given the hidden state
emit_prob_df = DataFrame(
data={ # Highest chance of trenchcoat & fedora is when confident
"Eating Pizza": (0.20, 0.10, 0.10, 0.35, 0.20),
"Browsing Reddit": (0.20, 0.10, 0.35, 0.10, 0.20),
"Drinking Mountain Dew": (0.30, 0.10, 0.30, 0.20, 0.30),
"Eating Doritos": (0.20, 0.10, 0.15, 0.15, 0.15),
"Wearing Trenchcoat & Fedora": (0.10, 0.60, 0.10, 0.20, 0.15),
}, # All should vertically sum to 1
columns=("Eating Pizza", "Browsing Reddit", "Drinking Mountain Dew",
"Eating Doritos", "Wearing Trenchcoat & Fedora"),
index=hidden_states)
# Initialize starting probabilities
start_probs = DataFrame(
data={"(0) {}".format(observations[0]): (0.10, 0.40, 0.10, 0.20, 0.20)},
index=hidden_states)
# Initialize dynammic programming matrix at probability 0
viterbi_df = start_probs.multiply(emit_prob_df[observations[0]], axis="index")
# Start dynammic programming
for i, observation in enumerate(observations[1:]):
max_trans_prob_df = trans_prob_df.multiply( # Offset by 1
viterbi_df.iloc[:, i], axis="index").max()
# Multiply entire trans_prob df by previous viterbi_df
# column and take vertical maximums
viterbi_df["({}) {}".format(
i + 1, # Then multiply the result by the observation emissions
observation)] = max_trans_prob_df * emit_prob_df.loc[:, observation]
# Provide the entire matrix with highest values darkest
viterbi_traceback_df = viterbi_df.style.background_gradient(
cmap=light_palette("green", as_cmap=True))
# At the last column, use the maximum value to begin traceback
traceback_prob = [viterbi_df.iloc[:, -1].max()]
dyn_prog_path = [viterbi_df.iloc[:, -1].idxmax()] # And its index
viterbi_traceback_df.highlight_max( # Highlight it
color="red", subset=IndexSlice[[viterbi_df.columns[-1]]])
# Start traceback
for i, observation in zip( # Reverse enumerate with offset
range(len(observations) - 2, -1, -1), reversed(observations[1:])):
# Isolate the previous location that gives the current probability
traceback_loc = viterbi_df.loc[ # Always going left-most
viterbi_df.iloc[:, i] * trans_prob_df.loc[:, dyn_prog_path[0]] *
emit_prob_df.loc[dyn_prog_path[0], observation] == traceback_prob[
0]].index[0]
# Record the value and its state
traceback_prob.insert(0,
viterbi_df.loc[traceback_loc, viterbi_df.columns[i]])
dyn_prog_path.insert(0, traceback_loc)
viterbi_traceback_df = viterbi_traceback_df.applymap(
lambda x: "background-color: red", # Color the path red
subset=IndexSlice[[dyn_prog_path[0]], [viterbi_df.columns[i]]])
# Print dynammic programming matrix and traceback results
print("The observations:", ", ".join(observations))
print("The most likely sequence of hidden states is:")
print((viterbi_df.isin(traceback_prob)).idxmax())
print("The final probability:", traceback_prob[-1])
viterbi_traceback_df
<file_sep>/viterbi_pandas_adv.py
from pandas import DataFrame, IndexSlice
from seaborn import light_palette
# Initialize tuples of conditions. Observations are the input
observations = ("Wearing Trenchcoat & Fedora", "Eating Pizza",
"Eating Doritos", "Browsing Reddit", "Playing WoW", "Smelly",
"Vaping", "Listening to Power Metal", "Brandishing Katana",
"Wearing Trenchcoat & Fedora", "Browsing 4chan",
"Playing Magic the Gathering", "Drinking Mountain Dew")
hidden_states = ("Depressed", "Confident", "Tired", "Hungry", "Thirsty",
"Angry", "Gamer", "Brony", "Libertarian", "Atheist")
emit_states = ("Eating Pizza", "Browsing Reddit", "Drinking Mountain Dew",
"Eating Doritos", "Wearing Trenchcoat & Fedora",
"Browsing 4chan", "Playing Magic the Gathering", "Playing WoW",
"Brandishing Katana", "Watching My Little Pony",
"Listening to Power Metal", "Vaping", "Smelly")
# Probability of transition from state to state, remaining static, etc.
trans_prob_df = DataFrame(
data={
"Depressed": (0.10, 0.10, 0.10, 0.15, 0.05, 0.15, 0.05, 0.05, 0.05,
0.05),
"Confident": (0.05, 0.05, 0.05, 0.10, 0.10, 0.15, 0.05, 0.15, 0.10,
0.10),
"Tired": (0.15, 0.05, 0.05, 0.05, 0.05, 0.05, 0.10, 0.05, 0.05, 0.05),
"Hungry": (0.15, 0.05, 0.10, 0.15, 0.10, 0.05, 0.05, 0.05, 0.05, 0.05),
"Thirsty": (0.10, 0.15, 0.15, 0.10, 0.10, 0.05, 0.05, 0.10, 0.05,
0.05),
"Angry": (0.05, 0.10, 0.15, 0.05, 0.15, 0.15, 0.15, 0.05, 0.15, 0.15),
"Gamer": (0.10, 0.10, 0.10, 0.10, 0.15, 0.10, 0.20, 0.15, 0.05, 0.05),
"Brony": (0.10, 0.10, 0.10, 0.10, 0.10, 0.10, 0.15, 0.30, 0.05, 0.05),
"Libertarian": (0.10, 0.15, 0.10, 0.10, 0.10, 0.10, 0.10, 0.05, 0.30,
0.15),
"Atheist": (0.10, 0.15, 0.10, 0.10, 0.10, 0.10, 0.10, 0.05, 0.15, 0.30)
},
columns=hidden_states,
index=hidden_states) # All should vertically sum to 1
# Probability of observation given the hidden state
emit_prob_df = DataFrame(
data={
"Eating Pizza": (0.10, 0.05, 0.05, 0.20, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05),
"Browsing Reddit": (0.10, 0.05, 0.10, 0.05, 0.05, 0.05, 0.05, 0.05,
0.15, 0.15),
"Drinking Mountain Dew": (0.10, 0.10, 0.15, 0.10, 0.20, 0.05, 0.15,
0.05, 0.05, 0.05),
"Eating Doritos": (0.10, 0.05, 0.05, 0.15, 0.10, 0.05, 0.10, 0.05,
0.05, 0.05),
"Wearing Trenchcoat & Fedora": (0.05, 0.20, 0.05, 0.05, 0.05, 0.05,
0.05, 0.10, 0.10, 0.10),
"Browsing 4chan": (0.10, 0.05, 0.10, 0.05, 0.05, 0.05, 0.05, 0.10,
0.05, 0.05),
"Playing Magic the Gathering": (0.05, 0.05, 0.05, 0.05, 0.05, 0.10,
0.15, 0.05, 0.05, 0.05),
"Playing WoW": (0.05, 0.05, 0.05, 0.05, 0.05, 0.10, 0.15, 0.05, 0.05,
0.05),
"<NAME>": (0.05, 0.10, 0.05, 0.05, 0.05, 0.10, 0.05, 0.05,
0.15, 0.15),
"Watching My Little Pony": (0.05, 0.05, 0.10, 0.05, 0.05, 0.05, 0.05,
0.25, 0.05, 0.10),
"Listening to Power Metal": (0.05, 0.05, 0.05, 0.05, 0.10, 0.15, 0.05,
0.05, 0.05, 0.10),
"Vaping": (0.05, 0.10, 0.05, 0.05, 0.10, 0.05, 0.05, 0.05, 0.10, 0.05),
"Smelly": (0.15, 0.10, 0.15, 0.10, 0.10, 0.15, 0.05, 0.10, 0.10, 0.05)
},
columns=emit_states,
index=hidden_states) # All should vertically sum to 1
# Initialize starting probabilities
start_probs = DataFrame(
data={
"(0) {}".format(observations[0]): (0.10, 0.10, 0.10, 0.15, 0.10, 0.10,
0.15, 0.10, 0.05, 0.05)
},
index=hidden_states)
# Initialize dynammic programming matrix at probability 0
viterbi_df = start_probs.multiply(emit_prob_df[observations[0]], axis="index")
# Start dynammic programming
for i, observation in enumerate(observations[1:]):
max_trans_prob_df = trans_prob_df.multiply( # Offset by 1
viterbi_df.iloc[:, i], axis="index").max()
# Multiply entire trans_prob df by previous viterbi_df
# column and take vertical maximums
viterbi_df["({}) {}".format(
i + 1, # Then multiply the result by the observation emissions
observation)] = max_trans_prob_df * emit_prob_df.loc[:, observation]
# Provide the entire matrix with highest values darkest
viterbi_traceback_df = viterbi_df.style.background_gradient(
cmap=light_palette("green", as_cmap=True))
# At the last column, use the maximum value to begin traceback
traceback_prob = [viterbi_df.iloc[:, -1].max()]
dyn_prog_path = [viterbi_df.iloc[:, -1].idxmax()] # And its index
viterbi_traceback_df.highlight_max( # Highlight it
color="red", subset=IndexSlice[[viterbi_df.columns[-1]]])
# Start traceback
for i, observation in zip( # Reverse enumerate with offset
range(len(observations) - 2, -1, -1), reversed(observations[1:])):
# Isolate the previous location that gives the current probability
traceback_loc = viterbi_df.loc[ # Always going left-most
viterbi_df.iloc[:, i] * trans_prob_df.loc[:, dyn_prog_path[0]] *
emit_prob_df.loc[dyn_prog_path[0], observation] == traceback_prob[
0]].index[0]
# Record the value and its state
traceback_prob.insert(0,
viterbi_df.loc[traceback_loc, viterbi_df.columns[i]])
dyn_prog_path.insert(0, traceback_loc)
viterbi_traceback_df = viterbi_traceback_df.applymap(
lambda x: "background-color: red", # Color the path red
subset=IndexSlice[[dyn_prog_path[0]], [viterbi_df.columns[i]]])
# Print dynammic programming matrix and traceback results
print("The observations:", ", ".join(observations))
print("The sequence of hidden states is most likely:")
print((viterbi_df.isin(traceback_prob)).idxmax())
print("The final probability:", traceback_prob[-1])
viterbi_traceback_df
<file_sep>/README.md
# hmm-pandas
Regarding the Hidden Markov Model (HMM) and its algorithms, much of the research, materials, and implementations are mathematically convoluted. This project presents the HMM and its algorithms using Pandas dataframes. The objectives of this project are to demonstrate the HMM using a simple, sane Python implementation; to make the HMM understandable to anyone; to create visually appealing representations; and to improve the performance of existing implementations. In addition, detailed comments are provided throughout the code.
## Viterbi

## Forward-Backward

For the Viterbi and Forward-Backward algorithms, a set of observations and hidden states are defined. The observations describe your average programmer and his outward appearance. What is the programmer wearing, eating, or drinking? The hidden states describe how the programmer is feeling. Does the programmer have a high and mighty attitude? When provided a sequence of observations, the 'viterbi_pandas.py' script will predict the most likely sequence of hidden states for the programmer, while the 'forward_backward_pandas.py' script will calculate the posterior marginals for all hidden states. Need more verbosity? Use the 'adv' versions!
Unlike previous implementations, this project utilizes a vectorized approach towards dynamic programming. Therefore, the scripts run much faster and more efficiently than implementations that loop continuously. The only source of iteration is the sequence of observations.
## Getting Started
This project requires few dependences and should be trivial to set up. However, an in-depth understanding of the HMM and its associated algorithms requires some knowledge of probability theory, data science, and dynamic programming.
## Notes
Occassionally, there may be ties that occur during the dynamic programming process. Pandas selects the upper-most value in the column to determine the tie breaking hidden state.
### Dependencies
* python3-pandas
* python3-seaborn
### Usage:
I'd recommend using these scripts interactively with Jupyter Notebook via VSCode, Atom's Hydrogen, Sublime's Hermes, Pycharm, or your web browser. Spyder and/or IPython will also work. Do not use standard Python.
<file_sep>/forward_backward_pandas_adv.py
from pandas import DataFrame
from itertools import cycle
# Initialize tuples of conditions. Observations are the input
observations = ("Wearing Trenchcoat & Fedora", "Eating Pizza",
"Eating Doritos", "Browsing Reddit", "Playing WoW", "Smelly",
"Vaping", "Listening to Power Metal", "Brandishing Katana",
"Wearing Trenchcoat & Fedora", "Browsing 4chan",
"Playing Magic the Gathering", "Drinking Mountain Dew")
hidden_states = ("Depressed", "Confident", "Tired", "Hungry", "Thirsty",
"Angry", "Gamer", "Brony", "Libertarian", "Atheist", "End")
emit_states = ("Eating Pizza", "Browsing Reddit", "Drinking Mountain Dew",
"Eating Doritos", "Wearing Trenchcoat & Fedora",
"Browsing 4chan", "Playing Magic the Gathering", "Playing WoW",
"Brandishing Katana", "Watching My Little Pony",
"Listening to Power Metal", "Vaping", "Smelly")
# Color pattern for final output
colors = cycle(["red", "orange", "green", "blue", "purple"]) # Rainbow effect
colors_dict = {} # Each observation gets a color
# Probability of transition from state to state, remaining static, etc.
trans_prob_df = DataFrame(
data={
"Depressed": (0.10, 0.10, 0.10, 0.15, 0.05, 0.15, 0.05, 0.05, 0.05,
0.05),
"Confident": (0.05, 0.05, 0.05, 0.10, 0.10, 0.14, 0.05, 0.15, 0.10,
0.10),
"Tired": (0.15, 0.05, 0.05, 0.05, 0.05, 0.05, 0.10, 0.05, 0.05, 0.05),
"Hungry": (0.14, 0.05, 0.10, 0.14, 0.10, 0.05, 0.05, 0.05, 0.05, 0.05),
"Thirsty": (0.10, 0.14, 0.15, 0.10, 0.10, 0.05, 0.05, 0.10, 0.05,
0.05),
"Angry": (0.05, 0.10, 0.14, 0.05, 0.15, 0.15, 0.15, 0.05, 0.15, 0.15),
"Gamer": (0.10, 0.10, 0.10, 0.10, 0.14, 0.10, 0.19, 0.15, 0.05, 0.05),
"Brony": (0.10, 0.10, 0.10, 0.10, 0.10, 0.10, 0.15, 0.29, 0.05, 0.05),
"Libertarian": (0.10, 0.15, 0.10, 0.10, 0.10, 0.10, 0.10, 0.05, 0.29,
0.15),
"Atheist": (0.10, 0.15, 0.10, 0.10, 0.10, 0.10, 0.10, 0.05, 0.15,
0.29),
"End": (0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01)
},
columns=hidden_states,
index=hidden_states[:-1]) # All should vertically sum to 1
# Probability of observation given the hidden state
emit_prob_df = DataFrame(
data={
"Eating Pizza": (0.10, 0.05, 0.05, 0.20, 0.05, 0.05, 0.05, 0.05, 0.05,
0.05),
"Browsing Reddit": (0.10, 0.05, 0.10, 0.05, 0.05, 0.05, 0.05, 0.05,
0.15, 0.15),
"Drinking Mountain Dew": (0.10, 0.10, 0.15, 0.10, 0.20, 0.05, 0.15,
0.05, 0.05, 0.05),
"Eating Doritos": (0.10, 0.05, 0.05, 0.15, 0.10, 0.05, 0.10, 0.05,
0.05, 0.05),
"Wearing Trenchcoat & Fedora": (0.05, 0.20, 0.05, 0.05, 0.05, 0.05,
0.05, 0.10, 0.10, 0.10),
"Browsing 4chan": (0.10, 0.05, 0.10, 0.05, 0.05, 0.05, 0.05, 0.10,
0.05, 0.05),
"Playing Magic the Gathering": (0.05, 0.05, 0.05, 0.05, 0.05, 0.10,
0.15, 0.05, 0.05, 0.05),
"Playing WoW": (0.05, 0.05, 0.05, 0.05, 0.05, 0.10, 0.15, 0.05, 0.05,
0.05),
"<NAME>": (0.05, 0.10, 0.05, 0.05, 0.05, 0.10, 0.05, 0.05,
0.15, 0.15),
"Watching My Little Pony": (0.05, 0.05, 0.10, 0.05, 0.05, 0.05, 0.05,
0.25, 0.05, 0.10),
"Listening to Power Metal": (0.05, 0.05, 0.05, 0.05, 0.10, 0.15, 0.05,
0.05, 0.05, 0.10),
"Vaping": (0.05, 0.10, 0.05, 0.05, 0.10, 0.05, 0.05, 0.05, 0.10, 0.05),
"Smelly": (0.15, 0.10, 0.15, 0.10, 0.10, 0.15, 0.05, 0.10, 0.10, 0.05)
},
columns=emit_states,
index=hidden_states[:-1]) # All should vertically sum to 1
# Initialize starting probabilities
start_probs = DataFrame(
data={
"(0) {}".format(observations[0]): (0.10, 0.10, 0.10, 0.15, 0.10, 0.10,
0.15, 0.10, 0.05, 0.05)
},
index=hidden_states[:-1])
# Initialize forward dataframe
forward_df = start_probs.multiply(emit_prob_df[observations[0]], axis="index")
colors_dict[forward_df.columns[0]] = next(colors) # For final colored output
# Start forward part - 1st pass
for i, observation in enumerate(observations[1:]): # Same as viterbi
previous_forward_sum = trans_prob_df.iloc[:, :-1].multiply(
forward_df.iloc[:, i], axis="index").sum()
forward_df["({}) {}".format(
i + 1, # Similar to Viterbi but sum, line below is identical
observation)] = previous_forward_sum * emit_prob_df.loc[:, observation]
colors_dict[forward_df.columns[i + 1]] = next(colors) # Update colors
# Calculate forward probability
# Multiply last columns and sum the result
forward_prob = (forward_df.iloc[:, -1] * trans_prob_df.iloc[:, -1]).sum()
# Initialize backward dataframe
backward_df = DataFrame(
data={ # The last column of trans_prob_df
"({}) {}".format(len(observations) - 1, observations[-1]):
trans_prob_df.iloc[:, -1]
})
# Start backward part - 2nd pass
for i, observation in zip( # Same as viterbi
range(len(observations) - 2, -1, -1), reversed(observations[1:])):
backward_df.insert( # Countdown to 2nd observation
0, # The left-most column updates itself by multiplying
# The entire trans_prob_df and emit_prob_df that matches observation
"({}) {}".format(i, observations[i]),
(backward_df.iloc[:, 0] * trans_prob_df.iloc[:, :-1] *
emit_prob_df.loc[:, observation]).sum(axis=1)) # Horizontal sum
# Calculate backward probability: Should == forward probability
# Now use beginning values, opposite of forward
backward_prob = (backward_df.iloc[:, 0] * start_probs.iloc[:, 0] *
emit_prob_df.loc[:, observations[0]]).sum()
# Now merge the two - vectorized multiplication of all and divide by either
# forward or backward probability
posterior_df = (forward_df * backward_df) / forward_prob
# Stylized output for reading top-down
posterior_df_style = posterior_df.style.apply( # Color the columns
lambda x: ["background-color: {}".format(colors_dict[x.name])] * len(x))
# Print final results - table should vertically sum to 1
print("The observations:", ", ".join(observations))
print("The most likely non-sequential hidden states are:")
print(posterior_df.idxmax())
print("The summed forward & backward probabilities: ", forward_prob, ",",
backward_prob)
posterior_df_style.highlight_max(color="black") # Highlight maximums
| 4f51b942f82dd69231e6edbee4509b0891ae012e | [
"Markdown",
"Python"
] | 4 | Python | summonholmes/hmm-pandas | 9f0e0db21bae57958980fa63670b9b77f109f3ca | 1bb751bed95d14631229f923be2606b3250a859e |
refs/heads/master | <repo_name>matthv/multi-k8s<file_sep>/deploy.sh
docker build -t matthv/multi-client:latest -t matthv/multi-client:$SHA -f ./client/Dockerfile ./client
docker build -t matthv/multi-server:latest -t matthv/multi-server:$SHA -f ./server/Dockerfile ./server
docker build -t matthv/multi-worker:latest -t matthv/multi-worker:$SHA -f ./worker/Dockerfile ./worker
docker push matthv/multi-client:latest
docker push matthv/multi-server:latest
docker push matthv/multi-worker:latest
docker push matthv/multi-client:$SHA
docker push matthv/multi-server:$SHA
docker push matthv/multi-worker:$SHA
kubectl apply -f k8s
kubectl set image deployments/server-deployment server=matthv/multi-server:$SHA
kubectl set image deployments/client-deployment client=matthv/multi-client:$SHA
kubectl set image deployments/worker-deployment worker=matthv/multi-worker:$SHA
| c3a7074e3afa3af12f609b06c7f11f1312db4e0b | [
"Shell"
] | 1 | Shell | matthv/multi-k8s | 70fcfbea49d156de410666377f3e66ab46db20f2 | 9b064eadcbd71520bb569dfcf37d252ef56bf95a |
refs/heads/master | <file_sep>import { routerRedux } from 'dva/router';
import { message } from 'antd';
import { fakeSubmitForm } from '@/services/api';
export default {
namespace: 'form',
state: {
step: {
payAccount: '<EMAIL>',
receiverAccount: '<EMAIL>',
receiverName: 'Alex',
amount: '500',
},
},
effects: {
*submitRegularForm({ payload }, { call, put }) {
yield call(fakeSubmitForm, payload);
// Login successfully
// if (response.status === 200) {
// const urlParams = new URL(window.location.href); // current URL
// const params = getPageQuery();
// let { redirect } = params;
// if (redirect) {
// const redirectUrlParams = new URL(redirect);
// if (redirectUrlParams.origin === urlParams.origin) {
// redirect = redirect.substr(urlParams.origin.length);
// if (redirect.startsWith('/#')) {
// redirect = redirect.substr(2);
// }
// } else {
// window.location.href = redirect;
// return;
// }
// }
// yield put(routerRedux.replace(redirect || '/'));
yield put(routerRedux.push('/result/success'));
// }
},
*submitStepForm({ payload }, { call, put }) {
yield call(fakeSubmitForm, payload);
yield put({
type: 'saveStepFormData',
payload,
});
yield put(routerRedux.push('/form/payment/result'));
},
*submitAdvancedForm({ payload }, { call }) {
yield call(fakeSubmitForm, payload);
message.success('提交成功');
},
},
reducers: {
saveStepFormData(state, { payload }) {
return {
...state,
step: {
...state.step,
...payload,
},
};
},
},
};
<file_sep>module.exports = {
API_BASE_URL: 'http://localhost:5000',
COPY_RIGHT: '2018 太乙数据',
};
<file_sep>import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, DatePicker, Button, Card, Icon, Upload } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import Exception403 from '@/pages/Exception/403';
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
@connect(({ loading }) => ({
submitting: loading.effects['form/submitRegularForm'],
}))
@Form.create()
class BasicForms extends PureComponent {
handleSubmit = e => {
const { dispatch, form } = this.props;
e.preventDefault();
form.validateFieldsAndScroll((err, values) => {
if (!err) {
dispatch({
type: 'form/submitRegularForm',
payload: values,
});
}
});
};
normFile = e => {
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
};
render() {
const { submitting } = this.props;
const {
form: { getFieldDecorator },
} = this.props; // what exactly is this.props???
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 7 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 12 },
md: { span: 10 },
},
};
const submitFormLayout = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 10, offset: 7 },
},
};
return (
<PageHeaderWrapper title="上传数据" content="请上传本月数据 (csv格式)">
<Authorized authority="PaidUser" noMatch={<Exception403 />}>
<Card bordered={false}>
<Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
<FormItem {...formItemLayout} label="文件">
{getFieldDecorator('upload', {
valuePropName: 'fileList',
getValueFromEvent: this.normFile,
})(
<Upload name="logo" action="/upload.do" listType="picture">
<Button>
<Icon type="upload" /> 导入
</Button>
</Upload>
)}
</FormItem>
<FormItem {...formItemLayout} label="起止日期">
{getFieldDecorator('date', {
rules: [
{
required: false,
message: '请选择起止日期',
},
],
})(
<RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} />
)}
</FormItem>
<FormItem {...formItemLayout} label="文件描述">
{getFieldDecorator('goal', {
rules: [
{
required: false,
message: '简要描述文件',
},
],
})(
<TextArea style={{ minHeight: 32 }} placeholder="请简要描述上传文件" rows={4} />
)}
</FormItem>
<FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
<Button type="primary" htmlType="submit" loading={submitting}>
提交
</Button>
<Button style={{ marginLeft: 8 }}>保存</Button>
</FormItem>
</Form>
</Card>
</Authorized>
</PageHeaderWrapper>
);
}
}
export default BasicForms;
<file_sep>import request from '@/utils/request';
export async function query() {
return request('/api/users');
}
export async function queryCurrent() {
return request('http://127.0.0.1:5000/api/user/me');
}
<file_sep>import React, { Fragment } from 'react';
import { Icon } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
import { COPY_RIGHT } from '@/constants';
const GlobalFooter = ({ className }) => {
const clsString = classNames(styles.globalFooter, className);
const links = [
{
key: 'help',
title: '帮助',
href: '',
},
{
key: 'privacy',
title: '隐私',
href: '',
},
{
key: 'terms',
title: '条款',
href: '',
},
];
const copyright = (
<Fragment>
Copyright <Icon type="copyright" /> {COPY_RIGHT}
</Fragment>
);
return (
<div className={clsString}>
{links && ( // Logical &&
<div className={styles.links}>
{links.map(link => (
<a
key={link.key}
title={link.key}
target={link.blankTarget ? '_blank' : '_self'}
href={link.href}
>
{link.title}
</a>
))}
</div>
)}
{copyright && <div className={styles.copyright}>{copyright}</div>}
</div>
);
};
export default GlobalFooter;
| 9787f073a3212bb58154ffbb613bb03aeb7110d1 | [
"JavaScript"
] | 5 | JavaScript | yuanpan102/ant-design-pro | 602f2300d145c47b2e46ce047d28713b39fc3506 | dd1d2921318c51f96118318ba2ba4f62e72b0510 |
refs/heads/master | <file_sep>import vk
import requests
from settings import APP_ID
from getpass import getpass
def get_user_login():
return input('Login: ')
def get_user_password():
return getpass('Password: ')
def fetch_online_friends(login, password):
try:
session = vk.AuthSession(
app_id=APP_ID,
user_login=login,
user_password=<PASSWORD>,
scope = 2
)
api = vk.API(session, v='5.78')
friends_online_ids = api.friends.getOnline()
friends_online_data = api.users.get(
user_ids = friends_online_ids,
lang = 3
)
friends_online_data = friends_online_data
except requests.exceptions.RequestException:
friends_online_data = None
except vk.exceptions.VkAuthError:
friends_online_data = []
return friends_online_data
def show_online_friends(friends_online_data):
print('\nOnline:\n')
for count, friend_online_data in enumerate(friends_online_data):
print('{}.{} {}'.format(
count,
friend_online_data['first_name'],
friend_online_data['last_name']
))
if __name__ == '__main__':
login = get_user_login()
password = <PASSWORD>()
friends_online_data = fetch_online_friends(login, password)
if friends_online_data:
show_online_friends(friends_online_data)
elif friends_online_data is None:
print('\nConnection error.')
# elif not friends_online_data:
# print('\nAuthorization error (incorrect password).')
<file_sep># Watcher of Friends Online
The program shows in CLI a list of your VK friends who are now online.
# How to Install
Python 3 should be already installed.
Then use pip (or pip3 if there is a conflict with old Python 2 setup) to install dependencies:
```pip install -r requirements.txt```. Alternatively try ```pip3```.
Remember, it is recommended to use virtualenv/venv for better isolation.
Run program in CLI by ```python 8_vk_friends_online.py``` and enter your VK login and password (password is hidden).
# Example of Script Launch
```
Y(env) C:\projects\devman\new\vk_online>python vk_friends_online.py
Login: <EMAIL>
Password:
Online:
0.<NAME>
1.<NAME>
2.<NAME>
3.<NAME>
4.<NAME>
5.<NAME>
6.<NAME>
7.<NAME>
8.<NAME>
9.<NAME>
10.<NAME>
11.<NAME>
12.<NAME>
13.<NAME>
14.<NAME>
```
# Project Goals
The code is written for educational purposes. Training course for web-developers - DEVMAN.org
| f0439dbdb4dd832842cf0191208f69694d348dd0 | [
"Markdown",
"Python"
] | 2 | Python | p-well/vk_online | 83e700af4003776375b3286ed3de9e21126b46cd | 91483aa7faf5b986c8c3bea2df58db7874f6e09d |
refs/heads/master | <repo_name>srujithanune/Playground<file_sep>/Amoeba multiplication/Main.java
#include<iostream>
using namespace std;
int main()
{
int n,i=2;;
std::cin>>n;
int arr[100];
arr[0]=0,arr[1]=1;
while(i<=n)
{
arr[i]=arr[i-1]+arr[i-2];
i++;
}
std::cout<<arr[n-1];
}<file_sep>/Series IV/Main.java
#include<iostream>
using namespace std;
int main()
{
int n;
std::cin>>n;
int arr[n],i,f=2;
arr[0]=0;
for(i=1;i<n;i++)
{
arr[i]=arr[i-1]+f;
if(i%2!=0)
f=f+4;
}
for(i=0;i<n;i++)
{
std::cout<<arr[i]<<" ";
}
}<file_sep>/Fibonacci series/Main.java
#include <stdio.h>
int main()
{
int n,min=0,max=1,sum,i=2;
scanf("%d",&n);
printf("%d ",min);
while(i<=n)
{
sum=min+max;
min=max;
max=sum;
printf("%d ",min);
i++;
}
}<file_sep>/Factorial of a number/Main.java
#include<iostream>
int main(){
int n;std::cin>>n;
int fact=1,i;
for(i=1;i<=n;i++)
fact*=i;
std::cout<<fact;
}<file_sep>/Change the case of alphabet/Main.java
#include <stdio.h>
#include<ctype.h>
int main()
{
char ch;
scanf("%c",&ch);
if(islower(ch))
printf("%c",toupper(ch));
else
printf("%c",tolower(ch));
}<file_sep>/Word is key/Main.java
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
char str[100];
int flag=0;
char input[16][10]={"break","case","continue","default","defer","else","fer'or",
"func","goto","if","map","range","return","struct","type","var"};
cin>>str;
int i;
for(i=0;i<16;i++)
{
if(strcmp(input[i],str)==0)
{
flag=1;
}
}
if(flag==1)
cout<<str<<" is a keyword";
else
cout<<str<<" is not a keyword";
}<file_sep>/Music Concert/Main.java
#include<iostream>
#include<cstdlib>
int main(){
// Type your code here
int n,ecount=0,ocount=0,i;
std::cin>>n;
int *p=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
std::cin>>*(p+i);
for(i=0;i<n;i++)
{
if(*(p+i)%2==0)
ecount+=1;
if(*(p+i)%2!=0)
ocount+=1;
}
std::cout<<ocount<<"\n";
std::cout<<ecount;
return 0;
}<file_sep>/Dept Repay/Main.java
#include<iostream>
using namespace std;
int main()
{
int p,r,t;
std::cin>>p>>r>>t;
float i,a,d,fs;
i=(p*t*r)/100;
a=p+i;
d=(i*2)/100;
fs=a-d;
std::cout<<i<<"\n"<<a<<"\n"<<d<<"\n"<<fs;
}<file_sep>/Pattern I/Main.java
#include<iostream>
int main()
{
int n,i,j,temp;
std::cin>>n;
temp=n;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
std::cout<<n;
std::cout<<"\n";
n++;
}
temp=n-1;
for(i=1;i<=4;i++)
{
for(j=4;j>=i;j--)
std::cout<<temp;
std::cout<<"\n";
temp--;
}
}<file_sep>/Length of string/Main.java
#include <stdio.h>
#include<string.h>
int main()
{
char str[100];
scanf("%[^\n]s",str);
printf("%d",strlen(str));
}<file_sep>/Nth Fibonacci Number/Main.java
#include <stdio.h>
int main()
{
int n,i=2;
scanf("%d",&n);
int arr[n];
arr[0]=0;
arr[1]=1;
while(i<n)
{
arr[i]=arr[i-2]+arr[i-1];
i++;
}
printf("%d",arr[n-1]);
}<file_sep>/Reverse a given number/Main.java
#include <stdio.h>
int main()
{
int n,m,rev=0,n1;
scanf("%d",&n);
n1=n;
while(n>0)
{
m=n%10;
rev=rev*10+m;
n=n/10;
}
printf("%d",rev);
}<file_sep>/To zero or not to zero/Main.java
#include <iostream>
using namespace std;
int main()
{
int m,n,i;
cin>>m>>n;
if(n>=100)
for(i=m;i<=n;i++)
{
printf("%03d ",i);
}
else if(n>=10)
for(i=m;i<=n;i++)
{
printf("%02d ",i);
}
else
for(i=m;i<=n;i++)
{
printf("%d ",i);
}
return 0;
}<file_sep>/Reverse Number/Main.java
#include <iostream>
int main()
{
int n,m,rev=0;
std::cin>>n;
while(n>0)
{
m=n%10;
if(m==0);
else
rev=rev*10+m;
n=n/10;
}
std::cout<<rev;
}<file_sep>/Ashok's homework/Main.java
#include<iostream>
int main()
{
int a,b,i,j;
std::cin>>a>>b;
int arr[a][b],arr2[a][b],arr3[a][b];
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
std::cin>>arr[i][j];
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
std::cin>>arr2[i][j];
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
arr3[i][j]=arr[i][j]+arr2[i][j];
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
std::cout<<arr3[i][j]<<" ";
}
std::cout<<"\n";
}
}
<file_sep>/Data mining/Main.java
#include<iostream>
using namespace std;
int main()
{
int n,e=0,o=0;
std::cin>>n;
while(n>0)
{
int m=n%10;
if(m%2==0)
{
e=e+m;
}
else
o=o+m;
n=n/10;
}
if(e==o)
std::cout<<"Yes";
else
std::cout<<"No";
}<file_sep>/Collatz problem/Main.java
#include<iostream>
using namespace std;
int main()
{
int n,arr[100],i=0,count=0,j;
std::cin>>n;
arr[0]=n;
if(n==1)
{
std::cout<<1<<"\n";
std::cout<<0;
}
else
{
do{
if(arr[i]%2==0)
{
i++;
arr[i]=arr[i-1]/2;
count++;
}
else
{
i++;
arr[i]=3*arr[i-1]+1;
count++;
}
}while(arr[i]!=1);
i=0;
while(arr[i]!=1){
std::cout<<arr[i]<<"\n";
i++;
}
std::cout<<1<<"\n";
std::cout<<count;
}
}<file_sep>/Centigrade to Fahrenheit./Main.java
#include <stdio.h>
int main()
{
int c;
float fa;
scanf("%d",&c);
fa=((1.8*c)+32);
printf("%0.2f",fa);
} | cb2e74e2753ad143f37f9172d4962cf21dafe500 | [
"Java"
] | 18 | Java | srujithanune/Playground | 16a0dd8161783083fdca5ed75cd0c8d5fe50b903 | bdeb8d7c40471370b5b64080bc6f61de44b1084b |
refs/heads/master | <file_sep>/**
* Makes a single API request to retrieve the user's IP address.
* Input:
* - A callback (to pass back an error or the IP string)
* Returns (via Callback):
* - An error, if any (nullable)
* - The IP address as a string (null if error). Example: "172.16.58.3"
*/
const request = require('request');
const website = 'https://api.ipify.org?format=json';
const fetchMyIP = function(callback) {
request(website, (error, response, body) => {
if (error) {
callback(error, null);
} else if (response.statusCode !== 200) {
const msg = `Status code: ${response.statusCode} when fetching IP. Response ${body}`;
callback(Error(msg), null);
return;
} else {
const data = JSON.parse(body);
if (data) {
callback(null, data["ip"]);
} else {
callback(null, 'not found');
}
}
});
};
const websiteCoord = 'https://ipvigilante.com/';
const fetchCoordsByIp = function(ip, callback) {
const dataOutgoingObject = {};
request(websiteCoord + ip, (error, response, body) => {
if (error) {
callback(error, null);
} else if (response.statusCode !== 200) {
const msg = `Status code: ${response.statusCode} when fetching IP. Response ${body}`;
callback(Error(msg), null);
return;
} else {
const dataIncomingObject = JSON.parse(body);
let latitude = dataIncomingObject.data["latitude"];
let longitude = dataIncomingObject.data["longitude"];
dataOutgoingObject['latitude'] = latitude;
dataOutgoingObject['longitude'] = longitude;
callback(null, dataOutgoingObject);
}
});
};
// module.exports = { fetchMyIP, fetchCoordsByIp };
/**
* Makes a single API request to retrieve upcoming ISS fly over times the for the given lat/lng coordinates.
* Input:
* - An object with keys `latitude` and `longitude`
* - A callback (to pass back an error or the array of resulting data)
* Returns (via Callback):
* - An error, if any (nullable)
* - The fly over times as an array of objects (null if error). Example:
* [ { risetime: 134564234, duration: 600 }, ... ]
*/
const issWeb = 'http://api.open-notify.org/iss-pass.json?lat=';
//lat=43.63830&lon=-79.43010
//going to put websiteFlyTimes + lat=${lat} + lon =${lon}
const fetchISSFlyOverTimes = function(coords, callback) {
request(`${issWeb}${coords.latitude}&lon=${coords.longitude}`, (error, response, body) => {
if (error) {
callback(error, null);
} else if (response.statusCode !== 200) {
const msg = `Status code: ${response.statusCode} when fetching IP. Response ${body}`;
callback(Error(msg), null);
return;
} else {
const dataFlyTimes = JSON.parse(body);
const flyTimes = dataFlyTimes["response"];
callback(null, flyTimes);
}
});
};
// module.exports = { fetchISSFlyOverTimes };
const nextISSTimesForMyLocation = function(callback) {
fetchMyIP((error, ipAddress) => {
if (error) {
callback(error);
} else {
fetchCoordsByIp(ipAddress, (error, coordinates) => {
if (error) {
callback(error);
} else {
fetchISSFlyOverTimes(coordinates, (error, flyTimes) => {
if (error) {
callback(error);
} else {
callback(null, flyTimes);
}
});
}
});
}
});
};
module.exports = { nextISSTimesForMyLocation }; | 9278860d9165e7b7fc7adfa1911fc16616a7ba86 | [
"JavaScript"
] | 1 | JavaScript | JashanB/iss_spotter | d1e8eab58e74d2222fcc20655aee18fb7854477c | d06f6ae7c73cd987bdbeec9d70263a7030d8c2aa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.