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/main
|
<file_sep>import {
Avatar,
Box,
Divider,
Grid,
List,
ListItem,
ListItemAvatar,
ListItemText,
makeStyles,
Typography,
} from "@material-ui/core";
import AppDrawer from "../../components/drawer";
import StatsCard from "../../components/statsCard";
import Calendar from "../../assets/icons/card-calendar.png";
import CalendarDark from "../../assets/icons/card-calendar-dark.png";
import Courses from "../../assets/icons/card-courses.png";
import Percentage from "../../assets/icons/card-percentage.png";
import Clock from "../../assets/icons/card-clock.png";
import NotificationCard from "../../components/notificationCard";
import Barchart from "../../components/barchart";
import Piechart from "../../components/piechart";
import CalendarPicker from "../../components/calendar";
const useStyles = makeStyles((theme) => ({
heading: {
fontFamily: "Montserrat",
letterSpacing: "0.48px",
color: "#707071",
opacity: "1",
fontSize: "24px",
},
}));
export default function Dashboard() {
const classes = useStyles();
return (
<AppDrawer>
<Box p={2}>
<Typography className={classes.heading}>Student Dashboard</Typography>
<Box mt={2}>
<Grid container spacing={3}>
<Grid item sm={4}>
<StatsCard
fill="#f3f2fe"
stroke="#1700FF"
title="Attendance percentage"
percentage="60%"
icon={Calendar}
/>
</Grid>
<Grid item sm={4}>
<StatsCard
fill="#fff7f2"
stroke="#FF761A"
title="Number of courses"
percentage="60%"
icon={Courses}
/>
</Grid>
<Grid item sm={4}>
<StatsCard
fill="#f9fcf2"
stroke="#00C3B3"
title="Total Marks Percentage"
percentage="60%"
icon={Percentage}
/>
</Grid>
</Grid>
</Box>
<Box>
<Grid container spacing={3}>
<Grid item sm={4}>
<Box mt={2}>
<NotificationCard
title="Next Class..."
description="Lorem Ipsum Dolor Sit Amet"
icon={Clock}
timer={true}
/>
</Box>
<Box mt={3}>
<NotificationCard
title="Up coming event"
description="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has text ever since the 1500."
icon={CalendarDark}
/>
</Box>
</Grid>
<Grid item sm={8}>
<Barchart />
</Grid>
</Grid>
</Box>
<Box>
<Grid container spacing={3}>
<Grid item sm={6}>
<Piechart />
</Grid>
<Grid item sm={6}>
<CalendarPicker />
</Grid>
</Grid>
</Box>
<Box mt={2}>
<Box
boxShadow={"0px 0px 10px #00000026"}
borderRadius={8}
css={{ background: "white" }}
p={3}>
<Grid container>
<Grid item xs={11}>
<List>
<ListItem alignItems="flex-start">
<ListItemAvatar>
<Avatar alt="<NAME>" />
</ListItemAvatar>
<ListItemText primary="Elizeu " secondary="Admin" />
</ListItem>
</List>
<Box p={2}>
<Typography
style={{
fontFamily: "Montserrat",
fontSize: 22,
color: "#192D3E",
}}>
Important Notice: Scheduled Maintenance of SMS
</Typography>
<Typography
style={{
fontFamily: "Montserrat",
fontSize: 20,
color: "#707071",
}}>
Dear SMS Users,
</Typography>
<Typography
style={{
fontFamily: "Montserrat",
fontSize: 20,
color: "#707071",
}}>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
diam nonumy eirmod tempor invidunt ut labore et dolore magna
aliquyam erat, sed diam voluptua. At vero eos et accusam et
justo duo dolores et ea rebum. Stet clita kasd gubergren, no
sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem
ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna
aliquyam erat, sed diam voluptua. At vero eos et accusam et
justo duo dolores et ea rebum. Stet clita kasd gubergren, no
sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem
ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore
</Typography>
</Box>
</Grid>
<Grid item xs={1}>
<Box pt={3}>
<Typography style={{ fontSize: 14, color: "gainsboro" }}>
19 Mar 2020
</Typography>
</Box>
</Grid>
</Grid>
<Divider />
</Box>
</Box>
</Box>
</AppDrawer>
);
}
<file_sep>import React, { useState } from "react";
import { Box, makeStyles } from "@material-ui/core";
import "react-modern-calendar-datepicker/lib/DatePicker.css";
import { Calendar } from "react-modern-calendar-datepicker";
import CardHeader from "../cardHeader";
const useStyles = makeStyles((theme) => ({
card: {
background: "#FFFFFF 0% 0% no-repeat padding-box",
boxShadow: "0px 0px 10px #00000026",
borderRadius: "8px",
opacity: "1",
height: 475,
width: "100%",
},
}));
export default function CalendarPicker() {
const classes = useStyles();
const [selectedDay, setSelectedDay] = useState(null);
return (
<Box className={classes.card} p={2}>
<CardHeader style={{ paddingTop: 12 }} />
<Box display="flex" justifyContent="center">
<Calendar
value={selectedDay}
onChange={setSelectedDay}
shouldHighlightWeekends
/>
</Box>
</Box>
);
}
<file_sep>import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import CssBaseline from "@material-ui/core/CssBaseline";
import List from "@material-ui/core/List";
import Divider from "@material-ui/core/Divider";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import InboxIcon from "@material-ui/icons/MoveToInbox";
import MailIcon from "@material-ui/icons/Mail";
import Appbar from "../appbar";
import { Avatar, Box, Typography } from "@material-ui/core";
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
const drawerWidth = 280;
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
color: "white",
background: "#192D3E",
"& svg": {
color: "white",
},
fontSize: 20,
fontFamily: "Montserrat",
},
// necessary for content to be below app bar
toolbar: {
...theme.mixins.toolbar,
"& div": {
padding: 18,
fontSize: 28,
fontFamily: "Montserrat",
},
},
content: {
flexGrow: 1,
},
}));
export default function AppDrawer({ children }) {
const classes = useStyles();
return (
<div className={classes.root}>
<CssBaseline />
<Drawer
className={classes.drawer}
variant="permanent"
classes={{
paper: classes.drawerPaper,
}}
anchor="left">
<div className={classes.toolbar}>
<div>INDEX.</div>
</div>
<Divider />
<Box py={4} px={2} display="flex" alignItems="center">
<Avatar style={{width: 86, height: 86}} />
<Box flexGrow={1} />
<Typography>John Doe</Typography>
<ExpandMoreIcon />
</Box>
<List>
{[
"Dashboard",
"Profile",
"Chat",
"Calendar",
"Notice Board",
"Class Routine",
"Live Class",
"Attendence",
"Assessment",
"Result",
"Course",
].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>
{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
</Drawer>
<main className={classes.content}>
<Appbar />
{children}
</main>
</div>
);
}
<file_sep>import { Box, makeStyles, Typography } from "@material-ui/core";
import { AreaChart, Area, ResponsiveContainer } from "recharts";
const useStyles = makeStyles((theme) => ({
card: {
background: "#FFFFFF 0% 0% no-repeat padding-box",
boxShadow: "0px 0px 10px #00000026",
borderRadius: "8px",
opacity: "1",
height: 277,
width: "100%",
},
title: {
fontSize: 18,
color: "#192D3E",
fontFamily: "Montserrat",
},
percentage: {
fontSize: 28,
color: "#192D3E",
fontFamily: "Montserrat",
},
}));
const data = [
{
name: "Page A",
uv: 4000,
pv: 2400,
amt: 2400,
},
{
name: "Page B",
uv: 3000,
pv: 1398,
amt: 2210,
},
{
name: "Page C",
uv: 2000,
pv: 9800,
amt: 2290,
},
{
name: "Page D",
uv: 2780,
pv: 3908,
amt: 2000,
},
{
name: "Page E",
uv: 1890,
pv: 4800,
amt: 2181,
},
{
name: "Page F",
uv: 2390,
pv: 3800,
amt: 2500,
},
{
name: "Page G",
uv: 3490,
pv: 4300,
amt: 2100,
},
];
export default function StatsCard({ fill, stroke, icon, percentage, title }) {
const classes = useStyles();
return (
<Box className={classes.card}>
<Box p={2} pb={0}>
<img src={icon} alt="card-calendar" width="61px" height="61px" />
<Typography className={classes.percentage}>{percentage}</Typography>
<Typography variant="body1" className={classes.title}>
{title}
</Typography>
</Box>
<div style={{ width: "100%", height: 130 }}>
<ResponsiveContainer>
<AreaChart
margin={{
top: 0,
right: 0,
left: 0,
bottom: 0,
}}
data={data}>
<Area type="monotone" dataKey="uv" stroke={stroke} fill={fill} />
</AreaChart>
</ResponsiveContainer>
</div>
</Box>
);
}
<file_sep>import { Box, makeStyles, Typography } from "@material-ui/core";
import Minimize from "../../assets/icons/minimize.png";
import Reload from "../../assets/icons/reload.png";
import Close from "../../assets/icons/close.png";
const useStyles = makeStyles(() => ({
title: {
fontFamily: "Montserrat",
fontSize: 20,
color: "#192D3E",
},
actionIcon:{
marginLeft: 16
}
}));
export default function CardHeader(props) {
const classes = useStyles();
return (
<Box {...props} py={3} display="flex" elevation={0}>
<Typography variant="body1" className={classes.title}>
Lorem ipsum
</Typography>
<Box flexGrow={1} />
<img className={classes.actionIcon} src={Minimize} alt="icon" width={24} height={24} />
<img className={classes.actionIcon} src={Reload} alt="icon" width={24} height={24} />
<img className={classes.actionIcon} src={Close} alt="icon" width={24} height={24} />
</Box>
);
}
|
d05edf8e1d6ab8034131c1db5ccd81b4321e109a
|
[
"JavaScript"
] | 5 |
JavaScript
|
sshahzaiib/student-dashboard
|
4d8ae0498496b365453fb6a74867fdb75bc03253
|
c0e69bef74f4b4c5c3c91ec0d4683b3268bd4970
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Model\Config;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
class ConfigController extends CommonController
{
//資源控制器給的get方法 全部配置項列表
public function index(){
$date = Config::orderBy('conf_order','asc')->get();
foreach ($date as $k => $v) {
switch ($v->field_type) {
case 'input'://單行文本
$date[$k]->_html='<input type="text" class="lg" name="conf_content[]" value="'.$v->conf_content.'">';
break;
case 'textarea'://多行文本
$date[$k]->_html='<textarea type="text" class="lg" name="conf_content[]" >'.$v->conf_content.'</textarea>';
break;
case 'radio'://單選框
//1|開啟,0關閉
$arr=explode(',',$v->field_value);
$str='';
if(strpos($arr,'|')){
foreach ($arr as $k1 => $v1) {
//1|開啟
$r=explode('|',$v1);
$c=$v->conf_content==$r[0]?' checked ':'';
var_dump($arr);die;
$str.='<input type="radio" name="conf_content[]" value="'.$r[0].'"'.$c.'>'.$r[1].' ';
}
}
$date[$k]->_html=$str;
break;
}
}
return view('admin.config.index',compact('date'));
}
//把配置項提交數據
public function changeContent(){
$input=Input::all();
foreach ($input['conf_id'] as $k => $v) {
Config::where('conf_id',$v)->update(['conf_content'=>$input['conf_content'][$k]]);
}
$this->putFile();
return back()->with('errors','配置項更新成功');
}
//get.admin/config ajax異步方法排序
public function changeOrder(){
$input=Input::all();
$Config=Config::find($input['conf_id']);
$Config->conf_order=$input['conf_order'];
$re=$Config->update();
if($re){
$data=[
'status'=>0,
'msg'=>'分類排序更新成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'分類排序更新失敗'
];
}
return $data;
}
//get.admin/config/create 添加配置項
public function create(){
return view('admin/config/add');
}
//post.admin/config 添加配置項提交
public function store(){
//排除某個不需要的input則可以用except()
$input=Input::except('_token');
var_dump($input);
// 定義驗證規則
$rules=[
'conf_name'=>'required',
'conf_title'=>'required',
];
// 定義觸發規則的警告語
$message=[
'conf_name.required'=>'配置項名稱不能為空',
'conf_title.required'=>'配置項標題不能為空',
];
//驗證
$Validator=Validator::make($input,$rules,$message);
if($Validator->passes()){
if(empty($_FILES)){
// 上傳圖片
if($_FILES["field_thumb"]["error"]>0){
return back()->with('errors','圖片上傳失敗');
}else{
$type=strrchr($_FILES['field_thumb']['name'],".");//獲取後墜
$_FILES['field_thumb']['name']=date('YmdHis',time()).$type;
move_uploaded_file($_FILES["field_thumb"]["tmp_name"],$_SERVER['DOCUMENT_ROOT']."/uploads/".$_FILES["field_thumb"]["name"]);
$input['field_thumb']="/uploads/".$_FILES["field_thumb"]["name"];
}
}
//將取得數值直接寫入數據庫
$re=Config::create($input);
if($re){
return redirect('admin/config');
}else{
return back()->with('errors','配置項填充失敗');
}
}else{
// 顯示錯誤訊息
// print_r($Validator->errors()->all());
//winhError可以把錯誤訊息傳遞回去並且賦值
return back()->withErrors($Validator);
}
}
//get.admin/config/{Config}/edit 編輯配置項
public function edit($Config_id){
$field=Config::find($Config_id);
return view('admin/config/edit',compact('field'));
}
//put.admin/config/{Config} 更新配置項
//put提交方式可以用<input type="hidden" name="_method" value="put">
public function update($conf_id){
$input=Input::except('_token','_method');
// print_r($input);die;
$re=Config::where('conf_id',$conf_id)->update($input);
if($re){
$this->putFile();
return redirect('admin/config');
}else{
return back()->with('errors','配置項更新失敗');
}
}
//get.admin/category/{category} 顯示單個分類訊息
public function show(){
}
//delete.admin/config/{Config} 刪除單個配置項
public function destroy($conf_id){
$re=Config::where('conf_id',$conf_id)->delete();
if($re){
$this->putFile();
$data=[
'status'=>0,
'msg'=>'配置項刪除成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'配置項刪除失敗'
];
}
return $data;
}
//把配置項寫入配置文件
public function putFile(){
$config=Config::pluck('conf_content','conf_name')->all();
//將數組轉換字符串
// echo var_export($config,true);
//設定配置文件路徑
$path=base_path().'\config\web.php';
//要寫入的內容
$str='<?php return '.var_export($config,true).';';
//此函數會將 路徑,內容寫入
file_put_contents($path,$str);
// echo $path;
}
}
<file_sep><?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
//更改數據表名稱
protected $table='category';
// 更改數據主鍵
protected $primaryKey='cate_id';
//關閉存處或者更新時間的自段
public $timestamps=false;
//框架的防護機制,必須定義不能填充字段,這裡我用一個空的表示全部都可以填充
protected $guarded=[];
public function tree(){
$categorys=$this->orderBy('cate_order','asc')->get();
return $this->getTree($categorys,'cate_name','cate_id','cate_pid');
}
// 以靜態方式呈現
// public Static function tree(){
// $categorys=Category::all();
// return (new Category)->getTree($categorys,'cate_name','cate_id','cate_pid');
// }
/**
* 文章的分類方法
* $data:需要分類的數據
* $name:數據庫裡的name字段
* $id:數據庫裡的id字段
* $pid:數據庫裡的上級分類字段
* $_pid:查詢該id的下級分類
*/
public function getTree($data,$name=name,$id=id,$pid=pid,$_pid=0){
Static $arr=array();
foreach ($data as $k => $v) {
if($v->$pid==$_pid){
$data[$k]['_'.$name]=$data[$k][$name];
$arr[]=$v;
foreach ($data as $k1 => $v1) {
if($v1->$pid==$v->$id){
$arr[]=$v1;
$data[$k1]['_'.$name]='-->'.$data[$k1][$name];
}
}
}
}
return $arr;
}
}
?><file_sep><?php return array (
'web_title' => '狗狗Blog系統',
'web_count' => 'Google統計',
'seo_title' => '尊重生命、關愛動物、共建和諧社會。',
'keywords' => '遊戲,動漫,動畫,漫畫,輕小說,線上遊戲,手機遊戲,手遊,Android,iOS,APP,PS4,PS3,討論區,論壇',
'description' => '華人最大動漫及遊戲社群網站,提供 ACG 每日最新新聞、熱門排行榜,以及豐富的討論交流空間,還有精采的個人影音實況、部落格文章。',
'copyright' => 'Design by 金門大學 <a href="https://www.nqu.edu.tw" target="_blank">http://www.houdunwang.com</a>',
);<file_sep><?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
//更改數據表名稱
protected $table='article';
// 更改數據主鍵
protected $primaryKey='art_id';
//關閉存處或者更新時間的自段
public $timestamps=false;
//框架的防護機制,必須定義不能填充字段,這裡我用一個空的表示全部都可以填充
protected $guarded=[];
}
?><file_sep><?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
//更改數據表名稱
protected $table='user';
// 更改數據主鍵
protected $primaryKey='user_id';
//關閉存處或者更新時間的字段
public $timestamps=false;
}
?><file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Model\Category;
use App\Http\Model\Article;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
class CategoryController extends CommonController
{
//資源控制器給的get方法 全部分類列表
public function index(){
//以靜態方式調用
// $categorys=Category::tree();
$categorys=(new Category)->tree();
//將數據分配到模板中
return view('admin.category.index')->with('date',$categorys);
}
//ajax異步方法排序
public function changeorder(){
$input=Input::all();
$cate=Category::find($input['cate_id']);
$cate->cate_order=$input['cate_order'];
$re=$cate->update();
if($re){
$data=[
'status'=>0,
'msg'=>'分類排序更新成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'分類排序更新失敗'
];
}
return $data;
}
//get.admin/category/create 添加分類
public function create(){
$data=Category::where('cate_pid',0)->get();
return view('admin/category/add',compact('data'));
}
//post.admin/category 添加分類提交
public function store(){
//排除某個不需要的input則可以用except()
$input=Input::except('_token');
// 定義驗證規則
$rules=[
'cate_name'=>'required',
];
// 定義觸發規則的警告語
$message=[
'cate_name.required'=>'分類名稱不能為空',
];
//驗證
$Validator=Validator::make($input,$rules,$message);
if($Validator->passes()){
//將取得數值直接寫入數據庫
$re=Category::create($input);
if($re){
return redirect('admin/category');
}else{
return back()->with('errors','數據填充失敗');
}
}else{
// 顯示錯誤訊息
// print_r($Validator->errors()->all());
//winhError可以把錯誤訊息傳遞回去並且賦值
return back()->withErrors($Validator);
}
}
//get.admin/category/{category}/edit 編輯分類
public function edit($cate_id){
$field=Category::find($cate_id);
$data=Category::where('cate_pid',0)->get();
return view('admin/category/edit',compact('field','data'));
}
//put.admin/category/{category} 更新分類
//put提交方式可以用<input type="hidden" name="_method" value="put">
public function update($cate_id){
$input=Input::except('_token','_method');
$re=Category::where('cate_id',$cate_id)->update($input);
if($re){
return redirect('admin/category');
}else{
return back()->with('errors','分類訊息更新失敗');
}
}
//get.admin/category/{category} 顯示單個分類訊息
public function show(){
}
//delete.admin/category/{category} 刪除單個分類
public function destroy($cate_id){
$ra=Article::where('cate_id',$cate_id)->select('art_id')->get();
$re=Category::where('cate_id',$cate_id)->delete();
Category::where('cate_pid',$cate_id)->update(['cate_pid'=>0]);
if($re){
$article=new ArticleController;
foreach ($ra as $k => $v) {
$article->destroy($v->art_id);
}
$data=[
'status'=>0,
'msg'=>'分類刪除成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'分類刪除失敗'
];
}
return $data;
}
}
<file_sep><?php
namespace App\Http\Controllers\Home;
use App\Http\Model\Navs;
use App\Http\Model\Category;
use App\Http\Model\Article;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\Controller;
class CommonController extends Controller
{
//初始化
public function __construct(){
$navs=Navs::all();
$cate=Category::orderBy('cate_order')->where('cate_pid',0)->get();
//點擊量最高的5篇文章
$hot=Article::orderBy('art_view','desc')->take(5)->get();
//最新發布文章8篇
$new=Article::orderBy('art_time','desc')->take(8)->get();
//模板參數共享
View::share('cate',$cate);
View::share('navs',$navs);
View::share('hot',$hot);
View::share('new',$new);
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Model\Category;
use App\Http\Model\Article;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
class ArticleController extends CommonController
{
//get.admin/article 全部文章列表
public function index(){
//框架中提供分頁paginate函數
$data=\DB::table('article')->select('article.*','category.cate_name','category.cate_name','category.cate_pid')->orderBy('art_time','desc')->join('category','category.cate_id','=','article.cate_id')->paginate(10);
return view('admin/article/index',compact('data'));
}
//get.admin/article/create 添加文章
public function create(){
$data=(new Category)->tree();
return view('admin/article/add',compact('data'));
}
//post.admin/article 添加分類提交
public function store(){
$input=Input::except('_token');
$input['art_view']=0;
// print_r($input);die;
$input['art_time']=time();
// 定義驗證規則
$rules=[
'art_title'=>'required',
'art_content'=>'required',
];
// 定義觸發規則的警告語
$message=[
'art_title.required'=>'文章名稱不能為空',
'art_content.required'=>'文章內容不能為空',
];
//驗證
$Validator=Validator::make($input,$rules,$message);
if($Validator->passes()){
// 上傳圖片
if($_FILES["art_thumb"]["error"]>0){
return back()->with('errors','圖片上傳失敗');
}else{
$type=strrchr($_FILES['art_thumb']['name'],".");//獲取後墜
$_FILES['art_thumb']['name']=date('YmdHis',time()).$type;
move_uploaded_file($_FILES["art_thumb"]["tmp_name"],$_SERVER['DOCUMENT_ROOT']."/uploads/".$_FILES["art_thumb"]["name"]);
$input['art_thumb']="/uploads/".$_FILES["art_thumb"]["name"];
}
//將取得數值直接寫入數據庫
$re=Article::create($input);
if($re){
// return '文章添加成功';
return redirect('admin/article');
}else{
return back()->with('errors','數據填充失敗');
}
}else{
// 顯示錯誤訊息
// print_r($Validator->errors()->all());
//winhError可以把錯誤訊息傳遞回去並且賦值
return back()->withErrors($Validator);
}
}
//get.admin/article/{article}/edit 編輯文章
public function edit($art_id){
$data=(new Category)->tree();
$field=Article::find($art_id);
return view('admin/article/edit',compact('data','field'));
}
//put.admin/article/{article} 更新文章
//put提交方式可以用<input type="hidden" name="_method" value="put">
public function update($art_id){
$input=Input::except('_method','_token');
$old_thumb=Article::select('art_thumb')->find($art_id);
// 上傳圖片
if($_FILES["art_thumb"]["name"]){
if($_FILES["art_thumb"]["error"]){
return back()->with('errors','圖片上傳失敗');
}else{
$type=strrchr($_FILES['art_thumb']['name'],".");//獲取後墜
$_FILES['art_thumb']['name']=date('YmdHis',time()).$type;
move_uploaded_file($_FILES["art_thumb"]["tmp_name"],$_SERVER['DOCUMENT_ROOT']."/uploads/".$_FILES["art_thumb"]["name"]);
if($old_thumb['art_thumb']){
unlink($_SERVER['DOCUMENT_ROOT'].$old_thumb['art_thumb']);
}
$input['art_thumb']="/uploads/".$_FILES["art_thumb"]["name"];
} }
$re=Article::where('art_id',$art_id)->update($input);
if($re){
return redirect('admin/article');
}else{
return back()->with('errors','文章更新失敗');
}
}
//delete.admin/article/{article} 刪除單篇文章
public function destroy($art_id){
$old_thumb=Article::select('art_thumb')->find($art_id);
unlink($_SERVER['DOCUMENT_ROOT'].$old_thumb['art_thumb']);
$re=Article::where('art_id',$art_id)->delete();
if($re){
$data=[
'status'=>0,
'msg'=>'文章刪除成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'文章刪除失敗'
];
}
return $data;
}
}
<file_sep><?php
namespace App\Http\Controllers\Home;
use App\Http\Model\Navs;
use App\Http\Model\Article;
use App\Http\Model\Links;
use App\Http\Model\Category;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
class IndexController extends CommonController
{
public function index(){
//點擊量最高的6篇文章(站長推薦區)
$pics=Article::orderBy('art_view','desc')->take(6)->get();
//圖文列表5篇(帶分頁)
$data=Article::orderBy('art_time','desc')->paginate(5);
//友情鏈接
$links=Links::orderBy('link_order','asc')->get();
return view('home/index',compact('pics','data','links'));
}
public function cate($cate_id){
//圖文列表4篇(帶分頁)
$data=Article::where('cate_id',$cate_id)->orderBy('art_time','desc')->paginate(4);
//查看分類次數的自增
Category::where('cate_id',$cate_id)->increment('cate_view');
//當前分類的子分類
$submenu=Category::where('cate_pid',$cate_id)->get();
$field=Category::find($cate_id);
return view('home/list',compact('field','data','submenu'));
}
public function article($art_id){
$field=Article::join('category','article.cate_id','=','category.cate_id')->where('art_id',$art_id)->first();
//查看文章次數的自增
Article::where('art_id',$art_id)->increment('art_view');
//取得上一篇內容
$article['pre']=Article::where('art_id','<',$art_id)->orderBy('art_id','desc')->first();
$article['next']=Article::where('art_id','>',$art_id)->orderBy('art_id','asc')->first();
//相關文章
$data=Article::where('cate_id',$field->cate_id)->take(6)->orderBy('art_id','desc')->get();
return view('home/new',compact('field','article','data'));
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Model\Links;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
class LinksController extends CommonController
{
//資源控制器給的get方法 全部分類列表
public function index(){
$date = Links::orderBy('link_order','asc')->get();
return view('admin.links.index',compact('date'));
}
//get.admin/links ajax異步方法排序
public function changeOrder(){
$input=Input::all();
$links=Links::find($input['link_id']);
$links->link_order=$input['link_order'];
$re=$links->update();
if($re){
$data=[
'status'=>0,
'msg'=>'分類排序更新成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'分類排序更新失敗'
];
}
return $data;
}
//get.admin/links/create 添加友情鏈接
public function create(){
return view('admin/links/add');
}
//post.admin/links 添加友情鏈接提交
public function store(){
//排除某個不需要的input則可以用except()
$input=Input::except('_token');
// 定義驗證規則
$rules=[
'link_name'=>'required',
'link_url'=>'required',
];
// 定義觸發規則的警告語
$message=[
'link_name.required'=>'友情鏈接名稱不能為空',
'link_url.required'=>'Url不能為空',
];
//驗證
$Validator=Validator::make($input,$rules,$message);
if($Validator->passes()){
//將取得數值直接寫入數據庫
$re=Links::create($input);
if($re){
return redirect('admin/links');
}else{
return back()->with('errors','友情鏈接填充失敗');
}
}else{
// 顯示錯誤訊息
// print_r($Validator->errors()->all());
//winhError可以把錯誤訊息傳遞回去並且賦值
return back()->withErrors($Validator);
}
}
//get.admin/links/{links}/edit 編輯友情鏈接
public function edit($link_id){
$field=Links::find($link_id);
return view('admin/links/edit',compact('field'));
}
//put.admin/links/{links} 更新友情鏈接
//put提交方式可以用<input type="hidden" name="_method" value="put">
public function update($link_id){
$input=Input::except('_token','_method');
// print_r($input);die;
$re=Links::where('link_id',$link_id)->update($input);
if($re){
return redirect('admin/links');
}else{
return back()->with('errors','友情鏈接更新失敗');
}
}
//get.admin/category/{category} 顯示單個分類訊息
public function show(){
}
//delete.admin/links/{links} 刪除單個友情鏈接
public function destroy($link_id){
$re=Links::where('link_id',$link_id)->delete();
if($re){
$data=[
'status'=>0,
'msg'=>'友情鏈接刪除成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'友情鏈接刪除失敗'
];
}
return $data;
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Model\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
class CommonController extends Controller
{
//圖片上傳
public function upload(){
$file=Input::file('Filedata');//獲取圖片訊息
if($file -> isValid()){//判斷上傳文件是否有效
// $realPath=$file->getRealPath();//緩存在tmp文件夾下的絕對路徑
$entension = $file -> getClientOriginalExtension(); //上传文件的后缀.
$newName = date('YmdHis').mt_rand(100,999).'.'.$entension;//重組文件名
$path = $file -> move(base_path().'/uploads',$newName);//指定文件夾,並賦予它新檔案名
$filepath = 'uploads/'.$newName;
return $filepath;//回傳文件路徑
}
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Model\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
//家仔第三方插鍵驗證碼
require_once 'resources/org/code/Code.class.php';
class LoginController extends CommonController
{
public function login()
{
if($input=Input::all()){
$code=new \Code;
$_code= $code->get();
if(strtoupper($input['code'])!=$_code){
// back視返回上一頁這個提示訊息存到session裡面
return back()->with('msg','驗證碼錯誤');
}
//first只取一條數據
$user=User::first();
if($user->user_name!=$input['user_name']||Crypt::decrypt($user->user_pass)!=$input['user_pass']){
return back()->with('msg','用戶名或者密碼錯誤');
}
//登入成功寫到session裡
session(['user'=>$user]);
return redirect('admin');
// print_r(session('user'));
// echo "ok";
}else{
return view('admin.login');
}
}
//退出方法
public function quit()
{
session(['user'=>null]);
return redirect('admin/login');
}
// 引入驗證碼
public function code()
{
$code=new \Code;
$code->make();
}
//測試密碼解密加密
public function crypt()
{
$str='123456';
$_str='<KEY>TE2YTQ3M2U2ODVkMmI4YzczNGY0YjczYmZmMTMxODg4MzgxNDBhMzE5ZjVjNjllZWIifQ==
==';
//利用框架來進行加密
echo Crypt::encrypt($str),'<br>';
//利用框架來進行解密
echo Crypt::decrypt($_str);
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Model\Navs;
use App\Http\Model\Category;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
class NavsController extends CommonController
{
//資源控制器給的get方法 全部分類列表
public function index(){
$date = Navs::orderBy('nav_order','asc')->get();
return view('admin.navs.index',compact('date'));
}
//get.admin/Navs ajax異步方法排序
public function changeOrder(){
$input=Input::all();
$Navs=Navs::find($input['nav_id']);
$Navs->nav_order=$input['nav_order'];
$re=$Navs->update();
if($re){
$data=[
'status'=>0,
'msg'=>'分類排序更新成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'分類排序更新失敗'
];
}
return $data;
}
//get.admin/Navs/create 添加自訂義導航
public function create(){
$cate = Category::where('cate_pid',0)->get();
return view('admin/navs/add',compact('cate'));
}
//post.admin/Navs 添加自訂義導航提交
public function store(){
//排除某個不需要的input則可以用except()
$input=Input::except('_token');
// 定義驗證規則
$rules=[
'nav_name'=>'required',
'nav_url'=>'required',
];
// 定義觸發規則的警告語
$message=[
'nav_name.required'=>'自訂義導航名稱不能為空',
'nav_url.required'=>'Url不能為空',
];
//驗證
$Validator=Validator::make($input,$rules,$message);
if($Validator->passes()){
//將取得數值直接寫入數據庫
$re=Navs::create($input);
if($re){
return redirect('admin/navs');
}else{
return back()->with('errors','自訂義導航填充失敗');
}
}else{
// 顯示錯誤訊息
// print_r($Validator->errors()->all());
//winhError可以把錯誤訊息傳遞回去並且賦值
return back()->withErrors($Validator);
}
}
//get.admin/Navs/{Navs}/edit 編輯自訂義導航
public function edit($navs_id){
$field=Navs::find($navs_id);
return view('admin/navs/edit',compact('field'));
}
//put.admin/Navs/{Navs} 更新自訂義導航
//put提交方式可以用<input type="hidden" name="_method" value="put">
public function update($nav_id){
$input=Input::except('_token','_method');
// print_r($input);die;
$re=Navs::where('nav_id',$nav_id)->update($input);
if($re){
return redirect('admin/navs');
}else{
return back()->with('errors','自訂義導航更新失敗');
}
}
//get.admin/category/{category} 顯示單個分類訊息
public function show(){
}
//delete.admin/Navs/{Navs} 刪除單個自訂義導航
public function destroy($nav_id){
$re=Navs::where('nav_id',$nav_id)->delete();
if($re){
$data=[
'status'=>0,
'msg'=>'自訂義導航刪除成功'
];
}else{
$data=[
'status'=>1,
'msg'=>'自訂義導航刪除失敗'
];
}
return $data;
}
}
|
584365163a8fa9749afcda793ab59355b941e75b
|
[
"PHP"
] | 13 |
PHP
|
as55518010/blog
|
951c3984479ce6165bad2cb5115b9e7801e84b0f
|
7792056279279446dd57568703e908143276accb
|
refs/heads/master
|
<file_sep>public class MalitiaActus { //malicious actions
public void admodumEnim() { // Findbugs doesnt approve of these usages, very malicious indeed
new Byte("19");
System.exit(0);
}
}
<file_sep>FindbugsJUnitWrapper
====================
JUnit testcase for Findbugs violations
Description
====================
Include as a jar to run Findbugs to test for violations as JUnit Testcases.
<file_sep>/*
Copyright (c) 2014 <NAME>
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.
*/
package org.marcoszenfold.junit.ext.findbugs;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
public class FindbugsWrapper {
private PrintStream out;
private ByteArrayOutputStream byteArrOutputStream;
public int execute(String sourcePath) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, SecurityException, NoSuchMethodException, IOException {
PrintStream out2 = System.out;
setupStreams();
Class<?> cls = Class.forName("edu.umd.cs.findbugs.FindBugs2");
Method main = cls.getMethod("main", String[].class);
String[] params = {"-home","D:\\Dev\\util\\findbugs-2.0.3","-excludeBugs","BaselineViolations.xml",sourcePath}; // init params accordingly
// String[] params = {"-help"}; // init params accordingly
main.invoke(null, (Object) params); // static invoke
byte[] byteArray = byteArrOutputStream.toByteArray();
InputStream inputStream=new ByteArrayInputStream(byteArray);
int len = inputStream.read(byteArray);
if(len>0){
out2.print(new String(byteArray,Charset.forName("UTF-8")));
}
return len;
}
private void setupStreams() {
byteArrOutputStream = new ByteArrayOutputStream();
out = new PrintStream(new BufferedOutputStream(byteArrOutputStream) );
System.setOut(out);
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, IOException {
new FindbugsWrapper().execute("D:\\Dev\\Workspaces\\Java_WS_Cassowary\\findbugsWrapper\\target\\classes\\MalitiaActus.class");
}
}
|
f3b843dd450a5a11e3b05d5378c5b682a23decf9
|
[
"Markdown",
"Java"
] | 3 |
Java
|
sandyrao/FindbugsJUnitWrapper
|
e30b7bf24243b653040f8fed6757bc243196db34
|
3f1745e09396bfde6cf6f48b45dbb07932688d04
|
refs/heads/master
|
<repo_name>ArturBraczkowski/sda-byd1-chat<file_sep>/src/main/java/com/sda/chat/DAO/ImplementDAO.java
package com.sda.chat.DAO;
public class ImplementDAO {
}
<file_sep>/src/main/java/com/sda/chat/service/MyChatService.java
package com.sda.chat.service;
import java.util.LinkedList;
import java.util.List;
import static java.util.Collections.unmodifiableList;
public class MyChatService {
private static MyChatService _instance;
private List<MyChat> myMessageList;
private MyChatService() {
myMessageList = new LinkedList<MyChat>();
}
public static MyChatService getInstance() {
if (_instance == null) {
_instance = new MyChatService();
}
return _instance;
}
public void addMessage(MyChat chat) {
myMessageList.add(chat);
}
public void delMessage(MyChat chat) {
myMessageList.(chat);
}
public void editMessage(MyChat chat) {
myMessageList.(chat);
}
public List <MyChat> getMyMessageList() {
return unmodifiableList(myMessageList);
}
}
|
7b40742fc16ace907d6b474945885c4f3563125d
|
[
"Java"
] | 2 |
Java
|
ArturBraczkowski/sda-byd1-chat
|
823dd23c0ee5767ecd10411a58a28e0447bb297d
|
a162f289672008e51fbecaf19935bacc617a83d8
|
refs/heads/master
|
<file_sep>Loan Prediction
-----------------------
Predict whether or not loans acquired by Fannie Mae will go into foreclosure. Fannie Mae acquires loans from other lenders as a way of inducing them to lend more. Fannie Mae releases data on the loans it has acquired and their performance afterwards [here](http://www.fanniemae.com/portal/funding-the-market/data/loan-performance-data.html)
Installation
----------------------
### Download the data
* Clone this repo to your computer.
* Get into the folder using `cd loan-prediction`.
* Run `mkdir data`.
* Switch into the `data` directory using `cd data`.
* Download the data files from Fannie Mae into the `data` directory.
* You can find the data [here](http://www.fanniemae.com/portal/funding-the-market/data/loan-performance-data.html).
* You'll need to register with <NAME> to download the data.
* It's recommended to download all the data from 2012 Q1 to present.
* Extract all of the `.zip` files you downloaded.
* On OSX, you can run `find ./ -name \*.zip -exec unzip {} \;`.
* At the end, you should have a bunch of text files called `Acquisition_YQX.txt`, and `Performance_YQX.txt`, where `Y` is a year, and `X` is a number from `1` to `4`.
* Remove all the zip files by running `rm *.zip`.
* Switch back into the `loan-prediction` directory using `cd ..`.
### Install the requirements
* Install the requirements using `pip install -r requirements.txt`.
* Make sure you use Python 3.
* You may want to use a virtual environment for this.
Usage
-----------------------
* Run `mkdir processed` to create a directory for our processed datasets.
* Run `python assemble.py` to combine the `Acquisition` and `Performance` datasets.
* This will create `Acquisition.txt` and `Performance.txt` in the `processed` folder.
* Run `python annotate.py`.
* This will create training data from `Acquisition.txt` and `Performance.txt`.
* It will add a file called `train.csv` to the `processed` folder.
* Run `python predict.py`.
* This will run cross validation across the training set, and print the accuracy score.
Extending this
-------------------------
If you want to extend this work, here are a few places to start:
* Generate more features in `annotate.py`.
* Switch algorithms in `predict.py`.
* Add in a way to make predictions on future data.
* Try seeing if you can predict if a bank should have issued the loan.
* Remove any columns from `train` that the bank wouldn't have known at the time of issuing the loan.
* Some columns are known when <NAME> bought the loan, but not before
* Make predictions.
* Explore seeing if you can predict columns other than `foreclosure_status`.
* Can you predict how much the property will be worth at sale time?
* Explore the nuances between performance updates.
* Can you predict how many times the borrower will be late on payments?
* Can you map out the typical loan lifecycle?
<file_sep>DATA_DIR = "data"
PROCESSED_DIR = "processed"
MINIMUM_TRACKING_QUARTERS = 4
TARGET = "foreclosure_status"
NON_PREDICTORS = [TARGET, "id"]
CV_FOLDS = 3
|
694ca95030d3c5e28e2e442d84f11164fc84d43f
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
sanjaytallolli/loan-prediction
|
ba72d42ca85dea318aee485c6745cf92e784c86b
|
3a6201a49ebb6c34f95455f3b8356a67217948ed
|
refs/heads/master
|
<repo_name>blindern/statuttgenerator<file_sep>/docs/nettsidene.md
# Dokumentasjon for nettsidene (hjemmesideoppmann)
[Tilbake til readme](../README.md)
Scriptet på serveren tar i mot filopplastingen, pakker den ut og legger i en mappe som heter statutter.
Den gamle ```statutter```-mappen arkiveres i en mappe som heter ```statutter_arkiv```. Dette for å ha en ekstra kopi av gamle dokumenter, samt mulig for andre å hente frem disse.
Se scriptet i mappa ```nettsidene``` for hvordan det fungerer.
## Forklaring av filer
* ```statutter_upload.php``` - hovedscriptet som tar i mot nye dokumenter, arkiverer de gamle og publiserer de nye
* ```rewrite_index.php``` - dette scriptet kjøres i stedet for ```index.html``` i gjeldende dokumenter, for å legge inn lenke til historisk arkiv
* ```HEADER.html``` - header-fil for mappevisning (lastes inn av Apache-serveren) på arkivmappa
## Oppsett av server
De nødvendige filene ligger i ```nettsidene```-mappa, men må plasseres litt ulike steder.
Sørg for at disse mappene finnes:
* ```/dokumenter/statutter_arkiv/```
Opprett symlinker for følgende filer:
* ```statutter_upload.php``` til ```/dokumenter/```-mappa
* ```rewrite_index.php``` til ```/dokumenter/```-mappa
* ```HEADER.html``` til ```/dokumenter/statutter_arkiv/```-mappa
Legg til følgende i ```/dokumenter/.htaccess``` eller tilsvarende:
```apacheconf
RewriteEngine On
RewriteRule ^statutter/(index.html)?$ rewrite_index.php [L]
```
Legg til følgende i ```/dokumenter/statutter_arkiv/.htaccess``` eller tilsvarende:
```apacheconf
Options +Indexes
IndexOptions Charset=UTF-8
```
Mappene må også ha noe rettigheter satt riktig, slik at nye statutter-mapper kan lastes opp og mapper kan flyttes til arkiv.
<file_sep>/nettsidene/README.md
Se [../docs/nettsidene.md](../docs/nettsidene.md) for dokumentasjon.
<file_sep>/nettsidene/statutter_upload.php
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
function logme($string, $exit = true) {
file_put_contents("/tmp/statuttupload", date('r').' ('.$_SERVER['REMOTE_ADDR'].'): '.$string."\n", FILE_APPEND);
if ($exit) die();
}
// kontroller at det er en forespørsel fra BS
if (substr($_SERVER['REMOTE_ADDR'], 0, 7) != "37.191.")
logme("Ugyldig IP-adresse!");
if (isset($_FILES['statutter'])) {
$dest = dirname(__FILE__) . "/gjeldende";
$dest_tmp = dirname(__FILE__) . "/gjeldende_tmp";
#@mkdir($dest);
@mkdir($dest_tmp);
if (!is_uploaded_file($_FILES['statutter']['tmp_name'])) {
logme("Feil ved opplasting!");
}
@unlink($dest_tmp ."/statutter.zip");
if (!move_uploaded_file($_FILES['statutter']['tmp_name'], $dest_tmp . "/statutter.zip")) {
logme("Kunne ikke lagre dokumentet på serveren...");
}
$zip = new ZipArchive;
$res = $zip->open($dest_tmp . "/statutter.zip");
if ($res !== true) {
logme("Kunne ikke åpne som zip...");
}
$zip->extractTo($dest_tmp);
$zip->close();
$time = date("Ymd_His", filemtime($dest).'/statutter.zip');
$dest_arc = dirname(__FILE__) . "/arkiv/statutter_".$time;
@rename($dest, $dest_arc);
@rrmdir($dest);
rename($dest_tmp, $dest);
logme("OK!");
}
logme("Ugyldig forespørsel.");
<file_sep>/nettsidene/rewrite_index.php
<?php
header("Content-Type: text/html; charset=windows-1252");
$data = file_get_contents("gjeldende/index.html");
// vi setter inn innehold etter første avsnitt
$offset = 0;
for ($i = 0; $i < 2; $i++)
{
$offset = strpos($data, "<p", $offset+1);
}
echo substr($data, 0, $offset);
echo '<p style="text-align: center; font-size: 110%; font-style: italic">For arkiv over tidligere dokumenter: <a href="https://foreningenbs.no/statutter/arkiv/">https://foreningenbs.no/statutter/arkiv/</a></p>';
echo substr($data, $offset);
die;
echo $data;
<file_sep>/README.md
# Statutt-generator
Dette er et system som brukes av kollegiet for å automatisk laste opp statutter o.l. til nettsiden for å gjøre det tilgjengelig for beboere.
Opprinnelig laget av <NAME> under kollegiet Grøgaard våren 2012.
Systemet er delt i to:
* Verktøy for kollegiet for å generere dokumenter og laste opp til nettsiden
* Script for hjemmesideoppmann (nettsidene) som gjør mottak og publiseringen
Statutter ligger under følgende adresse:<br />
http://blindern-studenterhjem.no/statutter/
I tillegg ligger arkiv over gamle statutter tilgjengelig her:<br />
http://blindern-studenterhjem.no/dokumenter/statutter_arkiv/
## Dokumentasjon
### For kollegiet
Se [dokumentasjon for kollegiet](docs/kollegiet.md)
### For hjemmesideoppmann
Se [dokumentasjon for nettsidene](docs/nettsidene.md)
<file_sep>/kollegiet/README.md
Se [../docs/kollegiet.md](../docs/kollegiet.md) for dokumentasjon.
<file_sep>/docs/kollegiet.md
# Dokumentasjon for kollegiet
[Tilbake til readme](../README.md)
## Informasjon om statutter på kollegie-pc
### Oppbevaring og oppdatering av statutter
På Kollegiets PC er det en mappe som heter *Statutter*. Inni denne ligger både gjeldende og tidligere statutter.
### Gjeldende statutter
Gjeldende statutter skal alltid ligge oppdatert i mappen *GJELDENDE STATUTTER*. Alle filene i denne mappen skal være skrivebeskyttet, for å unngå at disse skrives over ved nye endringer.
### Oppdatering av statutter
1. Flytt dokumentet som endres fra *GJELDENDE STATUTTER* til *TIDLIGERE STATUTTER*.
2. Tilføy hvilken dato statutten sist ble endret i filnavnet (ikke dagens dato, se vedtatt dato i dokumentet)
* Slik: 43 Instruks for medisinalkollegiet (2010-11-15).doc
3. Kopier dokumentet inn til *GJELDENDE STATUTTER*.
4. Fjern skrivebeskyttelsen
* Gå på egenskaper til filen og fjern haken for «Read only»
5. Gjør endringer
6. Sett på skrivebeskyttelse igjen
### Publisering av statutter
For publisering av statutter er det laget et eget verktøy. Dette verktøyet gjør følgende:
1. Genererer automatisk *innholdsfortegnelse*
* Datoen i innholdsfortegnelsen hentes fra slutten av dokumentet
2. Genererer *PDF-versjon* av alle dokumentene, samt en *samle-PDF* med alle dokumentene
3. Genererer *HTML-versjon* av alle dokumentene (for nettsiden)
4. Laster det automatisk opp til nettsiden
* http://blindern-studenterhjem.no/statutter
### Distribusjon
Når endringer gjøres må nytt dokument printes ut og legges inn i de ulike statutt-permene:
1. Biblioteket
2. Præces sin perm
3. Kontoret sine permer
Når endringen slås opp på Kollegietavla bør man kjøre en «sammenlikning» av det gamle og nye dokumentet slik at det klart kommer frem hva som er endret. (I Word: Review -> Compare)
### Statutt-systemet
Filene det er henvist til nedenfor ligger i mappen STATUTT-GENERATOR.
#### Tittel som brukes i innholdsfortegnelse
Når innholdsfortegnelsen genereres hentes tittelen ut fra selve metadataen til dokumentet. Hvis dette ikke finnes brukes filnavnet som tittel.
Dette kan overprøves ved å endre filen ALIASES.txt
#### Oppsett innholdsfortegnelse
Innholdsfortegnelsen kan endres ved å endre *Mal innholdsfortegnelse.doc*
Det kan legges til opp til 6 forskjellige kategorier (statutter, reglement, osv.). Se INNSTILLINGER.txt for detaljer.
Tabellen i innholdsfortegnelsen må ikke endre struktur. Da vil ikke systemet klare å generere teksten i tabellen.
#### Feilsøking
1. Hvis ny PC: Systemet er avhengig av et program som heter Ghostscript. Se INNSTILLINGER.txt og sørg for at korrekt adresse er satt til programmet.
2. Mapper flyttet: Hvis statutt-mappen flyttes må systemet gjøres kjent med den nye plasseringen. Se INNSTILLINGER.txt hvor adressene legges inn.
3. Hent ned statuttgeneratoren fra GitHub dersom systemet på maskinen ikke fungerer.
4. Hør med <NAME> (416 20 292) som har laget systemet.
|
98befe31511fce9b830074b422996b969a540227
|
[
"Markdown",
"PHP"
] | 7 |
Markdown
|
blindern/statuttgenerator
|
4c2c0d539f75d1188d33138ff50e1337c8affdf3
|
b359f40dba10f54ed8d5f1546151a029ce73a198
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// Whats-The-Weather
//
// Created by <NAME> on 6/4/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var txtFld: UITextField!
@IBOutlet weak var resultsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func submitPrssd(_ sender: Any) {
if !((txtFld.text?.isEmpty)!) {
if let name = txtFld.text?.replacingOccurrences(of: " ", with: "-") {
if let url = URL(string: "http://www.weather-forecast.com/locations/"+name+"/forecasts/latest") {
let request = URLRequest(url: url)
var message = ""
let task = URLSession.shared.dataTask(with: request) { (Data, URLResponse, Error) in
if Error != nil {
print("Error Occured")
} else {
if let unrappedData = Data {
let answer = NSString(data: unrappedData, encoding: String.Encoding.utf8.rawValue)
var stringSeparator = "Weather Forecast Summary:</b><span class=\"read-more-small\"><span class=\"read-more-content\"> <span class=\"phrase\">"
if let contentArray = answer?.components(separatedBy: stringSeparator) {
if contentArray.count > 1 {
stringSeparator = "</span>"
let newArray = contentArray[1].components(separatedBy: stringSeparator)
if newArray.count > 1 {
message = newArray[0].replacingOccurrences(of: "°", with: "°")
}
}
}
}
}
if message == "" {
message = "The weather there couldn't be found. Please try again."
}
DispatchQueue.main.async {
self.resultsLabel.text = message
}
}
task.resume()
} else {
resultsLabel.text = "The weather there couldn't be found. Please try again."
}
} else {
resultsLabel.text = "Please enter the name of the city properly."
}
} else {
resultsLabel.text = "Please Enter Some name of the city."
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
<file_sep># Whats-The-Weather
Handy Weather App that gives a short weather description of the city where you live in.
|
149fd3bd93deeb817ee6d10b6be9c7ab7fa01060
|
[
"Swift",
"Markdown"
] | 2 |
Swift
|
akilkumar28/Whats-The-Weather
|
a6386db3ea40de646d9a338352a5c0d89c1f5b4c
|
ca35264a1412cb60b23ab8b1f790ba6160302b21
|
refs/heads/master
|
<file_sep>import fontawesome from '@fortawesome/fontawesome';
import faCareUp from '@fortawesome/fontawesome-free-solid';
import faCareDown from '@fortawesome/fontawesome-free-solid';
import faStar from '@fortawesome/fontawesome-free-solid';
import faCheck from '@fortawesome/fontawesome-free-solid';
fontawesome.library.add([faCareUp, faCareDown, faCheck, faStar]);<file_sep>export default {
modify (user, model) {
return user.id === model.user_id;
},
accept (user, answer) {
return user.id === answer.question.user_id;
}
}
|
4f64026291df33dd00ddc75debb77fe19d2d7f9e
|
[
"JavaScript"
] | 2 |
JavaScript
|
adrian-zawada/laravel-qa
|
f9e3939a89220d8bc0dbb7b2b3c507b2cbfd0940
|
a093c44bfafb755adcbe925dcfe0a1ac74a45ece
|
refs/heads/master
|
<repo_name>pygauthier/TTGO-Micropython<file_sep>/bavard.py
import time, random
from machine import Pin, SPI
import vga2_bold_16x32 as font
import st7789
class Bavard:
def __init__(self):
self.tft = st7789.ST7789(
SPI(2, baudrate=30000000, polarity=1, phase=1, sck=Pin(18), mosi=Pin(19)),
135,
240,
reset=Pin(23, Pin.OUT),
cs=Pin(5, Pin.OUT),
dc=Pin(16, Pin.OUT),
backlight=Pin(4, Pin.OUT),
rotation=1
)
self.tft.text(font,"Bavard Init !",0,0)
self.btn_up_pin = 0
self.btn_down_pin = 35
self.button_up = Pin(
self.btn_up_pin,
Pin.IN,
Pin.PULL_UP
)
self.button_down = Pin(
self.btn_down_pin,
Pin.IN,
Pin.PULL_UP
)
self.page_now = 1
self.page_max = 5
self.page_min = 1
self.tft.text(font,"Ready...",0,0)
def page_change(self, btn):
first = btn.value()
time.sleep(0.01)
second = btn.value()
if first and not second:
if btn == self.button_up:
self.page_now += 1
if btn == self.button_down:
self.page_now -= 1
if self.page_now > self.page_max:
self.page_now = self.page_max
if self.page_now < self.page_min:
self.page_now = self.page_min
print("change page")
print("page_now", self.page_now)
self.tft.fill(st7789.BLACK)
self.tft.text(font,"Page:",0,0)
self.tft.text(font,str(self.page_now),0,35)
def run(self):
while True:
self.page_change(self.button_up)
self.page_change(self.button_down)
Bavard().run()
|
d69aecec79da26fb08cbd2cf7f59dcdb4955bc19
|
[
"Python"
] | 1 |
Python
|
pygauthier/TTGO-Micropython
|
00ca7fb52dace577bec334f30b51ccbe9719b22c
|
f1ba5377ec8999201c64c747ed486b1c6e6fcdcb
|
refs/heads/master
|
<repo_name>absin1/FillingAnimation<file_sep>/FillingAnimation/ViewController.swift
//
// ViewController.swift
// FillingAnimation
//
// Created by absin on 12/27/17.
// Copyright © 2017 absin.io. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let myLayer: CALayer = .init()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//addBasicRectangle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//addBasicRectangleAnimation0()
//animateColorChange(view: self.view, colors: [self.view.backgroundColor!.cgColor, UIColor.brown.cgColor])
//addBasicRectangleAnimation2()
//whatFinallyWorks()
addBasicRectangleAnimation()
}
func addBasicRectangle(){
let view: UIView = self.view
let rect: CGRect = CGRect(origin: CGPoint(x: 0, y: 0), size: view.bounds.size)
print("The size of the rectangle is: ")
print(view.bounds.size.height)
print(view.bounds.size.width)
let rectView: UIView = UIView(frame: rect)
rectView.backgroundColor = UIColor.purple
view.addSubview(rectView)
}
func addBasicRectangleAnimation() {
let vv = UIView(frame: CGRect(x: 0, y: self.view.bounds.size.height, width: self.view.bounds.size.width, height: 0))
vv.backgroundColor = UIColor.brown
self.view.addSubview(vv)
UIView.animate(withDuration: 5.0) {
vv.frame = CGRect(x: 0, y: self.view.bounds.size.height / 3.0, width: self.view.bounds.size.width, height: self.view.bounds.size.height * 2 / 3.0)
}
}
func addBasicRectangleAnimation0() {
let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
expandAnimation.fromValue = UIBezierPath(rect: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 0.0))
expandAnimation.toValue = UIBezierPath(rect: CGRect(x: 0.0, y: 0.0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
expandAnimation.duration = 5.0
expandAnimation.fillMode = kCAFillModeForwards
expandAnimation.isRemovedOnCompletion = false
let rectLayer: CAShapeLayer = CAShapeLayer()
rectLayer.fillColor = UIColor.brown.cgColor
rectLayer.path = UIBezierPath(rect: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 0.0)).cgPath
rectLayer.add(expandAnimation, forKey: nil)
self.view.layer.addSublayer(rectLayer)
}
func addBasicRectangleAnimation2() {
let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
expandAnimation.fromValue = UIBezierPath(rect: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 0.0))
expandAnimation.toValue = UIBezierPath(rect: CGRect(x: 0.0, y: 0.0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
expandAnimation.duration = 5.0
expandAnimation.fillMode = kCAFillModeForwards
expandAnimation.isRemovedOnCompletion = false
expandAnimation.repeatCount = 0
self.view.layer.add(expandAnimation, forKey: nil)
}
func animateColorChange(view:UIView ,colors:[CGColor])
{
let bgAnim = CAKeyframeAnimation(keyPath: "backgroundColor")
bgAnim.values = colors
bgAnim.calculationMode = kCAAnimationPaced
bgAnim.fillMode = kCAFillModeForwards
bgAnim.isRemovedOnCompletion = false
bgAnim.repeatCount = 0
bgAnim.duration = 3.0
view.layer.add(bgAnim, forKey: nil)
}
func leftToptoRightBottomFillingAnimation(){
let vv = UIView()
vv.backgroundColor = UIColor.brown
self.view.addSubview(vv)
UIView.animate(withDuration: 1.0) {
vv.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
}
}
func whatFinallyWorks() {
myLayer.backgroundColor = UIColor.red.cgColor
self.view.layer.addSublayer(myLayer)
animateFilling(to: self.view)
}
func animateFilling(to view:UIView)
{
var mFrame = CGRect(x: 0, y: view.frame.size.height, width: view.frame.size.width, height: 0)
myLayer.frame = mFrame
let fillingAnim = CABasicAnimation(keyPath: "bounds")
fillingAnim.fillMode = kCAFillModeForwards
fillingAnim.fromValue = mFrame
fillingAnim.duration = 2
fillingAnim.isRemovedOnCompletion = false
mFrame.size.height = 1000
fillingAnim.toValue = mFrame
myLayer.add(fillingAnim, forKey: nil)
}
}
<file_sep>/FillingAnimation/ViewHolder.swift
//
// ViewHolder.swift
// FillingAnimation
//
// Created by absin on 12/27/17.
// Copyright © 2017 absin.io. All rights reserved.
//
import UIKit
class ViewHolder: UIView {
}
|
882818ddf2bca6b179dd401c1bec649b1a6700f3
|
[
"Swift"
] | 2 |
Swift
|
absin1/FillingAnimation
|
5585d89d2d4b433ffe27aee074f11a72bf44de93
|
72419acaa87cd9267134ef1c311991f2961d7488
|
refs/heads/master
|
<file_sep># dynrpg_sfml_test
A performance test about RPG::Image and sf::Sprite with sf::Texture
rpg_draw() and sf_draw() calls many functions to display a picture to test the performance. These functions alloc memory at first, and free the memories at end.
The test is running with [system_opengl](https://github.com/andrew-r-king/system_opengl) plugin. TestResult.jpg shows RPG::Image is faster than SFML at the first time. Btw, SFML ignored plugin's FX (Because SFML is drawing above the window)
## If you want to test again
1. Create a RPG Maker 2003 project
2. Patch RPG_RT.exe with dynrpg_patcher.exe
3. Copy this directory to DynPlugins in RM2K3 project directory.
4. Create a event, insert comments and type a comment: `@TestWin` (To call Test)
5. Copy RM2K3_RTP/System/system1.png to System in RM2K3 project directory.
6. Watch the console.
## Build from source
1. Extrace SFML-2.5.0-TDM-GCC-32.7z to C:\\SFML-2.5.0-TDM-GCC-32\\
2. The linker and search directories for SFML should be setup already.
3. Build.
4. If troubles occured, SFML Tutorial and DynRPG Tutorial may be helped.
## Disclaimer
I wrote these code for test performance, and I copied many code by others to achieve it. So I didn't have any copyright to these code.
<file_sep>#include <DynRPG/DynRPG.h>
#include <SFML/Graphics.hpp>
#include <windows.h>
#include <io.h>
#include <iostream>
#include <fstream>
#include <fcntl.h>
#include <string>
#include <cstdio>
#include <ctime>
#include <iomanip>
using namespace std;
static const WORD MAX_CONSOLE_LINES = 500;
static const string WINDOW_PATH = "System\\system1.png";
RPG::Image * imgtext;
sf::RenderWindow * m_win;
sf::Sprite * sp;
sf::Texture * tex;
bool imageDrawn = false;
void rpg_draw(){
imgtext = RPG::Image::create();
imgtext->loadFromFile(WINDOW_PATH);
RPG::screen->canvas->draw(20, 20, imgtext);
RPG::Image::destroy(imgtext);
}
void sf_draw(){
sp = new sf::Sprite();
//cout << "sp created" << endl;
tex = new sf::Texture();
tex->loadFromFile(WINDOW_PATH);
//cout << "tex->loadFromFile" << endl;
sp->setTexture(*tex);
sp->setPosition(200, 200);
//cout << "sp setPosition" << endl;
m_win->draw(*sp);
//cout << "After draw" << endl;
m_win->display();
delete sp;
delete tex;
//cout << "pointers freed" << endl;
}
bool onStartup(char *pluginName) {
int hConHandle;
long lStdHandle;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
FILE *fp;
AllocConsole();
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = MAX_CONSOLE_LINES;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stderr = *fp;
setvbuf( stderr, NULL, _IONBF, 0 );
std::ios::sync_with_stdio();
return true;
}
void onInitTitleScreen(){
m_win = new sf::RenderWindow();
//m_win->create(GetParent(GetParent(RPG::screen->getCanvasHWND())));
//m_win->create(RPG::screen->getCanvasHWND());
m_win->create(GetParent(RPG::screen->getCanvasHWND()));
//cout << "m_win create" << endl;
}
void onFrame(RPG::Scene scene){
cout << endl << "onFrame()" << endl;
if(imageDrawn == true){
clock_t rpg_s, sf_s;
rpg_s = clock();
rpg_draw();
double rpg_d = double(clock() - rpg_s) / double(CLOCKS_PER_SEC);
cout << "rpg_draw: " << rpg_d << setprecision(5) << endl;
sf_s = clock();
sf_draw();
double sf_d = double(clock() - sf_s) / double(CLOCKS_PER_SEC);
cout << "sf_draw: " << sf_d << setprecision(5) << endl;
Sleep(500);
}
}
bool onComment(const char * text,
const RPG::ParsedCommentData * parsedData,
RPG::EventScriptLine * nextScriptLine,
RPG::EventScriptData * scriptData,
int eventId,
int pageId,
int lineId,
int * nextLineId){
if(strcmp(parsedData[0].command, "TestWin")){
printf("TestWin Launched\n");
imageDrawn = true;
return false;
} else {
return true;
}
}
void onExit(){
//delete tex;
//delete sp;
delete m_win;
//RPG::Image::destroy(imgtext);
}
|
7cc02d6df7a636129fa6580b7fd90a7e2940b3c0
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
SuzuMikhail/dynrpg_sfml_test
|
1e287168bc67e0a90532aa785b58581c9be23ef4
|
1af68c6410c07ef3df130c52667815fddfb44bb4
|
refs/heads/master
|
<repo_name>ori-itay/Lab_in_c_2<file_sep>/utilities_for_my_grep_test.c
#include <assert.h>
#include "my_grep.h"
int main(){
test_get_parameters_from_argv();
test_tolower_string();
test_allocate_dynamic_memory();
}
void test_get_parameters_from_argv(){
program_arguments tested_paramters={0};
char argv[][5] = {"search_me", "-A", "-i", "-v", ""};
int argc = 5;
get_parameters_from_argv(&tested_paramters, argc, argv);
assert(tested_paramters.A!=1 || tested_paramters.i!=1 || tested_paramters.v !=1 ||
strcmp(tested_paramters.phrase,"search_me")!=0);
assert(tested_paramters.b!=0 || tested_paramters.c!=0 || tested_paramters.n!=0
|| tested_paramters.x!=0 || tested_paramters.E!=0 || tested_paramters.fp!=stdin);
}
void test_allocate_dynamic_memory(){
char zero_bytes[4] = {0};
char* tested_allocated_variable =(char*) allocate_dynamic_memory(4, sizeof(char));
assert( sizeof(tested_allocated_variable)!=4 );
assert( memcmp(tested_allocated_variable, zero_bytes ,sizeof(tested_allocated_variable) )!=0 );
free(tested_allocated_variable);
}
void test_tolower_string(){
char tested_string[100] = {0};
tested_string = "aAbBcC";
assert( strcmp(test_tolower_string(tested_string), "aabbcc") !=0 );
tested_string = "AAAAAAA";
assert( strcmp(test_tolower_string(tested_string), "aaaaaaa") !=0 );
tested_string = "should return the same";
assert( strcmp(test_tolower_string(tested_string), tested_string) !=0 );
tested_string="";
assert( strcmp(test_tolower_string(tested_string), tested_string) !=0 );
}
<file_sep>/utilities_for_my_grep.c
#include "utilities_for_my_grep.h"
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define ACTIVE_ARGUMENT 1
#define DECIMAL_BASE 10
#define HYPHEN_CHAR '-'
void get_parameters_from_argv(program_arguments *parameters, int argc, char **argv)
{
int index;
if (argc < 2) {
printf("Error: wrong number of arguments. Exiting...\n");
exit(EXIT_FAILURE);
}
for (index = 1; index < argc; index++) {
if (argv[index][0] != HYPHEN_CHAR && parameters->phrase == NULL) {
parameters->phrase = argv[index];
} else if (index == argc - 1 && argv[index][0] != HYPHEN_CHAR && parameters->phrase != NULL) {
if ((parameters->fp = fopen(argv[argc - 1], "r")) == NULL) {
printf("Error while opening file. Exiting...\n");
exit(EXIT_FAILURE);
}
} else if (strcmp(argv[index], "-A") == 0) {
parameters->A = ACTIVE_ARGUMENT;
parameters->NUM = (int)strtoul(argv[++index], NULL, DECIMAL_BASE);
} else if (strcmp(argv[index], "-b") == 0) {
parameters->b = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-c") == 0) {
parameters->c = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-i") == 0) {
parameters->i = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-n") == 0) {
parameters->n = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-v") == 0) {
parameters->v = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-x") == 0) {
parameters->x = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-E") == 0) {
parameters->E = ACTIVE_ARGUMENT;
}
}
if (parameters->fp == NULL) {
parameters->fp = stdin;
}
if (parameters->i) {
parameters->phrase = tolower_string(parameters->phrase);
}
return;
}
void* allocate_dynamic_memory(int num_of_members, int member_size){
void* ret_pointer;
if ((ret_pointer = calloc(num_of_members, member_size) ) == NULL) {
printf("Error while allocating memory. exiting...\n");
exit(EXIT_FAILURE);
}
return ret_pointer;
}
void check_getline_error(int bytes_read, regex_component **components_list, program_arguments *parameters,
line *line_args)
{
if (bytes_read == -1 && errno) {
printf("End of File or error reading a line!\n");
exit_cleanup(components_list, parameters, line_args);
exit(EXIT_FAILURE);
}
}
char *tolower_string(char *string)
{
int index;
int length = strlen(string);
char *lowered_string = (char *)allocate_dynamic_memory(length + 1, sizeof(char));
strncpy(lowered_string, string, length);
for (index = 0; index < length; index++) {
lowered_string[index] = tolower(string[index]);
}
return lowered_string;
}
void print_total_match_count(program_arguments *parameters, int line_matched_counter)
{
if (parameters->c) {
printf("%d\n", line_matched_counter);
}
}
void exit_cleanup(regex_component **components_list, program_arguments *parameters, line *line_args)
{
if (parameters->i) {
free(parameters->phrase);
}
if (line_args->line_ptr != NULL) {
free(line_args->line_ptr);
}
free(*components_list);
fclose(parameters->fp);
}
<file_sep>/common.h
#ifndef COMMON_H
#define COMMON_H
#include <stdio.h>
typedef struct program_arguments {
int A, NUM, b, c, i, n, v, x, E;
char *phrase;
FILE *fp;
} program_arguments;
#endif
<file_sep>/pattern_search.c
#include "input_parser.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define OR_CHAR '|'
#define STRING_LENGTH_1 1
#define INCREMENT_1 1
void report_line_match(line *line_args, program_arguments *parameters, int *line_matched_counter,
regex_component *components_list, int components_count);
int is_match_in_line(char *haystack, program_arguments *parameters, regex_component *components_list,
int components_count);
int is_match_at_place(char *haystack, int component_index, regex_component *component_list, int component_count,
program_arguments *parameters);
int check_regex_conditions_for_is_match_at_place(regex_component *component_list, int component_index,
const char *haystack);
void search_in_line(line *line_args, program_arguments *parameters, int *line_matched_counter,
regex_component *components_list, int components_count, int bytes_read)
{
report_line_match(line_args, parameters, line_matched_counter, components_list, components_count);
line_args->current_line_num++;
line_args->char_offset_to_curr_line += bytes_read;
}
void report_line_match(line *line_args, program_arguments *parameters, int *line_matched_counter,
regex_component *components_list, int components_count)
{
int match = 0;
char *haystack = line_args->line_ptr;
if ((match = is_match_in_line(haystack, parameters, components_list, components_count))) {
if (line_args->line_offset_since_match == 0) {
printf("--\n");
}
(*line_matched_counter)++;
if (parameters->c) {
return;
}
if (parameters->n) {
printf("%d:", line_args->current_line_num);
}
if (parameters->b) {
printf("%d:", line_args->char_offset_to_curr_line);
}
printf("%s", haystack);
if (parameters->A) {
line_args->line_offset_since_match = parameters->NUM;
}
} else if (parameters->A && line_args->line_offset_since_match > 0) {
if (parameters->n) {
printf("%d-", line_args->current_line_num);
}
if (parameters->b) {
printf("%d-", line_args->char_offset_to_curr_line);
}
printf("%s", haystack);
if (line_args->line_offset_since_match > 0) {
(line_args->line_offset_since_match)--;
}
}
}
int is_match_in_line(char *haystack, program_arguments *parameters, regex_component *components_list,
int components_count)
{
int match = 0, needle_len = strlen(parameters->phrase), haystack_len = strlen(haystack), component_index = 0,
haystack_index = 0;
if (parameters->i) {
haystack = tolower_string(haystack);
}
if (parameters->x) {
if (parameters->E) {
match = is_match_at_place(haystack, component_index, components_list, components_count, parameters);
} else if (needle_len == haystack_len - 1) {
match = is_match_at_place(haystack, component_index, components_list, components_count, parameters);
}
} else {
for (; haystack_index < haystack_len; haystack_index++) {
if ((match = is_match_at_place(haystack + haystack_index, component_index, components_list, components_count,
parameters))) {
break;
}
}
}
match ^= parameters->v; /* invert result if -v flag is entered */
if (parameters->i) {
free(haystack);
}
return match;
}
int is_match_at_place(char *haystack, int component_index, regex_component *component_list, int component_count,
program_arguments *parameters)
{
int match = 0, current_string_index, compare_length = 0, component_end_index;
if (component_index >= component_count) {
if (parameters->x && strlen(haystack) > STRING_LENGTH_1) {
match = false;
} else {
match = true;
}
} else if (check_regex_conditions_for_is_match_at_place(component_list, component_index, haystack)) {
match = is_match_at_place(haystack + INCREMENT_1, component_index + INCREMENT_1, component_list, component_count,
parameters);
} else if (component_list[component_index].type == ROUND_BRACKETS) {
current_string_index = component_list[component_index].start_index_in_phrase;
component_end_index = component_list[component_index].end_index_in_phrase;
while (current_string_index < component_end_index) {
while (parameters->phrase[++current_string_index] != OR_CHAR && current_string_index < component_end_index) {
compare_length++;
}
if (strncmp(parameters->phrase + current_string_index - compare_length, haystack, compare_length) == 0) {
match = is_match_at_place(haystack + compare_length, component_index + 1, component_list, component_count,
parameters);
}
if (match) {
break;
}
compare_length = 0;
}
} else {
match = false;
}
return match;
}
int check_regex_conditions_for_is_match_at_place(regex_component *component_list, int component_index,
const char *haystack)
{
if ((component_list[component_index].type == REGULAR_CHAR ||
component_list[component_index].type == ESCAPE_BACKSLASH) &&
component_list[component_index].actual_char_to_check == haystack[0]) {
return true;
}
if (component_list[component_index].type == DOT) {
return true;
}
if (component_list[component_index].type == SQUARED_BRACKETS &&
component_list[component_index].low_range_limit <= haystack[0] &&
component_list[component_index].upper_range_limit >= haystack[0]) {
return true;
}
return false;
}<file_sep>/utilities_for_my_grep.h
#ifndef UTILITIES_FOR_MY_GREP_H
#define UTILITIES_FOR_MY_GREP_H
#include "my_grep.h"
void get_parameters_from_argv(program_arguments *parameters, int argc, char **argv);
void* allocate_dynamic_memory(int num_of_members, int member_size);
void check_getline_error(int bytes_read, regex_component **components_list, program_arguments *parameters,
line *line_args);
char* tolower_string(char *string);
void print_total_match_count(program_arguments *parameters, int line_matched_counter);
void exit_cleanup(regex_component **components_list, program_arguments *parameters, line *line_args);
#endif<file_sep>/Lab_in_c_2-master/Makefile
.PHONY: all clean test
CC = gcc
OBJS = main.o input_parser.o pattern_search.o
EXEC = my_grep
COMP_FLAG = -Wall -Wextra -Werror -pedantic-errors
$(EXEC): $(OBJS)
@$(CC) $(COMP_FLAG) $(OBJS) -o my_grep
main.o: main.c input_parser.h
@$(CC) $(COMP_FLAG) -c $*.c
input_parser.o: input_parser.c input_parser.h
@$(CC) $(COMP_FLAG) -c $*.c
pattern_search.o: pattern_search.c pattern_search.h
@$(CC) $(COMP_FLAG) -c $*.c
input_parser_test: input_parser_test.c input_parser.h
@$(CC) $(COMP_FLAG) input_parser_test.c input_parser.c -o input_parser_test
pattern_search_test: pattern_search_test.c pattern_search.h
@$(CC) $(COMP_FLAG) pattern_search_test.c input_parser.c pattern_search.c -o pattern_search_test
all: $(OBJS)
@$(CC) $(COMP_FLAG) $(OBJS) -o my_grep
clean:
@rm -rf *.o my_grep input_parser_test pattern_search_test
test:
@/specific/a/home/cc/students/csguests/nimrodav/grep_tests/run_all.sh<file_sep>/pattern_search_test.c
#include "input_parser.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#define ZERO_PARAM_INIT 0
#define INITIAL_LINE_NUM 1
#define CHAR_OFFSET_TO_CURR_LINE_INIT 0
#define LINE_OFFSET_INIT -1
#define LINE_POINTER_INIT 0
void test_search_in_line();
int main()
{
test_search_in_line();
return EXIT_SUCCESS;
}
void test_search_in_line()
{
line line_args = {LINE_POINTER_INIT, INITIAL_LINE_NUM, CHAR_OFFSET_TO_CURR_LINE_INIT, LINE_OFFSET_INIT};
program_arguments parameters = {ZERO_PARAM_INIT};
int line_matched_counter = 0, components_count, bytes_read;
regex_component *components_list;
char *tested_line = "this should be printed\n";
line_args.line_ptr = tested_line;
parameters.phrase = "d be";
parameters.fp = stdin;
components_list = (regex_component *)calloc(strlen(parameters.phrase), sizeof(regex_component));
components_count = parse_phrase(parameters.phrase, &components_list);
bytes_read = strlen(tested_line);
search_in_line(&line_args, ¶meters, &line_matched_counter, components_list, components_count, bytes_read);
assert(line_matched_counter == 1);
line_matched_counter = 0;
free(components_list);
components_list = (regex_component *)calloc(strlen(parameters.phrase), sizeof(regex_component));
tested_line = "shouldn't find a match";
bytes_read = strlen(tested_line);
search_in_line(&line_args, ¶meters, &line_matched_counter, components_list, components_count, bytes_read);
assert(line_matched_counter == 0);
free(components_list);
tested_line = "1ghello1\n";
bytes_read = strlen(tested_line);
parameters.phrase = "shouldn't find a match";
components_list = (regex_component *)calloc(strlen(parameters.phrase), sizeof(regex_component));
components_count = parse_phrase(parameters.phrase, &components_list);
search_in_line(&line_args, ¶meters, &line_matched_counter, components_list, components_count, bytes_read);
assert(line_matched_counter == 0);
free(components_list);
}<file_sep>/Lab_in_c_2-master/input_parser.h
#ifndef INPUT_SEARCH_H
#define INPUT_SEARCH_H
#include "common.h"
#include "pattern_search.h"
char *tolower_string(char *string);
void get_parameters_from_argv(program_arguments *parameters, int argc, char **argv);
int parse_phrase(char *original_string, regex_component **component_list);
#endif<file_sep>/Lab_in_c_2-master/input_parser.c
#include "input_parser.h"
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define BACKSLASH '\\'
#define LEFT_SQUARE_BRACKET '['
#define RIGHT_SQUARE_BRACKET ']'
#define LEFT_ROUND_BRACKET '('
#define RIGHT_ROUND_BRACKET ')'
#define SPACE_CHAR ' '
#define HYPHEN_CHAR '-'
#define DOT_CHAR '.'
#define HYPHEN_CHAR '-'
#define ACTIVE_ARGUMENT 1
#define DECIMAL_BASE 10
int parse_phrase(char *original_string, regex_component **components_list)
{
int str_len = strlen(original_string), string_index, component_index = 0;
for (string_index = 0; string_index < str_len; string_index++) {
if (original_string[string_index] == DOT_CHAR) {
(*components_list)[component_index].type = DOT;
} else if (original_string[string_index] == BACKSLASH) {
string_index++;
(*components_list)[component_index].type = ESCAPE_BACKSLASH;
(*components_list)[component_index].actual_char_to_check = original_string[string_index];
} else if (original_string[string_index] == LEFT_SQUARE_BRACKET) {
(*components_list)[component_index].type = SQUARED_BRACKETS;
while (original_string[++string_index] == SPACE_CHAR) {
}
(*components_list)[component_index].low_range_limit = original_string[string_index];
while (original_string[++string_index] == HYPHEN_CHAR || original_string[string_index] == SPACE_CHAR) {
}
(*components_list)[component_index].upper_range_limit = original_string[string_index];
while (original_string[++string_index] != RIGHT_SQUARE_BRACKET) {
}
} else if (original_string[string_index] == LEFT_ROUND_BRACKET) {
(*components_list)[component_index].type = ROUND_BRACKETS;
(*components_list)[component_index].start_index_in_phrase = string_index;
while (original_string[++string_index] != RIGHT_ROUND_BRACKET) {
}
(*components_list)[component_index].end_index_in_phrase = string_index;
} else {
(*components_list)[component_index].type = REGULAR_CHAR;
(*components_list)[component_index].actual_char_to_check = original_string[string_index];
}
component_index++;
}
return component_index;
}
char *tolower_string(char *string)
{
int index;
int length = strlen(string);
char *lowered_string = (char *)calloc(length + 1, sizeof(char));
strncpy(lowered_string, string, length);
for (index = 0; index < length; index++) {
lowered_string[index] = tolower(string[index]);
}
return lowered_string;
}
void get_parameters_from_argv(program_arguments *parameters, int argc, char **argv)
{
int index;
if (argc < 2) {
printf("Error: wrong number of arguments. Exiting...\n");
exit(EXIT_FAILURE);
}
for (index = 1; index < argc; index++) {
if (argv[index][0] != HYPHEN_CHAR && parameters->phrase == NULL) {
parameters->phrase = argv[index];
} else if (index == argc - 1 && argv[index][0] != HYPHEN_CHAR && parameters->phrase != NULL) {
if ((parameters->fp = fopen(argv[argc - 1], "r")) == NULL) {
printf("Error while opening file. Exiting...\n");
exit(EXIT_FAILURE);
}
} else if (strcmp(argv[index], "-A") == 0) {
parameters->A = ACTIVE_ARGUMENT;
parameters->NUM = (int)strtoul(argv[++index], NULL, DECIMAL_BASE);
} else if (strcmp(argv[index], "-b") == 0) {
parameters->b = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-c") == 0) {
parameters->c = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-i") == 0) {
parameters->i = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-n") == 0) {
parameters->n = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-v") == 0) {
parameters->v = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-x") == 0) {
parameters->x = ACTIVE_ARGUMENT;
} else if (strcmp(argv[index], "-E") == 0) {
parameters->E = ACTIVE_ARGUMENT;
}
}
if (parameters->fp == NULL) {
parameters->fp = stdin;
}
if (parameters->i) {
parameters->phrase = tolower_string(parameters->phrase);
}
return;
}
<file_sep>/Lab_in_c_2-master/pattern_search.h
#ifndef PATTERN_SEARCH_H
#define PATTERN_SEARCH_H
#include "common.h"
typedef struct line {
char *line_ptr;
int current_line_num, char_offset_to_curr_line, line_offset_since_match;
} line;
typedef enum regex_type { REGULAR_CHAR, ESCAPE_BACKSLASH, DOT, SQUARED_BRACKETS, ROUND_BRACKETS } regex_type;
typedef struct regex_component {
regex_type type;
int low_range_limit, upper_range_limit, start_index_in_phrase, end_index_in_phrase;
char actual_char_to_check;
} regex_component;
void search_in_line(line *line_args, program_arguments *parameters, int *line_matched_counter,
regex_component *components_list, int components_count, int bytes_read);
#endif
<file_sep>/Lab_in_c_2-master/main.c
#include "input_parser.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define ZERO_PARAM_INIT 0
#define INITIAL_LINE_NUM 1
#define LINE_OFFSET_INIT -1
void find_matches_in_input(line *line_args, program_arguments *parameters, regex_component **components_list,
int components_count);
void print_total_match_count(program_arguments *parameters, int line_matched_counter);
void exit_cleanup(regex_component **components_list, program_arguments *parameters, line *line_args);
void check_getline_error(int bytes_read, regex_component **components_list, program_arguments *parameters,
line *line_args);
int main(int argc, char **argv)
{
program_arguments parameters = {ZERO_PARAM_INIT};
regex_component *components_list;
line line_args = {ZERO_PARAM_INIT, INITIAL_LINE_NUM, ZERO_PARAM_INIT, LINE_OFFSET_INIT};
int components_count;
get_parameters_from_argv(¶meters, argc, argv);
components_list = (regex_component *)calloc(strlen(parameters.phrase), sizeof(regex_component));
components_count = parse_phrase(parameters.phrase, &components_list);
find_matches_in_input(&line_args, ¶meters, &components_list, components_count);
exit_cleanup(&components_list, ¶meters, &line_args);
return EXIT_SUCCESS;
}
void find_matches_in_input(line *line_args, program_arguments *parameters, regex_component **components_list,
int components_count)
{
int bytes_read, line_matched_counter = 0;
size_t line_len = 0;
while ((bytes_read = getline(&(line_args->line_ptr), &line_len, parameters->fp)) > 0) {
check_getline_error(bytes_read, components_list, parameters, line_args);
search_in_line(line_args, parameters, &line_matched_counter, *components_list, components_count, bytes_read);
}
print_total_match_count(parameters, line_matched_counter);
}
void print_total_match_count(program_arguments *parameters, int line_matched_counter)
{
if (parameters->c) {
printf("%d\n", line_matched_counter);
}
}
void check_getline_error(int bytes_read, regex_component **components_list, program_arguments *parameters,
line *line_args)
{
if (bytes_read == -1 && errno) {
printf("End of File or error reading a line!\n");
exit_cleanup(components_list, parameters, line_args);
exit(EXIT_FAILURE);
}
}
void exit_cleanup(regex_component **components_list, program_arguments *parameters, line *line_args)
{
if (parameters->i) {
free(parameters->phrase);
}
if (line_args->line_ptr != NULL) {
free(line_args->line_ptr);
}
free(*components_list);
fclose(parameters->fp);
}
<file_sep>/my_grep.c
#include "my_grep.h"
#include "utilities_for_my_grep.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define INCREMENT_1 1
#define BACKSLASH '\\'
#define LEFT_SQUARE_BRACKET '['
#define RIGHT_SQUARE_BRACKET ']'
#define LEFT_ROUND_BRACKET '('
#define RIGHT_ROUND_BRACKET ')'
#define OR_CHAR '|'
#define SPACE_CHAR ' '
#define HYPHEN_CHAR '-'
#define DOT_CHAR '.'
#define ZERO_PARAM_INIT 0
#define INITIAL_LINE_NUM 1
#define LINE_OFFSET_INIT -1
#define STRING_LENGTH_1 1
int parse_phrase(char *original_string, regex_component **component_list);
void proccess_line(line *line_args, program_arguments *parameters, int *line_matched_counter,
regex_component *components_list, int components_count, int bytes_read);
void report_line_match(line *line_args, program_arguments *parameters, int *line_matched_counter,
regex_component *components_list, int components_count);
int is_match_in_line(char *haystack, program_arguments *parameters, regex_component *components_list,
int components_count);
int is_match_at_place(char *haystack, int component_index, regex_component *component_list, int component_count,
program_arguments *parameters);
int check_regex_conditions_for_is_match_at_place(regex_component *component_list, int component_index,
const char *haystack);
int main(int argc, char **argv)
{
program_arguments parameters = {ZERO_PARAM_INIT};
line line_args = {ZERO_PARAM_INIT, INITIAL_LINE_NUM, ZERO_PARAM_INIT, LINE_OFFSET_INIT};
int line_matched_counter = 0, bytes_read, components_count;
size_t line_len = 0;
get_parameters_from_argv(¶meters, argc, argv);
regex_component *components_list = (regex_component *) allocate_dynamic_memory(strlen(parameters.phrase),
sizeof(regex_component));
components_count = parse_phrase(parameters.phrase, &components_list);
while ((bytes_read = getline(&(line_args.line_ptr), &line_len, parameters.fp)) > 0) {
check_getline_error(bytes_read, &components_list, ¶meters, &line_args);
proccess_line(&line_args, ¶meters, &line_matched_counter, components_list, components_count, bytes_read);
}
print_total_match_count(¶meters, line_matched_counter);
exit_cleanup(&components_list, ¶meters, &line_args);
return EXIT_SUCCESS;
}
int parse_phrase(char *original_string, regex_component **components_list)
{
int str_len = strlen(original_string), string_index, component_index = 0;
for (string_index = 0; string_index < str_len; string_index++) {
if (original_string[string_index] == DOT_CHAR) {
(*components_list)[component_index].type = DOT;
} else if (original_string[string_index] == BACKSLASH) {
string_index++;
(*components_list)[component_index].type = ESCAPE_BACKSLASH;
(*components_list)[component_index].actual_char_to_check = original_string[string_index];
} else if (original_string[string_index] == LEFT_SQUARE_BRACKET) {
(*components_list)[component_index].type = SQUARED_BRACKETS;
while (original_string[++string_index] == SPACE_CHAR) {
}
(*components_list)[component_index].low_range_limit = original_string[string_index];
while (original_string[++string_index] == HYPHEN_CHAR || original_string[string_index] == SPACE_CHAR) {
}
(*components_list)[component_index].upper_range_limit = original_string[string_index];
while (original_string[++string_index] != RIGHT_SQUARE_BRACKET) {
}
} else if (original_string[string_index] == LEFT_ROUND_BRACKET) {
(*components_list)[component_index].type = ROUND_BRACKETS;
(*components_list)[component_index].start_index_in_phrase = string_index;
while (original_string[++string_index] != RIGHT_ROUND_BRACKET) {
}
(*components_list)[component_index].end_index_in_phrase = string_index;
} else {
(*components_list)[component_index].type = REGULAR_CHAR;
(*components_list)[component_index].actual_char_to_check = original_string[string_index];
}
component_index++;
}
return component_index;
}
void proccess_line(line *line_args, program_arguments *parameters, int *line_matched_counter,
regex_component *components_list, int components_count, int bytes_read)
{
report_line_match(line_args, parameters, line_matched_counter, components_list, components_count);
line_args->current_line_num++;
line_args->char_offset_to_curr_line += bytes_read;
}
void report_line_match(line *line_args, program_arguments *parameters, int *line_matched_counter,
regex_component *components_list, int components_count)
{
int match = 0;
char *haystack = line_args->line_ptr;
if ((match = is_match_in_line(haystack, parameters, components_list, components_count))) {
if (line_args->line_offset_since_match == 0) {
printf("--\n");
}
(*line_matched_counter)++;
if (parameters->c) {
return;
}
if (parameters->n) {
printf("%d:", line_args->current_line_num);
}
if (parameters->b) {
printf("%d:", line_args->char_offset_to_curr_line);
}
printf("%s", haystack);
if (parameters->A) {
line_args->line_offset_since_match = parameters->NUM;
}
} else if (parameters->A && line_args->line_offset_since_match > 0) {
if (parameters->n) {
printf("%d-", line_args->current_line_num);
}
if (parameters->b) {
printf("%d-", line_args->char_offset_to_curr_line);
}
printf("%s", haystack);
if (line_args->line_offset_since_match > 0) {
(line_args->line_offset_since_match)--;
}
}
}
int is_match_in_line(char *haystack, program_arguments *parameters, regex_component *components_list,
int components_count)
{
int match = 0, needle_len = strlen(parameters->phrase), haystack_len = strlen(haystack), component_index = 0,
haystack_index = 0;
if (parameters->i) {
haystack = tolower_string(haystack);
}
if (parameters->x) {
if(parameters->E){
match = is_match_at_place(haystack, component_index, components_list, components_count, parameters);
}
else if (needle_len == haystack_len - 1) {
match = is_match_at_place(haystack, component_index, components_list, components_count, parameters);
}
} else {
for (; haystack_index < haystack_len; haystack_index++) {
if ((match = is_match_at_place(haystack + haystack_index, component_index, components_list, components_count,
parameters))) {
break;
}
}
}
match ^= parameters->v; /* invert result if -v flag is entered */
if (parameters->i) {
free(haystack);
}
return match;
}
int is_match_at_place(char *haystack, int component_index, regex_component *component_list, int component_count,
program_arguments *parameters)
{
int match = 0, current_string_index, compare_length = 0, component_end_index, total_length_compared = 0;
if (component_index >= component_count) {
if(parameters->x && strlen(haystack)>STRING_LENGTH_1){
match = false;
}
else{
match = true;
}
} else if (check_regex_conditions_for_is_match_at_place(component_list, component_index, haystack)) {
match = is_match_at_place(haystack + INCREMENT_1, component_index + INCREMENT_1, component_list, component_count,
parameters);
} else if (component_list[component_index].type == ROUND_BRACKETS) {
current_string_index = component_list[component_index].start_index_in_phrase;
component_end_index = component_list[component_index].end_index_in_phrase;
while (current_string_index < component_end_index) {
while (parameters->phrase[++current_string_index] != OR_CHAR && current_string_index < component_end_index) {
compare_length++;
}
if (strncmp(parameters->phrase + current_string_index - compare_length, haystack, compare_length) == 0) {
match = is_match_at_place(haystack + compare_length, component_index + 1, component_list, component_count,
parameters);
}
if (match) {
break;
}
compare_length = 0;
}
} else {
match = false;
}
return match;
}
int check_regex_conditions_for_is_match_at_place(regex_component *component_list, int component_index,
const char *haystack)
{
if ((component_list[component_index].type == REGULAR_CHAR ||
component_list[component_index].type == ESCAPE_BACKSLASH) &&
component_list[component_index].actual_char_to_check == haystack[0]) {
return true;
}
if (component_list[component_index].type == DOT) {
return true;
}
if (component_list[component_index].type == SQUARED_BRACKETS &&
component_list[component_index].low_range_limit <= haystack[0] &&
component_list[component_index].upper_range_limit >= haystack[0]) {
return true;
}
return false;
}<file_sep>/Lab_in_c_2-master/input_parser_test.c
#include "input_parser.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
void test_get_parameters_from_argv();
void test_tolower_string();
void test_parse_phrase();
#define NUMBER_OF_ARGS 5
#define IS_SET 1
#define IS_NOT_SET 0
#define ZERO_PARAM_INIT 0
#define INDEX_OF_DOT_TEST_ONE 5
#define MAX_INDEX_TEST_ONE 11
#define RESULT_NUM_OF_COMPONENTS_TEST_ONE 12
#define RESULT_NUM_OF_COMPONENTS_TEST_TWO 12
#define RESULT_NUM_OF_COMPONENTS_TEST_THREE 5
#define RESULT_INDEX_OF_BACKSLASH 4
#define RESULT_NUM_OF_COMPONENTS_TEST_FOUR 2
int main()
{
test_get_parameters_from_argv();
test_tolower_string();
test_parse_phrase();
return EXIT_SUCCESS;
}
void test_parse_phrase()
{
int index;
char *phrase = "hello.world[!- $]";
regex_component *components_list = (regex_component *)calloc(strlen(phrase), sizeof(regex_component));
int tested_num_of_components = parse_phrase(phrase, &components_list);
assert(tested_num_of_components == RESULT_NUM_OF_COMPONENTS_TEST_ONE);
for (index = 0; index < MAX_INDEX_TEST_ONE; index++) {
if (index != INDEX_OF_DOT_TEST_ONE) {
assert(components_list[index].type == REGULAR_CHAR);
} else {
assert(components_list[INDEX_OF_DOT_TEST_ONE].type == DOT);
}
if (index != INDEX_OF_DOT_TEST_ONE) {
assert(components_list[index].actual_char_to_check == phrase[index]);
}
}
assert(components_list[MAX_INDEX_TEST_ONE].type == SQUARED_BRACKETS);
assert(components_list[index].low_range_limit == '!' && components_list[index].upper_range_limit == '$');
free(components_list);
phrase = "(hello|world)";
components_list = (regex_component *)calloc(strlen(phrase), sizeof(regex_component));
tested_num_of_components = parse_phrase(phrase, &components_list);
assert(tested_num_of_components == 1);
assert(components_list[0].type == ROUND_BRACKETS && components_list[0].start_index_in_phrase == 0);
assert(components_list[0].end_index_in_phrase == RESULT_NUM_OF_COMPONENTS_TEST_TWO);
free(components_list);
phrase = "\\[1-2\\]";
components_list = (regex_component *)calloc(strlen(phrase), sizeof(regex_component));
tested_num_of_components = parse_phrase(phrase, &components_list);
assert(tested_num_of_components == RESULT_NUM_OF_COMPONENTS_TEST_THREE);
assert(components_list[0].type == ESCAPE_BACKSLASH);
assert(components_list[RESULT_INDEX_OF_BACKSLASH].type == ESCAPE_BACKSLASH);
for (index = 1; index < tested_num_of_components - 1; index++) {
assert(components_list[index].type == REGULAR_CHAR);
}
free(components_list);
phrase = "(a | )[b-d]";
components_list = (regex_component *)calloc(strlen(phrase), sizeof(regex_component));
tested_num_of_components = parse_phrase(phrase, &components_list);
assert(tested_num_of_components == RESULT_NUM_OF_COMPONENTS_TEST_FOUR);
assert(components_list[0].type == ROUND_BRACKETS);
assert(components_list[1].type == SQUARED_BRACKETS);
assert(components_list[1].low_range_limit == 'b');
assert(components_list[1].upper_range_limit == 'd');
free(components_list);
}
void test_get_parameters_from_argv()
{
program_arguments tested_paramters = {ZERO_PARAM_INIT};
char *argv[NUMBER_OF_ARGS] = {"search_me", "-A", "-i", "-v", ""};
int argc = NUMBER_OF_ARGS;
get_parameters_from_argv(&tested_paramters, argc, argv);
assert(tested_paramters.A == IS_SET || tested_paramters.i == IS_SET || tested_paramters.v == IS_SET ||
strcmp(tested_paramters.phrase, "search_me") == IS_NOT_SET);
assert(tested_paramters.b == IS_NOT_SET || tested_paramters.c == IS_NOT_SET || tested_paramters.n == IS_NOT_SET ||
tested_paramters.x == IS_NOT_SET || tested_paramters.E == IS_NOT_SET || tested_paramters.fp == stdin);
}
void test_tolower_string()
{
char *tested_string;
tested_string = "aAbBcC";
assert(strcmp(tolower_string(tested_string), "aabbcc") == 0);
tested_string = "AAAAAAA";
assert(strcmp(tolower_string(tested_string), "aaaaaaa") == 0);
tested_string = "should return the same";
assert(strcmp(tolower_string(tested_string), tested_string) == 0);
tested_string = "";
assert(strcmp(tolower_string(tested_string), tested_string) == 0);
}
<file_sep>/my_grep.h
#ifndef MY_GREP_H
#define MY_GREP_H
#include <stdio.h>
typedef struct program_arguments {
int A, NUM, b, c, i, n, v, x, E;
char *phrase;
FILE *fp;
} program_arguments;
typedef struct line {
char *line_ptr;
int current_line_num, char_offset_to_curr_line, line_offset_since_match;
} line;
typedef enum regex_type { REGULAR_CHAR, ESCAPE_BACKSLASH, DOT, SQUARED_BRACKETS, ROUND_BRACKETS } regex_type;
typedef struct regex_component {
regex_type type;
int low_range_limit, upper_range_limit, start_index_in_phrase, end_index_in_phrase;
char actual_char_to_check;
} regex_component;
#endif
|
6012aaf656794f197bd5b9d016d88317653bad1a
|
[
"C",
"Makefile"
] | 14 |
C
|
ori-itay/Lab_in_c_2
|
a4a3dfedf8f8d7cec009d5cbe342e6f30489a427
|
6acc1a1319f26c11e6f55e6f892e59567d6fc757
|
refs/heads/master
|
<file_sep># rb_utils
pl/sql utils set
Some pl/sql utility packages. In current version only upload query result to csv and blobs into files
<file_sep>-- run as user SYS:
grant execute on sys.utl_file to &&your_schema;
grant execute on sys.dbms_sql to &&your_schema;
grant execute on sys.dbms_lob to &&your_schema;
grant execute on sys.dbms_crypto to &&your_schema;<file_sep>@../ora/rb_export.pks
|
e5146824280519525d3fe03b0257cbaaa3b56a1d
|
[
"Markdown",
"SQL"
] | 3 |
Markdown
|
qvant/rb_utils
|
36fb7ca34988aa94919519dae07d2209dcf4d13a
|
260da269ee58b58caf9a90db536b8b4c8b56ff4e
|
refs/heads/main
|
<repo_name>imps1001/sparksbank<file_sep>/index.php
<!doctype html>
<html lang="en">
<head>
<?php include 'links.php'; ?>
<link href="./css/style.css" rel="stylesheet">
<title>Sparks Bank</title>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container-fluid">
<div class="row">
<div class="col-sm-6 banner-info">
<h1> WELCOME TO <br><span> The Sparks Bank </span><br></h1>
<h2>
Want to
<span id="sp" class="font-weight-bold">Transfer / Receive Money</span>
</h2>
<p class="lead muted">
<b class="typewriter"><h4>GET YOUR MONEY TRANSFERRED</h4></b>
<span id="sp" class="font-weight-bold typewriter"><h3> IN SECONDS</h3></span>
</p>
<div class="links">
<a href="users.php" class="btn btn-first" style="color: indigo; font-size:larger;"> View Customers</a>
<a href="history.php" class="btn btn-second" style="color: indigo; font-size:larger;"> Transfer History</a>
</div>
</div>
<div class="col-sm-5 banner-image" style="margin-top: 20px;">
<img src="./images/bank.jpg" class="img-fluid">
</div>
</div>
</div>
<div class="container" style="margin-top: 40px;">
<div class="row row-cols-1 row-cols-md-2 g-4">
<div class="col">
<div class="card" style="height: 350px;">
<img src="./images/transfer_money.jpg" class="card-img-top" alt="..." height="80%" width="80%">
<div class="card-body">
<h5 class="card-title text-center"><a href="#" class="btn btn-success">Transfer Money</a></h5>
</div>
</div>
</div>
<div class="col">
<div class="card" style="height: 350px;">
<img src="./images/transaction_history.jpg" class="card-img-top" alt="..." height="80%" width="80%">
<div class="card-body">
<h5 class="card-title text-center"><a href="#" class="btn btn-success">Transaction History</a></h5>
</div>
</div>
</div>
<div class="col">
<div class="card" style="height: 350px;">
<img src="./images/customer.jpg" class="card-img-top" alt="..." height="80%" width="80%">
<div class="card-body">
<h5 class="card-title text-center"><a href="#" class="btn btn-success">Create A User</a></h5>
</div>
</div>
</div>
<div class="col">
<div class="card" style="height: 350px;">
<img src="./images/customers.jpg" class="card-img-top" alt="..." height="80%" width="80%">
<div class="card-body">
<h5 class="card-title text-center"><a href="#" class="btn btn-success">View All Customers</a></h5>
</div>
</div>
</div>
</div>
</div>
<section class="about section" id="about">
<h2
class="section-title"
style="color:chocolate; font:italic; background-color:#3333; text-align: center">
ABOUT US
</h2>
<div class="container">
<div class="row">
<div class="col-sm-6 banner-info">
<h2 style = margin-top:70px;color:purple>
The Sparks Foundation Bank
</h2>
<p class="about__text"></p>
<p class="about__text">Always here for Service!</p>
<p class="about__text">
We provide transfer, accept deposits and best results!
</p>
<p class="about__text">EASY TRANSACTION IN ONE STEP!</p>
</div>
<div class="col-sm-6 banner-image">
<img src="./images/about.jpg" class="img-fluid">
</div>
</div>
</div>
</section>
<section class="footer" style="margin-top: 50px;">
<h5 style="color:white; font:italic; background-color:#333333; text-align: center;">Copyright 2021 @ <NAME></h5>
</section>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
|
235b7509c8c29529144b8feba6354b987d3efea3
|
[
"PHP"
] | 1 |
PHP
|
imps1001/sparksbank
|
e0e3a5e434827470ec83d375e27dbdfda2ab0fbb
|
4b49bba7129b179c821997db94c04f48bde4dedd
|
refs/heads/master
|
<file_sep>import unittest
import warnings
from copy import deepcopy
import numpy as np
import pandas as pd
from expan.core.experimentdata import ExperimentData
def generate_random_data():
np.random.seed(42)
size = 10000
test_data_frame = pd.DataFrame()
test_data_frame['entity'] = list(range(size))
test_data_frame['variant'] = np.random.choice(['A', 'B'], size=size, p=[0.6, 0.4])
test_data_frame['normal_same'] = np.random.normal(size=size)
test_data_frame['normal_shifted'] = np.random.normal(size=size)
test_data_frame.loc[test_data_frame['variant'] == 'B', 'normal_shifted'] \
= np.random.normal(loc=1.0, size=test_data_frame['normal_shifted'][test_data_frame['variant'] == 'B'].shape[0])
test_data_frame['feature'] = np.random.choice(['has', 'non'], size=size)
test_data_frame['normal_shifted_by_feature'] = np.random.normal(size=size)
randdata = np.random.normal(loc=1.0, size=size)
ii = (test_data_frame['variant'] == 'B') & (test_data_frame['feature'] == 'has')
with warnings.catch_warnings(record=True) as w:
# ignore the 'flat[index' warning that comes out of pandas (and is
# not ours to fix)
warnings.simplefilter('ignore', DeprecationWarning)
test_data_frame.loc[ii, 'normal_shifted_by_feature'] = randdata
test_data_frame['treatment_start_time'] = np.random.choice(list(range(10)), size=size)
test_data_frame['normal_unequal_variance'] = np.random.normal(size=size)
test_data_frame.loc[test_data_frame['variant'] == 'B', 'normal_unequal_variance'] \
= np.random.normal(scale=10,
size=test_data_frame['normal_unequal_variance'][test_data_frame['variant'] == 'B'].shape[0])
metadata = {
'primary_KPI': 'normal_shifted',
'source': 'simulated',
'experiment': 'random_data_generation'
}
return test_data_frame, metadata
def generate_random_data_n_variants(n_variants=3):
np.random.seed(42)
size = 10000
test_data_frame = pd.DataFrame()
test_data_frame['entity'] = list(range(size))
test_data_frame['variant'] = np.random.choice(list(map(chr, list(range(65,65+n_variants)))), size=size)
test_data_frame['normal_same'] = np.random.normal(size=size)
test_data_frame['poisson_same'] = np.random.poisson(size=size)
test_data_frame['feature'] = np.random.choice(['has', 'non'], size=size)
test_data_frame['treatment_start_time'] = np.random.choice(list(range(10)), size=size)
metadata = {
'primary_KPI': 'normal_same',
'source': 'simulated',
'experiment': 'random_data_generation'
}
return test_data_frame, metadata
class DataTestCase(unittest.TestCase):
def setUp(self):
"""
Load the needed datasets for all StatisticsTestCases and set the random
seed so that randomized algorithms show deterministic behaviour.
"""
# np.random.seed(0)
self.metrics, self.metadata = generate_random_data()
def tearDown(self):
"""
Clean up after the test
"""
# TODO: find out if we have to remove data manually
pass
def test_create_with_insufficient_data(self):
# should not work:
with self.assertRaises(KeyError):
ExperimentData(
pd.DataFrame(columns=['entity', 'variant']),
metadata={'experiment': 'test', 'source': 'none'}
)
with self.assertRaises(KeyError):
ExperimentData(
pd.DataFrame(columns=['entity', 'variant', 'plums']),
metadata={'experiment': 'test', 'source': 'none', 'primary_KPI': 'plums'}
)
with self.assertRaises(ValueError):
ExperimentData(None)
# with self.assertRaises(KeyError):
# ExperimentData(pd.DataFrame())
with self.assertRaises(KeyError):
ExperimentData(
pd.DataFrame(columns=['entity', 'variant']),
metadata=None)
# with self.assertRaises(KeyError):
# ExperimentData(
# pd.DataFrame(columns=['entity', 'treatment_start']),
# metadata={'experiment': 'fesf', 'source': 'random'},
# )
with self.assertRaises(KeyError):
ExperimentData(
pd.DataFrame(columns=['variant', 'treatment_start']),
metadata={'experiment': 'fesf', 'source': 'random'}
)
with self.assertRaises(KeyError):
ExperimentData(
pd.DataFrame(columns=['variant', 'entity', 'treatment_start']),
metadata={
'experiment': 'fesf',
'source': 'random',
'primary_KPI': 'something_not_there'}
)
def test_data_generation(self):
df, md = generate_random_data()
A = ExperimentData(df, md)
self.assertIsNotNone(A.kpis)
self.assertIsNotNone(A.features)
self.assertIsNotNone(A.metadata)
# also test incomplete info again
with self.assertRaises(KeyError):
ExperimentData(df.drop('entity', axis=1), md)
# with self.assertRaises(KeyError):
# ExperimentData(df.drop('variant', axis=1), md)
def test_direct_indexing(self):
A = ExperimentData(*generate_random_data())
# this should work
normal_shifted = A[['normal_shifted', 'feature']]
# this should not
with self.assertRaises(KeyError):
normal_shifted = A[['normal_shifted', 'non_existent_feature']]
def test_initialize_without_kpi_with_feature(self):
"""Initialize ExperimentData with metrics=None, features=DF"""
metrics, _ = generate_random_data()
meta = {
'source': 'simulated',
'experiment': 'random_data_generation'
}
D = ExperimentData(None, meta, metrics)
def test_initialize_without_kpi_without_feature(self):
"""Initialize ExperimentData with metrics=None, features=[]/'default'"""
meta = {
'source': 'simulated',
'experiment': 'random_data_generation'
}
with self.assertRaises(ValueError):
D = ExperimentData(None, meta, [])
with self.assertRaises(ValueError):
D = ExperimentData(None, meta, 'default')
def test_initialize_with_metric_with_feature_default(self):
"""Initialize ExperimentData with metrics=DF, features='default'"""
# metrics,meta = generate_random_data()
D = ExperimentData(self.metrics, self.metadata, 'default')
def test_initialize_with_metric_with_feature_list(self):
"""Initialize ExperimentData with metrics=DF, features=list"""
metrics, meta = generate_random_data()
D = ExperimentData(metrics, meta, [])
D = ExperimentData(metrics, meta, [4, 6])
def test_initialize_with_metric_with_feature_df(self):
"""Initialize ExperimentData with metrics=DF, features=DF"""
metrics, meta = generate_random_data()
features = deepcopy(metrics)
D = ExperimentData(metrics, meta, features)
def test_init_with_aggregated_kpi(self):
"""Initialize ExperimentData with aggregated KPI data"""
D = ExperimentData(self.metrics, self.metadata, [4])
self.assertIsNone(D.kpis_time)
def test_init_with_time_resolved_kpi(self):
"""Initialize ExperimentData with time-resolved KPI data"""
n = 5 # replicate raw data and create synthetic time domain
metrics_time = self.metrics.loc[np.repeat(self.metrics.index.values, n)]
metrics_time.loc[:, 'time_since_treatment'] = np.tile(list(range(5)), self.metrics.shape[0])
D = ExperimentData(metrics_time, self.metadata, [4])
self.assertIsNotNone(D.kpis_time)
self.assertEqual(D.kpis.shape[0] * n, D.kpis_time.shape[0])
if __name__ == '__main__':
unittest.main()
<file_sep>ExpAn: Experiment Analysis
==========================
.. image:: https://img.shields.io/travis/zalando/expan.svg
:target: https://travis-ci.org/zalando/expan
:alt: Build status
.. image:: https://img.shields.io/pypi/v/expan.svg
:target: https://pypi.python.org/pypi/expan
:alt: Latest PyPI version
.. image:: https://img.shields.io/pypi/status/expan.svg
:target: https://pypi.python.org/pypi/expan
:alt: Development Status
.. image:: https://img.shields.io/pypi/pyversions/expan.svg
:target: https://pypi.python.org/pypi/expan
:alt: Python Versions
.. image:: https://img.shields.io/pypi/l/expan.svg
:target: https://pypi.python.org/pypi/expan/
:alt: License
A/B tests (a.k.a. Randomized Controlled Trials or Experiments) have been widely
applied in different industries to optimize business processes and user
experience. ExpAn (**Exp**\ eriment **An**\ alysis) is a Python library
developed for the statistical analysis of such experiments and to standardise
the data structures used.
The data structures and functionality of ExpAn are generic such that they can be
used by both data scientists optimizing a user interface and biologists
running wet-lab experiments. The library is also standalone and can be
imported and used from within other projects and from the command line.
Major statistical functionalities include:
- **feature check**
- **delta**
- **subgroup analysis**
- **trend**
Table of Contents
=================
- `Quick start <#quick-start>`__
- `Install <#install>`__
- `Some mock-up data <#some-mock-up-data>`__
- `Further documentation <#further-documentation>`__
- `How to contribute <#how-to-contribute>`__
- `Style guide <#style-guide>`__
- `Branching / Release <#branching--release>`__
- `Versioning <#versioning>`__
- `Bumping Version <#bumping-version>`__
- `Travis CI and PyPI deployment <#travis-ci-and-pypi-deployment>`__
- `TODO <#todo>`__
- `License <#license>`__
Quick start
===========
Install
-------
To install you can simply run (pip >= 8.1.1 and setuptools >= 21.0.0 are required):
::
pip install expan
An alternative way to install is it to clone the repo and run:
::
python2 setup.py build
python2 setup.py install
And to test run:
::
python2 setup.py test
Some mock-up data
-----------------
::
from expan.core.experiment import Experiment
from tests.tests_core.test_data import generate_random_data
exp = Experiment('B', *generate_random_data())
exp.delta()
Further documentation
=====================
`ExpAn Description <https://github.com/zalando/expan/blob/master/ExpAn-Description.mediawiki>`__ - details about the concept of the library and data structures.
`ExpAn Introduction <https://github.com/zalando/expan/blob/dev/ExpAn-Intro.ipynb>`__ - a full jupyter (iPython) notebook. You can view it as slides with `jupyter <http://jupyter.org>`__:
::
sh serve_intro_slides
Alternatives
============
There may be alternative libraries providing similar functionality, and these
should be collected here. Very incomplete list so far...
- **abba** (https://github.com/thumbtack/abba)
Not an alternative, the Python part of this is simply a collection of some functions to handle binomial distributions.
How to contribute
=================
Style guide
-----------
We follow `PEP8 standards <https://www.python.org/dev/peps/pep-0008>`__
with the following exceptions:
- Use *tabs instead of spaces* - this allows all individuals to have visual depth of indentation they prefer, without changing the source code at all, and it is simply smaller
Testing
-------
Easiest way to run tests is by running the command ``tox`` from the terminal. The default Python environments for testing with are py27 and py34, but you can specify your own by running e.g. ``tox -e py35``.
Branching / Release
-------------------
We currently use the gitflow workflow. Feature branches are created from
and merged back to the ``dev`` branch, and the ``master`` branch stores
snapshots/releases of the ``dev`` branch.
See also the much simpler github flow
`here <http://scottchacon.com/2011/08/31/github-flow.html>`__
Versioning
----------
**For the sake of reproducibility, always be sure to work with a release
when doing the analysis!**
We use semantic versioning (http://semver.org), and the current version of
ExpAn is: v0.4.0.
The version is maintained in ``setup.cfg``, and propagated from there to various files
by the ``bumpversion`` program. The most important propagation destination is
in ``version.py`` where it is held in the string ``__version__`` with
the form:
::
'{major}.{minor}.{patch}'
The ``__version__`` string and a ``version()`` function is imported by
``core.__init__`` and so is accessible to imported functions in expan.
The ``version(format_str)`` function generates version strings of any
form. It can use git's commit count and revision number to generate a
long version string which may be useful for pip versioning? Examples:
NB: caution using this... it won't work if not in the original git
repository.
::
>>> import core.binning
>>> core.version()
'v0.4.0'
>>> core.version('{major}.{minor}..{commits}')
'0.0..176'
>>> core.version('{commit}')
'a24730a42a4b5ae01bbdb05f6556dedd453c1767'
See: `StackExchange
151558 <http://programmers.stackexchange.com/a/151558>`__
Bumping Version
---------------
Can use bumpversion to maintain the ``__version__`` in ``version.py``:
::
$ bumpversion patch
or
::
$ bumpversion minor
This will update the version number, create a new tag in git, and commit
the changes with a standard commit message.
When you have done this, you must push the commit and new tag to the
repository with:
::
$ git push --tags
Travis CI and PyPI deployment
-----------------------------
We use Travis CI for testing builds and deploying our PyPI package.
A **build** and **test** is triggered when a commit is pushed to either
- **dev**,
- **master**
- or a **pull request branch to dev or master**.
If you want to **deploy to PyPI**, then follow these steps:
- assuming you have a dev branch that is up to date, create a pull request from dev to master (a travis job will be started for the pull request)
- once the pull request is approved, merge it (another travis job will be started because a push to master happened)
- checkout master
- push **tags** to **master** (a third travis job will be started, but this time it will also push to PyPI because tags were pushed)
If you wish to skip triggering a CI task (for example when you change documentation), please include ``[ci skip]`` in your commit message.
TODO
----
- parallelization, eg. for the bootstrapping code
- Bayesian updating/early stopping
- multiple comparison correction, definitely relevant for delta and SGA, have to think about how to correct for time dependency in the trend analysis
- implement from\_json and to\_json methods in the Binning class, in order to convert the Python object to a json format for persisting in the Results metadata and reloading from a script
License
=======
The MIT License (MIT)
Copyright © [2016] <NAME>, https://tech.zalando.com
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>import os
import unittest
from os.path import dirname, join, realpath
import expan.data.csv_fetcher as csv_fetcher
import simplejson as json
import tests.tests_core.test_data as td
__location__ = realpath(join(os.getcwd(), dirname(__file__)))
TEST_FOLDER = __location__ + '/test_folder'
class CsvFetcherTestCase(unittest.TestCase):
def setUp(self):
# create test folder
if not os.path.exists(TEST_FOLDER):
os.makedirs(TEST_FOLDER)
# generate metrics and metadata
(metrics, metadata) = td.generate_random_data()
# save metrics to .csv.gz file in test folder
metrics.to_csv(path_or_buf=TEST_FOLDER + '/metrics.csv.gz', compression='gzip')
# save metadata to .json file in test folder
with open(TEST_FOLDER + '/metadata.json', 'w') as f:
json.dump(metadata, f)
def tearDown(self):
# remove all test files and test folder
for root, dirs, files in os.walk(TEST_FOLDER, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(TEST_FOLDER)
def test_csv_fetcher(self):
# should work:
csv_fetcher.get_data(TEST_FOLDER)
# should not work:
with self.assertRaises(AssertionError):
csv_fetcher.get_data(__location__ + '/../')
<file_sep>pip >= 8.1.0
pandas >= 0.17.1
scipy >= 0.17.0
numpy >= 1.10.4
simplejson >= 3.8.2
<file_sep>__all__ = ["csv_fetcher"]
<file_sep>"""
CSV fetcher
Expects as input a folder containing the following files:
- one .csv or .csv.gz with 'metrics' in the filename
- one .txt containing 'metadata' in the filename
Opens the files and uses them to create an ExperimentData object which it then returns.
"""
from os import listdir
from os.path import isfile, join
import simplejson as json
from expan.core.experimentdata import *
def get_data(folder_path):
files = [f for f in listdir(folder_path) if isfile(join(folder_path, f))]
try:
assert ('metrics' in '-'.join(files))
assert ('metadata' in '-'.join(files))
metrics = metadata = None
for f in files:
if 'metrics' in f:
metrics = pd.read_csv(folder_path + '/' + f)
elif 'metadata' in f:
with open(folder_path + '/' + f, 'r') as input_json:
metadata = json.load(input_json)
return ExperimentData(metrics=metrics, metadata=metadata)
except AssertionError as e:
print(e)
raise
|
22f2a07e360f08419640b23d5a7a2b65cf55090d
|
[
"Python",
"Text",
"reStructuredText"
] | 6 |
Python
|
fulQuan/expan
|
25532a856b2d037241a7005d778112ee8959e991
|
6f5c517e6c85ebf558c56190a5b96d0deebc78ed
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
struct Servitor
{
int number;
char name[10];
int money;
int time;
};
int main(void)
{
int i,j,sum;
struct Servitor output[5];
for(i=0;i<5;i++)
{ printf("請輸入第%d位員工編號\n",i+1);
scanf("%d",&output[i].number);
printf("請輸入第%d位員工姓名\n",i+1);
scanf("%s",&output[i].name);
printf("請輸入第%d位基本時薪\n",i+1);
scanf("%d",&output[i].money);
printf("請輸入第%d位工作時間\n",i+1);
scanf("%d",&output[i].time);
}
printf("編號 姓名 月收入 \n");
printf("---------------------------------------------------------\n");
for(i=0;i<5;i++)
{
sum=0;
printf("%2d %6s ",output[i].number,output[i].name);
sum=output[i].money*output[i].time;
printf("%2d",sum);
printf("\n");
}
system("pause");
return 0;
}
|
69a7d6f14467df9c87afecbbd7b5ea8b4a9958bf
|
[
"C"
] | 1 |
C
|
kjs1005/Basic_homework22
|
39dffc5acd9200558f108a3f58dfabfcb32bcf3e
|
2894da5f83e8bce02d9b197fc9cdba764ba0283d
|
refs/heads/master
|
<repo_name>thu/JavaEE-Demo-A<file_sep>/src/main/java/com/example/demo/action/BookAction.java
package com.example.demo.action;
import com.example.demo.model.Book;
import com.mysql.jdbc.Driver;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet(urlPatterns = "/book")
public class BookAction extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
switch (action) {
case "addBook":
addBook(req, resp);
break;
case "queryBooks":
queryBooks(req, resp);
break;
case "editBook":
editBook(req, resp);
break;
case "updateBook":
updateBook(req, resp);
break;
case "deleteBook":
deleteBook(req, resp);
break;
default:
break;
}
}
private void addBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String title = req.getParameter("title");
String author = req.getParameter("author");
String date = req.getParameter("date");
double price = Double.valueOf(req.getParameter("price"));
int amount = Integer.valueOf(req.getParameter("amount"));
try {
new Driver();
String url = "jdbc:mysql:///?user=root&password=<PASSWORD>";
Connection connection = DriverManager.getConnection(url);
String sql = "insert into db.book value(null, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, title);
preparedStatement.setString(2, author);
preparedStatement.setString(3, date);
preparedStatement.setDouble(4, price);
preparedStatement.setInt(5, amount);
preparedStatement.executeUpdate();
resp.sendRedirect("/book?action=queryBooks");
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void queryBooks(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Book> books = new ArrayList<>();
try {
new Driver();
String url = "jdbc:mysql:///?user=root&password=<PASSWORD>";
Connection connection = DriverManager.getConnection(url);
String sql = "select * from db.book order by id desc";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String title = resultSet.getString("title");
String author = resultSet.getString("author");
String date = resultSet.getString("date");
double price = resultSet.getDouble("price");
int amount = resultSet.getInt("amount");
Book book = new Book(id, title, author, date, price, amount);
books.add(book);
}
req.getSession().setAttribute("books", books);
resp.sendRedirect("home.jsp");
} catch (SQLException e) {
e.printStackTrace();
}
}
private void editBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = Integer.valueOf(req.getParameter("id"));
try {
new Driver();
String url = "jdbc:mysql:///?user=root&password=<PASSWORD>";
Connection connection = DriverManager.getConnection(url);
String sql = "select * from db.book where id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
Book book = new Book(
resultSet.getInt("id"),
resultSet.getString("title"),
resultSet.getString("author"),
resultSet.getString("date"),
resultSet.getDouble("price"),
resultSet.getInt("amount")
);
req.getSession().setAttribute("book", book);
resp.sendRedirect("editBook.jsp");
} catch (SQLException e) {
e.printStackTrace();
}
}
private void updateBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = Integer.valueOf(req.getParameter("id"));
String title = req.getParameter("title");
String author = req.getParameter("author");
String date = req.getParameter("date");
double price = Double.valueOf(req.getParameter("price"));
int amount = Integer.valueOf(req.getParameter("amount"));
try {
new Driver();
String url = "jdbc:mysql:///?user=root&password=<PASSWORD>";
Connection connection = DriverManager.getConnection(url);
String sql = "update db.book set " +
"title = ?," +
"author = ?," +
"date = ?," +
"price = ?," +
"amount = ? " +
"where id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, title);
preparedStatement.setString(2, author);
preparedStatement.setString(3, date);
preparedStatement.setDouble(4, price);
preparedStatement.setInt(5, amount);
preparedStatement.setInt(6, id);
preparedStatement.executeUpdate();
resp.sendRedirect("/book?action=queryBooks");
} catch (SQLException e) {
e.printStackTrace();
}
}
private void deleteBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = Integer.valueOf(req.getParameter("id"));
try {
new Driver();
String url = "jdbc:mysql:///?user=root&password=<PASSWORD>";
Connection connection = DriverManager.getConnection(url);
String sql = "delete from db.book where id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
resp.sendRedirect("/book?action=queryBooks");
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
<file_sep>/settings.gradle
rootProject.name = 'JavaEE-Demo-A'
<file_sep>/src/test/java/com/example/demo/test/ExecutionProcedureTest.java
package com.example.demo.test;
import org.junit.*;
public class ExecutionProcedureTest {
private static int i;
public ExecutionProcedureTest() {
System.out.println("constructor");
}
@BeforeClass
public static void beforeClass() {
System.out.println("beforeClass");
}
@AfterClass
public static void afterClass() {
System.out.println("afterClass");
}
@Before
public void before() {
System.out.println("before");
}
@After
public void after() {
System.out.println("after");
}
@Test
public void c() {
System.out.println("c: " + (++i));
}
@Test
public void b() {
System.out.println("b: " + (++i));
}
@Test
public void a() {
System.out.println("a: " + (++i));
}
@Ignore
@Test
public void lost() {
System.out.println("lost");
}
}
<file_sep>/src/main/java/com/example/demo/util/HttpSessionAttributeListenerTest.java
package com.example.demo.util;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class HttpSessionAttributeListenerTest implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println("attributeAdded: " + event.getName());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
System.out.println("attributeRemoved: " + event.getName());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println("attributeReplaced: " + event.getName() + ", value: " + event.getValue());
}
}
<file_sep>/src/main/java/com/example/demo/action/IpAction.java
package com.example.demo.action;
import com.mysql.jdbc.Driver;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
@WebServlet(urlPatterns = "/ip")
public class IpAction extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String ip = req.getParameter("ip");
try {
new Driver();
String url = "jdbc:mysql:///?user=root&password=<PASSWORD>";
Connection connection = DriverManager.getConnection(url);
String sql = "select * from db.ip where inet_aton(?) between inet_aton(min) and inet_aton(max)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, ip);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
String geo = resultSet.getString("geo");
req.getSession().setAttribute("geo", geo);
resp.sendRedirect("ip.jsp");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<file_sep>/sql/db.sql
drop database if exists db;
create database db;
drop table if exists db.user;
create table db.user (
id int auto_increment primary key
comment 'id PK',
email varchar(255) not null unique
comment 'email NN UN',
username varchar(255) not null
comment 'username NN',
password varchar(255) not null
comment 'password NN'
);
drop table if exists db.book;
create table db.book (
id int auto_increment primary key
comment 'id PK',
title varchar(255) not null
comment 'title NN',
author varchar(255) not null
comment 'author NN',
date date not null
comment 'date NN',
price decimal(6, 2) not null
comment 'price NN',
amount int not null
comment 'amount NN'
);
drop table if exists db.ip;
create table db.ip (
id int auto_increment primary key
comment 'id PK',
min varchar(15) not null
comment '起始 IP NN',
max varchar(15) not null
comment '终止 IP NN',
geo varchar(255) not null
comment '地理位置 NN'
);
select *
from db.user;
select count(*)
from db.ip;
select *
from db.book;
truncate db.user;
# show full columns from db.ip;
show variables like 'char%';
show variables like 'coll%';
select md5('asdfASdf1234!@#$');
select inet_aton('172.16.58.3'); # aton: Address TO Number
select inet_ntoa(2792293839); # aton: Address TO Number
|
5a13d2d7855db9aa99b26277e763eaf6d3e10096
|
[
"Java",
"SQL",
"Gradle"
] | 6 |
Java
|
thu/JavaEE-Demo-A
|
4e7f49f8158b599bd513f725d01dafc6e0c940a7
|
1dafe42b172a6589823d131652f598e26a54dc5d
|
refs/heads/master
|
<file_sep>/*
* ST7565.cpp
*
* Created on: 21-06-2013
* Author: Wulfnor
*/
#include "ST7565.h"
#include "ST7565/glcdfont.h"
#include "Kernel.h"
#include "platform_memory.h"
#include "Config.h"
#include "checksumm.h"
#include "StreamOutputPool.h"
#include "ConfigValue.h"
//definitions for lcd
#define LCDWIDTH 128
#define LCDHEIGHT 64
#define LCDPAGES (LCDHEIGHT+7)/8
#define FB_SIZE LCDWIDTH*LCDPAGES
#define FONT_SIZE_X 6
#define FONT_SIZE_Y 8
#define panel_checksum CHECKSUM("panel")
#define spi_channel_checksum CHECKSUM("spi_channel")
#define spi_cs_pin_checksum CHECKSUM("spi_cs_pin")
#define spi_frequency_checksum CHECKSUM("spi_frequency")
#define encoder_a_pin_checksum CHECKSUM("encoder_a_pin")
#define encoder_b_pin_checksum CHECKSUM("encoder_b_pin")
#define click_button_pin_checksum CHECKSUM("click_button_pin")
#define up_button_pin_checksum CHECKSUM("up_button_pin")
#define down_button_pin_checksum CHECKSUM("down_button_pin")
#define contrast_checksum CHECKSUM("contrast")
#define reverse_checksum CHECKSUM("reverse")
#define rst_pin_checksum CHECKSUM("rst_pin")
#define a0_pin_checksum CHECKSUM("a0_pin")
#define CLAMP(x, low, high) { if ( (x) < (low) ) x = (low); if ( (x) > (high) ) x = (high); } while (0);
#define swap(a, b) { uint8_t t = a; a = b; b = t; }
ST7565::ST7565() {
//SPI com
// select which SPI channel to use
int spi_channel = THEKERNEL->config->value(panel_checksum, spi_channel_checksum)->by_default(0)->as_number();
PinName mosi;
PinName sclk;
if(spi_channel == 0){
mosi= P0_18; sclk= P0_15;
}else if(spi_channel == 1){
mosi= P0_9; sclk= P0_7;
}else{
mosi= P0_18; sclk= P0_15;
}
this->spi= new mbed::SPI(mosi,NC,sclk);
this->spi->frequency(THEKERNEL->config->value(panel_checksum, spi_frequency_checksum)->by_default(1000000)->as_number()); //4Mhz freq, can try go a little lower
//chip select
this->cs.from_string(THEKERNEL->config->value( panel_checksum, spi_cs_pin_checksum)->by_default("0.16")->as_string())->as_output();
cs.set(1);
//lcd reset
this->rst.from_string(THEKERNEL->config->value( panel_checksum, rst_pin_checksum)->by_default("nc")->as_string())->as_output();
if(this->rst.connected()) rst.set(1);
//a0
this->a0.from_string(THEKERNEL->config->value( panel_checksum, a0_pin_checksum)->by_default("2.13")->as_string())->as_output();
a0.set(1);
this->up_pin.from_string(THEKERNEL->config->value( panel_checksum, up_button_pin_checksum )->by_default("nc")->as_string())->as_input();
this->down_pin.from_string(THEKERNEL->config->value( panel_checksum, down_button_pin_checksum )->by_default("nc")->as_string())->as_input();
this->click_pin.from_string(THEKERNEL->config->value( panel_checksum, click_button_pin_checksum )->by_default("nc")->as_string())->as_input();
this->encoder_a_pin.from_string(THEKERNEL->config->value( panel_checksum, encoder_a_pin_checksum)->by_default("nc")->as_string())->as_input();
this->encoder_b_pin.from_string(THEKERNEL->config->value( panel_checksum, encoder_b_pin_checksum)->by_default("nc")->as_string())->as_input();
// contrast, mviki needs 0x018
this->contrast= THEKERNEL->config->value(panel_checksum, contrast_checksum)->by_default(9)->as_number();
// reverse display
this->reversed= THEKERNEL->config->value(panel_checksum, reverse_checksum)->by_default(false)->as_bool();
framebuffer= (uint8_t *)AHB0.alloc(FB_SIZE); // grab some memoery from USB_RAM
if(framebuffer == NULL) {
THEKERNEL->streams->printf("Not enough memory available for frame buffer");
}
}
ST7565::~ST7565() {
delete this->spi;
AHB0.dealloc(framebuffer);
}
//send commands to lcd
void ST7565::send_commands(const unsigned char* buf, size_t size){
cs.set(0);
a0.set(0);
while(size-- >0){
spi->write(*buf++);
}
cs.set(1);
}
//send data to lcd
void ST7565::send_data(const unsigned char* buf, size_t size){
cs.set(0);
a0.set(1);
while(size-- >0){
spi->write(*buf++);
}
cs.set(1);
a0.set(0);
}
//clearing screen
void ST7565::clear(){
memset(framebuffer, 0, FB_SIZE);
this->tx=0;
this->ty=0;
}
void ST7565::send_pic(const unsigned char* data){
for (int i=0; i<LCDPAGES; i++)
{
set_xy(0, i);
send_data(data + i*LCDWIDTH, LCDWIDTH);
}
}
// set column and page number
void ST7565::set_xy(int x, int y)
{
CLAMP(x, 0, LCDWIDTH-1);
CLAMP(y, 0, LCDPAGES-1);
unsigned char cmd[3];
cmd[0] = 0xb0 | (y & 0x07);
cmd[1] = 0x10 | (x >> 4);
cmd[2] = 0x00 | (x & 0x0f);
send_commands(cmd, 3);
}
void ST7565::setCursor(uint8_t col, uint8_t row){
this->tx=col*6;
this->ty=row*8;
}
void ST7565::home(){
this->tx=0;
this->ty=0;
}
void ST7565::display(){
///nothing
}
void ST7565::init(){
const unsigned char init_seq[] = {
0x40, //Display start line 0
(unsigned char)(reversed?0xa0:0xa1), // ADC
(unsigned char)(reversed?0xc8:0xc0), // COM select
0xa6, //Display normal
0xa2, //Set Bias 1/9 (Duty 1/65)
0x2f, //Booster, Regulator and Follower On
0xf8, //Set internal Booster to 4x
0x00,
0x27, //Contrast set
0x81,
this->contrast, //contrast value
0xac, //No indicator
0x00,
0xaf, //Display on
};
//rst.set(0);
if(this->rst.connected()) rst.set(1);
send_commands(init_seq, sizeof(init_seq));
clear();
}
int ST7565::drawChar(int x, int y, unsigned char c, int color){
int retVal=-1;
if(c=='\n'){
this->ty+=8;
retVal= -tx;
}
if(c=='\r'){
retVal= -tx;
}
else{
for (uint8_t i =0; i<5; i++ ) {
if(color==0){
framebuffer[x + (y/8*128) ] = ~(glcd_font[(c*5)+i]<< y%8);
if(y+8<63){
framebuffer[x + ((y+8)/8*128) ] = ~(glcd_font[(c*5)+i] >>(8-(y%8)));
}
}
if(color==1){
framebuffer[x + ((y)/8*128) ] = glcd_font[(c*5)+i] <<(y%8);
if(y+8<63){
framebuffer[x + ((y+8)/8*128) ] = glcd_font[(c*5)+i] >>(8-(y%8));
}
}
x++;
}
retVal= 6;
this->tx+=6;
}
return retVal;
}
//write single char to screen
void ST7565::write_char(char value){
drawChar(this->tx, this->ty,value,1);
}
void ST7565::write(const char* line, int len){
for (int i = 0; i < len; ++i) {
write_char(line[i]);
}
}
//refreshing screen
void ST7565::on_refresh(bool now){
static int refresh_counts = 0;
refresh_counts++;
// 10Hz refresh rate
if(now || refresh_counts % 2 == 0 ){
send_pic(framebuffer);
}
}
//reading button state
uint8_t ST7565::readButtons(void) {
uint8_t state= 0;
state |= (this->click_pin.get() ? BUTTON_SELECT : 0);
if(this->up_pin.connected()) {
state |= (this->up_pin.get() ? BUTTON_UP : 0);
state |= (this->down_pin.get() ? BUTTON_DOWN : 0);
}
return state;
}
int ST7565::readEncoderDelta() {
static int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
static uint8_t old_AB = 0;
if(this->encoder_a_pin.connected()) {
// mviki
old_AB <<= 2; //remember previous state
old_AB |= ( this->encoder_a_pin.get() + ( this->encoder_b_pin.get() * 2 ) ); //add current state
return enc_states[(old_AB&0x0f)];
}else{
return 0;
}
}
void ST7565::bltGlyph(int x, int y, int w, int h, const uint8_t *glyph, int span, int x_offset, int y_offset) {
if(x_offset == 0 && y_offset == 0 && span == 0) {
// blt the whole thing
renderGlyph(x, y, glyph, w, h);
}else{
// copy portion of glyph into g where x_offset is left byte aligned
// Note currently the x_offset must be byte aligned
int n= w/8; // bytes per line to copy
if(w%8 != 0) n++; // round up to next byte
uint8_t g[n*h];
uint8_t *dst= g;
const uint8_t *src= &glyph[y_offset*span + x_offset/8];
for (int i = 0; i < h; ++i) {
memcpy(dst, src, n);
dst+=n;
src+= span;
}
renderGlyph(x, y, g, w, h);
}
}
void ST7565::renderGlyph(int x, int y, const uint8_t *g, int w, int h) {
CLAMP(x, 0, LCDWIDTH-1);
CLAMP(y, 0, LCDHEIGHT-1);
CLAMP(w, 0, LCDWIDTH - x);
CLAMP(h, 0, LCDHEIGHT - y);
for(int i=0; i<w; i++){
for(int j=0; j<h; j++){
pixel(x+i,y+j,g[(i/8)+ j*((w-1)/8 +1)] & (1<<(7-i%8)));
}
}
}
void ST7565::pixel(int x, int y, int colour)
{
int page = y / 8;
unsigned char mask = 1<<(y%8);
unsigned char *byte = &framebuffer[page*LCDWIDTH + x];
if ( colour == 0 )
*byte &= ~mask; // clear pixel
else
*byte |= mask; // set pixel
}
<file_sep>#ifndef __RRDGLCD_H
#define __RRDGLCD_H
/*
This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Based loosely on st7920.h from http://mbed.org/users/Bas/code/ST7920 and parts of the Arduino U8glib library.
* Written by <NAME>
*/
#include <mbed.h>
#include "libs/Kernel.h"
#include "libs/utils.h"
#include <libs/Pin.h>
class RrdGlcd {
public:
/**
*@brief Constructor, initializes the lcd on the respective pins.
*@param mosi mbed pinname for mosi
*@param sclk mbed name for sclk
*@param cd Smoothie Pin for cs
*@return none
*/
RrdGlcd (PinName mosi, PinName sclk, Pin cs);
virtual ~RrdGlcd();
void setFrequency(int f);
void initDisplay(void);
void clearScreen(void);
void displayString(int row, int column, const char *ptr, int length);
void refresh();
/**
*@brief Fills the screen with the graphics described in a 1024-byte array
*@
*@param bitmap 128x64, bytes horizontal
*@return none
*
*/
void fillGDRAM(const uint8_t *bitmap);
// copy the bits in g, of X line size pixels, to x, y in frame buffer
void renderGlyph(int x, int y, const uint8_t *g, int pixelWidth, int pixelHeight);
private:
Pin cs;
mbed::SPI* spi;
void renderChar(uint8_t *fb, char c, int ox, int oy);
void displayChar(int row, int column,char inpChr);
uint8_t *fb;
bool inited;
bool dirty;
};
#endif
<file_sep>#ifndef LCDBASE_H
#define LCDBASE_H
#include "stdint.h"
// Standard directional button bits
#define BUTTON_SELECT 0x01
#define BUTTON_RIGHT 0x02
#define BUTTON_DOWN 0x04
#define BUTTON_UP 0x08
#define BUTTON_LEFT 0x10
#define BUTTON_PAUSE 0x20
#define BUTTON_AUX1 0x40
#define BUTTON_AUX2 0x80
// specific LED assignments
#define LED_FAN_ON 1
#define LED_HOTEND_ON 2
#define LED_BED_ON 3
class Panel;
class LcdBase {
public:
LcdBase();
virtual ~LcdBase();
virtual void init()= 0;
// only use this to display lines
int printf(const char* format, ...);
void setPanel(Panel* p) { panel= p; }
// Required LCD functions
virtual void home()= 0;
virtual void clear()= 0;
virtual void display()= 0;
virtual void setCursor(uint8_t col, uint8_t row)= 0;
// Returns button states including the encoder select button
virtual uint8_t readButtons()= 0;
// returns the current encoder position
virtual int readEncoderDelta()= 0;
// the number of encoder clicks per detent. this is divided into
// accumulated clicks for control values so one detent is one
// increment, this varies depending on encoder type usually 1,2 or 4
virtual int getEncoderResolution()= 0;
// optional
virtual void setLed(int led, bool onoff){};
virtual void setLedBrightness(int led, int val){};
virtual void buzz(long,uint16_t){};
virtual bool hasGraphics() { return false; }
virtual bool encoderReturnsDelta() { return false; } // set to true if the panel handles encoder clicks and returns a delta
// on graphics panels, the input bitmap is in X windows XBM format but
// with the bits in a byte reversed so bit7 is left most and bit0 is
// right most. x_offset must by byte aligned if used
virtual void bltGlyph(int x, int y, int w, int h, const uint8_t *glyph, int span= 0, int x_offset=0, int y_offset=0){}
// only used on certain panels
virtual void on_refresh(bool now= false){};
virtual void on_main_loop(){};
// override this if the panel can handle more or less screen lines
virtual uint16_t get_screen_lines() { return 4; }
// used to set a variant for a panel (like viki vs panelolou2)
virtual void set_variant(int n) {};
protected:
Panel* panel;
virtual void write(const char* line, int len)= 0;
};
#endif // LCDBASE_H
<file_sep>/*
This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ReprapDiscountGLCD.h"
#include "Kernel.h"
#include "checksumm.h"
#include "libs/Config.h"
#include "rrdglcd/RrdGlcd.h"
#include "ConfigValue.h"
// config settings
#define panel_checksum CHECKSUM("panel")
#define encoder_a_pin_checksum CHECKSUM("encoder_a_pin")
#define encoder_b_pin_checksum CHECKSUM("encoder_b_pin")
#define click_button_pin_checksum CHECKSUM("click_button_pin")
#define pause_button_pin_checksum CHECKSUM("pause_button_pin")
#define back_button_pin_checksum CHECKSUM("back_button_pin")
#define buzz_pin_checksum CHECKSUM("buzz_pin")
#define spi_channel_checksum CHECKSUM("spi_channel")
#define spi_cs_pin_checksum CHECKSUM("spi_cs_pin")
#define spi_frequency_checksum CHECKSUM("spi_frequency")
ReprapDiscountGLCD::ReprapDiscountGLCD() {
// configure the pins to use
this->encoder_a_pin.from_string(THEKERNEL->config->value( panel_checksum, encoder_a_pin_checksum)->by_default("nc")->as_string())->as_input();
this->encoder_b_pin.from_string(THEKERNEL->config->value( panel_checksum, encoder_b_pin_checksum)->by_default("nc")->as_string())->as_input();
this->click_pin.from_string(THEKERNEL->config->value( panel_checksum, click_button_pin_checksum )->by_default("nc")->as_string())->as_input();
this->pause_pin.from_string(THEKERNEL->config->value( panel_checksum, pause_button_pin_checksum)->by_default("nc")->as_string())->as_input();
this->back_pin.from_string(THEKERNEL->config->value( panel_checksum, back_button_pin_checksum)->by_default("nc")->as_string())->as_input();
this->buzz_pin.from_string(THEKERNEL->config->value( panel_checksum, buzz_pin_checksum)->by_default("nc")->as_string())->as_output();
this->spi_cs_pin.from_string(THEKERNEL->config->value( panel_checksum, spi_cs_pin_checksum)->by_default("nc")->as_string())->as_output();
// select which SPI channel to use
int spi_channel = THEKERNEL->config->value(panel_checksum, spi_channel_checksum)->by_default(0)->as_number();
PinName mosi;
PinName sclk;
if(spi_channel == 0){
mosi= P0_18; sclk= P0_15;
}else if(spi_channel == 1){
mosi= P0_9; sclk= P0_7;
}else{
mosi= P0_18; sclk= P0_15;
}
this->glcd= new RrdGlcd(mosi, sclk, this->spi_cs_pin);
int spi_frequency = THEKERNEL->config->value(panel_checksum, spi_frequency_checksum)->by_default(1000000)->as_number();
this->glcd->setFrequency(spi_frequency);
}
ReprapDiscountGLCD::~ReprapDiscountGLCD() {
delete this->glcd;
}
uint8_t ReprapDiscountGLCD::readButtons() {
uint8_t state= 0;
state |= (this->click_pin.get() ? BUTTON_SELECT : 0);
// check the pause button
if(this->pause_pin.connected() && this->pause_pin.get()) state |= BUTTON_PAUSE;
if(this->back_pin.connected() && this->back_pin.get()) state |= BUTTON_LEFT;
return state;
}
int ReprapDiscountGLCD::readEncoderDelta() {
static const int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
static uint8_t old_AB = 0;
old_AB <<= 2; //remember previous state
old_AB |= ( this->encoder_a_pin.get() + ( this->encoder_b_pin.get() * 2 ) ); //add current state
return enc_states[(old_AB&0x0f)];
}
// cycle the buzzer pin at a certain frequency (hz) for a certain duration (ms)
void ReprapDiscountGLCD::buzz(long duration, uint16_t freq) {
if(!this->buzz_pin.connected()) return;
duration *=1000; //convert from ms to us
long period = 1000000 / freq; // period in us
long elapsed_time = 0;
while (elapsed_time < duration) {
this->buzz_pin.set(1);
wait_us(period / 2);
this->buzz_pin.set(0);
wait_us(period / 2);
elapsed_time += (period);
}
}
void ReprapDiscountGLCD::write(const char* line, int len) {
this->glcd->displayString(this->row, this->col, line, len);
this->col+=len;
}
void ReprapDiscountGLCD::home(){
this->col= 0;
this->row= 0;
}
void ReprapDiscountGLCD::clear(){
this->glcd->clearScreen();
this->col= 0;
this->row= 0;
}
void ReprapDiscountGLCD::display() {
// it is always on
}
void ReprapDiscountGLCD::setCursor(uint8_t col, uint8_t row){
this->col= col;
this->row= row;
}
void ReprapDiscountGLCD::init(){
this->glcd->initDisplay();
}
// displays a selectable rectangle from the glyph
void ReprapDiscountGLCD::bltGlyph(int x, int y, int w, int h, const uint8_t *glyph, int span, int x_offset, int y_offset) {
if(x_offset == 0 && y_offset == 0 && span == 0) {
// blt the whole thing
this->glcd->renderGlyph(x, y, glyph, w, h);
}else{
// copy portion of glyph into g where x_offset is left byte aligned
// Note currently the x_offset must be byte aligned
int n= w/8; // bytes per line to copy
if(w%8 != 0) n++; // round up to next byte
uint8_t g[n*h];
uint8_t *dst= g;
const uint8_t *src= &glyph[y_offset*span + x_offset/8];
for (int i = 0; i < h; ++i) {
memcpy(dst, src, n);
dst+=n;
src+= span;
}
this->glcd->renderGlyph(x, y, g, w, h);
}
}
void ReprapDiscountGLCD::on_refresh(bool now){
static int refresh_counts = 0;
refresh_counts++;
// 10Hz refresh rate
if(now || refresh_counts % 2 == 0 ) this->glcd->refresh();
}
|
5ad43db392b5fea99346dd43ff8c0287b06ac976
|
[
"C++"
] | 4 |
C++
|
ssloy/Smoothieware
|
fa123d1a8f41975c38f9a14dd6ef3ab70ac00cf4
|
67d484be1153f2b41f937e2786c6a6e68f4e2bf9
|
refs/heads/master
|
<repo_name>andrdmynti/lending-tools-using-phpNative<file_sep>/action/login.php
<?php
include "koneksi.php";
$username = $_POST["username"];
$password = md5($_POST["password"]);
$query ="SELECT * FROM user WHERE username='$username' AND password='$password'";
$login = mysqli_query($connect,$query) or die(mysqli_eror($connect));
$jlhrecord = mysqli_num_rows($login);
$data = mysqli_fetch_array($login,MYSQLI_BOTH);
$username = $data['username'];
$password = $data['<PASSWORD>'];
$nama = $data['nama'];
$level = $data['level'];
if($jlhrecord > 0){
session_start();
$_SESSION['id_user']=$id_user;
$_SESSION['username']=$username;
$_SESSION['nama']=$nama;
$_SESSION['level']=$level;
//redirect level
if($level == 1){
header('Location:../admin/index.php');
}
elseif ($level == 2){
header('Location:../user/index.php');
}
elseif ($level == 3){
header('Location:..k3/index.php');
}
}
else{
echo "<br><br><br><strong><center>Maaf Username atau Password yang anda masukkan salah.";
echo '<META HTTP-EQUIV="REFRESH" CONTENT ="2; URL=../index.php">';
}
?><file_sep>/action/logout.php
<?php
session_destroy();
?>
<!-- /<META HTTP-EQUIV="REFRESH" CONTENT ="2; URL=../index.php"> --><file_sep>/action/koneksi.php
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "websiteku";
$connect = mysqli_connect($hostname,$username,$password,$database);
?><file_sep>/user/index.php
<?php
session_start();
if (isset($_GET['konten']))
$konten = $_GET['konten'];
else
$konten = 'index';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
<script src="../jquery-3.3.1.min.js"></script>
<script src="../bootstrap/js/bootstrap.min.js"></script>
<style>
/* Remove the navbar's default margin-bottom and rounded borders */
.navbar {
margin-bottom: 0;
border-radius: 0;
}
/* Add a gray background color and some padding to the footer */
footer {
background-color: #450812;
padding: 25px;
}
.carousel-inner img {
width: 100%; /* Set width to 100% */
margin: auto;
min-height:200px;
}
/* Hide the carousel text when the screen is less than 600 pixels wide */
@media (max-width: 600px) {
.carousel-caption {
display: none;
}
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse" style="background:#450812">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- INI YANG DI BARIS 48 SAMA 49 DIISI GAMBAR LOGO SEKOLAH SAMA JURUSAN -->
<br>
<img src="../images/grf.png" style="width: 10%; height: 10%;">
<img src="../images/hmm.png" style="width: 10%; height: 10%;">
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<!-- DISINI DIISI MENU BUAT YANG HALAMAN AWAL DISESUAIIN SAMA YANG SEBELUMNYA-->
<li><a href="#" style="color:white"><span class="glyphicon glyphicon-home"></span> Home</a></li>
<li><a href="index.php?konten=form_user" style="color:white"><span class="glyphicon glyphicon-menu-hamburger"></span> Formulir Peminjaman</a></li>
<li><a href="../action/logout.php" style="color:white"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>
</ul>
</div>
</div>
</nav>
<?php
if ($konten=='index')
include 'tampilan_user.php';
elseif ($konten=='tampilan_user')
include 'tampilan_user.php';
elseif ($konten=='form_user')
include 'form_user.php';
?>
<footer class="container-fluid text-center">
<p style="color:white">"Bermimpilah setinggi langit dan jangan pernah takut jatuh,karena ketika kalian jatuh masih banyak bintang yang mau menopang mimpi-mimpi kalian" -Pak Hamrowi</p>
<p style="color:white">"Seni itu indah,dan kamu adalah seni" -Pak Polo</p>
</footer>
</body>
</html>
|
744d4ed1d01f2e47763b077888da229293d06bc5
|
[
"PHP"
] | 4 |
PHP
|
andrdmynti/lending-tools-using-phpNative
|
184f386a957d219c63fa5cd8e3daf3e4d0fd9563
|
84235dda30f86974524519bfeaeab7227c1d44a3
|
refs/heads/master
|
<repo_name>ppius/csc202<file_sep>/basic_data_structures/orderedlist.py
from Node import Node
class OrderedList:
def __init__(self):
self.head = None
def __str__(self):
ol = []
curr = self.head
while curr is not None:
ol.append(curr.data)
curr = curr.next
print (ol)
def isEmpty(self):
return self.head is None
def popPos(self, key):
if self.isEmpty():
return False
front = self.head
prev = None
count = 0
node = None
found = False
while front is not None:
if count == key:
found = True
break
count += 1
prev = front
front = front.next
if not found:
return node
if prev is None:
node = self.head
self.head = self.head.next
else:
node = front
prev.next = front.next
front.next = None
return node
def pop(self):
if self.isEmpty():
return None
# check if the list has single node
if self.head.next is None:
node = self.head
self.head = None
return node
front = self.head
back = None
while front.next is not None:
back = front
front = front.next
node = front
back.next = front.next
return node
def search(self, item):
if self.isEmpty():
current = self.head
index = 0
while not (current is None):
if current.getData() == key:
return index
elif item < current.get_data():
break
current = current.get_next()
index += 1
return -1
def size(self):
current = self.head
count = 0
while not (current is None):
count += 1
current = current.get_next()
return count
def add(self, item):
current = self.head
prev = None
while not (current is None):
if current.get_data() > item:
break
else:
prev = current
current = current.get_next()
temp = Node(item)
if prev is None:
temp.set_next(self.head)
self.head = temp
else:
temp.set_next(current)
prev.set_next(temp)
def remove(self, item):
if self.isEmpty():
return None
current = self.head
prev = None
found = False
while not found:
if current.get_data() == item:
found = True
else:
prev = current
current = current.get_next()
node = None
if prev is None:
node = self.head
self.head = current.get_next()
else:
node = current
prev.set_next(current.get_next())
return node
<file_sep>/ch4_recursion/list_reverse.py
def reverse_list(nlist):
"""
>>> reverse_list([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> reverse_list([5])
[5]
"""
if len(nlist) == 1:
return nlist
rev_list = reverse_list(nlist[1:])
rev_list.append(nlist[0])
return rev_list
if __name__ == '__main__':
import doctest
doctest.testmod()
<file_sep>/ch4_recursion/factorial.py
#normal solution
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
print(factorial(7))
# recursive solution
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(7))
<file_sep>/ch4_recursion/list_sum.py
#normal for loop function
def list_sum(num_list):
sum = 0
for i in num_list:
sum += i
return sum
print(list_sum([1, 3, 5, 7, 9]))
print(list_sum([0]))
print(list_sum([13, 1, 9, 17, 5]))
#recursive function for list_sum
def ls_sum(num_list):
if len(num_list) == 1:
return num_list[0]
else:
return num_list[0] + ls_sum(num_list[1:])
print(ls_sum([1, 3, 5, 7, 9]))
print(ls_sum([0]))
print(ls_sum([13, 1, 9, 17, 5]))
<file_sep>/basic_data_structures/linkedlist.py
from node import Node
class LinkedList:
def __init__(self):
self.head = None
self.N = 0
def __str__(self):
linked_list = []
curr = self.head
while curr is not None:
linlist.append(curr.data)
curr = curr.next
print (llist)
def search(self, key):
curr = self.head
while curr is not None:
if curr.data == key:
return True
curr = curr.next
return False
def add(self, ndata):
node = Node(ndata)
if self.head is None:
self.head = node
else:
node.next = self.head
self.head = node
self.N += 1
def remove(self, ndata):
curr = self.head
prev = None
found = False
while curr is not None:
if curr.data == ndata:
found = True
break
else:
prev = curr
curr = curr.next
if found:
if prev is None:
self.head = self.head.next
else:
prev.next = curr.next
curr.next = None
self.N -= 1
return found
def size(self):
return self.N
def isEmtpy(self):
return self.N == 0
<file_sep>/ch4_recursion/pascal_triangle.py
def print_pascal_triangle(nrow):
print_row([1], nrow)
pascal_triangle(nrow-1, [1])
def pascal_triangle(nrow, rlist):
if nrow == 0:
return
tmp_row = []
tmp_row.append(rlist[0])
for i in range(0, len(rlist)-1):
# print (rlist)
tmp_row.append(rlist[i] + rlist[i+1])
tmp_row.append(rlist[-1])
print_row(tmp_row, nrow)
pascal_triangle(nrow-1, tmp_row)
<file_sep>/ch4_recursion/recur_pal_checker.py
def pal_checker(word):
"""
>>> pal_checker("kayak")
True
>>> pal_checker("aibohphobia")
True
>>> pal_checker("Live not on evil")
False
>>> pal_checker("Go hang a salami; I'm a lasagna hog")
True
>>> pal_checker("Kanakanak")
True
>>> pal_checker("Wasamassaw")
True
"""
if ch in word = " " and "'":
if len(word) < 2:
return True
elif word[0] != word[-1]:
return False
return pal_checker(word[1:-1])
if __name__ == '__main__':
import doctest
doctest.testmod()
<file_sep>/ch4_recursion/fibonacci.py
def fibonacci_iter(num):
if num == 0 or num == 1:
return num
fib1 = 0
fib2 = 1
count = 2
result = 1
while count <= num:
result = fib1 + fib2
fib1, fib2 = fib2, result
count += 1
return result
def fibonacci_rec(num):
# if num == 0 or num == 1:
if num <= 2:
return 1
return fibonacci_rec(num-1) + fibonacci_rec(num-2)
|
497b4a4e481206c06d4628e3af042967f79d3d3b
|
[
"Python"
] | 8 |
Python
|
ppius/csc202
|
4c292cb1bd6169871dc496ac98a1a58d78dd17ee
|
7fe132870ce137e500eb405b2e1eed744f6e7709
|
refs/heads/master
|
<file_sep># CropperFit
### Create an image of the desired size with the original ratio and the size to fill the fields with the main color in the image
Installation
<pre>
composer require asmx/cropper
</pre>
Usage
<pre>
use Asmx\Cropper\Cropper;
$cropper = new Cropper();
$cropper->
from('input_path_file')->
to('output_path_file')->
size([600,200])->
fit();
</pre>
<file_sep><?php
namespace Asmx\Cropper;
/**
* Class Cropper
* @package Asmx\Cropper
*/
class Cropper
{
/**
* Weight for output file
* @var int
*/
protected $width = 0;
/**
* Height for output file
* @var int
*/
protected $height = 0;
/**
* Input file path
* @var
*/
protected $source_file;
/**
* Output file path
* @var
*/
protected $destination_file;
/**
* Quality for image
* @var int
*/
protected $quality = 90;
/**
* Allowed formats to create image
* @var array
*/
protected $allowed_formats = ['jpeg', 'jpg', 'gif', 'png', 'bmp', 'webp'];
/**
* Set source file.
*
* @param string $source_file
*
* @return $this
*/
public function from(string $source_file)
{
$this->source_file = $source_file;
return $this;
}
/**
* Set destination file
* if empty or not set, construct from sizes and '_fit'
* @param string $destination_file
*
* @return $this
*/
public function to(string $destination_file = '')
{
if ($destination_file != '') {
$this->destination_file = $destination_file;
} else {
$this->destination_file = preg_replace('/\.' . $this->getExtension($this->source_file) . '/i',
'_' . $this->width . '_' . $this->height . '_fit.' . $this->getExtension($this->source_file),
$this->source_file);
}
return $this;
}
/**
* Set quality
* @param int $quality
* @return $this
*/
public function quality(int $quality)
{
if ($quality <= 100 and $quality > 0)
$this->quality = $quality;
return $this;
}
/**
* Set need size
* @param array $size
* @return $this
*/
public function size(array $size)
{
isset($size[0]) and is_int($size[0]) ? $this->width = $size[0] : $this->width = 'auto';
isset($size[1]) and is_int($size[1]) ? $this->height = $size[1] : $this->height = 'auto';
return $this;
}
/**
* get extension of file for change create image method
* @param string $filename
* @return string
*/
private function getExtension(string $filename): string
{
$path_info = pathinfo($filename);
return strtolower($path_info['extension']);
}
/**
* main method
* @param bool $overwrite
* @throws \Exception
*/
public function fit(bool $overwrite = false)
{
if (!$this->destination_file) {
$this->to();
}
if (!$this->checkExistFile($this->destination_file) and
$this->checkExistFile($this->source_file) or
$overwrite != false and
$this->checkExistFile($this->source_file)
) {
list($width, $height) = getimagesize($this->source_file);
$new_width = $this->width;
$new_height = $this->height;
if ($this->width > 0 && $this->height > 0) {
$side_to_cute = ((($height / $width) - ($this->height / $this->width)) < 0) ? 'width' : 'height';
} else {
$side_to_cute = ($this->height === 0) ? 'width' : 'height';
}
if ($side_to_cute === 'width') {
$new_height = (int)ceil($this->width * $height / $width);
} else {
$new_width = (int)ceil($width * $this->height / $height);
}
if ($this->width == 0) {
$this->width = $new_width;
}
if ($this->height == 0) {
$this->height = $new_height;
}
$color_fill = $this->getPrimaryColor();
$new_img = imagecreatetruecolor($this->width, $this->height);
$primary_color = imagecolorallocate($new_img, $color_fill[0], $color_fill[1], $color_fill[2]);
imagefill($new_img, 0, 0, $primary_color);
$source = $this->imageCreateFrom();
$tmp = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($tmp, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$x = ($this->width - $new_width) / 2;
$y = ($this->height - $new_height) / 2;
imagecopy($new_img, $tmp, $x, $y, 0, 0, $new_width, $new_height);
$this->imageSaveTo($new_img);
// clear all
imagedestroy($tmp);
imagedestroy($source);
imagedestroy($new_img);
}
}
/**
* Method to calc primary color for input file
* @return array
* @throws \Exception
*/
private function getPrimaryColor()
{
$im = $this->imageCreateFrom();
$total_R = 0;
$total_G = 0;
$total_B = 0;
list($width, $height) = getimagesize($this->source_file);
for ($x = 0;
$x < $width;
$x++) {
for ($y = 0;
$y < $height;
$y++) {
$rgb = imagecolorat($im, $x, $y);
$total_R += ($rgb >> 16) & 0xFF;
$total_G += ($rgb >> 8) & 0xFF;
$total_B += $rgb & 0xFF;
}
}
imagedestroy($im);
$avg_R = round($total_R / $width / $height);
$avg_G = round($total_G / $width / $height);
$avg_B = round($total_B / $width / $height);
return array($avg_R, $avg_G, $avg_B);
}
/**
* Method create image from format
* @return false|resource
* @throws \Exception
*/
private function imageCreateFrom()
{
$ext = $this->getExtension($this->source_file);
if (!in_array($ext, $this->allowed_formats)) {
throw new \Exception('Not supported format');
}
switch ($ext) {
case 'jpg' or 'jpeg':
$image = imagecreatefromjpeg($this->source_file);
break;
case 'gif':
$image = imagecreatefromgif($this->source_file);
break;
case 'png':
$image = imagecreatefrompng($this->source_file);
break;
case 'webp':
$image = imagecreatefromwebp($this->source_file);
break;
case 'bmp':
$image = imagecreatefrombmp($this->source_file);
break;
}
return $image;
}
/**
* Method save image to format
* @param $resource
* @throws \Exception
*/
private function imageSaveTo($resource)
{
$ext = $this->getExtension($this->destination_file);
if (!in_array($ext, $this->allowed_formats)) {
throw new \Exception('Not supported format');
}
switch ($ext) {
case 'jpg' or 'jpeg':
imagejpeg($resource, $this->destination_file, $this->quality);
break;
case 'gif':
imagegif($resource, $this->destination_file);
break;
case 'png':
imagepng($resource, $this->destination_file, $this->quality);
break;
case 'webp':
imagewebp($resource, $this->destination_file, $this->quality);
break;
case 'bmp':
imagebmp($resource, $this->destination_file);
break;
}
}
/**
* @param $path_file
* @return bool
*/
private function checkExistFile($path_file): bool
{
try {
return file_exists($path_file);
} catch (\Exception $e) {
return false;
}
}
}
|
cc3943a90c8d2ffddea3a19d456f47d71171d779
|
[
"Markdown",
"PHP"
] | 2 |
Markdown
|
asmxaker/CropperFit
|
639cadd6c20a2de22de7fd83a8119a281339c99a
|
d3f2dedac3f348eef21b88d7d13ab18847272c14
|
refs/heads/master
|
<file_sep> let translate = function (lag) {
let language = {}
if (lag == 'zh_EN') {
language = {
loginWechat: 'Login via Wechat',
inputPhone: 'input phone No.',
getCode:'Get code',
logIn:'Log in',
purchaser:'Purchaser',
supplier:'Supplier',
all:'all',
print:'Print'
}
} else {
language = {
loginWechat: '微信一键登录',
inputPhone:'请输入手机号',
getCode:'获取验证码',
logIn:'登录',
purchaser:'我是采购商',
supplier:'我是供应商',
all:'全选',
print:'打印'
}
}
return language
}
export default translate<file_sep>$(function () {
$('.tab_bar ul li').click(function () {
$('.tab_bar ul li').eq($(this).index()).children().addClass("active");
$('.tab_bar ul li').eq($(this).index()).siblings().children().removeClass('active');
$(".tab_content").hide().eq($(this).index()).show();
});
})<file_sep>//index.js
//获取应用实例
const app = getApp();
const trans = app.trans();
Page({
data: {
trans:{
name: trans.name
},
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
//事件处理函数
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
// const arrayBuffer = new Uint8Array(['1','2']);
// const base64 = wx.arrayBufferToBase64(arrayBuffer);
// console.log(base64);
// const base64 = 'CxYh'
// const arrayBuffer = wx.base64ToArrayBuffer(base64);
// console.log(arrayBuffer);
// if (app.globalData.userInfo) {
// this.setData({
// userInfo: app.globalData.userInfo,
// hasUserInfo: true
// })
// } else if (this.data.canIUse){
// // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// // 所以此处加入 callback 以防止这种情况
// app.userInfoReadyCallback = res => {
// this.setData({
// userInfo: res.userInfo,
// hasUserInfo: true
// })
// }
// } else {
// // 在没有 open-type=getUserInfo 版本的兼容处理
// wx.getUserInfo({
// success: res => {
// app.globalData.userInfo = res.userInfo
// this.setData({
// userInfo: res.userInfo,
// hasUserInfo: true
// })
// }
// })
// }
// this.ajax('dsff','sfdsfads').then(res=>{
// console.log(res);
// }).catch(error=>{
// console.log(error);
// })
// let promise=new Promise((resolve,reject)=>{
// wx.chooseImage({
// count: 1, // 默认9
// sizeType: ['original', 'compressed'],
// sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者
// success:res=>resolve(res),
// fail:error=>reject(error)
// })
// })
// promise.then(res=>{
// console.log(res);
// return 2;
// }).then(res=>{
// console.log(res);
// })
/*****Set数据结构****** */
// const arr = new Set([2, 3, 4, 5, 6]);
// arr.add(7);//添加操作
// console.log(arr.has(6));
// arr.delete(4);
// //console.log(arr.keys());
// for(let item of arr.keys()){
// console.log(item);
// }
/******map数据结构****** */
//const mapObj=new Map();
// mapObj.set('k1','v1');
//console.log(mapObj.get('k1'));
//let s = Symbol();
//typeof s
// "symbol"
// let v1={
// 'obj':'2',
// 'obj1':3
// }
// let v2={
// 'obj':'2',
// 'obj1': 3
// }
// console.log(Object.is(v1,v2));
//console.log(...[1,2,3]);
// let _getSystemInfo=app.wxPromisify(wx.getSystemInfo);
// _getSystemInfo({ type: 'wgs84'}).then(res=>console.log(res));
},
ajax(url, requestData){
return new Promise((resolve,reject)=>{
wx.request({
url:url ||'',
data:requestData,
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
resolve(res);
},
fail(error){
resolve(error);
}
})
})
},
getUserInfo: function(e) {
console.log(e)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
}
})
<file_sep>$(function() {
$(window).scroll(function(){
var scrolltop=$(this).scrollTop();
if(scrolltop>=610){
$("#tab_usual1").addClass("cc_top");
}else{
$("#tab_usual1").removeClass("cc_top");
}
});
});<file_sep>$(function() {
if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.split(";")[1].replace(/[ ]/g, "") == "MSIE6.0") {
$('.J-mask').show()
alert("您使用的版本是IE6,出于安全考虑,请使用IE8及以上版本或其他浏览器");
} else if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.split(";")[1].replace(/[ ]/g, "") == "MSIE7.0") {
$('.J-mask').show()
alert("您使用的版本是IE7,出于安全考虑,请使用IE8及以上IE版本或其他浏览器");
}
})<file_sep>function upImg(obj) {
console.log(1)
initUploadImg($(obj))
}
function deleteLi(obj) {
$(obj).parents('li').remove()
// if (!$('.on').length) {
// $('.prompt').show()
// }
var str = '<li class="col-25">\
<div class="pos-wrap">\
<input class="upload-input-btn" type="file" name="file" accept="image/*" onclick="upImg(this)">\
<img class="preview">\
<a href="javascript:;" class="delete-img" onclick="deleteLi(this)"></a>\
</div>\
</li>'
$('.upload-img-wrap ul').append(str)
}
function initUploadImg(dom) {
//初始化每个图片上传提示UI
var preview = dom.next(),
deleteImg = preview.next()
dom.UploadImg({
url: "//m.tnc.com.cn/up/upload/bit/result.htm?adminId=0&modelCode=buy&src=mqfc&userAuth=HxZKAaOG4ww=",
width: "320",
quality: "0.8",
mixsize: "1000000000",
type: "image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/bmp,image/x-png",
before: function() {
preview.attr('src', 'loading.gif').show()
deleteImg.show()
//$('.prompt').hide()
dom.addClass('on').parents('li').next().css({ 'opacity': 1 }).find('.upload-input-btn').show()
},
success: function(b) {
if (b.code == 0) {
preview.attr({
"src": b.file,
"data-id": b.imageCode
})
} else {
//图片上传失败提示 b.message
}
}
})
}<file_sep>var myapp=angular.module('myapp',[]);
myapp.controller('abc',function($scope){
$scope.name='123'
})<file_sep>$(function(){
$("#goTop").on('click', function () {
$('html,body').scrollTop(0);
return false;
});
})<file_sep>Mock.mock('get.json', {
"bCode": "success",
"code": "0X000",
"data": {
"endRow": 10,
"firstPage": 1,
"hasNextPage": true,
"hasPreviousPage": false,
"isFirstPage": true,
"isLastPage": false,
"lastPage": 4,
"list": [
{
"content": "我也来凑个热闹!",
},
{
"content": "我也来凑个热闹!",
},
{
"content": "我也来凑个热闹!",
},
{
"content": "我也来凑个热闹!",
},
{
"content": "我也来凑个热闹!",
},
{
"content": "我也来凑个热闹!",
},
{
"content": "我也来凑个热闹!",
}
],
"navigatePages": 8,
"navigatepageNums": [
1,
2,
3,
4
],
"nextPage": 2,
"pageNum": 1,
"pageSize": 10,
"pages": 4,
"prePage": 0,
"size": 10,
"startRow": 1,
"total": 38
},
"success": true,
"msg": ""
})
|
0adab140cf9c5812ab76c09b5c1510f344a7f8f8
|
[
"JavaScript"
] | 9 |
JavaScript
|
lihaojun123/project
|
70e029f34398f3948108c69f3cb8374646396cac
|
9607a5790b79834bd79f6fed0e1a98acd5e824f6
|
refs/heads/master
|
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('register/',views.register, name="user-register"),
path('profile/',views.profile,name='user-profile'),
]<file_sep>
a = [x*x for x in range(10)]
print(a)
for num in a:
print(num)<file_sep>from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render,get_object_or_404
from .models import Post
from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin
from django.contrib import messages
from django.urls import reverse_lazy
from django.contrib.auth.models import User
class PostListView(ListView):
model = Post
template_name = 'home.html'
context_object_name = 'post'
paginate_by = 3
class UserPostListView(ListView):
model = Post
template_name = 'home.html'
context_object_name = 'post'
paginate_by = 3
def get_queryset(self,*args, **kwargs):
user = get_object_or_404(User, username = self.kwargs.get('username'))
return Post.objects.filter(author = user).order_by('-date_posted')
class PostDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class PostCreateView(LoginRequiredMixin,CreateView):
model = Post
template_name = 'post_create.html'
fields = ['title','content']
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
messages.warning(request,'Login to create post')
return super().dispatch(request, *args, **kwargs)
def form_valid(self,form):
form.instance.author = self.request.user
messages.success(self.request,f'{self.request.user.username} created a post!')
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
model = Post
template_name = 'post_update.html'
fields = ['title','content']
def form_valid(self, form):
messages.success(self.request, f"{self.request.user}'s post is updated")
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('blog-home')
def delete(self, request, *args, **kwargs):
post = self.get_object()
messages.success(request,f"{post.author}'s post is deleted")
return super().delete(request,*args,**kwargs)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
<file_sep>from django.urls import path
from . import views
from . views import PostListView,PostDetailView,PostCreateView,PostUpdateView,PostDeleteView,UserPostListView
from django.contrib.auth.views import PasswordResetView,PasswordResetDoneView,PasswordResetConfirmView,PasswordResetCompleteView
urlpatterns = [
path('home/', PostListView.as_view(), name= "blog-home"),
path('detail/<int:pk>/', PostDetailView.as_view(), name= "blog-detail"),
path('post/', PostCreateView.as_view(), name= "blog-create"),
path('update/<int:pk>/', PostUpdateView.as_view(), name= "blog-update"),
path('delete/<int:pk>/', PostDeleteView.as_view(), name= "blog-delete"),
path('postuser/<str:username>/', UserPostListView.as_view(), name= "user-post"),
path('password_reset/', PasswordResetView.as_view(template_name='password_rest.html'), name= "password_reset"),
path('password_reset/sent', PasswordResetDoneView.as_view(template_name='password_rest_done.html'), name= "password_reset_done"),
path('password_reset_confirm/<uidb64>/<token>', PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'), name= "password_reset_confirm"),
path('password_reset/complete', PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name= "password_reset_complete"),
] <file_sep>from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
from PIL import Image
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email', '<PASSWORD>','<PASSWORD>']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
def save(self):
super().save()
img = Image.open(self.image.path)
if img.height > 300 or img.width >300:
output_size =(250,250)
img.thumbnail(output_size)
img.save(self.image.path)
|
493366b230cbdb7590b674a2b2c64b667fe565b4
|
[
"Python"
] | 5 |
Python
|
TharLin123/SocialMedia
|
01ec515708464bcce308d41fb77f87ddf6a9dcf6
|
00dd8992bca4fa153cdc0c7b00ddc23b1654cfd1
|
refs/heads/master
|
<file_sep>$(function(){
$(".carousel").carousel(
interval:5000;
)
})
var scroll = new SmoothScroll('.menu a[href*="#"]', {
speed: 500
});
|
95234e87c47b83354851ad1dc4b7649fc71fd4d5
|
[
"JavaScript"
] | 1 |
JavaScript
|
ajkacca457/landingpagevidbg
|
41f27bc724d77ac1ab522b180c98ccbb4ca073ec
|
d821105883948dbfb2a377d2386ec8c64adf410d
|
refs/heads/master
|
<file_sep>#!/bin/bash
START="$1"
END="$2"
cat > config.yml << EOF
in:
type: mongodb
uri: mongodb://localhost:27017/tweet
collection: sample
query: '{"_timestamp": { \$gte: "${START}", \$lt: "${END}" }}'
projection: '{ "timestamp_ms": 1, "lang": 1, "text": 1 }'
out:
type: file
path_prefix: /tmp/twitter_sample_${START}/
file_ext: json.gz
formatter:
type: jsonl
encoders:
- type: gzip
EOF
#rm -rf /tmp/twitter_sample_${START}
#mkdir /tmp/twitter_sample_${START}
embulk run config.yml<file_sep>import datetime
import json
import pymongo
import requests_oauthlib
import tqdm
# Please enter your own
consumer_key = ''
consuer_secret = ''
access_token_key = ''
access_token_secret = ''
twitter = requests_oauthlib.OAuth1Session(consumer_key,consuer_secret,access_token_key,access_token_secret)
uri = 'https://stream.twitter.com/1.1/statuses/sample.json'
r = twitter.get(uri, stream=True)
r.raise_for_status()
mongo = pymongo.MongoClient()
for line in tqdm.tqdm(r.iter_lines(),unit='tweets',mininterval=1):
if line:
tweet = json.loads(line)
tweet['_timestamp'] = datetime.datetime.utcnow().isoformat()
mongo.tweet.sample.insert_one(tweet)<file_sep># bigdata-test
this is sample test for big data book
|
2a3de8c64272edaf3e90f44223449cbc50c2a3ff
|
[
"Markdown",
"Python",
"Shell"
] | 3 |
Shell
|
takanobu-watanabe/bigdata-test
|
b78ef79afa3d9a6472be1ed014ccf6c6b9fce73e
|
cb5c5f5ba52c91b6a2f47c03d472eaffb0746b15
|
refs/heads/main
|
<file_sep>#!/bin/bash
## create s3 bucket
function create_bucket(){
aws s3api create-bucket --object-lock-enabled-for-bucket \
--acl private --bucket $1 \
--region $2 \
--create-bucket-configuration LocationConstraint=$2
}
function put_bucket_version(){
aws s3api put-bucket-versioning --bucket $1 \
--region $2 --versioning-configuration Status=Enabled
}
function put_bucket_encryption(){
aws s3api put-bucket-encryption --bucket $1 \
--region $2 \
--server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
}
function put_bucket_block_public(){
aws s3api put-public-access-block --bucket $1 \
--region $2 \
--public-access-block-configuration \
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
}
function delete_bucket(){
aws s3api delete-bucket --bucket $1
}
# status
function output(){
if [ $1 != 0 ]
then
echo "ERROR! $2 failed"
exit $1
fi
echo "$2 DONE"
}
# create dynamodb
function create_dynamodb(){
aws dynamodb create-table --table-name $1 --no-verify-ssl \
--region $2 \
--provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--key-schema AttributeName=LockID,KeyType=HASH \
}
function args(){
if [ $ARGS -lt 2 ]
then
echo "Usage: $0 ENV AWS_REGION"
echo " ENV option: dev|prod|staging"
echo " AWS_REGION option: us-east-2"
echo "e.g. : $0 dev us-east-2 "
exit 1
fi
}
function main(){
## create resource
echo "==========================="
echo "= The following resource will be created ="
echo " S3 bucket: ${BUCKET_NAME}"
echo " DynamoDB Table: ${TABLE_NAME}"
echo "Enter 'Yes' to process:"
read answer
if [ $answer != "Yes" ]
then
echo "=== Bye ~~ ==="
exit 99
fi
## create s3 bucket
echo "Creating bucket"
# create_bucket $BUCKET_NAME $REGION
# output $? "Create bucket"
# put_bucket_version $BUCKET_NAME $REGION
# output $? "Put bucket versioning in bucket"
# put_bucket_encryption $BUCKET_NAME $REGION
# output $? "Put bucket encryption"
# put_bucket_block_public $BUCKET_NAME $REGION
# output $? "Put bucket block public access"
# echo "S3 Bucket [${BUCKET_NAME}] configured!"
# echo "..."
echo "Create dynamodb (table = ${TABLE_NAME})"
## create dynamodb table
create_dynamodb $TABLE_NAME $REGION
output $? "Create DynamoDB Table "
echo "DynamoDB Table [${TABLE_NAME}] created!"
}
# set env values
ARGS=$#
ENV=$1
REGION=$2
NAME_BASE="leman-terraform-state"
BUCKET_NAME=${ENV}-${NAME_BASE} # will use
TABLE_NAME=${ENV}-${NAME_BASE} # will use
# run
args
#delete_bucket $BUCKET_NAME
main
<file_sep>create ecs kong test
# 1. initial env
- create s3 bucket if not exsit
```bash
./initial/s3-setup.sh staging us-east-1
```
- terraform init
```bash
terraform init -backend-config=staging-leman-test.backend
```
# 2. ecr
- create ecr
```bash
terraform plan -var-file=staging-leman-test.tfvars -target=aws_ecr_lifecycle_policy.leman_test_ecs_kong \
-target=aws_ecr_repository.leman_test_ecs_kong
terraform apply -var-file=staging-leman-test.tfvars -target=aws_ecr_lifecycle_policy.leman_test_ecs_kong \
-target=aws_ecr_repository.leman_test_ecs_kong
➜ terraform git:(main) ✗ terraform apply -var-file=staging-leman-test.tfvars -target=aws_ecr_lifecycle_policy.leman_test_ecs_kong \
-target=aws_ecr_repository.leman_test_ecs_kong
Acquiring state lock. This may take a few moments...
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_ecr_lifecycle_policy.leman_test_ecs_kong will be created
+ resource "aws_ecr_lifecycle_policy" "leman_test_ecs_kong" {
+ id = (known after apply)
+ policy = jsonencode(
{
+ rules = [
+ {
+ action = {
+ type = "expire"
}
+ description = "Keep 100 images"
+ rulePriority = 1
+ selection = {
+ countNumber = 100
+ countType = "imageCountMoreThan"
+ tagStatus = "any"
}
},
]
}
)
+ registry_id = (known after apply)
+ repository = (known after apply)
}
# aws_ecr_repository.leman_test_ecs_kong will be created
+ resource "aws_ecr_repository" "leman_test_ecs_kong" {
+ arn = (known after apply)
+ id = (known after apply)
+ image_tag_mutability = "MUTABLE"
+ name = (known after apply)
+ registry_id = (known after apply)
+ repository_url = (known after apply)
+ tags = (known after apply)
}
Plan: 2 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ ecr_url = (known after apply)
Warning: Resource targeting is in effect
You are creating a plan with the -target option, which means that the result
of this plan may not represent all of the changes requested by the current
configuration.
The -target option is not for routine use, and is provided only for
exceptional situations such as recovering from errors or mistakes, or when
Terraform specifically suggests to use it as part of an error message.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_ecr_repository.leman_test_ecs_kong: Creating...
aws_ecr_repository.leman_test_ecs_kong: Creation complete after 4s [id=leman-test-ecr-kong-20210623]
aws_ecr_lifecycle_policy.leman_test_ecs_kong: Creating...
aws_ecr_lifecycle_policy.leman_test_ecs_kong: Creation complete after 2s [id=leman-test-ecr-kong-20210623]
Warning: Applied changes may be incomplete
The plan was created with the -target option in effect, so some changes
requested in the configuration may have been ignored and the output values may
not be fully updated. Run the following command to verify that no other
changes are pending:
terraform plan
Note that the -target option is not suitable for routine use, and is provided
only for exceptional situations such as recovering from errors or mistakes, or
when Terraform specifically suggests to use it as part of an error message.
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Releasing state lock. This may take a few moments...
Outputs:
ecr_url = "008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623"
```
- docker pull image
```bash
docker pull postgres:11
docker pull dpage/pgadmin4
docker pull kong
docker pull nginx
docker pull pgbouncer/pgbouncer
docker pull pantsel/konga
```
- tag image
```bash
docker tag postgres:11 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:postgres_11
docker tag dpage/pgadmin4 0008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:pgadmin4
docker tag kong 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:kong
docker tag nginx 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:nginx
docker tag pgbouncer/pgbouncer 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:pgbouncer
docker tag pantsel/konga 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:konga
```
- upload image
```bash
aws ecr get-login --no-include-email --region=us-east-1|bash
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Login Succeeded
docker push 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:postgres_11
docker push 0008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:pgadmin4
docker push 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:kong
docker push 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:nginx
docker push 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:pgbouncer
docker push 008629597077.dkr.ecr.us-east-1.amazonaws.com/leman-test-ecr-kong-20210623:konga
```
|
6e3c861673b17471ca9ed6e1c2aac2daacf11f7a
|
[
"Markdown",
"Shell"
] | 2 |
Shell
|
lemanlai/terraform
|
038821bad42111a88ce54f74d971f99dbca10215
|
af704d4759561e7e4f4526e94d0ae97274f5af48
|
refs/heads/master
|
<file_sep>
public class RoundRobinScheduler implements ProcessScheduler {
os object;
public RoundRobinScheduler(os obj){
object=obj;
}
public void schedule(){
System.out.println("Round robin scheduling algorithm here");
object.osname();
}
}
<file_sep>
public class Windows implements os {
public void osname(){
System.out.println("Windows specific implementation");
}
}
<file_sep>
public class Client {
public static void main(String[]args){
os object=new Windows();//Implementer
ProcessScheduler scheduler=new RoundRobinScheduler(object);
scheduler.schedule();
object=new Linux();
scheduler=new RoundRobinScheduler(object);
scheduler.schedule();
}
}
<file_sep>
public interface ProcessScheduler {
public void schedule();
}
|
1f5dfab8a7a4a2ad2c99ae7ab04476a5363d4586
|
[
"Java"
] | 4 |
Java
|
adwayskirwe/Structural-Bridge
|
86b9a42930a606fa494cb2ebd2291ffc4d849456
|
ccffbb343d07a45d23bdd080e970f6c860357215
|
refs/heads/master
|
<repo_name>allanawooley/PUI<file_sep>/week5_puilab/main.js
<!-- javascript -->
<script src="main.js" type="text/javascript"></script>
function addNewList() {
alert('hello world alert!');
console.log('hello world console');
}
|
7c6ec2ef736a3582fb11e86901b504d2f4a746f3
|
[
"JavaScript"
] | 1 |
JavaScript
|
allanawooley/PUI
|
7b70121adddd3b78b31714e6ea343fd4630a8825
|
a8e0760782e1d06b3fe48116bd32e49bd85bb703
|
refs/heads/master
|
<repo_name>Belzebbuz/ClickerCircles<file_sep>/Assets/Scripts/Game/BackgroundColor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class BackgroundColor : MonoBehaviour
{
public static BackgroundColor Instance { get; private set; }
private Camera camera;
private List<Color> colors = new List<Color> { new Color(0.946f, 1, 0.75f), new Color(0.8374f, 1, 0.75f), new Color(0.75f, 1, 0.77f),
new Color(0.5f, 1, 0.844f) , new Color(0.544f, 0.9725f, 1), new Color(0.544f, 0.8157f, 1), new Color(0.544f, 0.5513f, 1),new Color(0.7684f,0.545f,1),
new Color(1,0.545f,0.989f),new Color(1,0.545f,0.718f),new Color(1,0.545f,0.557f),new Color(1,0.7052f,0.533f) };
private void Awake()
{
Instance = this;
}
private void Start()
{
camera = GetComponent<Camera>();
}
public void BackgroundColorSwitch()
{
if (GameManager.Instance.countCombo >= 0 && GameManager.Instance.countCombo < 2)
camera.backgroundColor = Color.white;
if (GameManager.Instance.countCombo >= 2 && GameManager.Instance.countCombo < 5)
camera.DOColor(colors[0], 1.2f);
else if (GameManager.Instance.countCombo >= 5 && GameManager.Instance.countCombo < 8)
camera.DOColor(colors[1], 1.2f);
else if (GameManager.Instance.countCombo >= 8 && GameManager.Instance.countCombo < 12)
camera.DOColor(colors[2], 1.2f);
else if (GameManager.Instance.countCombo >= 12 && GameManager.Instance.countCombo < 15)
camera.DOColor(colors[3], 1.2f);
else if (GameManager.Instance.countCombo >= 15 && GameManager.Instance.countCombo < 17)
camera.DOColor(colors[4], 1.2f);
else if (GameManager.Instance.countCombo >= 17 && GameManager.Instance.countCombo < 20)
camera.DOColor(colors[5], 1.2f);
else if (GameManager.Instance.countCombo >= 20 && GameManager.Instance.countCombo < 23)
camera.DOColor(colors[6], 1.2f);
else if (GameManager.Instance.countCombo >= 23 && GameManager.Instance.countCombo < 25)
camera.DOColor(colors[7], 1.2f);
else if (GameManager.Instance.countCombo >= 25 && GameManager.Instance.countCombo < 27)
camera.DOColor(colors[8], 1.2f);
else if (GameManager.Instance.countCombo >= 27 && GameManager.Instance.countCombo < 30)
camera.DOColor(colors[9], 1.2f);
else if (GameManager.Instance.countCombo >= 30)
camera.DOColor(colors[10], 1.2f);
}
public void MissBackgroundColor()
{
camera.DOColor(Color.white, 1f);
}
}
<file_sep>/Assets/Scripts/Game/HealthBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class HealthBar : MonoBehaviour
{
public static HealthBar Instance { get; private set; }
public Image _healthBar;
private bool startDicriment;
private void Awake()
{
Instance = this;
startDicriment = false;
}
void Start()
{
_healthBar = GetComponent<Image>();
_healthBar.DOFillAmount(1, Border.Instance.DistanceFromSpawn()/GameManager.Instance.speedArrow);
startDicriment = true;
}
private void FixedUpdate()
{
if (startDicriment)
_healthBar.fillAmount -= 0.0005f;
}
public void AddHealth()
{
_healthBar.DOFillAmount(_healthBar.fillAmount + 0.1f, 0.1f);
}
public void MinusHealth()
{
_healthBar.DOFillAmount(_healthBar.fillAmount - 0.1f, 0.1f);
}
}
<file_sep>/Assets/Scripts/Game/AudioPeer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class AudioPeer : MonoBehaviour
{
private AudioSource _audioSource;
private float[] _samples = new float[512];
private float[] freqBand = new float[8];
private float[] bandBuffer = new float[8];
private float[] bufferDecrease = new float[8];
private float[] freqBandHighest = new float[8];
public static float[] audioBand = new float[8];
public static float[] audioBandBuffer = new float[8];
private void Start()
{
_audioSource = GetComponent<AudioSource>();
}
private void Update()
{
GetSpectrumAudioSource();
MakeFrequencyBand();
BandBuffer();
CreateAudioBands();
}
private void CreateAudioBands()
{
for (int i = 0; i < 8; i++)
{
if(freqBand[i] > freqBandHighest[i])
{
freqBandHighest[i] = freqBand[i];
}
audioBand[i] = (freqBand[i] / freqBandHighest[i]);
audioBandBuffer[i] = (bandBuffer[i] / freqBandHighest[i]);
}
}
private void GetSpectrumAudioSource()
{
_audioSource.GetSpectrumData(_samples, 0, FFTWindow.Blackman);
}
private void BandBuffer()
{
for (int g = 0; g < 8; g++)
{
if(freqBand[g] > bandBuffer[g])
{
bandBuffer[g] = freqBand[g];
bufferDecrease[g] = 0.005f;
}
if (freqBand[g] < bandBuffer[g])
{
bandBuffer[g] -= bufferDecrease[g];
bufferDecrease[g] *= 1.2f;
}
}
}
private void MakeFrequencyBand()
{
int count = 0;
for (int i = 0; i < 8; i++)
{
float average = 0;
int sampleCount = (int)Mathf.Pow(2, i) * 2;
if(i == 7)
{
sampleCount += 2;
}
for (int j = 0; j < sampleCount; j++)
{
average += _samples[count] * (count +1);
count++;
}
average /= count;
freqBand[i] = average * 10;
}
}
}
<file_sep>/Assets/Scripts/Game/CheckRing.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.EventSystems;
public class CheckRing : MonoBehaviour
{
public static CheckRing Instance { get; private set; }
public bool checker;
private Color colorSwitchGreen = new Color(0.172f, 0.849f, 0.471f);
private Color colorSwitchRed = new Color(0.858f, 0.117f, 0.117f);
public Arrow triggerIcon { get; private set; }
public SpriteRenderer colorRing;
private void Awake()
{
checker = false;
Instance = this;
}
private void OnValidate()
{
colorRing = GetComponent<SpriteRenderer>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
checker = true;
triggerIcon = collision.gameObject.GetComponent<Arrow>();
}
private void OnTriggerExit2D(Collider2D collision)
{
GameManager.Instance.countArrow++;
checker = false;
triggerIcon = null;
}
public void ColorRingGreen()
{
colorRing.DOColor(colorSwitchGreen, 0.5f).OnComplete(() =>
{
colorRing.DOColor(Color.black, 0.5f);
});
}
public void ColorRingRed()
{
colorRing.DOColor(colorSwitchRed, 0.5f).OnComplete(() =>
{
colorRing.DOColor(Color.black, 0.5f);
});
}
}
<file_sep>/Assets/Scripts/Game/Button.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Button : MonoBehaviour, IPointerDownHandler
{
[SerializeField] private ArrowsType arrowType;
private string grade;
private float fcountHit;
private float fcountArrow;
private int scoreAdd;
private void Awake()
{
scoreAdd = 0;
}
private void CheckZone()
{
if (CheckRing.Instance.checker && arrowType == CheckRing.Instance.triggerIcon.arrT)
{
HealthBar.Instance.AddHealth();
CheckRing.Instance.ColorRingGreen();
Destroy(CheckRing.Instance.triggerIcon.gameObject);
GameManager.Instance.countHit += 1;
GameManager.Instance.countCombo++;
scoreAdd = 10 * GameManager.Instance.countCombo;
GameManager.Instance.AddScore(scoreAdd);
BackgroundColor.Instance.BackgroundColorSwitch();
CountHitRate();
}
else
{
GameManager.Instance.countCombo = 0;
}
}
private void Update()
{
if (CheckRing.Instance.checker && arrowType == CheckRing.Instance.triggerIcon.arrT)
GameManager.Instance.miss = false;
}
private void CountHitRate()
{
fcountArrow = GameManager.Instance.countArrow;
fcountHit = GameManager.Instance.countHit;
GameManager.Instance.hitCountRate = (fcountHit / fcountArrow) * 100;
GameUI.Instance.hitRate.text = "Hit rate : " + GameManager.Instance.hitCountRate.ToString("#0.00") + " %";
}
public void OnPointerDown(PointerEventData eventData)
{
CheckZone();
GameUI.Instance.textCombo.text = "Combo: " + GameManager.Instance.countCombo.ToString() + "x";
Vibration.Vibrate(30);
}
}
<file_sep>/Assets/Scripts/Menu/Animations.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Animations : MonoBehaviour, IPointerDownHandler,IPointerUpHandler
{
public void OnPointerDown(PointerEventData eventData)
{
transform.localScale = new Vector3(1.1f, 1.1f, 1.1f);
}
public void OnPointerUp(PointerEventData eventData)
{
transform.localScale = new Vector3(1f, 1f, 1f);
}
}
<file_sep>/Assets/Scripts/Game/Spawn.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
public class Spawn : MonoBehaviour
{
[SerializeField] private Arrow arrow;
private float _spawnTimer;
public static Spawn Instance { get; private set; }
private void Awake()
{
Instance = this;
}
private void Start()
{
transform.position = Border.Instance.GetSpawnPoint();
}
void Update()
{
_spawnTimer -= Time.deltaTime;
if (_spawnTimer <= 0f)
{
_spawnTimer = GameManager.Instance.spawnTime;
Spawn_a();
}
}
public void Spawn_a()
{
int value = Random.Range(1, 5);
if (value == 1)
{
InitIcon(new Quaternion(1, 1, 0, 0), ArrowsType.Up);
}
else if (value == 2)
{
InitIcon(new Quaternion(0, 0, 0, 0), ArrowsType.Right);
}
else if (value == 3)
{
InitIcon(new Quaternion(0, 1, 0, 0), ArrowsType.Left);
}
else
{
InitIcon(new Quaternion(1, -1, 0, 0), ArrowsType.Down);
}
}
private void InitIcon(Quaternion quaternion, ArrowsType arrowType)
{
Arrow t = Instantiate(arrow, transform.position, quaternion);
t.arrT = arrowType;
}
}
<file_sep>/Assets/Scripts/Menu/Flash.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Flash : MonoBehaviour
{
[SerializeField] private Text gameName;
[SerializeField] private Text menuLevel;
[SerializeField] private Text levelTextLevelMenu;
[SerializeField] private Text GetReady;
[SerializeField] private Text levelGetready;
private void Update()
{
gameName.color = new Color(gameName.color.r, gameName.color.g, gameName.color.b, Mathf.PingPong(Time.time/2.5f,1f));
menuLevel.color = new Color(menuLevel.color.r, menuLevel.color.g, menuLevel.color.b, Mathf.PingPong(Time.time/2.5f,1f));
levelTextLevelMenu.color = new Color(levelTextLevelMenu.color.r, levelTextLevelMenu.color.g, levelTextLevelMenu.color.b, Mathf.PingPong(Time.time/2.5f,1f));
GetReady.color = new Color(GetReady.color.r, GetReady.color.g, GetReady.color.b, Mathf.PingPong(Time.time/2.5f,1f));
levelGetready.color = new Color(levelGetready.color.r, levelGetready.color.g, levelGetready.color.b, Mathf.PingPong(Time.time/2.5f,1f));
}
}
<file_sep>/Assets/Scripts/Game/GameUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameUI : MonoBehaviour
{
public static GameUI Instance { get; private set; }
[SerializeField] private Text textScore;
[SerializeField] private GameObject pauseButton;
[SerializeField] private GameObject _gameManager;
[SerializeField] private GameObject _spawnPoint;
[SerializeField] private GameObject _missPoint;
[SerializeField] private GameObject pausePanel;
[SerializeField] private GameObject restartButton;
[SerializeField] private GameObject backButton;
[SerializeField] private Sprite pauseSprite;
[SerializeField] private Sprite unpauseSprite;
[SerializeField] private Text scorePauseText;
[SerializeField] private Text winUIText;
[SerializeField] private Text gradeText;
public Text textCombo;
public Text hitRate;
private Image pauseImage;
public bool gameOnPause;
private bool pauseMusic;
private void Awake()
{
Instance = this;
}
private void Start()
{
gameOnPause = false;
pauseImage = pauseButton.gameObject.GetComponent<Image>();
}
private void Update ()
{
LoseGameUI();
WinGameUI();
}
private void LoseGameUI()
{
GameManager.Instance.Grade();
if (GameManager.Instance._loseGame)
{
pausePanel.gameObject.SetActive(true);
pauseButton.gameObject.SetActive(false);
gradeText.text = "Grade : " + GameManager.Instance.grade;
winUIText.text = "You lose!";
scorePauseText.text = "Score : " + GameManager.Instance.score.ToString();
}
}
private void WinGameUI()
{
GameManager.Instance.Grade();
if (GameManager.Instance._winGame)
{
pausePanel.gameObject.SetActive(true);
pauseButton.gameObject.SetActive(false);
gradeText.text = "Grade : " + GameManager.Instance.grade;
winUIText.text = "You win!";
scorePauseText.text ="Score : " + GameManager.Instance.score.ToString();
}
}
public void Restart()
{
SceneManager.LoadScene("Game");
}
public void BackToMenu()
{
SceneManager.LoadScene("Menu");
}
public void Pause_Game()
{
GameManager.Instance.Grade();
if (gameOnPause == false)
{
Time.timeScale = 0;
gradeText.text = "Grade : " + GameManager.Instance.grade;
pauseImage.sprite = unpauseSprite;
gameOnPause = true;
pausePanel.gameObject.SetActive(true);
scorePauseText.text = "Score : " + GameManager.Instance.score.ToString();
GameManager.Instance.gameModAudio.Pause();
}
else
{
GameManager.Instance.gameModAudio.Play();
pauseImage.sprite = pauseSprite;
gameOnPause = false;
Time.timeScale = 1;
pausePanel.gameObject.SetActive(false);
}
}
}
<file_sep>/Assets/Scripts/Game/MissPointInit.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class MissPointInit : MonoBehaviour
{
private float fcountHit;
private float fcountArrow;
private void Start()
{
transform.position = Border.Instance.GetMissPoint();
}
private void OnTriggerEnter2D(Collider2D collision)
{
HealthBar.Instance.MinusHealth();
GameManager.Instance.countMiss += 1;
GameManager.Instance.miss = true;
ComboExit();
CountHitRate();
CheckRing.Instance.ColorRingRed();
GameUI.Instance.textCombo.text = "Combo: " + GameManager.Instance.countCombo.ToString() + "x";
BackgroundColor.Instance.MissBackgroundColor();
}
private void ComboExit()
{
if (GameManager.Instance.miss && GameManager.Instance.countCombo != 0)
{
GameManager.Instance.countCombo = 0;
}
}
private void CountHitRate()
{
fcountArrow = GameManager.Instance.countArrow;
fcountHit = GameManager.Instance.countHit;
GameManager.Instance.hitCountRate = (fcountHit / fcountArrow)*100;
GameUI.Instance.hitRate.text = "Hit rate : " + GameManager.Instance.hitCountRate.ToString("#0.00") + " %";
}
}
<file_sep>/Assets/Scripts/Game/SongLenghtScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class SongLenghtScript : MonoBehaviour
{
private Image songLenght;
private void Start()
{
songLenght = GetComponent<Image>();
SongLengthCircle();
}
private void SongLengthCircle()
{
songLenght.DOFillAmount(1, GameManager.Instance.gameModAudio.clip.length);
}
}
<file_sep>/Assets/Scripts/Game/GameManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public enum ArrowsType { Up, Down, Left, Right };
public class GameManager : MonoBehaviour
{
public static GameManager Instance { get; private set; }
[SerializeField] private CheckRing prefabCheckRing;
[SerializeField] private GameObject prefabBands;
[SerializeField] private AudioClip easyModMusic;
[SerializeField] private AudioClip normalModMusic;
[SerializeField] private AudioClip hardModMusic;
public AudioSource gameModAudio;
public float speedArrow;
public float spawnTime;
public string grade;
public bool _loseGame;
public bool _winGame;
public bool _restartGame;
public Text scoreUIText;
public float ScoreAnimationTime;
public int score;
public int lifeCount;
public bool miss;
public int countCombo;
public int countMiss;
public int countHit;
public int maxCountLife;
public int countArrow;
public float hitCountRate;
private void Awake()
{
Time.timeScale = 1;
gameModAudio = GetComponent<AudioSource>();
SetLevel();
CheckRingInit();
BandsInit();
Instance = this;
}
private void Start()
{
AddScore(0);
maxCountLife = lifeCount;
countMiss = 0;
countHit = 0;
hitCountRate = 100;
score = 0;
countCombo = 0;
_loseGame = false;
_winGame = false;
_restartGame = false;
}
private void Update()
{
GameOver();
WinGame();
}
private void GameOver()
{
if (HealthBar.Instance._healthBar.fillAmount <= 0 && GameUI.Instance.gameOnPause == false)
{
Time.timeScale = 0;
_loseGame = true;
_restartGame = true;
gameModAudio.Stop();
}
}
private void WinGame()
{
if(HealthBar.Instance._healthBar.fillAmount != 0 && !gameModAudio.isPlaying && GameUI.Instance.gameOnPause == false)
{
Time.timeScale = 0;
_winGame = true;
_restartGame = true;
gameModAudio.Stop();
}
}
private void SetLevel()
{
try
{
SelectedLevel();
}
catch
{
spawnTime = 0.6123f;
speedArrow = Border.Instance.DistanceFromSpawn() / (spawnTime * 1.5f);
}
}
private void SelectedLevel()
{
if (MenuUI.Instance._easyModOn)
{
speedArrow = 3f;
spawnTime = 3f;
gameModAudio.clip = easyModMusic;
gameModAudio.Play();
}
else if (MenuUI.Instance._normalModOn)
{
speedArrow = 2.61f;
spawnTime = 0.7317f;
gameModAudio.clip = normalModMusic;
gameModAudio.Play();
}
else
{
spawnTime = 0.6123f;
speedArrow = Border.Instance.DistanceFromSpawn() / (spawnTime * 1.5f);
gameModAudio.clip = hardModMusic;
gameModAudio.Play();
}
}
private void CheckRingInit()
{
CheckRing checkRing = Instantiate(prefabCheckRing);
checkRing.transform.position = Border.Instance.GetCheckRingPoint();
}
private void BandsInit()
{
Instantiate(prefabBands).transform.position = Border.Instance.BandPoint();
}
public void AddScore(int value)
{
score += value;
var animTime = ScoreAnimationTime / 2f;
float deltaTime = 0f;
if (value > 0)
{
scoreUIText.transform.DOScale(1.2f, animTime).OnUpdate(() =>
{
deltaTime += Time.deltaTime;
var newTime = (int)(value * (1 - deltaTime / animTime));
SetTxt(score - value + (value - newTime), scoreUIText);
}).OnComplete(() =>
{
scoreUIText.transform.DOScale(1f, animTime / 2f);
});
}
else
{
scoreUIText.text = score.ToString();
}
}
public void SetTxt(int value, Text txt, string prefix = "")
{
txt.text = string.Format("{0}{1}", prefix, value);
}
public void Grade()
{
if (hitCountRate == 100)
grade = "SS";
else if (hitCountRate <= 100 && hitCountRate >= 95)
grade = "S";
else if (hitCountRate <= 95 && hitCountRate >= 90)
grade = "A";
else if (hitCountRate <= 90 && hitCountRate >= 85)
grade = "B";
else if (hitCountRate <= 85 && hitCountRate >= 80)
grade = "C";
else if (hitCountRate <= 80)
grade = "D";
}
}
<file_sep>/Assets/Scripts/Game/Border.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Border : MonoBehaviour
{
public static Border Instance { get; private set; }
[Range(0, 1)] [SerializeField] private float coefHiegth;
private float width;
private float height;
private float CenterOX;
private float TopBorder;
private float BottonBorder;
private float LeftBorder;
private float RightBorder;
private Camera camera;
private void Awake()
{
Instance = this;
camera = Camera.main;
height = camera.pixelHeight;
width = camera.pixelWidth;
RightBorder = camera.ScreenToWorldPoint(new Vector2(width, 0)).x;
TopBorder = camera.ScreenToWorldPoint(new Vector2(0, height)).y;
BottonBorder = camera.ScreenToWorldPoint(new Vector2(0, height/3.5f)).y;
LeftBorder = camera.ScreenToWorldPoint(new Vector2(0, 0)).x;
CenterOX = camera.ScreenToWorldPoint(new Vector2(width * 0.5f, 0)).x;
}
public Vector3 BandPoint()
{
return new Vector3(CenterOX +0.7f, BottonBorder, 0);
}
public float colorPoint()
{
return CenterOX + 1;
}
public float GetDestroyPoint()
{
return RightBorder + 1 ;
}
public Vector3 GetSpawnPoint()
{
return new Vector3(LeftBorder - 1, TopBorder - TopBorder * coefHiegth, 1);
}
public Vector3 GetCheckRingPoint()
{
return new Vector3(CenterOX, TopBorder - TopBorder * coefHiegth, 0);
}
public Vector3 GetMissPoint()
{
return new Vector3(CenterOX+0.527f, TopBorder - TopBorder * coefHiegth, 0);
}
public Vector3 GetHealthBarPoint()
{
return new Vector3(CenterOX, TopBorder - 0.1f, 0);
}
public float DistanceFromSpawn()
{
return CenterOX - (LeftBorder - 1);
}
}
<file_sep>/Assets/Scripts/Game/Arrow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Arrow : MonoBehaviour
{
public ArrowsType arrT;
private Color arrowColor;
void FixedUpdate ()
{
moveArrow();
}
private void Update()
{
DestroyArrow();
}
private void moveArrow()
{
transform.position = Vector3.Lerp(transform.position,
new Vector3(transform.position.x + GameManager.Instance.speedArrow, transform.position.y), Time.deltaTime);
}
private void DestroyArrow()
{
if (transform.position.x >= Border.Instance.GetDestroyPoint())
{
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/Menu/MenuUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MenuUI : MonoBehaviour
{
public static MenuUI Instance { get; private set; }
[SerializeField] private GameObject menuPanel;
[SerializeField] private GameObject playButton;
[SerializeField] private GameObject exitButton;
[SerializeField] private GameObject levelPanel;
[SerializeField] private GameObject easyModButton;
[SerializeField] private GameObject normalModButton;
[SerializeField] private GameObject hardModButton;
[SerializeField] private GameObject backToMenuButton;
[SerializeField] private GameObject readyPanel;
[SerializeField] private Text levelText;
[SerializeField] private Text timerText;
public bool _easyModOn;
public bool _normalModOn;
public bool _hardModOn;
public bool levelMenuIn;
public bool getReadyIn;
private float timer;
private void Awake()
{
Time.timeScale = 1;
Instance = this;
getReadyIn = false;
_easyModOn = false;
_normalModOn = false;
_hardModOn = false;
timer = 3;
}
private void Update()
{
TimerStart();
GameStart();
}
private void TimerStart()
{
if(getReadyIn)
{
timer -= Time.deltaTime;
timerText.text = Mathf.Round(timer).ToString();
}
}
private void GameStart()
{
if (timer <= 0)
{
SceneManager.LoadScene("Game");
}
}
public void EasyMod_On()
{
levelPanel.SetActive(false);
_easyModOn = true;
getReadyIn = true;
levelText.text = "Easy mod!";
readyPanel.gameObject.SetActive(true);
}
public void NormalMod_On()
{
levelPanel.SetActive(false);
_normalModOn = true;
getReadyIn = true;
levelText.text = "Normal mod!";
readyPanel.gameObject.SetActive(true);
}
public void HardMod_On()
{
levelPanel.SetActive(false);
_hardModOn = true;
getReadyIn = true;
levelText.text = "Hard mod!";
readyPanel.gameObject.SetActive(true);
}
public void BackToMainMenu()
{
levelMenuIn = false;
menuPanel.gameObject.SetActive(true);
levelPanel.gameObject.SetActive(false);
}
public void StartGame()
{
levelMenuIn = true;
menuPanel.gameObject.SetActive(false);
levelPanel.gameObject.SetActive(true);
}
public void ExitGame()
{
Application.Quit();
}
}
|
d0fb812338cadfcfc02ee53106a556dff1a45262
|
[
"C#"
] | 15 |
C#
|
Belzebbuz/ClickerCircles
|
5400d2a30308413d1b01e8039acaf29054547470
|
757e45ed232c8661f99339a0eead593023ca5c5d
|
refs/heads/master
|
<repo_name>dmcruz/IntrospectTest<file_sep>/IntrospectTest/Controllers/ValuesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace IntrospectTest.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
const string URL = "";
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// GET api/values/userinfo/tk
[HttpGet("userinfo/{tk}")]
public string GetUserInfo(string tk)
{
return validateAccessToken(tk);
}
private string validateAccessToken(string at)
{
try
{
var response = string.Empty;
using (WebClient client = new WebClient())
{
client.Headers.Add("Authorization", "Bearer " + at);
response = client.DownloadString(URL);
return response;
}
}
catch(Exception ex)
{
return ex.Message + " ::: " + ex.StackTrace + " ::: " + (ex.InnerException != null ? ex.InnerException.Message + " :: " + ex.InnerException.StackTrace : "");
}
}
}
}
|
93979e9ade281752d167ca39e0cc242d1fad3e7d
|
[
"C#"
] | 1 |
C#
|
dmcruz/IntrospectTest
|
118085bfe4ab673bedba323df36cb4db4f4543cf
|
214afe111a87369f14fc63030c0b3ba7d0c57671
|
refs/heads/main
|
<file_sep>from jvm_embedding import *
import sys
import json
inpath = sys.argv[1]
outpath = sys.argv[2]
tf_dataset, df, n_methods = build_tf_df(inpath)
idf = compute_idf(df, n_methods)
print(json.dumps(idf, indent=4))
with open(outpath, 'w') as fd:
json.dump(idf, fd, indent=4)
print("Total", n_methods, "methods")
<file_sep>#Copyright (c) <NAME>
#Released under MIT License
import sys
import json
import os
from subprocess import Popen, PIPE
from math import log, sqrt
from collections import defaultdict
from sklearn.feature_extraction import DictVectorizer
def lines_to_feature_dict(lines, df):
d = defaultdict(float)
features = set()
n_features = 0
#unigrams:
for ins in lines:
d[ins] += 1
features.add(ins)
n_features += 1
#bigram subsequences:
for i in range(0, len(lines)):
for j in range(i+1, len(lines)):
f = lines[i] + "/" + lines[j]
d[f] += 1
features.add(f)
n_features += 1
if df is not None:
for f in features:
df[f] += 1
for k in d.keys():
d[k] = d[k] / n_features
return d
def dict_featurize(mod, df):
res = {}
n_methods = 0
for method, lines in mod.items():
res[method] = lines_to_feature_dict(lines, df)
n_methods += 1
return res, n_methods
def build_tf_df(inpath):
tf_dataset = {}
df = defaultdict(float)
n_methods = 0
for root, dirs, files in os.walk(inpath):
path = root.split(os.sep)
print((len(path) - 1) * '...', os.path.basename(root))
for file in files:
if file.endswith(".class"):
file_path = root + os.sep + file
print(len(path) * '...', file)
process = Popen(["javap", "-v", file_path], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
output = output.decode("latin1")
#print(output)
lines = output.split("\n")
#print(lines)
res = parse_jsonp(lines)
#print(json.dumps(res, indent=4))
res, n_mod_methods = dict_featurize(res, df)
tf_dataset[file_path] = res
n_methods += n_mod_methods
print("processed", n_mod_methods, "methods")
return tf_dataset, df, n_methods
def build_nsubseqs(inpath, outpath):
n_methods = 0
with open(outpath, 'w') as outfd:
for root, dirs, files in os.walk(inpath):
path = root.split(os.sep)
print((len(path) - 1) * '...', os.path.basename(root))
for file in files:
if file.endswith(".class"):
file_path = root + os.sep + file
print(len(path) * '...', file)
process = Popen(["javap", "-v", file_path], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
output = output.decode("latin1")
#print(output)
lines = output.split("\n")
#print(lines)
res = parse_jsonp(lines)
#print(json.dumps(res, indent=4))
res, n_mod_methods = dict_featurize(res, None)
for method, method_features in res.items():
features_line = " ".join(list(method_features.keys()))
outfd.write(features_line + "\n")
n_methods += n_mod_methods
print("processed", n_mod_methods, "methods")
return n_methods
def compute_idf(df, n_methods):
idf = {}
for k, v in df.items():
idf[k] = log(n_methods/(v + 1))
return idf
def flatten(dataset):
res = []
for path, feature_dicts in dataset.items():
for method, feature_dict in feature_dicts.items():
res.append(feature_dict)
return res
def dict_norm(d):
n = 0
for v in d.values():
n += v * v
return sqrt(n)
def dict_cosine(d1, d2):
n1 = dict_norm(d1)
n2 = dict_norm(d2)
res = 0
for k1, v1 in d1.items():
v2 = d2.get(k1, None)
if v2 is not None:
res += v1 * v2
n = n1 * n2
return res / n if n != 0 else 0
def normalize_line(line):
if line.startswith("invoke"):
ins = line.split(" ", 1)[0]
type_ = line.split(":")[-1]
return ins + type_
elif line.startswith("new"):
fields = line.split(" ", 1)
ins = fields[0]
if "class " in line:
class_ = line.split("class ")[1]
else:
class_ = fields[1]
class_ = class_.strip()
return "new(" + class_ + ")"
else:
return line.split(" ", 1)[0]
def parse_jsonp(src):
MODULE = 0
METHOD_DEFS = 1
METHOD_BODY = 2
state = MODULE
curr_method = ""
curr_method_code = []
res = {}
for line in src:
sline = line.strip()
if state == MODULE:
if line != "" and line[0] == '{':
state = METHOD_DEFS
elif state == METHOD_DEFS:
if sline.endswith(";"):
sline = sline[0:-1]
curr_method = sline
curr_method_code = []
state = METHOD_BODY
elif state == METHOD_BODY:
if sline == "" or sline == "}":
state = METHOD_DEFS if sline == "" else MODULE
if curr_method != "":
res[curr_method] = curr_method_code
curr_method = ""
curr_method_code = []
else:
fields = sline.split(":", 1)
if len(fields) == 2 and fields[0].isnumeric():
curr_method_code.append(normalize_line(fields[1].strip()))
return res
if __name__ == "__main__":
pass
<file_sep>from jvm_embedding import *
import sys
import json
import gensim
import numpy as np
inpath = sys.argv[1]
vecpath = sys.argv[2]
if len(sys.argv) > 3:
scale = float(sys.argv[3])
else:
scale = 1.0
def similarity(v1, v2):
#return np.dot(v1, v2)
return np.linalg.norm(v1 - v2)/scale
model = gensim.models.KeyedVectors.load_word2vec_format(vecpath, binary=False)
tf_dataset, df, n_methods = build_tf_df(inpath)
method_embeddings = {}
for path, method_features in tf_dataset.items():
method_embeddings[path] = {}
for method in method_features.keys():
feature_dict = method_features[method]
method_embeddings[path][method] = sum(model[f]*v for f, v in feature_dict.items() if f in model)
for path1, method_features1 in tf_dataset.items():
for method1, feature_dict1 in method_features1.items():
print()
print(path1, "@", method1, "vs: ")
res = []
for path2, method_features2 in tf_dataset.items():
for method2, feature_dict2 in method_features2.items():
if path1 == path2 and method1 == method2:
continue
sim = similarity(method_embeddings[path1][method1], method_embeddings[path2][method2])
res.append( (path2 + " " + method2, sim))
res.sort(reverse=False, key=lambda t: t[1])
for target, sim in res:
print(" ", target, ":", sim)
<file_sep>import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from data_reader import DataReader, Word2vecDataset
from model import SkipGramModel
class Ctx(object):
def __init__(self):
self.initialized = False
class Word2VecMTLTrainer:
def __init__(self, input_file1, input_file2, output_file, emb_dimension=100, batch_size=32, window_size=5, iterations=3,
initial_lr=0.001, min_count=12):
self.ctx = ctx = Ctx()
self.data = [DataReader(input_file1, min_count, ctx), DataReader(input_file2, min_count, ctx)]
datasets = [Word2vecDataset(self.data[0], window_size), Word2vecDataset(self.data[1], window_size)]
self.dataloaders = []
for dataset in datasets:
dataloader = DataLoader(dataset, batch_size=batch_size,
shuffle=False, num_workers=0, collate_fn=dataset.collate)
self.dataloaders.append(dataloader)
self.output_file_name = output_file
self.emb_size = len(self.ctx.word2id)
self.emb_dimension = emb_dimension
self.batch_size = batch_size
self.iterations = iterations
self.initial_lr = initial_lr
self.skip_gram_model = SkipGramModel(self.emb_size, self.emb_dimension)
self.use_cuda = torch.cuda.is_available()
self.device = torch.device("cuda" if self.use_cuda else "cpu")
if self.use_cuda:
self.skip_gram_model.cuda()
def train(self):
for iteration in range(self.iterations):
print("\n\n\nIteration: " + str(iteration + 1))
optimizer = optim.SparseAdam(self.skip_gram_model.parameters(), lr=self.initial_lr)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(self.dataloaders[0]) + len(self.dataloaders[1]) )
running_loss = 0.0
for i, (sample_batched1, sample_batched2) in enumerate( tqdm( zip(self.dataloaders[0], self.dataloaders[1]) ) ):
task = 1
for sample_batched in (sample_batched1, sample_batched2):
if len(sample_batched[0]) > 1:
pos_u = sample_batched[0].to(self.device)
pos_v = sample_batched[1].to(self.device)
neg_v = sample_batched[2].to(self.device)
scheduler.step()
optimizer.zero_grad()
loss = self.skip_gram_model.forward(pos_u, pos_v, neg_v, task)
loss.backward()
optimizer.step()
running_loss = running_loss * 0.9 + loss.item() * 0.1
if i > 0 and i % 500 == 0:
print(" Loss: " + str(running_loss))
task = 2
self.skip_gram_model.save_embedding(self.ctx.id2word, self.output_file_name)
if __name__ == '__main__':
import sys
w2v = Word2VecMTLTrainer(input_file1=sys.argv[1], input_file2=sys.argv[2], output_file=sys.argv[3], window_size=1000)
w2v.train()
<file_sep>#Copyright (c) <NAME>
#Released under MIT License
import sys
import json
import os
from subprocess import Popen, PIPE
from math import log, sqrt
import random
from collections import defaultdict
from sklearn.feature_extraction import DictVectorizer
#Hyperparameter: Maximum number of paths explored via CFG random walk. Higher is better of course
#Currently set to 10 owing to the compute limitations of my laptop :)
MAX_PATHS = 10
def inseq_to_feature_dict(lines):
d = defaultdict(float)
#unigrams:
for ins in lines:
d[ins] += 1
#bigram subsequences:
for i in range(0, len(lines)):
for j in range(i+1, len(lines)):
f = lines[i] + "/" + lines[j]
d[f] += 1
return d
def cfg_walk(cfg, paths, curr_path=None, curr_idx=0):
if curr_path is None:
curr_path = []
curr_idx = 0
ins_desc = cfg[curr_idx]
while len(ins_desc['next']) == 1 and curr_path.count(ins_desc['next'][0]) < 2:
curr_path.append(curr_idx)
if "return" in ins_desc['ins']:
break
curr_idx = ins_desc['next'][0]
ins_desc = cfg[curr_idx]
if len(ins_desc['next']) <= 1:
paths.append(curr_path)
else:
for next in ins_desc['next']:
if curr_path.count(next) < 2:
path = curr_path.copy()
cfg_walk(cfg, paths, path, next)
def dict_featurize(mod):
global MAX_PATHS
res = {}
n_methods = 0
for method, cfg in mod.items():
print(method, end=" ")
if len(cfg) == 0:
continue
paths = []
#print(json.dumps(cfg, indent=4))
print(len(cfg), "instructions", end=" ")
cfg_walk(cfg, paths, curr_path=None, curr_idx=0)
feature_dicts = []
print(len(paths), "paths")
if len(paths) > MAX_PATHS:
pruned_paths = []
for i in range(0, MAX_PATHS):
n = int(random.random()*(MAX_PATHS-1))
pruned_paths.append(paths[n])
paths = pruned_paths
for path in paths:
path = [cfg[idx]['ins'] for idx in path]
#print(".", end="")
sys.stdout.flush()
#print("PATH", path)
d = inseq_to_feature_dict(path)
#print(json.dumps(d, indent=4))
feature_dicts.append(d)
res[method] = feature_dicts
n_methods += 1
return res, n_methods
def build_nsubseqs(inpath, outpath):
n_methods = 0
with open(outpath, 'w') as outfd:
for root, dirs, files in os.walk(inpath):
path = root.split(os.sep)
print((len(path) - 1) * '...', os.path.basename(root))
for file in files:
if file.endswith(".class"):
file_path = root + os.sep + file
print(len(path) * '...', file)
process = Popen(["javap", "-v", file_path], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
output = output.decode("latin1")
#print(output)
lines = output.split("\n")
#print(lines)
res = parse_jsonp(lines)
#print(json.dumps(res, indent=4))
res, n_mod_methods = dict_featurize(res)
for method, method_paths in res.items():
for path_features in method_paths:
features_line = " ".join(list(path_features.keys()))
outfd.write(features_line + "\n")
n_methods += n_mod_methods
print("processed", n_mod_methods, "methods")
return n_methods
def build_path_features(inpath):
dataset = {}
df = defaultdict(float)
n_methods = 0
for root, dirs, files in os.walk(inpath):
path = root.split(os.sep)
print((len(path) - 1) * '...', os.path.basename(root))
for file in files:
if file.endswith(".class"):
file_path = root + os.sep + file
print(len(path) * '...', file)
process = Popen(["javap", "-v", file_path], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
output = output.decode("latin1")
#print(output)
lines = output.split("\n")
#print(lines)
res = parse_jsonp(lines)
#print(json.dumps(res, indent=4))
res, n_mod_methods = dict_featurize(res)
dataset[file_path] = res
n_methods += n_mod_methods
print("processed", n_mod_methods, "methods")
return dataset, n_methods
def compute_idf(df, n_methods):
idf = {}
for k, v in df.items():
idf[k] = log(n_methods/(v + 1))
return idf
def flatten(dataset):
res = []
for path, feature_dicts in dataset.items():
for method, feature_dict in feature_dicts.items():
res.append(feature_dict)
return res
def dict_norm(d):
n = 0
for v in d.values():
n += v * v
return sqrt(n)
def dict_cosine(d1, d2):
n1 = dict_norm(d1)
n2 = dict_norm(d2)
res = 0
for k1, v1 in d1.items():
v2 = d2.get(k1, None)
if v2 is not None:
res += v1 * v2
n = n1 * n2
return res / n if n != 0 else 0
def normalize_line(line):
if line.startswith("invoke"):
ins = line.split(" ", 1)[0]
type_ = line.split(":")[-1]
return ins + type_, None
elif line.startswith("new"):
fields = line.split(" ", 1)
ins = fields[0]
if "class " in line:
class_ = line.split("class ")[1]
else:
class_ = fields[1]
class_ = class_.strip()
return "new(" + class_ + ")", None
else:
fields = line.split(" ", 1)
if len(fields) == 2:
ins, rest = fields
if ins.startswith("if") or ins == "goto":
return ins, int(rest)
else:
ins = fields[0]
return ins, None
def parse_jsonp(src):
MODULE = 0
METHOD_DEFS = 1
METHOD_BODY = 2
SWITCH = 3
state = MODULE
curr_method = ""
curr_method_cfg = {}
res = {}
next = None
for line in src:
sline = line.strip()
#print(sline)
if state == SWITCH:
if sline == "}":
state = METHOD_BODY
next = None
else:
val, label = line.split(":")
label = int(label.strip())
if label not in next:
next.append(label)
elif state == MODULE:
if line != "" and line[0] == '{':
state = METHOD_DEFS
elif state == METHOD_DEFS:
if sline.endswith(";"):
sline = sline[0:-1]
curr_method = sline
curr_method_cfg = {}
state = METHOD_BODY
next = None
elif state == METHOD_BODY:
if sline == "" or sline == "}":
state = METHOD_DEFS if sline == "" else MODULE
if curr_method != "":
res[curr_method] = curr_method_cfg
curr_method = ""
curr_method_cfg = {}
else:
fields = sline.split(":", 1)
if len(fields) == 2 and fields[0].isnumeric():
idx = int(fields[0])
if next is not None and ins != "goto":
next.append(idx)
ins, next_idx = normalize_line(fields[1].strip())
next = []
if next_idx is not None:
next.append(next_idx)
node = {'ins': ins, 'next': next}
curr_method_cfg[idx] = node
if ins == "lookupswitch" or ins == "tableswitch":
state = SWITCH
return res
if __name__ == "__main__":
import sys
build_nsubseqs(inpath=sys.argv[1], outpath=sys.argv[2])
<file_sep>class test4{
static void matrix_mul(int ar[][],int rows, int columns)
{
int[][] resultMatix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatix[i][j] = ar[i][j] + ar[i][j];
}
}
}
static void mul_matrix(int arr[][], int rows, int columns)
{
int[][] productMatrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
for (int k = 0; k < columns; k++) {
productMatrix[i][j] = productMatrix[i][j] + arr[i][k] * arr[k][j];
}
}
}
}
}<file_sep>from jvm_embedding import *
import sys
import json
inpath = sys.argv[1]
idfpath = sys.argv[2]
tf_dataset, df, n_methods = build_tf_df(inpath)
with open(idfpath) as fd:
idf = json.load(fd)
for path, method_features in tf_dataset.items():
for method in method_features.keys():
feature_dict = method_features[method]
for f in feature_dict.keys():
feature_dict[f] = feature_dict[f] * idf.get(f, 1.0)
for path1, method_features1 in tf_dataset.items():
for method1, feature_dict1 in method_features1.items():
print()
print(path1, "@", method1, "vs: ")
res = []
for path2, method_features2 in tf_dataset.items():
for method2, feature_dict2 in method_features2.items():
if path1 == path2 and method1 == method2:
continue
sim = dict_cosine(feature_dict1, feature_dict2)
res.append( (path2 + " " + method2, sim))
res.sort(reverse=True, key=lambda t: t[1])
for target, sim in res:
print(" ", target, ":", sim)
<file_sep>from cfg_embedding import *
import sys
import json
import gensim
import numpy as np
inpath = sys.argv[1]
vecpath = sys.argv[2]
if len(sys.argv) > 3:
scale = float(sys.argv[3])
else:
scale = 1.0
def similarity(v1, v2):
#return np.dot(v1, v2)
return np.linalg.norm(v1 - v2)/scale
model = gensim.models.KeyedVectors.load_word2vec_format(vecpath, binary=False)
dataset, n_methods = build_path_features(inpath)
method_embeddings = {}
for path, method_features in dataset.items():
method_embeddings[path] = {}
for method, feature_dicts in method_features.items():
for feature_dict in feature_dicts:
vec = sum(model[f]*v for f, v in feature_dict.items() if f in model)
if method in method_embeddings[path]:
method_embeddings[path][method] += vec
else:
method_embeddings[path][method] = vec
for path1, method_features1 in dataset.items():
for method1, feature_dict1 in method_features1.items():
print()
print(path1, "@", method1, "vs: ")
res = []
for path2, method_features2 in dataset.items():
for method2, feature_dict2 in method_features2.items():
if path1 == path2 and method1 == method2:
continue
sim = similarity(method_embeddings[path1][method1], method_embeddings[path2][method2])
res.append( (path2 + " " + method2, sim))
res.sort(reverse=False, key=lambda t: t[1])
for target, sim in res:
print(" ", target, ":", sim)
<file_sep>from jvm_embedding import *
import sys
import json
inpath = sys.argv[1]
outpath = sys.argv[2]
n_methods = build_nsubseqs(inpath, outpath)
print("Total", n_methods, "methods")
<file_sep>
class test4{
int mn(int y){
return y * 3;
}
public int m(int x){
int i = 0;
while (true){
x = x + 3;
i += 1;
if( i > 3){
break;
}
}
test2 t = new test2();
return t.n(x);
}
public String m2(String x, int n){
String res= "";
for(int i=0;i<n;i++){
res += x;
}
return res;
}
public String m3(String x, int n){
String res= "";
for(int i=0;i<n;i++){
res += "~";
}
return res;
}
}
<file_sep>class test3{
int fib(int n)
{
if(n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
public void string_rep(String x)
{
int count;
char string[] = x.toCharArray();
for(int i = 0; i <string.length; i++) {
count = 1;
for(int j = i+1; j <string.length; j++) {
if(string[i] == string[j] && string[i] != ' ') {
count++;
string[j] = '0';
}
}
if(count > 1 && string[i] != '0')
System.out.println(string[i]);
}
}
}<file_sep># Java code embeddings from compiled class files for code similarity tasks
### Summary
A novel and simple approach for generating source code embeddings for code similarity tasks.
This *compiler-in-the-loop* approach works by compiling the high level source code to a typed intermediate language. Here we demonstrate for Java using the JVM instruction set. For other languages such as C/C++, LLVM intermediate language could be used.
We take the instruction sequence in each method and generate k-subsequences of instructions.
* Extra type information is attached to 'invoke' instructions: Function calls are abstracted using the parameter and return types and attached to invoke instructions.
* Class name is attached to the 'new' instruction.
* Parameter and return types from function definition are currently not used since they're not part of the instruction stream.
k-subsequences of instructions:
* For k = 1 .. N (currently N = 2):
* We take every k-subsequence in the instruction sequence, generating a k-gram.
I experiment with 4 approaches:
* Subsequence k-gram embeddings generated by 3 methods:
* Random walks on the control flow graph (CFG) of a method, similar to graph vertex embeddings.
* On the entire instruction sequence of a method without any path sensitivity.
* Multi-tasking learning jointly on the above 2 tasks.
* TF-IDF-style method embeddings.
### Path sensitive k-gram embeddings
Here, we generate path sequences via random walks on the control flow graph (CFG). If number of paths are small, complete walks are performed. We then learn k-gram embeddings from these path sequences using a Skip-Gram model, similar to graph vertex embeddings.
Method embeddings are generated by summing up all its path embeddings and path embeddings are generated by summing up all the k-gram embeddings in the path.
Method similarity checking is done by computing vector similarity on method embeddings.
### Path insensitive k-gram embeddings
In this approach, embeddings for subsequence n-grams (of instruction sequences) are learnt using a Word2Vec-style skip-gram model (currently n <= 2). Method embeddings are generated by summing up the embeddings of subsequence n-grams contained in it.
Method similarity checking is done by computing vector similarity on method embeddings.
### Multi-Task Learning (MTL) of k-gram embeddings
Here, k-gram embeddings are learnt by a Multi-Task Skip-Gram Model that jointly optimizes on the above two tasks: the path sensitive learning and path insensitive learning.
### TF-IDF embeddings
In this approach, during the learning phase, the IDF values for the features are learnt and stored in a JSON file.
During similarity checking, the TF vectors are generated and scaled using the previously learnt IDF values. Cosine similarity is used as the similarity measure.
### Pre-requisites
* A recent version of Python 3.
* A recent version of JDK (javap is used to generate JVM disassembly) - must be in the path.
* scikit-learn: pip install scikit-learn
* pytorch: pip install torch (not required for TF-IDF embeddings)
### Running (n-subsequence embeddings)
#### Embedding generation (path insensitive)
```console
python compute_nsubseqs.py <folder containing class files> <subseq output path>
cd word2vec
python trainer.py <subseq output path> <vec output file path>
```
#### Embedding generation (path sensitive)
```console
python cfg_embedding.py <folder containing class files> <subseq output path>
cd word2vec
python trainer.py <subseq output path> <vec output file path>
```
#### MTL Embedding generation
```console
cd word2vec-mtl
python mtl-trainer.py <path insensitive subseq output path> <path sensitive subseq output path> <vec output file path>
```
#### Similarity checking
```console
python compute_nsubseq_emb_similarity.py <folder containing class files> <vec file path>
```
#### IDF generation:
```console
python compute_idf.py <folder containing class files> <IDF output path>
```
The folder containing class files is recursively searched for class files and the IDF is computed by aggregating data from all methods in all the class files.
#### Similarity checking
```console
python compute_tf_idf_similarity.py <folder containing class files> <IDF path>
```
To run against the test files using the pretrained vectors from commons-lang library:
```console
cd test
javac *.java
cd ..
python compute_nsubseq_emb_similarity test test/commons_lang_ngrams.vec
```
### Running (TF-IDF embeddings)
#### IDF generation:
```console
python compute_idf.py <folder containing class files> <IDF output path>
```
The folder containing class files is recursively searched for class files and the IDF is computed by aggregating data from all methods in all the class files.
#### Similarity checking
```console
python compute_tf_idfsimilarity.py <folder containing class files> <IDF path>
```
The IDF path must point to a previously computed IDF file. All the class files are read and pair-wise similarity of all methods are printed.
To run against the test files:
```console
cd test
javac *.java
cd ..
python compute_tf_idf_similarity test test/idf_commons_lang.json
```
### Pre-computed
* The file test/idf_commons_lang.json contains IDF computed from all the class files in the Apache Commons Lang library.
* The file test/commons_lang_ngrams.vec contains unary and binary-subsequence embeddings trained from all the class files in Apache Commongs Lang library.
### Citing
If you are using or extending this work as part of your research, please cite as:
<NAME>, "Java code embeddings from compiled class files for code similarity tasks", (2021), GitHub repository, https://github.com/jayarajporoor/code_embedding
BibTex:
@misc{Poroor2021,
author = {<NAME>},
title = {Java code embeddings from compiled class files for code similarity tasks},
year = {2021},
publisher = {GitHub},
journal = {GitHub repository},
howpublished = {\url{https://github.com/jayarajporoor/code_embedding}}
}
### Related work
A few deep learning models have been proposed in recent years to generate source code embeddings:
* Code2Vec - https://github.com/tech-srl/code2vec
* CodeBERT - https://github.com/microsoft/CodeBERT
<file_sep>import argparse
import numpy as np
from sklearn.decomposition import PCA, TruncatedSVD
import gensim
from jvm_embedding import *
scale = 1.0
def similarity(v1, v2):
#return np.dot(v1, v2)
return np.linalg.norm(v1 - v2)/scale
def Dimenionality_reduction(model_path, n_components,dim_red):
model = gensim.models.KeyedVectors.load_word2vec_format(model_path, binary=False)
wv = model.vectors
mean = np.average(wv,axis=0)
if dim_red == 1:
dim_m = PCA(n_components=n_components)
else:
dim_m = TruncatedSVD(n_components=n_components)
dim_m.fit(wv - mean)
components = np.matmul(np.matmul(wv, dim_m.components_.T), dim_m.components_)
processed_vec = wv - mean - components
return processed_vec
def compare(processed_vec,test_path,model_path):
model = gensim.models.KeyedVectors.load_word2vec_format(model_path, binary=False)
model.vectors = processed_vec
tf_dataset, df, n_methods = build_tf_df(test_path)
method_embeddings = {}
for path, method_features in tf_dataset.items():
method_embeddings[path] = {}
for method in method_features.keys():
feature_dict = method_features[method]
method_embeddings[path][method] = sum(model[f]*v for f, v in feature_dict.items() if f in model)
for path1, method_features1 in tf_dataset.items():
for method1, feature_dict1 in method_features1.items():
print()
print(path1, "@", method1, "vs: ")
res = []
for path2, method_features2 in tf_dataset.items():
for method2, feature_dict2 in method_features2.items():
if path1 == path2 and method1 == method2:
continue
sim = similarity(method_embeddings[path1][method1], method_embeddings[path2][method2])
res.append( (path2 + " " + method2, sim))
res.sort(reverse=False, key=lambda t: t[1])
for target, sim in res:
print(" ", target, ":", sim)
pass
def args_parse():
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--model_path', nargs='*', help='path of model(s)')
parser.add_argument('-n', '--n_components', type=int, default=5, help='number of dimensions postprocessing')
parser.add_argument('-c', '--dim_red', type=int, default=0, help=' Dimenionality Reduction: 0 for TSVD or 1 for PCA')
parser.add_argument('-t', '--test_path', type=str, help='test_classes')
args = parser.parse_args()
for model_path in args.model_path:
processed_vec = Dimenionality_reduction(model_path,args.n_components,args.dim_red)
compare(processed_vec,args.test_path,model_path)
if __name__ == '__main__':
args_parse()
|
b09d15afb60123fce2a17961be25afc0df8356fa
|
[
"Markdown",
"Java",
"Python"
] | 13 |
Python
|
Vishwaak/code_embedding
|
7cf6463da4deb2e2a41bd43ceeee65334d3d61bc
|
37a7faef7a84da9585f9125509776cadb9d56d33
|
refs/heads/master
|
<repo_name>lillheaton/eols.UmbracoContentApi<file_sep>/src/Interfaces/IDocumentTypeExtender.cs
using System.Collections.Generic;
using Umbraco.Core.Models;
using Umbraco.Web;
namespace EOls.UmbracoContentApi.Interfaces
{
public interface IDocumentTypeExtender
{
Dictionary<string, object> Extend(IPublishedContent content, ContentSerializer serializer, UmbracoHelper umbraco);
}
}<file_sep>/src/Util/ReflectionHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Umbraco.Core;
namespace EOls.UmbracoContentApi.Util
{
public static class ReflectionHelper
{
/// <summary>
/// Get all classes that inherit T in assembly
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assembly"></param>
/// <returns></returns>
public static IEnumerable<Type> GetAssemblyClassesInheritInterface<T>(Assembly assembly)
{
try
{
return
assembly
.GetTypes()
.Where(x => x.IsClass && typeof(T).IsAssignableFrom(x));
}
catch
{
return Enumerable.Empty<Type>();
}
}
/// <summary>
/// Get all classes that inherit T in assemblies
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assemblies"></param>
/// <returns></returns>
public static IEnumerable<Type> GetAssemblyClassesInheritInterface<T>(IEnumerable<Assembly> assemblies)
{
return assemblies.SelectMany(GetAssemblyClassesInheritInterface<T>);
}
/// <summary>
/// Gets all classes that inherit T in all currentDomainAssemblies
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<Type> GetAssemblyClassesInheritInterface<T>()
{
return GetAssemblyClassesInheritInterface<T>(AppDomain.CurrentDomain.GetAssemblies());
}
/// <summary>
/// Get all classes that inherit attribute T in assembly
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assembly"></param>
/// <returns></returns>
public static IEnumerable<Type> GetAssemblyClassesInheritAttribute<T>(Assembly assembly)
{
try
{
return
assembly
.GetTypes()
.Where(x => x.IsClass && x.GetCustomAttributes(typeof(T)).Any());
}
catch
{
return Enumerable.Empty<Type>();
}
}
/// <summary>
/// Get all classes that inherit attribute T in all currentDomainAssemblies
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<Type> GetAssemblyClassesInheritAttribute<T>()
{
return AppDomain.CurrentDomain.GetAssemblies().SelectMany(GetAssemblyClassesInheritAttribute<T>);
}
}
}<file_sep>/src/Attributes/PropertyTypeAttribute.cs
using System;
namespace EOls.UmbracoContentApi.Attributes
{
public class PropertyTypeAttribute : Attribute
{
public string Type { get; set; }
}
}<file_sep>/src/Extensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace EOls.UmbracoContentApi
{
public static class Extensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, Func<KeyValuePair<TKey, TValue>, bool> predicate)
{
KeyValuePair<TKey, TValue>? result =
source
.Where(predicate)
.Select(x => x as KeyValuePair<TKey, TValue>?)
.FirstOrDefault();
if (!result.HasValue)
return default(TValue);
return result.Value.Value;
}
}
}
<file_sep>/README.md
# Umbraco Content Api
A generic content api for Umbraco CMS. <br>Serializes the content in Umbraco to Json. It's possible to adapt how a specific Umbraco property gets serialized by adding custom "Property converter". The nuget package include a set of standard property converters.
<br><br>
Latest known version of Umbraco that this nuget have been successfully tested with: **v7.7.7**
### Installation
PM> Install-Package EOls.UmbracoContentApi
### Usage
[GET] /umbraco/api/content/get/{id}
### Custom Property Converters
If you want to adapt how a specific Umbraco property is serialized. Just add a class that implements the interface IApiPropertyConverter, and decorate the class with the PropertyTypeAttribute.
<br><br>
All property converters (and document extenders) will be located by using reflection during site startup.
#### Example
In this example the text "Awesome!" will be added to the content when an Umbraco property of type "Umbraco.TinyMCEv3" is serialized.
```C#
[PropertyType(Type = "Umbraco.TinyMCEv3")]
public class RichTextEditorConverter : IApiPropertyConverter
{
public object Convert(IPublishedProperty property, IPublishedContent owner, ContentSerializer serializer, UmbracoHelper umbraco)
{
var htmlString = property.Value as HtmlString;
return htmlString != null ? htmlString.ToHtmlString() + "Awesome!" : string.Empty;
}
}
```
<br>
### Extend document Type
It's possible to extend a document type by creating a class with the IDocumentTypeExtender interface.
When the api returns content with this document type, it will include the additional data.
#### Example
Let's say you have a document type named "Home". For this specific document type you also want to return some additional data.
```C#
public class HomeDocument : IDocumentTypeExtender
{
public Dictionary<string, object> Extend(IPublishedContent content, ContentSerializer serializer, UmbracoHelper umbra)
{
return new Dictionary<string, object>() { { "Foo", "Bar" } };
}
}
```
<br>
### Hide document or properties
It's possible to "hide" a specific property, or the entire document type, from being returned by the API. <br>
#### Example
Hide document type named "Settings"
```C#
[DocumentTypeSettingsAttribute(Hide = true)]
public class SettingsDocument { }
```
<br>
Hide properties "myNonPublicProperty" and "myOtherProperty" on document type "Settings"
```C#
[DocumentTypeSettingsAttribute(HideProperties = new[]{"myNonPublicProperty","myOtherProperty"}))]
public class SettingsDocument { }
```
<file_sep>/src/ContentController.cs
using Newtonsoft.Json;
using System.Web.Http;
using Umbraco.Web.WebApi;
namespace EOls.UmbracoContentApi
{
public class ContentController : UmbracoApiController
{
private ContentSerializer _serializer;
private JsonSerializerSettings _jsonSettings;
public ContentController()
{
this._serializer = new ContentSerializer(this.Umbraco);
this._jsonSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
if (SerializerManager.ContractResolver != null)
this._jsonSettings.ContractResolver = SerializerManager.ContractResolver;
}
[HttpGet]
public IHttpActionResult Get(int id)
{
var content = Umbraco.TypedContent(id);
if (content == null)
{
return BadRequest("No content with that ID");
}
return Json(this._serializer.Serialize(content), this._jsonSettings);
}
}
}<file_sep>/src/ContentSerializer.cs
using EOls.UmbracoContentApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
namespace EOls.UmbracoContentApi
{
public sealed class ContentSerializer
{
private UmbracoHelper _umbraco;
public ContentSerializer(UmbracoHelper umbraco)
{
this._umbraco = umbraco;
}
private static bool KeyStartsWith<T>(KeyValuePair<string, T> pair, string s) => pair.Key.StartsWith(s, StringComparison.InvariantCultureIgnoreCase);
private static bool ShouldHideDocument(IPublishedContent content)
{
// Check if there is any settings for the specific document type
var docTypeSettings = SerializerManager.DocumentSettings.GetValueOrDefault(x => KeyStartsWith(x, content.DocumentTypeAlias));
return docTypeSettings != null && docTypeSettings.Hide;
}
private static bool ShouldHideProperty(IPublishedContent content, IPublishedProperty property)
{
var docTypeSettings = SerializerManager.DocumentSettings.GetValueOrDefault(x => KeyStartsWith(x, content.DocumentTypeAlias));
return docTypeSettings != null && docTypeSettings.HideProperties.Contains(property.PropertyTypeAlias);
}
private Dictionary<string, object> ExtendedContent(IPublishedContent content)
{
IDocumentTypeExtender docExtender = SerializerManager.Extenders.GetValueOrDefault(x => KeyStartsWith(x, content.DocumentTypeAlias));
if (docExtender != null)
return docExtender.Extend(content, this, this._umbraco);
return new Dictionary<string, object>();
}
private object ConvertProperty(IPublishedProperty property, IPublishedContent owner, PublishedContentType contentType)
{
string editorAlias = contentType.GetPropertyType(property.PropertyTypeAlias).PropertyEditorAlias.ToLowerInvariant();
// Property converter exist
if (SerializerManager.PropertyConverters.ContainsKey(editorAlias))
{
return SerializerManager.PropertyConverters[editorAlias].Convert(property, owner, this, this._umbraco);
}
return property.Value;
}
public object Serialize(IPublishedContent content)
{
if (ShouldHideDocument(content))
return null;
return new
{
ContentId = content.Id,
Name = content.Name,
Url = content.Url,
ContentTypeId = content.DocumentTypeId,
ContentTypeAlias = content.DocumentTypeAlias,
Content = ConvertContent(content)
};
}
public Dictionary<string, object> ConvertContent(IPublishedContent content)
{
if (ShouldHideDocument(content))
return null;
// Continue and convert all the properties and Union the extended dictionary
return
content
.Properties
.Where(p => !ShouldHideProperty(content, p))
.OrderBy(p => p.PropertyTypeAlias)
.ToDictionary(
s => s.PropertyTypeAlias,
s => ConvertProperty(s, content, content.ContentType))
.Union(ExtendedContent(content))
.ToDictionary(s => s.Key, s => s.Value);
}
}
}<file_sep>/src/SerializerManager.cs
using EOls.UmbracoContentApi.Attributes;
using EOls.UmbracoContentApi.Interfaces;
using EOls.UmbracoContentApi.Util;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Linq;
namespace EOls.UmbracoContentApi
{
public static class SerializerManager
{
private static Dictionary<string, IApiPropertyConverter> _propertyConverters;
private static Dictionary<string, IDocumentTypeExtender> _extenders;
private static Dictionary<string, DocumentTypeSettingsAttribute> _documentSettings;
private static IContractResolver GetDefaultContractResolver() => new CamelCasePropertyNamesContractResolver();
private static Dictionary<string, T> GetAssemblyClasses<T>() =>
ReflectionHelper.GetAssemblyClassesInheritAttribute<T>()
.Select(x => new KeyValuePair<string, T>(x.Name.ToLowerInvariant(), (T)x.GetCustomAttributes(typeof(T), false).First()))
.ToDictionary(x => x.Key, x => x.Value);
public static IContractResolver ContractResolver { get; set; }
public static Dictionary<string, IApiPropertyConverter> PropertyConverters
{
get { return _propertyConverters = (_propertyConverters == null ? Setup.PropertyConverters.Setup() : _propertyConverters); }
}
public static Dictionary<string, IDocumentTypeExtender> Extenders
{
get { return _extenders = (_extenders == null ? Setup.DocumentTypeExtenders.Setup() : _extenders); }
}
public static Dictionary<string, DocumentTypeSettingsAttribute> DocumentSettings
{
get { return _documentSettings = (_documentSettings == null ? GetAssemblyClasses<DocumentTypeSettingsAttribute>() : _documentSettings); }
}
static SerializerManager()
{
ContractResolver = GetDefaultContractResolver();
_propertyConverters = Setup.PropertyConverters.Setup();
_extenders = Setup.DocumentTypeExtenders.Setup();
_documentSettings = GetAssemblyClasses<DocumentTypeSettingsAttribute>();
}
}
}
<file_sep>/src/PropertyConverters/MediaPicker2Converter.cs
using EOls.UmbracoContentApi.Attributes;
using EOls.UmbracoContentApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Core.Models;
using Umbraco.Web;
namespace EOls.UmbracoContentApi.PropertyConverters
{
[PropertyType(Type = "Umbraco.MediaPicker2")]
public class MediaPicker2Converter : IApiPropertyConverter
{
public object Convert(IPublishedProperty property, IPublishedContent owner, ContentSerializer serializer, UmbracoHelper umbraco)
{
if (!property.HasValue)
return null;
if (property.Value is IPublishedContent)
{
return ((IPublishedContent)property.Value).Url;
}
else if (property.Value is IEnumerable<IPublishedContent>)
{
return ((IEnumerable<IPublishedContent>)property.Value).Select(s => s.Url).ToArray();
}
else
{
return null;
}
}
}
}
<file_sep>/src/Interfaces/IApiPropertyConverter.cs
using Umbraco.Core.Models;
using Umbraco.Web;
namespace EOls.UmbracoContentApi.Interfaces
{
public interface IApiPropertyConverter
{
object Convert(IPublishedProperty property, IPublishedContent owner, ContentSerializer serializer, UmbracoHelper umbraco);
}
}<file_sep>/src/Setup/PropertyConverters.cs
using EOls.UmbracoContentApi.Attributes;
using EOls.UmbracoContentApi.Interfaces;
using EOls.UmbracoContentApi.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace EOls.UmbracoContentApi.Setup
{
public static class PropertyConverters
{
private static IEnumerable<Type> AssemblyPropertyConverters(Func<Assembly, bool> isAssemblies)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(isAssemblies);
return ReflectionHelper.GetAssemblyClassesInheritInterface<IApiPropertyConverter>(assemblies);
}
private static KeyValuePair<string, IApiPropertyConverter> Instantiate(Type converter)
{
var attr = converter.GetCustomAttributes(typeof(PropertyTypeAttribute), false).FirstOrDefault() as PropertyTypeAttribute;
if (attr == null) throw new Exception("Converter needs to have the PropertyTypeAttribute");
return new KeyValuePair<string, IApiPropertyConverter>(attr.Type.ToLowerInvariant(), Activator.CreateInstance(converter) as IApiPropertyConverter);
}
public static Dictionary<string, IApiPropertyConverter> Setup()
{
// EOls.UmbracoContentApi IApiPropertyConverter
IEnumerable<KeyValuePair<string, IApiPropertyConverter>> localAssemblyTypes =
AssemblyPropertyConverters(s => s == typeof(PropertyConverters).Assembly)
.Select(Instantiate).ToArray();
// All namespace IApiPropertyConverter except EOls.UmbracoContentApi
IEnumerable<KeyValuePair<string, IApiPropertyConverter>> assembliesTypes =
AssemblyPropertyConverters(s => s != typeof(PropertyConverters).Assembly)
.Select(Instantiate).ToArray();
Func<KeyValuePair<string, IApiPropertyConverter>, bool> isNotPartOfAssembliesTypes = x => !assembliesTypes.Any(y => y.Key == x.Key);
return
assembliesTypes
.Concat(
localAssemblyTypes.Where(isNotPartOfAssembliesTypes)
).ToDictionary(x => x.Key, x => x.Value);
}
}
}
<file_sep>/src/PropertyConverters/ContentPickerConverter.cs
using EOls.UmbracoContentApi.Attributes;
using EOls.UmbracoContentApi.Interfaces;
using Umbraco.Core.Models;
using Umbraco.Web;
namespace EOls.UmbracoContentApi.PropertyConverters
{
[PropertyType(Type = "Umbraco.ContentPickerAlias")]
public class ContentPickerConverter : IApiPropertyConverter
{
public object Convert(IPublishedProperty property, IPublishedContent owner, ContentSerializer serializer, UmbracoHelper umbraco)
{
if (property.Value is IPublishedContent)
return serializer.Serialize(property.Value as IPublishedContent);
IPublishedContent content = umbraco.TypedContent(property.Value);
if (content == null)
return null;
return serializer.Serialize(content);
}
}
}<file_sep>/src/PropertyConverters/RichTextEditorConverter.cs
using EOls.UmbracoContentApi.Attributes;
using EOls.UmbracoContentApi.Interfaces;
using System.Web;
using Umbraco.Core.Models;
using Umbraco.Web;
namespace EOls.UmbracoContentApi.PropertyConverters
{
[PropertyType(Type = "Umbraco.TinyMCEv3")]
public class RichTextEditorConverter : IApiPropertyConverter
{
public object Convert(IPublishedProperty property, IPublishedContent owner, ContentSerializer serializer, UmbracoHelper umbraco)
{
var htmlString = property.Value as HtmlString;
return htmlString != null ? htmlString.ToHtmlString() : string.Empty;
}
}
}<file_sep>/src/Setup/DocumentTypeExtenders.cs
using EOls.UmbracoContentApi.Interfaces;
using EOls.UmbracoContentApi.Util;
using System;
using System.Collections.Generic;
using System.Linq;
namespace EOls.UmbracoContentApi.Setup
{
public static class DocumentTypeExtenders
{
private static KeyValuePair<string, IDocumentTypeExtender> Initiate(Type type) =>
new KeyValuePair<string, IDocumentTypeExtender>(type.Name.ToLowerInvariant(), Activator.CreateInstance(type) as IDocumentTypeExtender);
public static Dictionary<string, IDocumentTypeExtender> Setup()
{
return
ReflectionHelper.GetAssemblyClassesInheritInterface<IDocumentTypeExtender>()
.Select(Initiate)
.ToDictionary(x => x.Key, x => x.Value);
}
}
}<file_sep>/src/Attributes/DocumentTypeSettingsAttribute.cs
using System;
namespace EOls.UmbracoContentApi.Attributes
{
public class DocumentTypeSettingsAttribute : Attribute
{
public bool Hide { get; set; }
public string[] HideProperties { get; set; }
}
}
|
320ade2dc2f99d0a386fe99d5a68d1cce82d6175
|
[
"Markdown",
"C#"
] | 15 |
C#
|
lillheaton/eols.UmbracoContentApi
|
63345b1b7cbaeb23f836e5435066397e552b0fed
|
4895ad2ff91d932bb13b8fa60007eab6e880596f
|
refs/heads/master
|
<file_sep>package user;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/UserListServlet")
public class UserListServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
UserInfo user = (UserInfo) request.getSession().getAttribute("user");
int type = user.getAuth();
UserDB userBean = new UserDB();
ArrayList<UserInfo> list = new ArrayList<>();
list = userBean.GetUserInfo(type);
ObjectMapper obj = new ObjectMapper();
String str = obj.writeValueAsString(list);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(str);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<file_sep>package room;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/RoomUpdate")
public class RoomUpdate extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int id = Integer.parseInt(request.getParameter("id"));
String code = request.getParameter("code");
String location = request.getParameter("location");
Room room = new Room(id, code, location);
RoomDB roomDB = new RoomDB();
int update = roomDB.update(room);
response.sendRedirect(request.getContextPath()+"/room/room_list.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<file_sep>package grade;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/searchSubGradeServlet")
public class searchSubGradeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int sub=Integer.parseInt(request.getParameter("sub"));
gradeService service=new gradeService();
ArrayList<StudentGrade> ar=service.searchSubGrade(sub);
request.getSession().setAttribute("flag",5);
if(ar!=null){
request.getSession().setAttribute("stuGrades",ar);
response.getWriter().print(true);
}
else{
response.getWriter().print(false);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<file_sep>package grade;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/searchAllServlet")
public class searchAllServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
gradeService service=new gradeService();
ArrayList<StudentGrade> ar=service.searchAll();
request.getSession().setAttribute("gradeList",ar);
response.sendRedirect(request.getContextPath()+"/grade/grade_List.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<file_sep>package teach;
import commom.DBConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class teachDao {
private Connection con =null;
public ArrayList<teachInfo> searchTeacher(int id){
ArrayList<teachInfo> ar=new ArrayList<teachInfo>();
PreparedStatement pStmt=null;
ResultSet rs=null;
try{
con= DBConnection.getConnection();
pStmt=con.prepareStatement("select * from t_teaching where id=?");
pStmt.setInt(1,id);
rs=pStmt.executeQuery();
while(rs.next()){
teachInfo teach=new teachInfo();
teach.setId(rs.getInt("id"));
teach.settName(rs.getString("tName"));
teach.setSubject(rs.getInt("subject"));
ar.add(teach);
}
}catch(Exception e){
e.printStackTrace();
}finally {
DBConnection.closeConnection();
try{
pStmt.close();
rs.close();
}catch(SQLException a){
a.printStackTrace();
}
}
return ar;
}
public ArrayList<teachInfo> searchAll(){
ArrayList<teachInfo> ar=new ArrayList<teachInfo>();
PreparedStatement pStmt=null;
ResultSet rs=null;
try{
con= DBConnection.getConnection();
pStmt=con.prepareStatement("select * from t_teaching");
rs=pStmt.executeQuery();
while(rs.next()){
teachInfo teach=new teachInfo();
teach.setId(rs.getInt("id"));
teach.settName(rs.getString("tName"));
teach.setSubject(rs.getInt("subject"));
ar.add(teach);
}
}catch(Exception e){
e.printStackTrace();
}finally {
DBConnection.closeConnection();
try{
pStmt.close();
rs.close();
}catch(SQLException a){
a.printStackTrace();
}
}
return ar;
}
public ArrayList<teachInfo> searchSub(int subname){
ArrayList<teachInfo> ar=new ArrayList<teachInfo>();
PreparedStatement pStmt=null;
ResultSet rs=null;
try{
con= DBConnection.getConnection();
pStmt=con.prepareStatement("select * from t_teaching where subject=?");
pStmt.setInt(1,subname);
rs=pStmt.executeQuery();
while(rs.next()){
teachInfo teach=new teachInfo();
teach.setId(rs.getInt("id"));
teach.settName(rs.getString("tName"));
teach.setSubject(rs.getInt("subject"));
ar.add(teach);
}
}catch(Exception e){
e.printStackTrace();
}finally {
DBConnection.closeConnection();
try{
pStmt.close();
rs.close();
}catch(SQLException a){
a.printStackTrace();
}
}
return ar;
}
public boolean insertTeaching(teachInfo teach){
PreparedStatement pStmt=null;
try{
con= DBConnection.getConnection();
pStmt=con.prepareStatement("insert into t_teaching values(?,?,?)");
pStmt.setInt(1,teach.getId());
pStmt.setString(2,teach.gettName());
pStmt.setInt(3,teach.getSubject());
int count=pStmt.executeUpdate();
if(count>0){
return true;
}
return false;
}catch(Exception e){
e.printStackTrace();
return false;
}finally {
DBConnection.closeConnection();
try {
pStmt.close();
} catch (SQLException a) {
a.printStackTrace();
}
}
}
public boolean deleteTeaching(int id,int sub){
PreparedStatement pStmt=null;
try{
con= DBConnection.getConnection();
pStmt=con.prepareStatement("delete from t_teaching where id=? and subject=?");
pStmt.setInt(1,id);
pStmt.setInt(2,sub);
int count=pStmt.executeUpdate();
if(count>0){
return true;
}
return false;
}catch(Exception e){
e.printStackTrace();
return false;
}finally {
DBConnection.closeConnection();
try {
pStmt.close();
} catch (SQLException a) {
a.printStackTrace();
}
}
}
public boolean updateTeaching(teachInfo teach,int sub){
PreparedStatement pStmt=null;
try{
con= DBConnection.getConnection();
pStmt=con.prepareStatement("update t_teaching set subject=? where id=? and subject=?");
pStmt.setInt(1,teach.getSubject());
pStmt.setInt(2,teach.getId());
pStmt.setInt(3,sub);
int count=pStmt.executeUpdate();
if(count>0){
return true;
}
return false;
}catch(Exception e){
e.printStackTrace();
return false;
}finally {
DBConnection.closeConnection();
try {
pStmt.close();
} catch (SQLException a) {
a.printStackTrace();
}
}
}
}
<file_sep>package login;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import user.*;
@WebServlet("/MenuInitServlet")
public class MenuInitServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//取出id
int id = Integer.parseInt(request.getParameter("id"));
UserDB userBean = new UserDB();
UserInfo user = userBean.GetUserbyId(id);
int type = user.getAuth();
//处用户管理外的菜单,要改改这个 下面两个是分流用的管理员菜单
String menuList =
"\t{\"main\":\"学生管理\",\"sub\":[\n" +
"\t\t{\"name\":\"专业信息管理\",\"link\":\"waiting.html\"},\n" +
"\t\t{\"name\":\"院系信息管理\",\"link\":\"waiting.html\"},\n" +
"\t\t{\"name\":\"学生信息管理\",\"link\":\"../StudentListAction\"}]},\n" +
"{\"main\":\"教师管理\",\"sub\":[{\"name\":\"教师信息管理\",\"link\":\"../teacher/teacher_list.jsp\"}]},\n" +
"{\"main\":\"教室管理\",\"sub\":[{\"name\":\"教室信息管理\",\"link\":\"../room/room_list.jsp\"}]},"+
"\t{\"main\":\"课程管理\",\"sub\":[{\"name\":\"课程信息管理\",\"link\":\"../CourseListAction\"}]},\n" +
"\t{\"main\":\"成绩管理\",\"sub\":[\n" +
"\t\t{\"name\":\"学生成绩查询\",\"link\":\"../grade/searchStuGrade.jsp\"},\n" +
"\t\t{\"name\":\"课程成绩查询\",\"link\":\"../grade/searchSubGrade.jsp\"},\n" +
"\t\t{\"name\":\"成绩列表\",\"link\":\"../searchAllServlet\"}]},\n" +
"\t{\"main\":\"授课信息管理\",\"sub\":[\n" +
"\t\t{\"name\":\"授课教师查询\",\"link\":\"../teach/searchTeach.jsp\"},\n" +
"\t\t{\"name\":\"教师授课查询\",\"link\":\"../teach/searchSub.jsp\"},\n" +
"\t\t{\"name\":\"授课信息列表\",\"link\":\"../searchAlltServlet\"}]}\n" +
"]";
String P_menuList = "{\"main\":\"用户信息管理\",\"sub\":[{\"name\":\"个人信息管理\",\"link\":\"../user/userInfo_edit.jsp?status=1\"}]},";
String A_menuList = "{\"main\":\"用户信息管理\",\"sub\":[\n" +
"\t\t{\"name\":\"个人信息管理\",\"link\":\"../user/userInfo_edit.jsp?status=1\"},\n" +
"\t\t{\"name\":\"普通用户信息管理\",\"link\":\"../user/user_list.jsp\"}]},";
String S_menuList = "{\"main\":\"用户信息管理\",\"sub\":[\n" +
"\t\t{\"name\":\"个人信息管理\",\"link\":\"../user/userInfo_edit.jsp?status=1\"},\n" +
"\t\t{\"name\":\"用户信息管理\",\"link\":\"../user/user_list.jsp\"},\n" +
"\t\t{\"name\":\"管理员设置\",\"link\":\"../user/user_auth.jsp\"}]},";
if(type == 2){
menuList = "[ \n" + P_menuList + menuList;
}else if(type == 1){
menuList = "[ \n" + A_menuList + menuList;
}else if(type == 0){
menuList = "[ \n" + S_menuList + menuList;
}
ObjectMapper obj = new ObjectMapper();
String list = obj.writeValueAsString(menuList);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(list);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<file_sep>package course;
import commom.MyTools;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/CourseUpdateAction")
public class CourseUpdateAction extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、获取客户端提交数据
request.setCharacterEncoding("UTF-8");
CourseInfo course=new CourseInfo();
//TODO 1 获取新课程的其他信息并保存到course中
course.setCourseID(MyTools.strToint(request.getParameter("courseid")));
course.setType(MyTools.strToint(request.getParameter("type")));
course.setCredit(MyTools.strToFloat(request.getParameter("credit")));
course.setGrade(MyTools.strToint(request.getParameter("grade")));
course.setMajor(MyTools.strToint(request.getParameter("major")));
course.setDetail(MyTools.toChinese(request.getParameter("detail")));
//2、处理客户端提交数据
//TODO 2 调用CourseDB插入新对象的方法实现新课程的添加
CourseDB beanDB = new CourseDB();
beanDB.update(course);
//3、向客户端做出响应
//TODO 3 重定向到查询显示课程信息列表的servlet
response.setCharacterEncoding("UTF-8");
response.sendRedirect(request.getContextPath()+"/CourseListAction");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<file_sep>package student;
import commom.DBConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StudentDB {
private Connection connection = null;
public List<StudentInfo> findAll(){
List<StudentInfo> list = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DBConnection.getConnection();
statement = connection.prepareStatement("select * from t_student");
resultSet = statement.executeQuery();
list = new ArrayList<StudentInfo>();
while (resultSet.next()){
StudentInfo stduent = new StudentInfo();
stduent.setId(resultSet.getInt(1));
stduent.setCode(resultSet.getString(2));
stduent.setName(resultSet.getString(3));
stduent.setSex(resultSet.getInt(4));
stduent.setGrade(resultSet.getInt(5));
stduent.setMajor(resultSet.getInt(6));
stduent.setDetail(resultSet.getString(7));
list.add(stduent);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnection.closeConnection();
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return list;
}
public int insert(StudentInfo studentInfo){
PreparedStatement statement = null;
int count = 0;
try {
connection = DBConnection.getConnection();
statement = connection.prepareStatement("insert into t_student values (null,?,?,?,?,?,?)");
statement.setString(1,studentInfo.getCode());
statement.setString(2,studentInfo.getName());
statement.setInt(3,studentInfo.getSex());
statement.setInt(4,studentInfo.getGrade());
statement.setInt(5,studentInfo.getMajor());
statement.setString(6,studentInfo.getDetail());
count = statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnection.closeConnection();
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return count;
}
public int update(StudentInfo studentInfo){
PreparedStatement statement = null;
int count = 0;
try {
connection = DBConnection.getConnection();
statement = connection.prepareStatement("update t_student set VC_STUDENT_CODE = ?,N_SEX = ?," +
"N_GRADE =?,N_MAJOR = ?,VC_DETAIL = ?,VC_STUDENT_NAME =? where N_STUDENT_ID = ?");
statement.setString(1,studentInfo.getCode());
statement.setInt(2,studentInfo.getSex());
statement.setInt(3,studentInfo.getGrade());
statement.setInt(4,studentInfo.getMajor());
statement.setString(5,studentInfo.getDetail());
statement.setString(6,studentInfo.getName());
statement.setInt(7,studentInfo.getId());
count = statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnection.closeConnection();
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return count;
}
public int delete(String code) {
PreparedStatement statement = null;
int count = 0;
try {
connection = DBConnection.getConnection();
statement = connection.prepareStatement("delete from t_student where VC_STUDENT_CODE = ?");
statement.setString(1,code);
count = statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnection.closeConnection();
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return count;
}
public StudentInfo findOne(String code){
PreparedStatement statement = null;
ResultSet resultSet = null;
StudentInfo info = new StudentInfo();
try {
connection = DBConnection.getConnection();
statement = connection.prepareStatement("select * from t_student where VC_STUDENT_CODE = ?");
statement.setString(1,code);
resultSet = statement.executeQuery();
while (resultSet.next()){
info.setId(resultSet.getInt(1));
info.setCode(resultSet.getString(2));
info.setName(resultSet.getString(3));
info.setSex(resultSet.getInt(4));
info.setGrade(resultSet.getInt(5));
info.setMajor(resultSet.getInt(6));
info.setDetail(resultSet.getString(7));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBConnection.closeConnection();
try {
resultSet.close();
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return info;
}
}
<file_sep>package teach;
import teach.teachService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/searchAlltServlet")
public class searchAlltServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
teachService service=new teachService();
ArrayList<teachInfo> ar=service.searchAll();
request.getSession().setAttribute("teachAllList",ar);
response.sendRedirect(request.getContextPath()+"/teach/teach_List.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<file_sep># web课程实践
教学管理
<file_sep>package login;
import com.fasterxml.jackson.databind.ObjectMapper;
import user.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("userName");
String pwd = request.getParameter("pwd");
String result = null;
//System.out.println(name);
//System.out.println(pwd);
UserDB userBean = new UserDB();
UserInfo user = userBean.GetUserbyName(name);
ObjectMapper obj = new ObjectMapper();
if (user == null) {
result="1";
result= obj.writeValueAsString(result);
}else if(!user.getUserPwd().equals(pwd)){
result="2";
result= obj.writeValueAsString(result);
}else{
request.getSession().setAttribute("user",user);
result=obj.writeValueAsString(user);
}
//System.out.println("result:"+result);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(result);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<file_sep>package student;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/StudentGetOne")
public class StudentGetOne extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String code = request.getParameter("code");
StudentDB db = new StudentDB();
StudentInfo info = db.findOne(code);
request.getSession().setAttribute("student",info);
response.sendRedirect(request.getContextPath()+"/student/student_edit.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<file_sep>package course;
import commom.MyTools;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/CourseDeleteAction")
public class CourseDeleteAction extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CourseDB beanDB = new CourseDB();
beanDB.delete(MyTools.strToint(request.getParameter("CourseID")));
response.sendRedirect(request.getContextPath()+"/CourseListAction");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<file_sep>package room;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/RoomDelete")
public class RoomDelete extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int id = Integer.parseInt(request.getParameter("id"));
RoomDB db = new RoomDB();
int delete = db.delete(id);
response.sendRedirect(request.getContextPath()+"/room/room_list.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<file_sep>package teacher;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/TeacherList")
public class TeacherList extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TeacherDB db = new TeacherDB();
List<Teacher> list = db.findAll();
ObjectMapper objectMapper = new ObjectMapper();
String string = objectMapper.writeValueAsString(list);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(string);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<file_sep>package student;
import java.io.Serializable;
public class StudentInfo implements Serializable {
private Integer id;
private String code;
private String name;
private Integer sex;
private Integer grade;
private Integer major;
private String detail;
@Override
public String toString() {
return "StudentInfo{" +
"id=" + id +
", code='" + code + '\'' +
", name='" + name + '\'' +
", sex=" + sex +
", grade=" + grade +
", major=" + major +
", detail='" + detail + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Integer getMajor() {
return major;
}
public void setMajor(Integer major) {
this.major = major;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
<file_sep>package teach;
import grade.StudentGrade;
import grade.gradeService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
@WebServlet("/updatetServlet")
public class updatetServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String[] subjects={"Java程序设计","数据库原理","数据结构","Web程序设计"};
int id= Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("tName");
int sub=Integer.parseInt(request.getParameter("subject"));
int qsub=(int)request.getSession().getAttribute("qsub");
request.getSession().removeAttribute("qsub");
teachInfo teach=new teachInfo(id,name,sub);
teachService service=new teachService();
request.getSession().setAttribute("flag",4);
if(service.updateTeaching(teach,qsub)){
response.sendRedirect("grade/resSuccessShow.jsp");
}
else{
response.sendRedirect("grade/resFailShow.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<file_sep>package teacher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/TeacherUpdate")
public class TeacherUpdate extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int id = Integer.parseInt(request.getParameter("id"));
System.out.println("????");
System.out.println("id="+id);
String code = request.getParameter("code");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
String title = request.getParameter("title");
Teacher teacher = new Teacher(id,code,name,sex,age,title);
TeacherDB db = new TeacherDB();
int update = db.update(teacher);
response.sendRedirect(request.getContextPath()+"/teacher/teacher_list.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
|
7c4fe31909ef9baaa57812af831b2f3f2c362531
|
[
"Markdown",
"Java"
] | 18 |
Java
|
zhongguodiyi/hmp
|
4c1020a821fac416dcecc2e14e6841580d96fa13
|
5977d225a812d4047bdc61d76527d03f0db959dd
|
refs/heads/master
|
<file_sep>'use-strict';
const package = require('./package.json');
// purposeful destructuring to remove first two elements
const [, , ...flags] = process.argv;
module.exports = (() => {
const flagObject = flags.reduce((prev, current, index) => {
if (/^-h/.test(current) || /^--help/.test(current)) {
return {...prev, help: true};
}
if (/^-v/.test(current) || /^--version/.test(current)) {
return {...prev, version: true};
}
if (/^-(.?)$/.test(current)) {
return {...prev, [/^-(.?)/.exec(current)[1]]: flags[index + 1]};
}
if (/^-{2}(.+)/.test(current)) {
return {...prev, [/^-{2}(.*)/.exec(current)[1]]: flags[index + 1]};
}
if (/^https?\:\/\//.test(current)) {
return {...prev, baseUrl: current};
}
return {...prev};
}, {});
if (flagObject.version) {
console.log(package.version);
process.exit(0);
}
if (flagObject.help) {
console.log(`
nodeBuster [options] <baseUrl>
-w, --wordlist specifies the wordlist file
-o, --output specifies the output file
`);
process.exit(0);
}
return flagObject;
})();
<file_sep># PyBuster
PyBuster is a python implementation of a CLI web server directory enumerator, with features modeled on dirBuster. Current version is non-functional skeleton. Currently tested on python 3.7 with plans for general python 3.x support.
## Virtual Environment Setup
To create an anaconda environment on macOS exactly duplicating the development environment of PyBuster, use
```shell
conda create --name <env> --file requirements.txt
```
For other systems, instead use
```shell
conda env create --name <env> --file requirements.yml
```<file_sep># Contributors
- [<NAME>](https://github.com/randy5235/)
- [<NAME>](https://github.com/anaaktge/)
- [<NAME>](https://github.com/MissManaphy)
- [<NAME>](https://github.com/kaelynflow)
- [<NAME>](https://github.com/joshgesler/)
- [<NAME>](https://github.com/CaptainNemo7)
- [<NAME>](https://github.com/BadGoatDreams)
- [<NAME>](https://github.com/NicoN00b)
- [<NAME>](https://github.com/jwiedeman)
<file_sep># build2learn
Welcome to the build2learn repository.
The github page for this can be found [here](https://randy5235.github.io/build2learn)
The purpose of this repository is to provide a resource for documentation and source code for the build2learn session(s) at [Pascal PDX](https://www.pascalpdx.org/).
The general idea of these sessions is to take several categories of tools, analyze their functionality, and re-implement them using _your_ language of choice.
The goal is not to present a tutorial. The goal is to have discussion around the the process of breaking the problem down into specific use cases and requirements. Tasks that can be more easily implemented.
The core goal of programming is problem solving, the aim here is to facilitate and encourage this skill.
There will be a focus on performing code review and encouraging peoples to demo their progress to the group.
### Session_0
The purpose of Session_0:
* Help individuals setup their development environment
* Make sure that the git workflow is well understood
* Help with a language selection
While there will not be any _prescribed_ languages,we suggest either python or javascript. This is not to deter the use of other languages. Just to suggest that there may be more help available using something listed above.
- Help users install [git](https://git-scm.com/downloads) for their operating system
- Help users create a github account and setup git to use it
- Help users decide which language they will use
- Help users install language and tooling (if needed)
- Help users install text editor and discuss the merits of different options
### Meetup
The goal is to meet once every two weeks were we will discuss and demo our progress, Ask for assistance and help each other.
### Contributing
Contributing is done by utilizing the standard [fork and pull request workflow](https://reflectoring.io/github-fork-and-pull/). Also please add your name to the [contributors.md](./contributors.md) file.
<file_sep>#!/usr/bin/env node
'use strict';
const {promisify} = require('util');
const fs = require('fs');
const readFileAsync = promisify(fs.readFile);
const optionsObject = require('./options');
async function getWordListStream(parsedOptions) {
const {wordList} = parsedOptions;
return await readFileAsync(wordList, {encoding: 'utf8'});
}
async function optionsParser(optionsObject) {
return await {
wordList: optionsObject.wordlist || optionsObject.w,
outputFile: optionsObject.output || optionsObject.o
};
}
optionsParser(optionsObject)
.then(getWordListStream)
.then(output => console.log(output));
<file_sep>#trying to make dirbuster but for python I guesss?
import os
import click
import requests
#from http import HTTPStatus
#basic use: python3 busssted.py (flags) http://www.url.com/
@click.command()
@click.option('-f', '--file', default="small.txt", help="Filepath of wordlist you want to use")
@click.option('-r', '--recursive', is_flag=True, help="Will have program search through directories recursively")
@click.option('-w', '--write', default="busssted.txt", help = "Saves output under a specified filename")
@click.option('-v', '--verbose', is_flag=True, help = "Will output the response code of every url it checks, not just ones with a 200")
#<EMAIL>('args')
#imma be honest, I can't figure out why it's not parsing the inputs or recogninzing defined variables so i'm just gonna leave this here for now
#hey, does anyone know if it's possible to thread recursive processes so it can finish the first layer check without getting hung up in the middle?
def urlCheck(url, file):
with open(file) as keywords:
for keyword in enumerate(keywords):
test = url + keyword + "/"
if (verbose): #verbose prints everything
#write full URL to file + requests.get(test).status_code
print(test + " Code: " + requests.get(test).status_code)
if (recursive and (requests.get(test).status_code == 200)): #if you want it to be recursive and it gets a 200, go deeper
urlCheck(test, file)
elif (requests.get(test).status_code == 200): #if it ain't verbose, just return the "200" responses
#write full URL to file + requests.get(test).status_code
print(test + " Code: " + requests.get(test).status_code)
if (recursive): #if you wanted it to be rescusive, go deeper
urlCheck(test, file)
def main(url, file):
urlCheck(url, file)
#maybe something else
if __name__ == '__main__':
main(url, file)
<file_sep># This file may be used to create an environment using:
# $ conda create --name <env> --file <this file>
# platform: osx-64
@EXPLICIT
https://repo.anaconda.com/pkgs/main/osx-64/ca-certificates-2019.1.23-0.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/libcxxabi-4.0.1-hcfea43d_1.tar.bz2
https://repo.continuum.io/pkgs/main/osx-64/xz-5.2.4-h1de35cc_4.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/zlib-1.2.11-h1de35cc_3.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/libcxx-4.0.1-hcfea43d_1.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/openssl-1.1.1a-h1de35cc_0.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/tk-8.6.8-ha441bb4_0.tar.bz2
https://repo.continuum.io/pkgs/main/osx-64/libffi-3.2.1-h475c297_4.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/ncurses-6.1-h0a44026_1.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/libedit-3.1.20181209-hb402a30_0.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/readline-7.0-h1de35cc_5.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/sqlite-3.26.0-ha441bb4_0.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/python-3.7.2-haf84260_0.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/certifi-2018.11.29-py37_0.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/setuptools-40.8.0-py37_0.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/wheel-0.32.3-py37_0.tar.bz2
https://repo.anaconda.com/pkgs/main/osx-64/pip-19.0.1-py37_0.tar.bz2
<file_sep># nodeBuster
```shell
nodeBuster [options] <baseUrl>
-w, --wordlist specifies the wordlist file
-o, --output specifies the output file
```
Command line tool to help enumerate a web server
eg.
```shell
nodeBuster -w dir/file.txt http://example.com
```
## Requirements:
- Node 10.x or higher
- NPM 6.x
To install and use nodeBuster, navigate to the nodeBuster folder and run:
```shell
npm install -g
```
This will install the nodeBuster bin alias into your path variable
|
59af13be0d0761718e0e0fc0d14832461ee136e3
|
[
"JavaScript",
"Python",
"Text",
"Markdown"
] | 8 |
JavaScript
|
randy5235/build2learn
|
276a469782724475acb07f5c5673683d983c2b48
|
774f10f37f9453a5ba362d200623832f65eb834f
|
refs/heads/master
|
<file_sep>// constant
const STAR_LIST = 'STAR_LIST'
const INIT_STARRED_LIST = 'INIT_STRRED_LIST'
// action creator
const initStarredListAct = allList => ({
type: INIT_STARRED_LIST,
payload: allList,
})
const starListAct = list => ({
type: STAR_LIST,
payload: list,
})
// initial State
const initState = {
items: [],
}
// reducer
export function starredlist(state = initState, action) {
switch (action.type) {
case INIT_STARRED_LIST:
return {
...state,
items: [...state.items, ...action.payload],
}
case STAR_LIST:
return {
...state,
items: [...state.items, action.payload],
}
default:
return {
...state,
}
}
}
// login operation
// 初始化本地数据操作
export function initStarredList() {
return (dispatch) => {
const allStarredList =
JSON.parse(localStorage.getItem('allStarredList')) || []
dispatch(initStarredListAct(allStarredList))
}
}
// 收藏歌单操作
export function star(item) {
// 先处理本地存储
let allStarredList = JSON.parse(localStorage.getItem('allStarredList'))
if (!allStarredList) {
allStarredList = []
}
allStarredList.push(item)
localStorage.setItem('allStarredList', JSON.stringify(allStarredList))
// 再处理redux
return (dispatch) => {
dispatch(starListAct(item))
}
}
|
40a3d3f3814bbc8c41067c77c0abae2295681581
|
[
"JavaScript"
] | 1 |
JavaScript
|
zcgong/music-react
|
7238e00c3812357d1f86de527f47dffcd7ab361b
|
b9d17ade25cfa11e11f2764146ffe21a759416f8
|
refs/heads/master
|
<file_sep>const OBSTACLE_HEIGHT = 60;
const OBSTACLE_WIDTH = 52;
const OBSTACLE_SPEED = 8;
class Obstacle {
constructor(gameArea, image, speed) {
this.gameArea = gameArea;
this.image = image;
this.frameWidth = OBSTACLE_WIDTH;
this.frameHeight = OBSTACLE_HEIGHT;
this.endFrame = 4;
this.frameSpeed = OBSTACLE_SPEED;
this.framesPerRow = Math.floor(this.image.width / this.frameWidth);
this.currentFrame = 0;
this.counter = 0;
this.x = 600;
this.y = 230;
this.speed = speed;
}
updateSpeed(newSpeed) {
this.speed = newSpeed;
}
update() {
// update to the next frame if it is time
if (this.counter == (this.frameSpeed - 1)) {
this.currentFrame = (this.currentFrame + 1) % this.endFrame;
}
// update the counter
this.counter = (this.counter + 1) % this.frameSpeed;
};
draw() {
if (this.x < -this.image.width) return;
// Pan background
this.x -= this.speed;
const row = Math.floor(this.currentFrame / this.framesPerRow);
const col = Math.floor(this.currentFrame % this.framesPerRow);
this.gameArea.context.drawImage(
this.image,
col * this.frameWidth, row * this.frameHeight,
this.frameWidth, this.frameHeight,
this.x, this.y,
this.frameWidth, this.frameHeight);
}
}
module.exports = Obstacle;
<file_sep>const RUNNER_HEIGHT = 72;
const RUNNER_WIDTH = 40;
const RUNNER_SPEED = 8;
const JUMP_TIME = 130;
class Runner {
constructor(gameArea, image, level) {
this.gameArea = gameArea;
this.level = level;
this.image = image;
this.frameWidth = RUNNER_WIDTH;
this.frameHeight = RUNNER_HEIGHT;
this.endFrame = 3;
this.frameSpeed = RUNNER_SPEED;
this.framesPerRow = Math.floor(this.image.width / this.frameWidth);
this.currentFrame = 0;
this.counter = 0;
this.jumpCounter = JUMP_TIME;
this.jumpTime = JUMP_TIME;
this.dy = 0;
this.isFalling = false;
this.isJumping = false;
this.isCrashed = false;
this.x = 60;
this.y = 220;
this.increaseLevel = false;
const self = this;
const canvasElement = document.querySelector('#minigame');
window.addEventListener('keydown', function(e) {
if (e.keyCode === 32 && !self.isFalling) {
self.isJumping = true;
}
});
canvasElement.addEventListener('mousedown', function(e) {
if(!self.isFalling) {
self.isJumping = true;
}
});
canvasElement.addEventListener('touchstart', function(e) {
if(!self.isFalling) {
self.isJumping = true;
}
});
}
_updateLevel() {
this.jumpTime = JUMP_TIME - this.level * 10;
this.jumpCounter = this.jumpTime;
}
_calculateHeightChange(time) {
let oldHeight = - 450 * Math.pow((time/this.jumpTime - 0.5), 2);
let newHeight = - 450 * Math.pow(((time + 1)/this.jumpTime - 0.5), 2);
return newHeight - oldHeight;
}
_jump() {
if (this.isJumping) {
this.dy -= this._calculateHeightChange(this.jumpTime - this.jumpCounter);
this.jumpCounter--;
}
if (this.isFalling) {
this.dy -= this._calculateHeightChange(this.jumpTime - this.jumpCounter);
this.jumpCounter--;
}
if (this.jumpCounter === this.jumpTime / 2) {
this.isJumping = false;
this.isFalling = true;
}
if (this.jumpCounter === 0) {
this.isFalling = false;
this.jumpCounter = this.jumpTime;
}
}
_runningAnim(col, row, frameWidth, frameHeight, x, y) {
this.gameArea.context.drawImage(
this.image,
col * frameWidth, row * frameHeight,
frameWidth, frameHeight,
x, y + this.dy,
frameWidth, frameHeight);
}
_jumpingAnim(col, row, frameWidth, frameHeight, x, y) {
this.gameArea.context.drawImage(
this.image,
frameWidth, 0,
frameWidth, frameHeight,
x, y + this.dy,
frameWidth, frameHeight);
}
_crashAnim(col, row, frameWidth, frameHeight, x, y) {
this.gameArea.context.drawImage(
this.image,
frameWidth * 3, 0,
frameWidth, frameHeight,
x, y + this.dy,
frameWidth, frameHeight);
}
nextLevel(level) {
this.level = level;
this.increaseLevel = true;
}
crash() {
this.isCrashed = true;
}
update() {
// update to the next frame if it is time
if (this.counter == (this.frameSpeed - 1)) {
this.currentFrame = (this.currentFrame + 1) % this.endFrame;
}
// update the counter
this.counter = (this.counter + 1) % this.frameSpeed;
}
reset() {
this.isCrashed = false;
this.isJumping = false;
this.isFalling = false;
this.level = 0;
this.dy = 0;
this.currentFrame = 0;
this.counter = 0;
this.jumpTime = JUMP_TIME - this.level * 15;
this.jumpCounter = this.jumpTime;
}
draw() {
// get the row and col of the frame
const row = Math.floor(this.currentFrame / this.framesPerRow);
const col = Math.floor(this.currentFrame % this.framesPerRow);
this._jump();
if (this.isCrashed) {
this._crashAnim(col, row, this.frameWidth, this.frameHeight, this.x, this.y)
} else if (this.isJumping || this.isFalling) {
this._jumpingAnim(col, row, this.frameWidth, this.frameHeight, this.x, this.y);
} else {
if (this.increaseLevel) {
this._updateLevel();
this.increaseLevel = false;
}
this._runningAnim(col, row, this.frameWidth, this.frameHeight, this.x, this.y);
}
}
}
module.exports = Runner;
<file_sep>(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.MiniGame = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Background = function () {
function Background(gameArea, image, speed, x, y) {
_classCallCheck(this, Background);
this.gameArea = gameArea;
this.x = x;
this.y = y;
this.image = image;
this.speed = speed;
}
_createClass(Background, [{
key: "updateSpeed",
value: function updateSpeed(newSpeed) {
this.speed = newSpeed;
}
}, {
key: "draw",
value: function draw() {
// Pan background
this.x -= this.speed;
this.gameArea.context.drawImage(this.image, this.x, this.y);
this.gameArea.context.drawImage(this.image, this.x + this.image.width, this.y);
// If the image scrolled off the screen, reset
if (Math.abs(this.x) >= this.image.width) this.x = 0;
}
}]);
return Background;
}();
module.exports = Background;
},{}],2:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _background = require('./background');
var _background2 = _interopRequireDefault(_background);
var _obstacle = require('./obstacle');
var _obstacle2 = _interopRequireDefault(_obstacle);
var _runner = require('./runner');
var _runner2 = _interopRequireDefault(_runner);
var _score = require('./score');
var _score2 = _interopRequireDefault(_score);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var GROUND_SPEED = 2;
var MiniGame = function () {
function MiniGame() {
_classCallCheck(this, MiniGame);
var _this = this;
this.gameArea = {
canvas: document.getElementById('minigame'),
start: function start() {
_this._setCanvasWidth('initial');
this.context = this.canvas.getContext('2d');
this.frameNo = 0;
this.canvas.classList.add('minigame--started');
},
stop: function stop() {
window.cancelAnimationFrame(_this.myReq);
}
};
this.totalAssets = 0;
this.loadedAssets = 0;
this.splashScreen = false;
this.initalStart = true;
this.myReq = null;
this.level = 0;
this.isCrashed = false;
this.images = {};
this.ground = null;
this.clouds = null;
this.skyline = null;
this.runner = null;
this.score = null;
this.obstaclesArray = new Array();
this.referenceSpeed = GROUND_SPEED;
this._preloader();
}
_createClass(MiniGame, [{
key: '_setCanvasWidth',
value: function _setCanvasWidth(type) {
var clientWidth = document.getElementsByClassName('minigame-container')[0].clientWidth;
var maxWidth = 600;
var newCanvasWidth = clientWidth < maxWidth ? clientWidth : maxWidth;
this.gameArea.canvas.width = newCanvasWidth;
this.gameArea.x = newCanvasWidth;
this.gameArea.canvas.height = 300;
this.gameArea.y = 300;
if (type === 'resize') {
this.score.onResize(newCanvasWidth);
}
}
}, {
key: '_debounce',
value: function _debounce(func, wait, immediate) {
var timeout = void 0;
return function () {
var context = this;
var args = arguments;
var later = function later() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
}, {
key: '_assetLoaded',
value: function _assetLoaded() {
var _this2 = this;
this.loadedAssets++;
this.splashScreen = true;
if (this.loadedAssets === this.totalAssets) {
window.addEventListener('keydown', function (e) {
if (e.keyCode == 32) {
e.preventDefault();
_this2._hideSplashscreen();
}
});
var canvasElement = document.querySelector('#minigame');
canvasElement.addEventListener('touchstart', function () {
_this2._hideSplashscreen();
});
canvasElement.addEventListener('mousedown', function () {
_this2._hideSplashscreen();
});
}
}
}, {
key: '_hideSplashscreen',
value: function _hideSplashscreen() {
if (this.splashScreen === true) {
this.splashScreen = false;
document.getElementById('minigame').style.display = 'block';
this._startGame();
}
}
}, {
key: '_preloader',
value: function _preloader() {
var _this3 = this;
// set image list
var urls = {
'ground': 'https://amp.sportscheck.com/i/sportscheck/minigame_ground',
'clouds': 'https://amp.sportscheck.com/i/sportscheck/minigame_clouds',
'skyline': 'https://amp.sportscheck.com/i/sportscheck/minigame_skyline',
'runner': 'https://amp.sportscheck.com/i/sportscheck/minigame_runner_sprite',
'fire': 'https://amp.sportscheck.com/i/sportscheck/minigame_fire_sprite'
};
this.totalAssets = Object.keys(urls).length;
// start preloading
Object.keys(urls).forEach(function (key) {
_this3.images[key] = new Image();
_this3.images[key].onload = function () {
this._assetLoaded();
}.bind(_this3);
_this3.images[key].src = urls[key];
});
}
}, {
key: '_crash',
value: function _crash(runner, obstacle) {
var runnerLeft = runner.x;
var runnerRight = runner.x + runner.frameWidth;
var runnerTop = runner.y;
var runnerBottom = runner.y + runner.dy + runner.frameHeight;
var obstacleLeft = obstacle.x;
var obstacleRight = obstacle.x + obstacle.frameWidth;
var obstacleTop = obstacle.y;
var obstacleBottom = obstacle.y + obstacle.frameHeight;
if (runnerRight < obstacleLeft || runnerLeft > obstacleRight || runnerBottom < obstacleTop) {
return;
}
this.isCrashed = true;
}
}, {
key: '_animate',
value: function _animate() {
var _this4 = this;
this.myReq = window.requestAnimationFrame(this._animate.bind(this));
this.gameArea.context.clearRect(0, 0, this.gameArea.canvas.width, this.gameArea.canvas.height);
this.obstaclesArray.forEach(function (obstacle) {
_this4._crash(_this4.runner, obstacle);
});
this.skyline.draw();
this.clouds.draw();
this.ground.draw();
if (this.isCrashed) {
this.runner.crash();
}
this.runner.update();
this.runner.draw();
this._createObstacles();
this.obstaclesArray.forEach(function (obstacle) {
obstacle.update();
obstacle.draw();
var obstacleNo = _this4.obstaclesArray.length;
if (obstacleNo > 6) {
var i = 0;
while (i < obstacleNo - 2) {
i++;
_this4.obstaclesArray.shift();
}
}
});
this.score.update();
if (this.isCrashed) {
this.runner.reset();
this.ground.updateSpeed(GROUND_SPEED);
this.referenceSpeed = GROUND_SPEED;
this.score.done();
this.gameArea.stop();
this.splashScreen = true;
}
this.gameArea.frameNo++;
if (this.gameArea.frameNo % 500 === 0) {
this._nextLevel();
}
}
}, {
key: '_createObstacles',
value: function _createObstacles() {
if (this.gameArea.frameNo == 1 || this.gameArea.frameNo / (130 - this.level * 5) % 1 == 0) {
var randomFactor = Math.floor(Math.random() * (100 - 1) + 1);
if (randomFactor % 2 === 0) {
this.obstaclesArray.push(new _obstacle2.default(this.gameArea, this.images.fire, this.referenceSpeed, 600 + randomFactor));
}
}
}
}, {
key: '_updateObstaclesSpeed',
value: function _updateObstaclesSpeed(obstacles, newSpeed) {
for (var i = 0; i < obstacles.length; i++) {
obstacles[i].updateSpeed(newSpeed);
}
}
}, {
key: '_nextLevel',
value: function _nextLevel() {
this.level += 1;
this.referenceSpeed = GROUND_SPEED + this.level / 2;
this.runner.nextLevel(this.level);
this.ground.updateSpeed(this.referenceSpeed);
this._updateObstaclesSpeed(this.obstaclesArray, this.referenceSpeed);
}
}, {
key: '_startGame',
value: function _startGame() {
if (this.initalStart) {
this.initalStart = false;
this.gameArea.start();
this.skyline = new _background2.default(this.gameArea, this.images.skyline, 0.3, 0, 40);
this.clouds = new _background2.default(this.gameArea, this.images.clouds, 0.6, 0, 40);
this.ground = new _background2.default(this.gameArea, this.images.ground, GROUND_SPEED, 0, 280);
this.runner = new _runner2.default(this.gameArea, this.images.runner, this.level);
this.score = new _score2.default(this.gameArea);
} else {
this.gameArea.frameNo = 0;
this.obstaclesArray = [];
this.isCrashed = false;
this.level = 0;
this.runner.reset();
}
var myEfficientFn = this._debounce(function () {
this._setCanvasWidth('resize');
window.cancelAnimationFrame(this.myReq);
this._animate();
}.bind(this), 250);
window.addEventListener('resize', myEfficientFn);
this._animate();
}
}]);
return MiniGame;
}();
module.exports = MiniGame;
},{"./background":1,"./obstacle":3,"./runner":4,"./score":5}],3:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var OBSTACLE_HEIGHT = 60;
var OBSTACLE_WIDTH = 52;
var OBSTACLE_SPEED = 8;
var Obstacle = function () {
function Obstacle(gameArea, image, speed) {
_classCallCheck(this, Obstacle);
this.gameArea = gameArea;
this.image = image;
this.frameWidth = OBSTACLE_WIDTH;
this.frameHeight = OBSTACLE_HEIGHT;
this.endFrame = 4;
this.frameSpeed = OBSTACLE_SPEED;
this.framesPerRow = Math.floor(this.image.width / this.frameWidth);
this.currentFrame = 0;
this.counter = 0;
this.x = 600;
this.y = 230;
this.speed = speed;
}
_createClass(Obstacle, [{
key: "updateSpeed",
value: function updateSpeed(newSpeed) {
this.speed = newSpeed;
}
}, {
key: "update",
value: function update() {
// update to the next frame if it is time
if (this.counter == this.frameSpeed - 1) {
this.currentFrame = (this.currentFrame + 1) % this.endFrame;
}
// update the counter
this.counter = (this.counter + 1) % this.frameSpeed;
}
}, {
key: "draw",
value: function draw() {
if (this.x < -this.image.width) return;
// Pan background
this.x -= this.speed;
var row = Math.floor(this.currentFrame / this.framesPerRow);
var col = Math.floor(this.currentFrame % this.framesPerRow);
this.gameArea.context.drawImage(this.image, col * this.frameWidth, row * this.frameHeight, this.frameWidth, this.frameHeight, this.x, this.y, this.frameWidth, this.frameHeight);
}
}]);
return Obstacle;
}();
module.exports = Obstacle;
},{}],4:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var RUNNER_HEIGHT = 72;
var RUNNER_WIDTH = 40;
var RUNNER_SPEED = 8;
var JUMP_TIME = 130;
var Runner = function () {
function Runner(gameArea, image, level) {
_classCallCheck(this, Runner);
this.gameArea = gameArea;
this.level = level;
this.image = image;
this.frameWidth = RUNNER_WIDTH;
this.frameHeight = RUNNER_HEIGHT;
this.endFrame = 3;
this.frameSpeed = RUNNER_SPEED;
this.framesPerRow = Math.floor(this.image.width / this.frameWidth);
this.currentFrame = 0;
this.counter = 0;
this.jumpCounter = JUMP_TIME;
this.jumpTime = JUMP_TIME;
this.dy = 0;
this.isFalling = false;
this.isJumping = false;
this.isCrashed = false;
this.x = 60;
this.y = 220;
this.increaseLevel = false;
var self = this;
var canvasElement = document.querySelector('#minigame');
window.addEventListener('keydown', function (e) {
if (e.keyCode === 32 && !self.isFalling) {
self.isJumping = true;
}
});
canvasElement.addEventListener('mousedown', function (e) {
if (!self.isFalling) {
self.isJumping = true;
}
});
canvasElement.addEventListener('touchstart', function (e) {
if (!self.isFalling) {
self.isJumping = true;
}
});
}
_createClass(Runner, [{
key: '_updateLevel',
value: function _updateLevel() {
this.jumpTime = JUMP_TIME - this.level * 10;
this.jumpCounter = this.jumpTime;
}
}, {
key: '_calculateHeightChange',
value: function _calculateHeightChange(time) {
var oldHeight = -450 * Math.pow(time / this.jumpTime - 0.5, 2);
var newHeight = -450 * Math.pow((time + 1) / this.jumpTime - 0.5, 2);
return newHeight - oldHeight;
}
}, {
key: '_jump',
value: function _jump() {
if (this.isJumping) {
this.dy -= this._calculateHeightChange(this.jumpTime - this.jumpCounter);
this.jumpCounter--;
}
if (this.isFalling) {
this.dy -= this._calculateHeightChange(this.jumpTime - this.jumpCounter);
this.jumpCounter--;
}
if (this.jumpCounter === this.jumpTime / 2) {
this.isJumping = false;
this.isFalling = true;
}
if (this.jumpCounter === 0) {
this.isFalling = false;
this.jumpCounter = this.jumpTime;
}
}
}, {
key: '_runningAnim',
value: function _runningAnim(col, row, frameWidth, frameHeight, x, y) {
this.gameArea.context.drawImage(this.image, col * frameWidth, row * frameHeight, frameWidth, frameHeight, x, y + this.dy, frameWidth, frameHeight);
}
}, {
key: '_jumpingAnim',
value: function _jumpingAnim(col, row, frameWidth, frameHeight, x, y) {
this.gameArea.context.drawImage(this.image, frameWidth, 0, frameWidth, frameHeight, x, y + this.dy, frameWidth, frameHeight);
}
}, {
key: '_crashAnim',
value: function _crashAnim(col, row, frameWidth, frameHeight, x, y) {
this.gameArea.context.drawImage(this.image, frameWidth * 3, 0, frameWidth, frameHeight, x, y + this.dy, frameWidth, frameHeight);
}
}, {
key: 'nextLevel',
value: function nextLevel(level) {
this.level = level;
this.increaseLevel = true;
}
}, {
key: 'crash',
value: function crash() {
this.isCrashed = true;
}
}, {
key: 'update',
value: function update() {
// update to the next frame if it is time
if (this.counter == this.frameSpeed - 1) {
this.currentFrame = (this.currentFrame + 1) % this.endFrame;
}
// update the counter
this.counter = (this.counter + 1) % this.frameSpeed;
}
}, {
key: 'reset',
value: function reset() {
this.isCrashed = false;
this.isJumping = false;
this.isFalling = false;
this.level = 0;
this.dy = 0;
this.currentFrame = 0;
this.counter = 0;
this.jumpTime = JUMP_TIME - this.level * 15;
this.jumpCounter = this.jumpTime;
}
}, {
key: 'draw',
value: function draw() {
// get the row and col of the frame
var row = Math.floor(this.currentFrame / this.framesPerRow);
var col = Math.floor(this.currentFrame % this.framesPerRow);
this._jump();
if (this.isCrashed) {
this._crashAnim(col, row, this.frameWidth, this.frameHeight, this.x, this.y);
} else if (this.isJumping || this.isFalling) {
this._jumpingAnim(col, row, this.frameWidth, this.frameHeight, this.x, this.y);
} else {
if (this.increaseLevel) {
this._updateLevel();
this.increaseLevel = false;
}
this._runningAnim(col, row, this.frameWidth, this.frameHeight, this.x, this.y);
}
}
}]);
return Runner;
}();
module.exports = Runner;
},{}],5:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var SCORE_FONT = '"Press Start 2P"';
var SCORE_SIZE = 0.003;
var HEADLINE_SIZE = 0.006;
var SPACE = 40;
var MAX_TEXT = 1.4;
var MAX_HEADLINE = 2.5;
var Score = function () {
function Score(gameArea) {
_classCallCheck(this, Score);
this.gameArea = gameArea;
this.font = SCORE_FONT;
this.size = SCORE_SIZE * this.gameArea.x;
this.headlineSize = HEADLINE_SIZE * this.gameArea.x;
this.speed = 3;
this.color = 'black';
this.distance = 0;
this.calories = 0;
this.x = this.gameArea.x / 2;
this.y = 40;
}
_createClass(Score, [{
key: '_checkFontSize',
value: function _checkFontSize() {
if (this.size > MAX_TEXT) {
this.size = MAX_TEXT;
};
if (this.headlineSize > MAX_HEADLINE) {
this.headlineSize = MAX_HEADLINE;
};
}
}, {
key: 'onResize',
value: function onResize(newCanvasWidth) {
this.x = newCanvasWidth / 2;
this.size = SCORE_SIZE * (this.x * 2);
this.headlineSize = HEADLINE_SIZE * (this.x * 2);
}
}, {
key: 'update',
value: function update() {
var ctx = this.gameArea.context;
this.distance = parseInt(this.gameArea.frameNo / 50 * this.speed);
var text = '<NAME>: ' + this.distance + 'M';
this._checkFontSize();
ctx.font = this.size + 'em' + ' ' + this.font;
ctx.fillStyle = this.color;
ctx.textAlign = "center";
ctx.fillText(text, this.x, this.y);
}
}, {
key: 'done',
value: function done() {
var ctx = this.gameArea.context;
this.calories = parseInt(this.gameArea.frameNo / 50 * 0.2);
// text blocks
var text = '<NAME> O V E R';
var text2 = '<NAME> ' + this.calories + ' KCAL VERBRANNT!';
var text3 = 'STARTEN & SPRINGEN MIT';
var text4 = '<NAME>';
// text positions
var positionYText = SPACE * 2.5;
var positionYText2 = SPACE * 3.5;
var positionYText3 = SPACE * 4.5;
var positionYText4 = SPACE * 5;
// general text style
ctx.fillStyle = this.color;
ctx.textAlign = 'center';
this._checkFontSize();
// define size and set headline on canvas
ctx.font = this.headlineSize + 'em' + ' ' + this.font;
ctx.fillText(text, this.x, positionYText);
if (this.size > MAX_TEXT) {
this.size = MAX_TEXT;
};
// define size and set text on canvas
ctx.font = this.size + 'em' + ' ' + this.font;
ctx.fillText(text2, this.x, positionYText2);
ctx.fillText(text3, this.x, positionYText3);
ctx.fillText(text4, this.x, positionYText4);
}
}]);
return Score;
}();
module.exports = Score;
},{}]},{},[2])(2)
});
<file_sep>const SCORE_FONT = '"Press Start 2P"';
const SCORE_SIZE = 0.003;
const HEADLINE_SIZE = 0.006;
const SPACE = 40;
const MAX_TEXT = 1.4;
const MAX_HEADLINE = 2.5;
class Score {
constructor(gameArea) {
this.gameArea = gameArea;
this.font = SCORE_FONT;
this.size = SCORE_SIZE * this.gameArea.x;
this.headlineSize = HEADLINE_SIZE * this.gameArea.x;
this.speed = 3;
this.color = 'black';
this.distance = 0;
this.calories = 0;
this.x = this.gameArea.x / 2;
this.y = 40;
}
_checkFontSize() {
if (this.size > MAX_TEXT) {
this.size = MAX_TEXT;
};
if(this.headlineSize > MAX_HEADLINE) {
this.headlineSize = MAX_HEADLINE;
};
}
onResize(newCanvasWidth) {
this.x = newCanvasWidth / 2;
this.size = SCORE_SIZE * (this.x * 2);
this.headlineSize = HEADLINE_SIZE * (this.x * 2);
}
update() {
const ctx = this.gameArea.context;
this.distance = parseInt((this.gameArea.frameNo / 50) * this.speed);
const text = 'GELAUFENE STRECKE: ' + this.distance + 'M';
this._checkFontSize();
ctx.font = this.size + 'em' + ' ' + this.font;
ctx.fillStyle = this.color;
ctx.textAlign="center";
ctx.fillText(text, this.x, this.y);
}
done() {
const ctx = this.gameArea.context;
this.calories = parseInt((this.gameArea.frameNo / 50) * 0.2);
// text blocks
const text = 'G A M E O V E R';
const text2 = 'DU HAST ' + this.calories + ' <NAME>!';
const text3 = 'STARTEN & SPRINGEN MIT';
const text4 = '<NAME>'
// text positions
const positionYText = SPACE * 2.5;
const positionYText2 = SPACE * 3.5;
const positionYText3 = SPACE * 4.5;
const positionYText4 = SPACE * 5;
// general text style
ctx.fillStyle = this.color;
ctx.textAlign = 'center';
this._checkFontSize()
// define size and set headline on canvas
ctx.font = this.headlineSize + 'em' + ' ' + this.font;
ctx.fillText(text, this.x, positionYText);
if(this.size > MAX_TEXT) {
this.size = MAX_TEXT;
};
// define size and set text on canvas
ctx.font = this.size + 'em' + ' ' + this.font;
ctx.fillText(text2, this.x, positionYText2);
ctx.fillText(text3, this.x, positionYText3);
ctx.fillText(text4, this.x, positionYText4);
}
}
module.exports = Score;
<file_sep>const gulp = require('gulp');
const babelify = require('babelify');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const path = require('path');
const uglify = require('gulp-uglify');
const gulpIf = require('gulp-if');
const browserSync = require('browser-sync').create();
const rename = require('gulp-rename');
gulp.task('scripts', () => {
browserify({
standalone: 'MiniGame',
entries: './app/js/game.js',
})
.transform('babelify', {presets: ['es2015']})
.bundle()
.pipe(source('minigame.js'))
.pipe(gulp.dest('dist/js'))
});
gulp.task('bundleJS', ['scripts'], () => {
gulp.src('dist/js/minigame.js')
.pipe(rename('minigame.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/js'))
})
gulp.task('browserSync', ['bundleJS'], function() {
browserSync.init({
server: {
baseDir: 'dist'
}
})
});
gulp.task('js-watch', ['bundleJS'], function (done) {
browserSync.reload();
done();
});
gulp.task('copy-index-html', function() {
gulp.src('./app/index.html')
// Perform minification tasks, etc here
.pipe(gulp.dest('./dist'));
});
gulp.task('watch', ['copy-index-html', 'browserSync'], function (){
// Reloads the browser whenever HTML or JS files change
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', ['js-watch']);
});
gulp.task('build', ['copy-index-html', 'bundleJS']);
<file_sep>class Background {
constructor(gameArea, image, speed, x, y) {
this.gameArea = gameArea;
this.x = x;
this.y = y;
this.image = image;
this.speed = speed;
}
updateSpeed(newSpeed) {
this.speed = newSpeed;
}
draw() {
// Pan background
this.x -= this.speed;
this.gameArea.context.drawImage(this.image, this.x, this.y);
this.gameArea.context.drawImage(this.image, this.x + this.image.width, this.y);
// If the image scrolled off the screen, reset
if (Math.abs(this.x) >= this.image.width)
this.x = 0;
}
}
module.exports = Background;
<file_sep># mini-game
Endless running game
## Installation
npm i
npm run start
## Build
npm run build
## Usage as Module
import MiniGame from 'sportscheck-mini-game/dist/js/minigame';
new MiniGame();
The Markup must contain a canvas element with the id *minigame*
<canvas id='minigame'></canvas>
## Splash-Screen
The CSS for the Splashscreen is not part of the bundle. For example Code have a look into the index.html
|
1f4d33c6ee4d573ebd721fae3e4d4973e106cce2
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
SportScheck/mini-game
|
1a9c39be965ed3794601ccd0f15003b75767bc85
|
30e30b2d615037586ff8adbda981cd66219d47ab
|
refs/heads/master
|
<file_sep>import os
def loadim(image_path = '', ext = 'png', key_word = 'car_door'):
image_list = []
for filename in os.listdir(image_path):
if filename.endswith(ext) and filename.find(key_word) != -1:
current_path = os.path.abspath(image_path)
image_abs_path = os.path.join(current_path,filename)
image_list.append(image_abs_path)
return image_list
for i in range(46,91):
kw = "car_door_{}".format(i)
im_list = loadim("/home/hangwu/Repositories/Dataset/dataset/car_door_all","jpg",kw)
print(i, len(im_list))
# for i in [50,55,62,69,78,87]:
# kw = "car_door_{}".format(i)
# for j in range(1,361):
# kw_2 = "{}_{}".format(kw,j)
# if len(loadim("/home/hangwu/Repositories/Dataset/dataset/car_door_all","jpg",kw_2)) == 0:
# print(i,j)
<file_sep>import numpy as np
import skimage.io
import os
# EIGEN
import load_image
def LOAD_MASK(img_path):
"""Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# Get mask directory from image path
mask_dir = img_path
# Read mask files from .png image
mask = []
for f in next(os.walk(mask_dir))[2]:
if f.endswith(".png"):
m = skimage.io.imread(os.path.join(mask_dir, f)).astype(np.bool)
mask.append(m)
mask = np.stack(mask, axis=-1)
print(mask[0])
print(mask.shape)
# Return mask, and array of class IDs of each instance. Since we have
# one class ID, we return an array of ones
return mask, np.ones([mask.shape[-1]], dtype=np.int32)
if __name__ == '__main__':
img_path = '/home/hangwu/CyMePro/data/annotations/trimaps'
mask, mlist = LOAD_MASK(img_path)
print(mlist)
raws, cols = mask[0].shape
for i in range(raws):
for j in range(cols):
if mask[0][i][j]:
print(1)
<file_sep># coding: utf-8
# created by <NAME> on 2018.10.07
# feedback: <EMAIL>
import cv2
import numpy as np
from numpy import random
import os
import time
# Eigen
import load_image
import generate_dict
def overlap(background, foreground, bnd_pos, image_output_path, mask_output_path, mask_bw_output_path, car_door_subcat):
background = cv2.cvtColor(background, cv2.COLOR_BGR2BGRA)
# print(foreground.shape)
# print(background.shape)
rows, cols = foreground.shape[:2]
rows_b, cols_b = background.shape[:2]
# Mask initialization
"""# solid mask
object_mask = np.zeros([rows_b, cols_b, 3], np.uint8)
"""
# mask with window
object_mask_with_window = np.zeros([rows_b, cols_b, 3], np.uint8)
# mask with window in black white
object_mask_with_window_bw = np.zeros([rows_b, cols_b], np.uint8)
# Range of x and y
low_x = bnd_pos['xmin']
low_y = bnd_pos['ymin']
high_x = bnd_pos['xmax']
high_y = bnd_pos['ymax']
# Movement for random position
move_x = int(random.randint(- low_x, cols_b - high_x, 1))
move_y = int(random.randint(- low_y, rows_b - high_y, 1))
# move_y = random.randint(rows_b - high_y -1, rows_b - high_y, 1)
# print('movement x:',move_x)
# print(high_y)
# print('movement y:',move_y)
for i in range(rows):
for j in range(cols):
if foreground[i,j][3] != 0:
# Overlap images
try:
background[i + move_y, j + move_x] = foreground[i,j]
except:
break
if car_door_subcat == 1:
# Mask generating (for nomal mask with window)
object_mask_with_window[i + move_y, j + move_x] = [0, 0, 255]
elif car_door_subcat == 2:
object_mask_with_window[i + move_y, j + move_x] = [0, 255, 0]
# Mask in black and white
object_mask_with_window_bw[i + move_y, j + move_x] = 1
output_image = cv2.cvtColor(background, cv2.COLOR_BGRA2BGR)
save_name = "{}_cat_{}_id_{:0.0f}".format(bnd_pos['filename'][:-4], car_door_subcat, time.time()*1000)
# Path
image_output_name = "{}.jpg".format(save_name)
image_output_dest = os.path.join(image_output_path, image_output_name)
# Update xml data
## file info
bnd_pos['folder'] = image_output_dest.split(os.path.sep)[-2]
bnd_pos['filename'] = image_output_dest.split(os.path.sep)[-1]
bnd_pos['path'] = image_output_dest
## image info
rows_out, cols_out, channels_out = output_image.shape
bnd_pos['width'] = cols_out
bnd_pos['height'] = rows_out
bnd_pos['depth'] = channels_out
## x-y value
bnd_pos['xmin'] += move_x
bnd_pos['ymin'] += move_y
bnd_pos['xmax'] += move_x
bnd_pos['ymax'] += move_y
# test
# print(bnd_pos)
# Save images
# Synthetized images
cv2.imwrite(image_output_dest, output_image)
# Masks
mask_output_name = "{}.png".format(save_name)
mask_output_dest = os.path.join(mask_output_path, mask_output_name)
cv2.imwrite(mask_output_dest, object_mask_with_window)
# Masks in black and white
mask_bw_output_dest = os.path.join(mask_bw_output_path, mask_output_name)
cv2.imwrite(mask_bw_output_dest, object_mask_with_window_bw)
# Test
# cv2.imwrite('images/{}.jpg'.format(save_name), output_image)
# cv2.imwrite('masks/{}.png'.format(save_name), object_mask)
# cv2.imwrite('masks_with_window/{}.png'.format(save_name), object_mask_with_window)
# Display
# cv2.imshow('{}.jpg'.format(save_name), output_image)
# cv2.imshow('mask', object_mask)
# cv2.imshow('mask with window', object_mask_with_window)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
return bnd_pos
if __name__ == '__main__':
fg_list = load_image.loadim('images')
print(fg_list)
bg_list = load_image.loadim('background','jpg','Fabrik')
print(bg_list)
for fg in fg_list:
bnd_info = generate_dict.object_dict(fg, 1)
fg = cv2.imread(fg, -1)
bg_path = random.choice(bg_list)
print(bg_path)
bg = cv2.imread(bg_path, -1)
overlap(bg, fg, bnd_info)
<file_sep>import numpy as np
import yaml
from config import Config
import utils
import random
from PIL import Image, ImageDraw
import skimage.io
import os
'''
def from_yaml_get_class(yaml_path):
with open(yaml_path) as f:
temp = yaml.load(f.read())
labels = temp['label_names']
del labels[0]
return labels
class ShapesConfig(Config):
"""Configuration for training on the toy shapes dataset.
Derives from the base Config class and overrides values specific
to the toy shapes dataset.
"""
# Give the configuration a recognizable name
NAME = "car_door"
# Train on 1 GPU and 8 images per GPU. We can put multiple images on each
# GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
GPU_COUNT = 1
IMAGES_PER_GPU = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 1 # background + 3 shapes
# Use small images for faster training. Set the limits of the small side
# the large side, and that determines the image shape.
IMAGE_MIN_DIM = 800
IMAGE_MAX_DIM = 1600
# Use smaller anchors because our image and objects are small
RPN_ANCHOR_SCALES = (8 * 6, 16 * 6, 32 * 6, 64 * 6, 128 * 6) # anchor side in pixels
# Reduce training ROIs per image because the images are small and have
# few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
TRAIN_ROIS_PER_IMAGE = 32
# Use a small epoch since the data is simple
STEPS_PER_EPOCH = 100
# use small validation steps since the epoch is small
VALIDATION_STEPS = 5
# config = ShapesConfig()
# config.display()
class CarPartsDataset(utils.Dataset):
def load_car_door(self):
# Add class
self.add_class("car_parts", 1, "car_door")
# color = tuple([random.randint(0, 255) for _ in range(3)])
# print(color)
def get_obj_index(image):
n = np.max(image)
return n
# if __name__ == '__main__':
# yaml_path = 'info.yaml'
# labels = from_yaml_get_class(yaml_path)
# print(labels)
# img = 'car_door_0_12.png'
# img = Image.open(img)
# print(img)
# n = get_obj_index(img)
# print(n)
instance_masks = []
mask = Image.new('1', (1080, 810))
mask_draw = ImageDraw.ImageDraw(mask, '1')
print(mask_draw)
segmentation = [893.0, 587.5, 897.5, 581.0, 897.5, 537.0, 900.5, 485.0, 899.5, 387.0, 886.5, 343.0, 880.5, 342.0, 881.5, 339.0, 878.5, 334.0, 862.0, 316.5, 813.0, 278.5, 761.0, 243.5, 729.0, 224.5, 703.0, 211.5, 685.0, 204.5, 641.0, 193.5, 594.0, 187.5, 501.0, 183.5, 480.0, 183.5, 477.5, 186.0, 484.5, 208.0, 483.5, 212.0, 485.5, 218.0, 490.5, 224.0, 501.5, 257.0, 500.5, 262.0, 506.5, 272.0, 511.5, 288.0, 515.5, 302.0, 514.5, 307.0, 516.5, 314.0, 519.5, 316.0, 521.5, 324.0, 526.5, 330.0, 536.5, 350.0, 548.5, 382.0, 556.5, 435.0, 558.5, 486.0, 562.5, 519.0, 561.5, 537.0, 564.5, 540.0, 564.5, 552.0, 560.5, 574.0, 560.5, 583.0, 562.0, 584.5, 893.0, 587.5]
mask_draw.polygon(segmentation, fill=1)
print(mask_draw)
bool_array = np.array(mask) > 0
print('bool_array: ',bool_array.shape)
instance_masks.append(bool_array)
print('instance_masks: ', instance_masks)
mask = np.dstack(instance_masks)
print(mask.shape)
# print(mask)
img_path = '/home/hangwu/CyMePro/data/annotations/trimaps_with_window/car_door_0_0.png'
m = skimage.io.imread(img_path).astype(np.bool)
mask = []
mask.append(m)
mask = np.stack(mask, axis=-1)
# print(mask)
print(mask.shape)
'''
PATH_TO_SAVE_IMAGES_DIR = '/home/hangwu/Mask_RCNN/detected_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_SAVE_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]
# print(os.path.join(PATH_TO_SAVE_IMAGES_DIR, 'image{}.png'.format(i)) for i in range(i))
print(TEST_IMAGE_PATHS)
<file_sep>
# coding: utf-8
# # Mask R-CNN For Car Door Detection
# In[14]:
import os
import sys
import json
import numpy as np
import time
from PIL import Image, ImageDraw
# In[15]:
# Set the ROOT_DIR variable to the root directory of the Mask_RCNN git repo
ROOT_DIR = '../../'
assert os.path.exists(ROOT_DIR), 'ROOT_DIR does not exist. Did you forget to read the instructions above? ;)'
# Import mrcnn libraries
sys.path.append(ROOT_DIR)
from mrcnn.config import Config
import mrcnn.utils as utils
from mrcnn import visualize
import mrcnn.model as modellib
# ## Set up logging and pre-trained model paths
# This will default to sub-directories in your mask_rcnn_dir, but if you want them somewhere else, updated it here.
#
# It will also download the pre-trained coco model.
# In[16]:
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# ## Configuration
# Define configurations for training on the car door dataset.
# In[17]:
class CarDoorConfig(Config):
"""
Configuration for training on the car door dataset.
Derives from the base Config class and overrides values specific
to the car door dataset.
"""
# Give the configuration a recognizable name
NAME = "car_door"
# Train on 1 GPU and 1 image per GPU. Batch size is 1 (GPUs * images/GPU).
GPU_COUNT = 1
IMAGES_PER_GPU = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 1 # background + 1 (car_door)
# All of our training images are 512x512
IMAGE_MIN_DIM = 378
IMAGE_MAX_DIM = 512
# You can experiment with this number to see if it improves training
STEPS_PER_EPOCH = 500
# This is how often validation is run. If you are using too much hard drive space
# on saved models (in the MODEL_DIR), try making this value larger.
VALIDATION_STEPS = 5
# Matterport originally used resnet101, alternative resnet50
BACKBONE = 'resnet101'
# To be honest, I haven't taken the time to figure out what these do
RPN_ANCHOR_SCALES = (16, 32, 64, 128, 256) # (8, 16, 32, 64, 128)
TRAIN_ROIS_PER_IMAGE = 32
MAX_GT_INSTANCES = 50
POST_NMS_ROIS_INFERENCE = 500
POST_NMS_ROIS_TRAINING = 1000
config = CarDoorConfig()
config.display()
# # Define the dataset
# In[18]:
class CarPartsDataset(utils.Dataset):
""" Generates a COCO-like dataset, i.e. an image dataset annotated in the style of the COCO dataset.
See http://cocodataset.org/#home for more information.
"""
def load_data(self, annotation_json, images_dir):
""" Load the coco-like dataset from json
Args:
annotation_json: The path to the coco annotations json file
images_dir: The directory holding the images referred to by the json file
"""
# Load json from file
json_file = open(annotation_json)
car_door_json = json.load(json_file)
json_file.close()
# Add the class names using the base method from utils.Dataset
source_name = "car_parts"
for category in car_door_json['categories']:
class_id = category['id']
class_name = category['name']
if class_id < 1:
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(class_name))
return
self.add_class(source_name, class_id, class_name)
# Get all annotations
annotations = {}
for annotation in car_door_json['annotations']:
image_id = annotation['image_id']
if image_id not in annotations:
annotations[image_id] = []
annotations[image_id].append(annotation)
# Get all images and add them to the dataset
seen_images = {}
for image in car_door_json['images']:
image_id = image['id']
if image_id in seen_images:
print("Warning: Skipping duplicate image id: {}".format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print("Warning: Skipping image (id: {}) with missing key: {}".format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
image_annotations = annotations[image_id]
# Add the image using the base method from utils.Dataset
self.add_image(
source=source_name,
image_id=image_id,
path=image_path,
width=image_width,
height=image_height,
annotations=image_annotations
)
def load_mask(self, image_id):
""" Load instance masks for the given image.
MaskRCNN expects masks in the form of a bitmap [height, width, instances].
Args:
image_id: The id of the image to load masks for
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
image_info = self.image_info[image_id]
annotations = image_info['annotations']
instance_masks = []
class_ids = []
for annotation in annotations:
class_id = annotation['category_id']
mask = Image.new('1', (image_info['width'], image_info['height']))
mask_draw = ImageDraw.ImageDraw(mask, '1')
for segmentation in annotation['segmentation']:
mask_draw.polygon(segmentation, fill=1)
bool_array = np.array(mask) > 0
instance_masks.append(bool_array)
class_ids.append(class_id)
mask = np.dstack(instance_masks)
class_ids = np.array(class_ids, dtype=np.int32)
return mask, class_ids
# # Create the Training and Validation Datasets
# In[19]:
dataset_train = CarPartsDataset()
dataset_train.load_data('/home/hangwu/CyMePro/botVision/JSON_generator/output/car_door_train.json', '/home/hangwu/CyMePro/data/dataset/train_data')
dataset_train.prepare()
dataset_val = CarPartsDataset()
dataset_val.load_data('/home/hangwu/CyMePro/botVision/JSON_generator/output/car_door_val.json', '/home/hangwu/CyMePro/data/dataset/val_data')
dataset_val.prepare()
# ## Display a few images from the training dataset
# In[20]:
dataset = dataset_train
image_ids = np.random.choice(dataset.image_ids, 4)
for image_id in image_ids:
image = dataset.load_image(image_id)
mask, class_ids = dataset.load_mask(image_id)
visualize.display_top_masks(image, mask, class_ids, dataset.class_names)
# In[21]:
# # Create the Training Model and Train
# This code is largely borrowed from the train_shapes.ipynb notebook.
# Create model in training mode
model = modellib.MaskRCNN(mode="training", config=config,
model_dir=MODEL_DIR)
# In[22]:
# Which weights to start with?
init_with = "coco" # imagenet, coco, or last
if init_with == "imagenet":
model.load_weights(model.get_imagenet_weights(), by_name=True)
elif init_with == "coco":
# Load weights trained on MS COCO, but skip layers that
# are different due to the different number of classes
# See README for instructions to download the COCO weights
model.load_weights(COCO_MODEL_PATH, by_name=True,
exclude=["mrcnn_class_logits", "mrcnn_bbox_fc",
"mrcnn_bbox", "mrcnn_mask"])
elif init_with == "last":
# Load the last model you trained and continue training
model.load_weights(model.find_last(), by_name=True)
# ## Training
#
# Train in two stages:
#
# 1. Only the heads. Here we're freezing all the backbone layers and training only the randomly initialized layers (i.e. the ones that we didn't use pre-trained weights from MS COCO). To train only the head layers, pass layers='heads' to the train() function.
#
# 2. Fine-tune all layers. For this simple example it's not necessary, but we're including it to show the process. Simply pass layers="all to train all layers.
#
#
# In[23]:
# Train the head branches
# Passing layers="heads" freezes all layers except the head
# layers. You can also pass a regular expression to select
# which layers to train by name pattern.
start_train = time.time()
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE,
epochs=4,
layers='heads')
end_train = time.time()
minutes = round((end_train - start_train) / 60, 2)
print(f'Training took {minutes} minutes')
# In[24]:
# Fine tune all layers
# Passing layers="all" trains all layers. You can also
# pass a regular expression to select which layers to
# train by name pattern.
start_train = time.time()
model.train(dataset_train, dataset_val,
learning_rate=config.LEARNING_RATE / 10,
epochs=8,
layers="all")
end_train = time.time()
minutes = round((end_train - start_train) / 60, 2)
print(f'Training took {minutes} minutes')
# # Prepare to run Inference
# Create a new InferenceConfig, then use it to create a new model.
# In[26]:
class InferenceConfig(CarDoorConfig):
GPU_COUNT = 1
IMAGES_PER_GPU = 1
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 512
DETECTION_MIN_CONFIDENCE = 0.85
inference_config = InferenceConfig()
# In[27]:
# Recreate the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=inference_config,
model_dir=MODEL_DIR)
# In[28]:
# Get path to saved weights
# Either set a specific path or find last trained weights
# model_path = os.path.join(ROOT_DIR, ".h5 file name here")
model_path = model.find_last()
# Load trained weights (fill in path to trained weights here)
assert model_path != "", "Provide path to trained weights"
print("Loading weights from ", model_path)
model.load_weights(model_path, by_name=True)
# # Run Inference
# Run model.detect() on real images.
#
# We get some false positives, and some misses. More training images are likely needed to improve the results.
# In[31]:
import skimage
real_test_dir = '/home/hangwu/CyMePro/data/test' # '/home/hangwu/CyMePro/data/dataset/test_data'
image_paths = []
for filename in os.listdir(real_test_dir):
if os.path.splitext(filename)[1].lower() in ['.png', '.jpg', '.jpeg', '.JPG']:
image_paths.append(os.path.join(real_test_dir, filename))
for image_path in image_paths:
img = skimage.io.imread(image_path)
img_arr = np.array(img)
results = model.detect([img_arr], verbose=1)
r = results[0]
visualize.display_instances(img, r['rois'], r['masks'], r['class_ids'],
dataset_val.class_names, r['scores'], figsize=(5,5))
<file_sep># Mask R-CNN for Car Door Detection and Pose Estimation
This is an implementation of [Mask R-CNN](https://arxiv.org/abs/1703.06870) on Python 3, Keras, and TensorFlow. The model generates bounding boxes and segmentation masks for each instance of an object in the image. It's based on Feature Pyramid Network (FPN) and a ResNet101 backbone.
forked from [matterport/Mask R-CNN](https://github.com/matterport/Mask_RCNN)
<file_sep># import the necessary packages
from keras import applications
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation
from keras.layers.core import Dropout
from keras.layers.core import Lambda
from keras.layers.core import Dense
from keras.layers import Flatten
from keras.layers import Input
from keras.layers import GlobalAveragePooling2D
import tensorflow as tf
class PoseNet:
'''
@staticmethod
def build_shared_layers(inputs, numLongitudes,
finalAct="softmax", chanDim=-1):
# VGG16
# Block 1
x = Conv2D(64, (3, 3),
activation='relu',
padding='same',
name='block1_conv1')(inputs)
x = Conv2D(64, (3, 3),
activation='relu',
padding='same',
name='block1_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
# Block 2
x = Conv2D(128, (3, 3),
activation='relu',
padding='same',
name='block2_conv1')(x)
x = Conv2D(128, (3, 3),
activation='relu',
padding='same',
name='block2_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)
# Block 3
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv1')(x)
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv2')(x)
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv3')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)
# Block 4
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv1')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv2')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv3')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)
# Block 5
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv1_2')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv2_2')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv3_2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool_2')(x)
# return the longitude prediction sub-network
return x
@staticmethod
def build_latitude_branch(inputs, numLatitudes,
finalAct="softmax", chanDim=-1):
# VGG16
# Block 1
x = Conv2D(64, (3, 3),
activation='relu',
padding='same',
name='block1_conv1_1')(inputs)
x = Conv2D(64, (3, 3),
activation='relu',
padding='same',
name='block1_conv2_1')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool_1')(x)
# Block 2
x = Conv2D(128, (3, 3),
activation='relu',
padding='same',
name='block2_conv1_1')(x)
x = Conv2D(128, (3, 3),
activation='relu',
padding='same',
name='block2_conv2_1')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool_1')(x)
# Block 3
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv1_1')(x)
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv2_1')(x)
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv3_1')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool_1')(x)
# Block 4
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv1_1')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv2_1')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv3_1')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool_1')(x)
# Block 5
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv1_1')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv2_1')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv3_1')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool_1')(x)
# define a branch of output layers for the number of latitudes
x = Flatten(name='flatten_1')(x)
x = Dense(4096, activation='relu', name='fc1_1')(x)
x = Dense(4096, activation='relu', name='fc2_1')(x)
x = Dense(numLatitudes)(x)
x = Activation(finalAct, name="latitude_output")(x)
# return the latitude prediction sub-network
return x
@staticmethod
def build_longitude_branch(inputs, numLongitudes,
finalAct="softmax", chanDim=-1):
# VGG16
# Block 1
x = Conv2D(64, (3, 3),
activation='relu',
padding='same',
name='block1_conv1_2')(inputs)
x = Conv2D(64, (3, 3),
activation='relu',
padding='same',
name='block1_conv2_2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool_2')(x)
# Block 2
x = Conv2D(128, (3, 3),
activation='relu',
padding='same',
name='block2_conv1_2')(x)
x = Conv2D(128, (3, 3),
activation='relu',
padding='same',
name='block2_conv2_2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool_2')(x)
# Block 3
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv1_2')(x)
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv2_2')(x)
x = Conv2D(256, (3, 3),
activation='relu',
padding='same',
name='block3_conv3_2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool_2')(x)
# Block 4
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv1_2')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv2_2')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block4_conv3_2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool_2')(x)
# Block 5
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv1_2')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv2_2')(x)
x = Conv2D(512, (3, 3),
activation='relu',
padding='same',
name='block5_conv3_2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool_2')(x)
# define a branch of output layers for the number of longitudes
x = Flatten(name='flatten_2')(x)
x = Dense(4096, activation='relu', name='fc1_2')(x)
x = Dense(4096, activation='relu', name='fc2_2')(x)
x = Dense(numLongitudes)(x)
x = Activation(finalAct, name="longitude_output")(x)
# return the longitude prediction sub-network
return x
@staticmethod
def build(width, height, numLatitudes, numLongitudes,
finalAct="softmax"):
# initialize the input shape and channel dimension (this code
# assumes you are using TensorFlow which utilizes channels
# last ordering)
inputShape = (height, width, 3)
chanDim = -1
# construct both the "category" and "color" sub-networks
inputs = Input(shape=inputShape)
latitudeBranch = PoseNet.build_latitude_branch(inputs,
numLatitudes, finalAct=finalAct, chanDim=chanDim)
longitudeBranch = PoseNet.build_longitude_branch(inputs,
numLongitudes, finalAct=finalAct, chanDim=chanDim)
# create the model using our input (the batch of images) and
# two separate outputs -- one for the clothing category
# branch and another for the color branch, respectively
model = Model(
inputs=inputs,
outputs=[latitudeBranch, longitudeBranch],
name="posenet")
# weights_path = 'vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'
# model.load_weights(weights_path)
# return the constructed network architecture
return model
'''
@staticmethod
def ResNet_mod(width, height, numLatitudes, numLongitudes,
finalAct="softmax"):
base_model = applications.ResNet50(weights="imagenet", include_top=False, input_shape=(width, height, 3))
x = base_model.output
x = GlobalAveragePooling2D()(x)
# x_la = Dense(128, activation='relu', name='fc1_1')(x)
# x_la = Dense(1024, activation='relu', name='fc2_1')(x_la)
x_la = Dense(numLatitudes)(x)
latitudeBranch = Activation(finalAct, name="latitude_output")(x_la)
# x_lo = Dense(128, activation='relu', name='fc1_2')(x)
# x_lo = Dense(1024, activation='relu', name='fc2_2')(x_lo)
x_lo = Dense(numLongitudes)(x)
longitudeBranch = Activation(finalAct, name="longitude_output")(x_lo)
model = Model(
inputs=base_model.input,
outputs=[latitudeBranch, longitudeBranch],
name='posenet')
for i,layer in enumerate(model.layers):
print(i,layer.name)
for layer in model.layers[:30]:
layer.trainable = False
return model
@staticmethod
def VGG16_mod(width, height, numLatitudes, numLongitudes,
finalAct="softmax"):
base_model = applications.VGG16(weights="imagenet", include_top=False, input_shape=(width, height, 3))
x = base_model.output
x = Flatten()(x)
x_la = Dense(1024, activation='relu', name='fc1_1')(x)
x_la = Dense(1024, activation='relu', name='fc2_1')(x_la)
x_la = Dense(numLatitudes)(x_la)
latitudeBranch = Activation(finalAct, name="latitude_output")(x_la)
x_lo = Dense(1024, activation='relu', name='fc1_2')(x)
x_lo = Dense(1024, activation='relu', name='fc2_2')(x_lo)
x_lo = Dense(numLongitudes)(x_lo)
longitudeBranch = Activation(finalAct, name="longitude_output")(x_lo)
model = Model(
inputs=base_model.input,
outputs=[latitudeBranch, longitudeBranch],
name='posenet')
for i,layer in enumerate(model.layers):
print(i,layer.name)
for layer in model.layers[:10]:
layer.trainable = False
return model
<file_sep># Annotation script for 2 car door classes
# Author: <NAME>
# Date: 2019.07.09
import json
from PIL import Image
import numpy as np
from skimage import measure
from shapely.geometry import Polygon, MultiPolygon
import os
# EIGEN
from sub_mask_annotation import create_image_annotation, create_sub_mask_annotation
from sub_masks_create import create_sub_masks
from load_image import loadim
# Define which colors match which categories in the images
car_door_first_id = 1
car_door_second_id = 2
category_ids = {
1: {
'(255, 0, 0)': car_door_first_id,
'(0, 255, 0)': car_door_second_id,
},
}
is_crowd = 0
# Create the annotations
car_door_annotation = {
'info': {
'description': "Car Door Dataset",
'url': "hangwudy.github.io",
'version': '0.1',
'year': 2019,
'contributor': '<NAME>',
'date_created': '2019/07/09',
},
'licenses': [
{
"url": "hangwudy.github.io",
"id": 1,
"name": 'MIT'
}
],
"images": [
{
}
],
"annotations": [
{
}
],
"categories": [
{
"supercategory": "car_parts",
"id": 1,
"name": 'car_door_1'
},
{
"supercategory": "car_parts",
"id": 2,
"name": 'car_door_2'
}
]
}
def images_annotations_info(maskpath):
annotations = []
images = []
mask_images_path = loadim(maskpath)
for id_number, mask_image_path in enumerate(mask_images_path, 1):
file_name = mask_image_path.split(os.path.sep)[-1][:-4]+'.jpg'
mask_image = Image.open(mask_image_path)
sub_masks = create_sub_masks(mask_image)
for color, sub_mask in sub_masks.items():
category_id = category_ids[1][color]
# ID number
image_id = id_number
annotation_id = id_number
# image shape
width, height = mask_image.size
# 'images' info
image = create_image_annotation(file_name, height, width, image_id)
images.append(image)
# 'annotations' info
annotation = create_sub_mask_annotation(sub_mask, is_crowd, image_id, category_id, annotation_id)
annotations.append(annotation)
print('{:.2f}% finished.'.format((id_number / len(mask_images_path) * 100)))
return images, annotations
if __name__ == '__main__':
for keyword in ['train', 'val']:
mask_path = '/home/hangwu/Repositories/Dataset/car_door_mix_annotations/mask_{}'.format(keyword)
car_door_annotation['images'], car_door_annotation['annotations'] = images_annotations_info(mask_path)
print(json.dumps(car_door_annotation))
with open('/home/hangwu/Repositories/Dataset/car_door_mix_annotations/json/car_door_{}.json'.format(keyword),'w') as outfile:
json.dump(car_door_annotation, outfile)
<file_sep>import numpy as np
from skimage import measure
from shapely.geometry import Polygon, MultiPolygon
def create_image_annotation(file_name, height, width, image_id):
images = {
'license': 1,
'file_name': file_name,
'height': height,
'width': width,
'id': image_id
}
return images
def create_sub_mask_annotation(sub_mask, is_crowd, image_id, category_id, annotation_id):
# Find contours (boundary lines) around each sub-mask
# Note: there could be multiple contours if the object
# is partially occluded. (E.g. an elephant behind a tree)
"""
contours = measure.find_contours(sub_mask, 0.5, positive_orientation='low')
print(contours)
segmentations = []
polygons = []
for contour in contours:
# Flip from (row, col) representation to (x, y)
# and subtract the padding pixel
for i in range(len(contour)):
row, col = contour[i]
contour[i] = (col - 1, row - 1)
# Make a polygon and simplify it
poly = Polygon(contour)
poly = poly.simplify(0.4, preserve_topology=False)
print(poly)
polygons.append(poly)
segmentation = np.array(poly.exterior.coords).ravel().tolist()
segmentations.append(segmentation)
# Combine the polygons to calculate the bounding box and area
multi_poly = MultiPolygon(polygons)
x, y, max_x, max_y = multi_poly.bounds
width = max_x - x
height = max_y - y
bbox = (x, y, width, height)
area = multi_poly.area
"""
annotation = {
# 'segmentation': segmentations,
# 'area': area,
'iscrowd': is_crowd,
'image_id': image_id,
# 'bbox': bbox,
'category_id': category_id,
'id': annotation_id
}
return annotation
<file_sep>'''
# USAGE
python classify_pose.py --model output/pose.model \
--latitudebin output/latitude_lb.pickle --longitudebin output/longitude_lb.pickle \
--image /home/hangwu/Workspace/Car_Door
'''
# import the necessary packages
from keras.preprocessing.image import img_to_array
from keras.models import load_model
import tensorflow as tf
import numpy as np
import argparse
import imutils
import pickle
import cv2
import os
from numpy import random
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model",
default="/home/hangwu/Workspace/multi-output-classification/output/pose.model",
# required=True,
help="path to trained model model")
ap.add_argument("-a", "--latitudebin",
default="/home/hangwu/Workspace/multi-output-classification/output/latitude_lb.pickle",
# required=True,
help="path to output latitude label binarizer")
ap.add_argument("-o", "--longitudebin",
default="/home/hangwu/Workspace/multi-output-classification/output/longitude_lb.pickle",
# required=True,
help="path to output longitude label binarizer")
ap.add_argument("-i", "--image",
default="/home/hangwu/Workspace/car_door_half",
# required=True,
help="path to input image directory")
args = vars(ap.parse_args())
# load the trained convolutional neural network from disk, followed
# by the latitude and longitude label binarizers, respectively
print("[INFO] loading network...")
model = load_model(args["model"], custom_objects={"tf": tf})
latitudeLB = pickle.loads(open(args["latitudebin"], "rb").read())
longitudeLB = pickle.loads(open(args["longitudebin"], "rb").read())
def inference(image_path):
# load the image
image = cv2.imread(image_path)
if image.shape[0] > image.shape[1]:
img_width = image.shape[1]
img_height = image.shape[0]
side_len_diff_half = round(abs(img_height - img_width) / 2)
new_patch = np.zeros((img_height, img_height ,3), np.uint8)
for row in range(img_height):
for col in range(img_width):
new_patch[row, col + side_len_diff_half] = image[row, col]
image = new_patch
cv2.imshow("resized image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
elif image.shape[0] < image.shape[1]:
img_width = image.shape[1]
img_height = image.shape[0]
side_len_diff_half = round(abs(img_height - img_width) / 2)
new_patch = np.zeros((img_width, img_width ,3), np.uint8)
for row in range(img_height):
for col in range(img_width):
new_patch[row + side_len_diff_half, col] = image[row, col]
image = new_patch
cv2.imshow("resized image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
output = imutils.resize(image, width=400)
# pre-process the image for classification
image = cv2.resize(image, (128, 128))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
# classify the input image using Keras' multi-output functionality
print("[INFO] classifying image...")
(latitudeProba, longitudeProba) = model.predict(image)
# find indexes of both the latitude and longitude outputs with the
# largest probabilities, then determine the corresponding class
# labels
latitudeIdx = latitudeProba[0].argmax()
longitudeIdx = longitudeProba[0].argmax()
latitudeLabel = latitudeLB.classes_[latitudeIdx]
longitudeLabel = longitudeLB.classes_[longitudeIdx]
# draw the latitude label and longitude label on the image
latitudeText = "latitude: {} ({:.2f}%)".format(latitudeLabel,
latitudeProba[0][latitudeIdx] * 100)
longitudeText = "longitude: {} ({:.2f}%)".format(longitudeLabel,
longitudeProba[0][longitudeIdx] * 100)
cv2.putText(output, latitudeText, (10, 25), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2)
cv2.putText(output, longitudeText, (10, 55), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2)
# display the predictions to the terminal as well
print("[INFO] {}".format(latitudeText))
print("[INFO] {}".format(longitudeText))
# show the output image
cv2.imshow("Output", output)
image_compare_name = 'car_door_{}_{}.png'.format(latitudeLabel, longitudeLabel)
image_compare_path = os.path.join('/home/hangwu/Workspace/Car_Door', image_compare_name)
print(image_compare_path)
image_compare = cv2.imread(image_compare_path)
image_compare = imutils.resize(image_compare, width=400)
cv2.imshow("Comparison", image_compare)
cv2.waitKey(0)
def loadim(image_path = 'Car_Door', ext = 'png', key_word = 'car_door'):
image_list = []
for filename in os.listdir(image_path):
if filename.endswith(ext) and filename.find(key_word) != -1:
current_path = os.path.abspath(image_path)
image_abs_path = os.path.join(current_path,filename)
image_list.append(image_abs_path)
return image_list
def main():
# img_path_list = loadim(args["image"])
# # print(img_path_list)
# test_img = random.choice(img_path_list, 6)
# # print(img_path_choice)
test_img_1 = '/home/hangwu/Workspace/multi-output-classification/test_pics/car_door_test_1.png'
test_img_2 = '/home/hangwu/Workspace/multi-output-classification/test_pics/car_door_test_2.png'
test_img_3 = '/home/hangwu/Workspace/multi-output-classification/test_pics/car_door_test_3.png'
test_img_4 = '/home/hangwu/Workspace/multi-output-classification/test_pics/car_door_test_4.png'
test_img_5 = '/home/hangwu/Workspace/multi-output-classification/test_pics/door333.png'
test_img = []
test_img.append(test_img_1)
test_img.append(test_img_2)
test_img.append(test_img_3)
test_img.append(test_img_4)
test_img.append(test_img_5)
for image_file in test_img:
print(image_file)
inference(image_file)
if __name__ == "__main__":
main()
<file_sep># coding: utf-8
# created by <NAME> on 2018.10.07
# feedback: <EMAIL>
from lxml.etree import Element, SubElement, tostring
import pprint
from xml.dom.minidom import parseString
import cv2
from numpy import random
import os
# Eigen
import image_overlay
import load_image
import generate_dict
def xml_generator(bndbox, xml_destination_path):
# Root
node_root = Element('annotation')
## Folder
node_folder = SubElement(node_root, 'folder')
node_folder.text = bndbox['folder']
## Filename
node_filename = SubElement(node_root, 'filename')
node_filename.text = bndbox['filename']
## Path
node_path = SubElement(node_root, 'path')
node_path.text = bndbox['path']
## Source
node_source = SubElement(node_root, 'source')
node_database = SubElement(node_source, 'database')
node_database.text = 'Unknown'
## Size
node_size = SubElement(node_root, 'size')
### Width
node_width = SubElement(node_size, 'width')
node_width.text = str(bndbox['width'])
### Height
node_height = SubElement(node_size, 'height')
node_height.text = str(bndbox['height'])
### Depth
node_depth = SubElement(node_size, 'depth')
node_depth.text = str(bndbox['depth'])
## Segmented
node_segmented = SubElement(node_root, 'segmented')
node_segmented.text = '0'
## Object
node_object = SubElement(node_root, 'object')
### Name
node_name = SubElement(node_object, 'name')
node_name.text = 'car_door'
### Pose
node_pose = SubElement(node_object, 'pose')
node_pose.text = 'Unspecified'
### Truncated
node_truncated = SubElement(node_object, 'truncated')
node_truncated.text = '0'
### Difficult
node_difficult = SubElement(node_object, 'difficult')
node_difficult.text = '0'
### Bounding box
node_bndbox = SubElement(node_object, 'bndbox')
#### x-y value
node_xmin = SubElement(node_bndbox, 'xmin')
node_xmin.text = str(bndbox['xmin'])
node_ymin = SubElement(node_bndbox, 'ymin')
node_ymin.text = str(bndbox['ymin'])
node_xmax = SubElement(node_bndbox, 'xmax')
node_xmax.text = str(bndbox['xmax'])
node_ymax = SubElement(node_bndbox, 'ymax')
node_ymax.text = str(bndbox['ymax'])
# format display
xml = tostring(node_root, pretty_print=True)
xml_name = bndbox['filename'][:-4]+".xml"
xml_path = os.path.join(xml_destination_path, xml_name)
fp = open(xml_path, 'w')
fp.write(xml.decode())
fp.close()
if __name__ == '__main__':
# Foreground and background imags
fg_path = '/home/hangwu/Repositories/Dataset/dataset/ergaenzen'
bg_path = '/home/hangwu/Downloads/val2017'
# Output paths
xml_dest_path = "/home/hangwu/Repositories/Dataset/dataset/annotation_all/xml"
image_dest_path = "/home/hangwu/Repositories/Dataset/dataset/car_door_all"
mask_dest_path = "/home/hangwu/Repositories/Dataset/dataset/annotation_all/mask"
mask_bw_dest_path = "/home/hangwu/Repositories/Dataset/dataset/annotation_all/mask_bw"
# Car Door Subcategory: 1 or 2, IMPORTANT for naming the training data
cd_subcat = 2
# Test
test = False
if test:
fg_path = '/home/hangwu/Repositories/Mask_RCNN/dataset_tools/Test_Workspace/Image_Generation/Foreground'
bg_path = '/home/hangwu/Repositories/Mask_RCNN/dataset_tools/Test_Workspace/Image_Generation/Background'
xml_dest_path = "/home/hangwu/Repositories/Mask_RCNN/dataset_tools/Test_Workspace/Image_Generation/output/xml"
image_dest_path = "/home/hangwu/Repositories/Mask_RCNN/dataset_tools/Test_Workspace/Image_Generation/output/image"
mask_dest_path = "/home/hangwu/Repositories/Mask_RCNN/dataset_tools/Test_Workspace/Image_Generation/output/mask"
mask_bw_dest_path = "/home/hangwu/Repositories/Mask_RCNN/dataset_tools/Test_Workspace/Image_Generation/output/mask_bw"
fg_list = load_image.loadim(fg_path)
# print(fg_list[1230:1250])
bg_list = load_image.loadim(bg_path,'jpg','0000')
# Counter
progress_show = 1
for fg_p in fg_list:
# IMPORTANT: if you want to resize images, don't forget resize in generate_dict
img_scale = 0.8
try:
bnd_info = generate_dict.object_dict(fg_p, img_scale)
fg = cv2.imread(fg_p, -1)
# resize the car door images
fg = cv2.resize(fg, (0,0), fx = img_scale, fy = img_scale, interpolation = cv2.INTER_CUBIC)
bg_path = random.choice(bg_list)
bg = cv2.imread(bg_path, -1)
object_bndbox = image_overlay.overlap(bg, fg, bnd_info, image_dest_path, mask_dest_path, mask_bw_dest_path, cd_subcat)
xml_generator(object_bndbox, xml_dest_path)
except:
print("===========================")
print(fg_p)
print(bg_path)
print("===========================")
# print(object_bndbox)
if progress_show % 1 == 0:
print("++++++++++++++")
print("{:.2f}%".format(progress_show/len(fg_list)*100))
print("++++++++++++++")
progress_show += 1
<file_sep># coding: utf-8
# # FusionNet for Car Door Detection and Pose Estimation
# @author: <NAME>
# @date: 2018.12.20
import os
import sys
import json
import numpy as np
import skimage.io
import matplotlib.pyplot as plt
import csv
from skimage.color import gray2rgb
from keras.preprocessing.image import img_to_array
from keras.models import load_model
import tensorflow as tf
import argparse
import imutils
import pickle
import cv2
import re
# Set the ROOT_DIR variable to the root directory of the Mask_RCNN git repo
ROOT_DIR = '../../'
sys.path.append(ROOT_DIR)
from mrcnn.config import Config
import mrcnn.utils as utils
import time
from mrcnn import visualize_car_door
import mrcnn.model_new as modellib
# PoseNet
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model",
default="/home/hangwu/Repositories/Model_output/Attitude_CNN/attitude_vgg16_random.h5",
# required=True,
help="path to trained Attitude CNN model model")
ap.add_argument("-mm", "--model_m",
default="/media/hangwu/TOSHIBA_EXT/Dataset/weights/mask_rcnn_car_door_0250.h5",
# required=True,
help="path to trained Mask R-CNN model model")
ap.add_argument("-a", "--latitudebin",
default="/home/hangwu/Repositories/Model_output/Attitude_CNN/latitude_lb.pickle",
# required=True,
help="path to output latitude label binarizer")
ap.add_argument("-o", "--longitudebin",
default="/home/hangwu/Repositories/Model_output/Attitude_CNN/longitude_lb.pickle",
# required=True,
help="path to output longitude label binarizer")
ap.add_argument("-r", "--renderings",
default="/media/hangwu/TOSHIBA_EXT/Dataset/renderings_square",
# required=True,
help="path to input renderings directory")
ap.add_argument("-j", "--valjson",
default="/media/hangwu/TOSHIBA_EXT/Dataset/annotations/mask_rcnn/car_door_val.json",
# required=True,
help="path to validation data annotation directory")
ap.add_argument("-v", "--valdata",
default="/media/hangwu/TOSHIBA_EXT/Dataset/val_data",
# required=True,
help="path to validation data directory")
ap.add_argument("-test", "--test",
# default="/media/hangwu/TOSHIBA_EXT/Dataset/test_data",
# default="/home/hangwu/CyMePro/data/test",
default="/media/hangwu/TOSHIBA_EXT/Dataset/images_from_robot/dataset/images",
# required=True,
help="path to test dataset directory")
args = vars(ap.parse_args())
# load the trained convolutional neural network from disk, followed
# by the latitude and longitude label binarizers, respectively
print("[INFO] loading network...")
model2 = load_model(args["model"], custom_objects={"tf": tf})
latitudeLB = pickle.loads(open(args["latitudebin"], "rb").read())
longitudeLB = pickle.loads(open(args["longitudebin"], "rb").read())
def loadim(image_path='Car_Door', ext='png', key_word='car_door'):
image_list = []
for filename in os.listdir(image_path):
if filename.endswith(ext) and filename.find(key_word) != -1:
current_path = os.path.abspath(image_path)
image_abs_path = os.path.join(current_path, filename)
image_list.append(image_abs_path)
return image_list
def pose_estimation(image):
scale = 500
output = cv2.resize(image, (scale, scale))
image_name = image_path.split(os.path.sep)[-1]
gt_latitude, gt_longitude = gt_name(image_name)
print("output size:", output.shape)
# pre-process the image for classification
image = cv2.resize(image, (224, 224))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
# classify the input image using Keras' multi-output functionality
print("[INFO] classifying image...")
(latitudeProba, longitudeProba) = model2.predict(image)
# find indexes of both the latitude and longitude outputs with the
# largest probabilities, then determine the corresponding class
# labels
latitudeIdx = latitudeProba[0].argmax()
longitudeIdx = longitudeProba[0].argmax()
latitudeLabel = latitudeLB.classes_[latitudeIdx]
longitudeLabel = longitudeLB.classes_[longitudeIdx]
"""
# draw the latitude label and longitude label on the image
latitudeText = "latitude: {} ({:.2f}%)".format(latitudeLabel,
latitudeProba[0][latitudeIdx] * 100)
longitudeText = "longitude: {} ({:.2f}%)".format(longitudeLabel,
longitudeProba[0][longitudeIdx] * 100)
cv2.putText(output, latitudeText, (10, 25), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2)
cv2.putText(output, longitudeText, (10, 55), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2)
# display the predictions to the terminal as well
print("[INFO] {}".format(latitudeText))
print("[INFO] {}".format(longitudeText))
"""
# show the output image
# cv2.imshow("Output", output)
image_compare_name = 'car_door_{}_{}.png'.format(latitudeLabel, longitudeLabel)
image_compare_path = os.path.join(args["renderings"], image_compare_name)
# print(image_compare_path)
image_compare = cv2.imread(image_compare_path)
image_compare = cv2.resize(image_compare, (scale, scale))
# print("Compare size:", image_compare.shape)
image_horizontal_concat = np.concatenate((output, image_compare), axis=1)
plt_fig_save(image_horizontal_concat,
image_name[:-4],
latitudeLabel,
longitudeLabel,
gt_latitude,
gt_longitude)
cv2.imwrite("/home/hangwu/Mask_RCNN/detected_images/Results_{:4.0f}.png".format(time.time()), image_horizontal_concat)
# cv2.imshow("Reality and Prediction", image_horizontal_concat)
# # cv2.imshow("Comparison", image_compare)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
return [image_name[:-4], latitudeLabel, gt_latitude, longitudeLabel, gt_longitude]
def plt_fig_save(img, img_name, pred_latitude, pred_longitude, gt_latitude, gt_longitude):
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
_, ax = plt.subplots(1,1)
text_on_image = "Prediction: ({},{})\nGround Truth: ({},{})".format(pred_latitude,
pred_longitude, gt_latitude, gt_longitude)
ax.text(
0, 1, text_on_image,
size='small',
horizontalalignment='left',
verticalalignment='top',
# family='serif',
bbox={'facecolor': 'white', 'alpha':0.5, 'pad':2},
color='white',
transform=ax.transAxes
)
ax.axis('off')
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
plt.imshow(img)
plt.savefig("/media/hangwu/TOSHIBA_EXT/Dataset/PoseNet_output/prediction_{}.pdf".format(img_name),
dpi=500,
transparent=True,
bbox_inches='tight',
pad_inches=0)
def gt_name(file_name):
match = re.match(r'([0-9]+)(_+)([0-9]+)(_+)([0-9]+)(\.png)', file_name, re.I)
latitude = int(match.groups()[0])
if latitude == 1:
latitude_fixed = 27
elif latitude == 2:
latitude_fixed = 30
elif latitude == 3:
latitude_fixed = 18
elif latitude == 4:
latitude_fixed = 28
elif latitude == 5:
latitude_fixed = 23
else:
latitude_fixed = latitude
longitude = int(match.groups()[4])
longitude_fixed = 360 - longitude
if longitude_fixed == 360:
print("longitude_fixed: ", longitude_fixed)
longitude_fixed = 0
return latitude_fixed, longitude_fixed
##########################################################################################
# ## Set up logging and pre-trained model paths
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# ## Configuration
# Define configurations for training on the car door dataset.
class CarDoorConfig(Config):
"""
Configuration for training on the car door dataset.
Derives from the base Config class and overrides values specific
to the car door dataset.
"""
# Give the configuration a recognizable name
NAME = "car_door"
# Train on 1 GPU and 1 image per GPU. Batch size is 1 (GPUs * images/GPU).
GPU_COUNT = 1
IMAGES_PER_GPU = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 1 # background + 1 (car_door)
# All of our training images are 512x512
IMAGE_MIN_DIM = 378
IMAGE_MAX_DIM = 512
# You can experiment with this number to see if it improves training
STEPS_PER_EPOCH = 500
# This is how often validation is run. If you are using too much hard drive space
# on saved models (in the MODEL_DIR), try making this value larger.
VALIDATION_STEPS = 5
# use resnet101 or resnet50
BACKBONE = 'resnet101'
# To be honest, I haven't taken the time to figure out what these do
RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128)
TRAIN_ROIS_PER_IMAGE = 32
MAX_GT_INSTANCES = 50
PRE_NMS_LIMIT = 6000
POST_NMS_ROIS_INFERENCE = 500
POST_NMS_ROIS_TRAINING = 1000
config = CarDoorConfig()
config.display()
# # Define the dataset
class CarPartsDataset(utils.Dataset):
def load_data(self, annotation_json, images_dir):
""" Load the coco-like dataset from json
Args:
annotation_json: The path to the coco annotations json file
images_dir: The directory holding the images referred to by the json file
"""
# Load json from file
json_file = open(annotation_json)
car_door_json = json.load(json_file)
json_file.close()
# Add the class names using the base method from utils.Dataset
source_name = "car_parts"
for category in car_door_json['categories']:
class_id = category['id']
class_name = category['name']
if class_id < 1:
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(
class_name))
return
self.add_class(source_name, class_id, class_name)
# Get all annotations
annotations = {}
for annotation in car_door_json['annotations']:
image_id = annotation['image_id']
if image_id not in annotations:
annotations[image_id] = []
annotations[image_id].append(annotation)
# Get all images and add them to the dataset
seen_images = {}
for image in car_door_json['images']:
image_id = image['id']
if image_id in seen_images:
print("Warning: Skipping duplicate image id: {}".format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print("Warning: Skipping image (id: {}) with missing key: {}".format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
image_annotations = annotations[image_id]
# Add the image using the base method from utils.Dataset
self.add_image(
source=source_name,
image_id=image_id,
path=image_path,
width=image_width,
height=image_height,
annotations=image_annotations
)
# # Create the Training and Validation Datasets
# In[6]:
dataset_val = CarPartsDataset()
dataset_val.load_data(args["valjson"], args["valdata"])
dataset_val.prepare()
# ## Display a few images from the training dataset
# In[7]:
class InferenceConfig(CarDoorConfig):
GPU_COUNT = 1
IMAGES_PER_GPU = 1
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 512
DETECTION_MIN_CONFIDENCE = 0.85
inference_config = InferenceConfig()
# In[8]:
# Recreate the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=inference_config,
model_dir=MODEL_DIR)
# In[9]:
# Get path to saved weights
# Either set a specific path or find last trained weights
# model_path = os.path.join(ROOT_DIR, ".h5 file name here")
# model_path = model.find_last()
model_path = args["model_m"]
# Load trained weights (fill in path to trained weights here)
assert model_path != "", "Provide path to trained weights"
print("Loading weights from ", model_path)
model.load_weights(model_path, by_name=True)
# # Run Inference
# Run model.detect()
# import skimage
real_test_dir = args["test"]
# '/home/hangwu/CyMePro/data/dataset/test'
# '/home/hangwu/CyMePro/data/test' # '/home/hangwu/CyMePro/data/dataset/test_data'
image_paths = []
for filename in os.listdir(real_test_dir):
if os.path.splitext(filename)[1].lower() in ['.png', '.jpg', '.jpeg', '.JPG']:
image_paths.append(os.path.join(real_test_dir, filename))
# analysis
M_analysis = []
for image_path in image_paths:
img = skimage.io.imread(image_path)
# img = imutils.resize(img, width=360)
if len(img.shape) < 3:
img = gray2rgb(img)
img_arr = np.array(img)
results = model.detect([img_arr], verbose=1)
r = results[0]
image_name = image_path.split(os.path.sep)[-1][:-4]
if len(r['rois']):
# xmin ymin
print('======================================================')
print('{}: '.format(image_name), r['rois'])
xmin = r['rois'][:, 1][0]
ymin = r['rois'][:, 0][0]
xmax = r['rois'][:, 3][0]
ymax = r['rois'][:, 2][0]
xbar = (xmin + xmax) / 2
ybar = (ymin + ymax) / 2
center_of_mask = [xbar, ybar]
print('xmin: {}\nymin: {}\nxmax: {}\nymax: {}'.format(xmin, ymin, xmax, ymax))
print('Center of the Mask: ', center_of_mask)
print('======================================================')
# visualize_car_door.display_instances(img, r['rois'], r['masks'], r['class_ids'],
# dataset_val.class_names, r['scores'], figsize=(5, 5), image_name=image_name)
mask_for_pose = visualize_car_door.mask_to_squares(img, r['masks'], xmin, ymin, xmax, ymax)
# mask_for_pose = visualize_car_door.mask_highlight(img, r['masks'], xmin, ymin, xmax, ymax)
analysis = pose_estimation(mask_for_pose)
M_analysis.append(analysis)
# write into a csv
with open("output.csv", 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Test_Group","Pred_Latitude", "GT_Latitude","Pred_Longitude","GT_Longitude"])
writer.writerows(M_analysis)
<file_sep>import lxml
from lxml import etree
import tensorflow as tf
import cv2
import numpy as np
def recursive_parse_xml_to_dict(xml):
"""Recursively parses XML contents to python dict.
We assume that `object` tags are the only ones that can appear
multiple times at the same level of a tree.
Args:
xml: xml tree obtained by parsing XML file contents using lxml.etree
Returns:
Python dictionary holding XML contents.
"""
# if not xml:
if not len(xml):
return {xml.tag: xml.text}
result = {}
for child in xml:
child_result = recursive_parse_xml_to_dict(child)
if child.tag != 'object':
result[child.tag] = child_result[child.tag]
else:
if child.tag not in result:
result[child.tag] = []
result[child.tag].append(child_result[child.tag])
return {xml.tag: result}
def bndbox_from_xml(xml_path):
with tf.gfile.GFile(xml_path, 'r') as fid:
xml_str = fid.read()
xml = etree.fromstring(xml_str)
xml_dict = recursive_parse_xml_to_dict(xml)
# bndbox_xy = []
bbox = {}
xmin = xml_dict['annotation']['object'][0]['bndbox']['xmin']
ymin = xml_dict['annotation']['object'][0]['bndbox']['ymin']
xmax = xml_dict['annotation']['object'][0]['bndbox']['xmax']
ymax = xml_dict['annotation']['object'][0]['bndbox']['ymax']
# bndbox_xy.append(int(xmin))
# bndbox_xy.append(int(ymin))
# bndbox_xy.append(int(xmax))
# bndbox_xy.append(int(ymax))
file_path = xml_dict['annotation']['path']
bbox['path'] = file_path
bbox['xmin'] = int(xmin)
bbox['ymin'] = int(ymin)
bbox['xmax'] = int(xmax)
bbox['ymax'] = int(ymax)
# print(bndbox_xy)
return bbox
if __name__ == "__main__":
bndbox= bndbox_from_xml('car_door_0_0.xml')
origin_image = cv2.imread(bndbox['path'])
crop_image = origin_image[bndbox['ymin']:bndbox['ymax'], bndbox['xmin']:bndbox['xmax']]
resize_image = cv2.resize(crop_image, (227, 227))
# bbox width and height
img_width = bndbox['xmax'] - bndbox['xmin']
img_heigth = bndbox['ymax'] - bndbox['ymin']
# left or upon part
edge_to_minus = round(abs(img_heigth - img_width) / 2)
if img_width > img_heigth:
long_edge = img_width
edge_to_plus = img_width - img_heigth - edge_to_minus
bndbox['ymin'] -= edge_to_minus
bndbox['ymax'] += edge_to_plus
else:
long_edge = img_heigth
print(long_edge)
edge_to_plus = img_heigth - img_width - edge_to_minus
print(img_width)
print(edge_to_minus)
print(edge_to_plus)
bndbox['xmin'] -= edge_to_minus
bndbox['xmax'] += edge_to_plus
print(bndbox['xmax']-bndbox['xmin'])
print(bndbox['xmax'])
crop_image2 = origin_image[bndbox['ymin']:bndbox['ymax'], bndbox['xmin']:bndbox['xmax']]
resize_image2 = cv2.resize(crop_image2, (227, 227))
print(crop_image2.shape[0])
print(crop_image2.shape[1])
# here is not equal because out of the range of the original image
# for extrem situation can the above method exeed the range
blanck_image = np.zeros((long_edge, long_edge, 3), np.uint8)
cv2.imshow("test2", blanck_image)
for row in range(crop_image.shape[0]):
for col in range(crop_image.shape[1]):
if img_width > img_heigth:
blanck_image[row + edge_to_minus, col] = crop_image[row, col]
else:
blanck_image[row, col + edge_to_minus] = crop_image[row, col]
cv2.imshow("test3", blanck_image)
cv2.imshow('original', origin_image)
cv2.imshow('cropped', crop_image)
cv2.imshow('resized', resize_image)
cv2.imshow('cropped2', crop_image2)
cv2.imshow('resized2', resize_image2)
cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep># Annotation script for 2 car door classes
# Author: <NAME>
# Date: 2019.07.09
import json
from PIL import Image
import numpy as np
from skimage import measure
# from shapely.geometry import Polygon, MultiPolygon
import os
# EIGEN
from load_image import loadim
# Define which colors match which categories in the images
car_door_first_id = 1
car_door_second_id = 2
is_crowd = 0
# Create the annotations
car_door_annotation = {
'info': {
'description': "Car Door Dataset",
'url': "hangwudy.github.io",
'version': '0.1',
'year': 2019,
'contributor': '<NAME>',
'date_created': '2019/07/09',
},
'licenses': [
{
"url": "hangwudy.github.io",
"id": 1,
"name": 'MIT'
}
],
"images": [
{
}
],
"annotations": [
{
}
],
"categories": [
{
"supercategory": "car_parts",
"id": 1,
"name": 'car_door_1'
},
{
"supercategory": "car_parts",
"id": 2,
"name": 'car_door_2'
}
]
}
def create_image_annotation(file_name, height, width, image_id):
images = {
'license': 1,
'file_name': file_name,
'height': height,
'width': width,
'id': image_id
}
return images
def create_sub_mask_annotation(is_crowd, image_id, category_id, annotation_id):
# Find contours (boundary lines) around each sub-mask
# Note: there could be multiple contours if the object
# is partially occluded. (E.g. an elephant behind a tree)
annotation = {
'iscrowd': is_crowd,
'image_id': image_id,
'category_id': category_id,
'id': annotation_id
}
return annotation
def cat_determine(file_name):
if file_name.find("_cat_1_") != -1:
car_cat = car_door_first_id
elif file_name.find("_cat_2_") != -1:
car_cat = car_door_second_id
return car_cat
def images_annotations_info(maskpath):
annotations = []
images = []
mask_images_path = loadim(maskpath)
for id_number, mask_image_path in enumerate(mask_images_path, 1):
file_name = mask_image_path.split(os.path.sep)[-1][:-4]+'.jpg'
mask_image = Image.open(mask_image_path)
category_id = cat_determine(file_name)
# ID number
image_id = id_number
annotation_id = id_number
# image shape
width, height = mask_image.size
# 'images' info
image = create_image_annotation(file_name, height, width, image_id)
images.append(image)
# 'annotations' info
annotation = create_sub_mask_annotation(is_crowd, image_id, category_id, annotation_id)
annotations.append(annotation)
print('{:.2f}% finished.'.format((id_number / len(mask_images_path) * 100)))
return images, annotations
if __name__ == '__main__':
for keyword in ['val']:
mask_path = '/home/hangwu/Repositories/Dataset/dataset/car_door_all/split/mask_{}'.format(keyword)
car_door_annotation['images'], car_door_annotation['annotations'] = images_annotations_info(mask_path)
print(json.dumps(car_door_annotation))
with open('/home/hangwu/Repositories/Dataset/dataset/car_door_all/json/car_door_{}.json'.format(keyword),'w') as outfile:
json.dump(car_door_annotation, outfile)
for keyword in ['train']:
mask_path = '/home/hangwu/Repositories/Dataset/dataset/car_door_all/mask_bw'
car_door_annotation['images'], car_door_annotation['annotations'] = images_annotations_info(mask_path)
print(json.dumps(car_door_annotation))
with open('/home/hangwu/Repositories/Dataset/dataset/car_door_all/json/car_door_{}.json'.format(keyword),'w') as outfile:
json.dump(car_door_annotation, outfile)
<file_sep>"""
Car Door Orientation
@author: <NAME>
@date: 2018.12.05
"""
import os
import random
import numpy as np
import tensorflow as tf
import skimage.io
import skimage.transform
import matplotlib.pyplot as plt
import re
# Eigen
import load_image
def load_img(path):
img = skimage.io.imread(path)[:, :, : 3] # for RGBA
img = img / 255.0
# print "Original Image Shape: ", img.shape
# we crop image from center
short_edge = min(img.shape[:2])
yy = int((img.shape[0] - short_edge) / 2)
xx = int((img.shape[1] - short_edge) / 2)
crop_img = img[yy: yy + short_edge, xx: xx + short_edge]
# resize to 224, 224
resized_img = skimage.transform.resize(crop_img, (224, 224))[None, :, :, :] # shape [1, 224, 224, 3]
return resized_img
def get_car_door_pose_from_filename(file_name):
# car_door_1_125.png ==>> 'car_door', 1, 125
match = re.match(r'([A-Za-z_]+)(_+)([0-9]+)(_+)([0-9]+)(\.png)', file_name, re.I)
class_name = match.groups()[0]
latitude = match.groups()[2]
longitude = match.groups()[4]
# print(class_name, latitude, longitude)
return latitude, longitude
def load_data():
imgs_car_door = {'car_door': [], }
latitude_car_door = []
longitude_car_door = []
counter = 0
for w in imgs_car_door.keys():
image_paths = load_image.loadim('/home/hangwu/Workspace/car_door_half')
for image_path in image_paths:
resized_img = load_img(image_path)
image_name = image_path.split(os.path.sep)[-1]
la_cd, lo_cd = get_car_door_pose_from_filename(image_name)
imgs_car_door[w].append(resized_img)
latitude_car_door.append(la_cd)
longitude_car_door.append(lo_cd)
if counter % 100 == 0:
print("loading {:.2f}%".format(counter/len(image_paths)*100))
counter += 1
return imgs_car_door['car_door'], latitude_car_door, longitude_car_door
class Vgg16:
vgg_mean = [103.939, 116.779, 123.68]
def __init__(self, vgg16_npy_path=None, restore_from=None):
# pre-trained parameters
try:
self.data_dict = np.load(vgg16_npy_path, encoding='latin1').item()
except FileNotFoundError:
print('Please download VGG16 parameters')
self.tfx = tf.placeholder(tf.float32, [None, 224, 224, 3])
# self.tfy = tf.placeholder(tf.float32, [None, 1])
self.tfy_1 = tf.placeholder(tf.float32, [None, 1])
self.tfy_2 = tf.placeholder(tf.float32, [None, 1])
# Convert RGB to BGR
red, green, blue = tf.split(axis=3, num_or_size_splits=3, value=self.tfx * 255.0)
bgr = tf.concat(axis=3, values=[
blue - self.vgg_mean[0],
green - self.vgg_mean[1],
red - self.vgg_mean[2],
])
# pre-trained VGG layers are fixed in fine-tune
conv1_1 = self.conv_layer(bgr, "conv1_1")
conv1_2 = self.conv_layer(conv1_1, "conv1_2")
pool1 = self.max_pool(conv1_2, 'pool1')
conv2_1 = self.conv_layer(pool1, "conv2_1")
conv2_2 = self.conv_layer(conv2_1, "conv2_2")
pool2 = self.max_pool(conv2_2, 'pool2')
conv3_1 = self.conv_layer(pool2, "conv3_1")
conv3_2 = self.conv_layer(conv3_1, "conv3_2")
conv3_3 = self.conv_layer(conv3_2, "conv3_3")
pool3 = self.max_pool(conv3_3, 'pool3')
conv4_1 = self.conv_layer(pool3, "conv4_1")
conv4_2 = self.conv_layer(conv4_1, "conv4_2")
conv4_3 = self.conv_layer(conv4_2, "conv4_3")
pool4 = self.max_pool(conv4_3, 'pool4')
conv5_1 = self.conv_layer(pool4, "conv5_1")
conv5_2 = self.conv_layer(conv5_1, "conv5_2")
conv5_3 = self.conv_layer(conv5_2, "conv5_3")
pool5 = self.max_pool(conv5_3, 'pool5')
# detach original VGG fc layers and
# reconstruct your own fc layers serve for your own purpose
# from now on
# self.flatten = tf.reshape(pool5, [-1, 7*7*512])
# self.fc6 = tf.layers.dense(self.flatten, 256, tf.nn.relu, name='fc6')
# self.out = tf.layers.dense(self.fc6, 1, name='out')
# for latitude
self.flatten = tf.reshape(pool5, [-1, 7*7*512])
self.fc6_1 = tf.layers.dense(self.flatten, 256, tf.nn.relu, name='fc6_1')
self.out_1 = tf.layers.dense(self.fc6_1, 1, name='out_1')
# for longitude
self.flatten = tf.reshape(pool5, [-1, 7*7*512])
self.fc6_2 = tf.layers.dense(self.flatten, 256, tf.nn.relu, name='fc6_2')
self.out_2 = tf.layers.dense(self.fc6_2, 1, name='out_2')
self.sess = tf.Session()
if restore_from:
saver = tf.train.Saver()
saver.restore(self.sess, restore_from)
else: # training graph
# self.loss = tf.losses.mean_squared_error(labels=self.tfy, predictions=self.out)
self.loss_1 = tf.losses.mean_squared_error(labels=self.tfy_1, predictions=self.out_1)
self.loss_2 = tf.losses.mean_squared_error(labels=self.tfy_2, predictions=self.out_2)
self.loss = 0.5*self.loss_1 + 0.5*self.loss_2
self.train_op = tf.train.AdamOptimizer(0.001).minimize(self.loss)
self.sess.run(tf.global_variables_initializer())
def max_pool(self, bottom, name):
return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def conv_layer(self, bottom, name):
with tf.variable_scope(name): # CNN's filter is constant, NOT Variable that can be trained
conv = tf.nn.conv2d(bottom, self.data_dict[name][0], [1, 1, 1, 1], padding='SAME')
lout = tf.nn.relu(tf.nn.bias_add(conv, self.data_dict[name][1]))
return lout
def train(self, x, y_1, y_2):
loss, _ = self.sess.run([self.loss, self.train_op], {self.tfx: x, self.tfy_1: y_1, self.tfy_2: y_2})
return loss
def predict(self, paths):
fig, axs = plt.subplots(1, 4)
for i, path in enumerate(paths):
x = load_img(path)
latitude = self.sess.run(self.out_1, {self.tfx: x})
longitude = self.sess.run(self.out_2, {self.tfx: x})
img_name = path.split(os.path.sep)[-1]
axs[i].imshow(x[0])
axs[i].set_title('Latitude: %d \nLongitude: %d \nName: %s' % (latitude, longitude, img_name))
axs[i].set_xticks(()); axs[i].set_yticks(())
# plt.ion()
plt.show()
def save(self, path='/home/hangwu/Mask_RCNN/logs/door_pose_x_y/car_door_pose'):
saver = tf.train.Saver()
saver.save(self.sess, path, write_meta_graph=False)
def train():
# tigers_x, cats_x, tigers_y, cats_y = load_data()
car_door_x, car_door_y_1, car_door_y_2 = load_data()
xs = np.concatenate(car_door_x, axis=0) # np.concatenate(tigers_x + cats_x, axis=0)
# latitude
ys_1 = np.asarray(car_door_y_1)
ys_1 = ys_1.reshape(len(ys_1), 1)
# print('=========================================================')
# print(ys.shape)
# print('=========================================================')
# longitude
ys_2 = np.asarray(car_door_y_2)
ys_2 = ys_2.reshape(len(ys_2), 1)
vgg = Vgg16(vgg16_npy_path='/home/hangwu/Mask_RCNN/transferlearning/for_transfer_learning/vgg16.npy')
print('Net built')
for i in range(100000):
b_idx = np.random.randint(0, len(xs), 6)
# print('=========================================================')
# print(xs[b_idx], ys[b_idx])
# print('=========================================================')
train_loss = vgg.train(xs[b_idx], ys_1[b_idx], ys_2[b_idx])
if i%100 == 0:
print(i, 'train loss: ', train_loss)
vgg.save('/home/hangwu/Mask_RCNN/logs/door_pose_x_y/car_door_pose') # save learned fc layers
def eval():
vgg = Vgg16(vgg16_npy_path='/home/hangwu/Mask_RCNN/transferlearning/for_transfer_learning/vgg16.npy',
restore_from='/home/hangwu/Mask_RCNN/logs/door_pose_x_y/car_door_pose')
imgs = {'car_door': [], }
for k in imgs.keys():
img_dir = '/home/hangwu/CyMePro/data/car_door'
for file in os.listdir(img_dir):
if not file.lower().endswith('.png'):
continue
try:
img_path = os.path.join(img_dir, file)
except OSError:
continue
imgs[k].append(img_path) # [1, height, width, depth] * n
# print(imgs['car_door'])
# print(random.choice(imgs['car_door']))
image_real = '/home/hangwu/Dropbox/Masterarbeit/Photos/door_pure5.jpg'
vgg.predict(
[random.choice(imgs['car_door']), random.choice(imgs['car_door']),
random.choice(imgs['car_door']), image_real]
)
if __name__ == '__main__':
# image_paths = load_image.loadim('/home/hangwu/CyMePro/data/car_door')
# for image_path in image_paths:
# image_name = image_path.split(os.path.sep)[-1]
# img_shape = load_img(image_path)
# print(img_shape.shape)
# # print(image_name)
# get_car_door_pose_from_filename(image_name)
# train()
eval()
<file_sep>import cv2
import numpy as np
import os
import json
# Label file
json_path = "/home/hangwu/Workspace/annotations/car_door_pose.json"
annotation_json = open(json_path)
annotation_list = json.load(annotation_json)
# Dataset file
img_dataset_path = "/home/hangwu/Workspace/Car_Door"
# save path
save_path = "/home/hangwu/Workspace/car_door_square"
_ = 0
for d in annotation_list['annotations']:
image_name = d.get('image_id')
image_path = os.path.join(img_dataset_path, image_name)
latitude = d.get('latitude')
longitude = d.get('longitude')
# Bounding Box information >>>
xmin = d.get('xmin')
ymin = d.get('ymin')
xmax = d.get('xmax')
ymax = d.get('ymax')
bbox_width = xmax - xmin
bbox_height = ymax - ymin
side_len_diff_half = int(abs(bbox_height - bbox_width) / 2)
image = cv2.imread(image_path)
crop_image = image[ymin:ymax, xmin:xmax]
if bbox_height >= bbox_width:
new_patch = np.zeros((bbox_height, bbox_height ,3), np.uint8)
for row in range(crop_image.shape[0]):
for col in range(crop_image.shape[1]):
new_patch[row, col + side_len_diff_half] = crop_image[row, col]
else:
new_patch = np.zeros((bbox_width, bbox_width ,3), np.uint8)
for row in range(crop_image.shape[0]):
for col in range(crop_image.shape[1]):
new_patch[row + side_len_diff_half, col] = crop_image[row, col]
cv2.imwrite("{}/{}".format(save_path, image_name), new_patch)
if _ % 100 == 0:
print('{:.2f}% finished'.format(_/len(annotation_list['annotations'])*100))
_ += 1
<file_sep># -*- coding: UTF-8 -*-
# 2019/02/13 by <NAME>
import shutil
import os
import re
def loadim(image_path = 'images', ext = 'png', key_word = 'car_door'):
image_list = []
for filename in os.listdir(image_path):
if filename.endswith(ext) and filename.find(key_word) != -1:
current_path = os.path.abspath(image_path)
image_abs_path = os.path.join(current_path,filename)
image_list.append(image_abs_path)
return image_list
def copy_and_rename(original_path, destination_path):
file_name = os.path.split(original_path)[-1]
match = re.match(r'([A-Za-z_]+)(_+)([0-9]+)(_+)([0-9]+)(\.png)', file_name, re.I)
latitude = int(match.groups()[2])
longitude = int(match.groups()[4])
longitude_fixed = longitude - 250
if longitude_fixed < 0:
longitude_fixed += 360
new_name = "car_door_{}_{}.png".format(latitude, longitude_fixed)
new_file_path = os.path.join(destination_path, new_name)
shutil.copy2(original_path, new_file_path)
# print("Original path:", original_path)
# print("New path:", new_file_path)
if longitude_fixed < 0:
print("Something goes wrong!!!!!")
def copy_and_rename_anticlockwise(original_path, destination_path):
file_name = os.path.split(original_path)[-1]
match = re.match(r'([A-Za-z_]+)(_+)([0-9]+)(_+)([0-9]+)(\.png)', file_name, re.I)
latitude = int(match.groups()[2])
longitude = int(match.groups()[4])
longitude_fixed = longitude - 270
if longitude_fixed < 0:
longitude_fixed += 360
longitude_final = 360 - longitude_fixed
latitude_final = 90 - latitude
new_name = "car_door_{}_{}.png".format(latitude_final, longitude_final)
new_file_path = os.path.join(destination_path, new_name)
shutil.copy2(original_path, new_file_path)
# print("Original path:", original_path)
# print("New path:", new_file_path)
if longitude_final < 0:
print("Something goes wrong!!!!!")
if __name__ == "__main__":
dataset_path = "/home/hangwu/Repositories/Dataset/Tuer_2_all"
dest_path = "/home/hangwu/Repositories/Dataset/dataset/car_door_2"
image_list = loadim(image_path=dataset_path)
i = 0
for image_p in image_list:
copy_and_rename_anticlockwise(image_p, dest_path)
i += 1
percentage = round(i/len(image_list)*100, 2)
if i%1000 == 0:
print("{}% finished".format(percentage))
<file_sep># coding: utf-8
# # Mask R-CNN for Car Door Detection
import os
import sys
import json
import numpy as np
import time
import skimage.io
from PIL import Image, ImageDraw
# Set the ROOT_DIR variable to the root directory of the Mask_RCNN git repo
ROOT_DIR = '/home/hangwu/Mask_RCNN'
sys.path.append(ROOT_DIR)
from mrcnn.config import Config
import mrcnn.utils as utils
from mrcnn import visualize_car_door
import mrcnn.model as modellib
# ## Set up logging and pre-trained model paths
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# ## Configuration
# Define configurations for training on the car door dataset.
class CarDoorConfig(Config):
"""
Configuration for training on the car door dataset.
Derives from the base Config class and overrides values specific
to the car door dataset.
"""
# Give the configuration a recognizable name
NAME = "car_door"
# Train on 1 GPU and 1 image per GPU. Batch size is 1 (GPUs * images/GPU).
GPU_COUNT = 1
IMAGES_PER_GPU = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 1 # background + 1 (car_door)
# All of our training images are 512x512
IMAGE_MIN_DIM = 378
IMAGE_MAX_DIM = 512
# You can experiment with this number to see if it improves training
STEPS_PER_EPOCH = 500
# This is how often validation is run. If you are using too much hard drive space
# on saved models (in the MODEL_DIR), try making this value larger.
VALIDATION_STEPS = 5
# use resnet101 or resnet50
BACKBONE = 'resnet101'
# To be honest, I haven't taken the time to figure out what these do
RPN_ANCHOR_SCALES = (16, 32, 64, 128, 256) # (8, 16, 32, 64, 128)
TRAIN_ROIS_PER_IMAGE = 32
MAX_GT_INSTANCES = 50
POST_NMS_ROIS_INFERENCE = 500
POST_NMS_ROIS_TRAINING = 1000
config = CarDoorConfig()
config.display()
# # Define the dataset
# In[5]:
class CarPartsDataset(utils.Dataset):
def load_data(self, annotation_json, images_dir):
""" Load the coco-like dataset from json
Args:
annotation_json: The path to the coco annotations json file
images_dir: The directory holding the images referred to by the json file
"""
# Load json from file
json_file = open(annotation_json)
car_door_json = json.load(json_file)
json_file.close()
# Add the class names using the base method from utils.Dataset
source_name = "car_parts"
for category in car_door_json['categories']:
class_id = category['id']
class_name = category['name']
if class_id < 1:
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(
class_name))
return
self.add_class(source_name, class_id, class_name)
# Get all annotations
annotations = {}
for annotation in car_door_json['annotations']:
image_id = annotation['image_id']
if image_id not in annotations:
annotations[image_id] = []
annotations[image_id].append(annotation)
# Get all images and add them to the dataset
seen_images = {}
for image in car_door_json['images']:
image_id = image['id']
if image_id in seen_images:
print("Warning: Skipping duplicate image id: {}".format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print("Warning: Skipping image (id: {}) with missing key: {}".format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
image_annotations = annotations[image_id]
# Add the image using the base method from utils.Dataset
self.add_image(
source=source_name,
image_id=image_id,
path=image_path,
width=image_width,
height=image_height,
annotations=image_annotations
)
'''
def load_mask(self, image_id):
"""
Load instance masks for the given image.
MaskRCNN expects masks in the form of a bitmap [height, width, instances].
Args:
image_id: The id of the image to load masks for
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# print(image_id) ##
image_info = self.image_info[image_id]
# print(image_info.items()) ##
# print(image_info['path']) ##
mask_name = image_info['path'].split(os.path.sep)[-1][:-4]+'.png' ##
# print(mask_name)
mask_path = os.path.join('/home/hangwu/CyMePro/data/annotations/trimaps_with_window', mask_name)
# print(mask_path)
annotations = image_info['annotations']
instance_masks = []
class_ids = []
mask_with_window = [] ##
mask_ww = [] ##
for annotation in annotations:
class_id = annotation['category_id']
mask = Image.new('1', (image_info['width'], image_info['height']))
mask_draw = ImageDraw.ImageDraw(mask, '1')
for segmentation in annotation['segmentation']:
mask_draw.polygon(segmentation, fill=1)
bool_array = np.array(mask) > 0
instance_masks.append(bool_array)
class_ids.append(class_id)
##
instance_masks_ww = skimage.io.imread(mask_path).astype(np.bool) # #
mask_ww.append(instance_masks_ww)
##
mask = np.dstack(instance_masks)
class_ids = np.array(class_ids, dtype=np.int32)
##
mask_with_window = np.stack(mask_ww, axis = -1)
# print(class_ids)
# print('mask origin: ', mask.shape)
# print('mask with window: ', mask_with_window.shape)
return mask_with_window, class_ids # mask, class_ids
'''
# # Create the Training and Validation Datasets
# In[6]:
# dataset_train = CarPartsDataset()
# dataset_train.load_data('/home/hangwu/CyMePro/botVision/JSON_generator/output/car_door_train.json',
# '/home/hangwu/CyMePro/data/dataset/train_data')
# dataset_train.prepare()
dataset_val = CarPartsDataset()
dataset_val.load_data('/home/hangwu/CyMePro/botVision/JSON_generator/output/car_door_val.json',
'/home/hangwu/CyMePro/data/dataset/val_data')
dataset_val.prepare()
# ## Display a few images from the training dataset
# In[7]:
# dataset = dataset_train
# image_ids = np.random.choice(dataset.image_ids, 4)
# for image_id in image_ids:
# image = dataset.load_image(image_id)
# mask, class_ids = dataset.load_mask(image_id)
# visualize_car_door.display_top_masks(image, mask, class_ids, dataset.class_names)
# # Prepare to run Inference
# Create a new InferenceConfig, then use it to create a new model.
# In[7]:
class InferenceConfig(CarDoorConfig):
GPU_COUNT = 1
IMAGES_PER_GPU = 1
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 512
DETECTION_MIN_CONFIDENCE = 0.85
inference_config = InferenceConfig()
# In[8]:
# Recreate the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=inference_config,
model_dir=MODEL_DIR)
# In[9]:
# Get path to saved weights
# Either set a specific path or find last trained weights
# model_path = os.path.join(ROOT_DIR, ".h5 file name here")
# model_path = model.find_last()
model_path = '/home/hangwu/Mask_RCNN/logs/car_door20181030T1413/mask_rcnn_car_door_0008.h5'
# Load trained weights (fill in path to trained weights here)
assert model_path != "", "Provide path to trained weights"
print("Loading weights from ", model_path)
model.load_weights(model_path, by_name=True)
# # Run Inference
# Run model.detect()
# import skimage
real_test_dir = '/home/hangwu/CyMePro/data/dataset/bwmin'
# "/home/hangwu/CyMePro/data/CachedObjects"
# '/home/hangwu/CyMePro/data/dataset/blackwhite'
# '/home/hangwu/CyMePro/data/test' # '/home/hangwu/CyMePro/data/dataset/test_data'
image_paths = []
for filename in os.listdir(real_test_dir):
if os.path.splitext(filename)[1].lower() in ['.png', '.jpg', '.jpeg', '.JPG']:
image_paths.append(os.path.join(real_test_dir, filename))
image_paths.sort()
for image_path in image_paths:
img = skimage.io.imread(image_path)
img_arr = np.array(img)
results = model.detect([img_arr], verbose=1)
r = results[0]
image_name = image_path.split(os.path.sep)[-1][:-4]
if len(r['rois']):
# xmin ymin
print('======================================================')
print('{}: '.format(image_name), r['rois'])
xmin = r['rois'][:, 1][0]
ymin = r['rois'][:, 0][0]
xmax = r['rois'][:, 3][0]
ymax = r['rois'][:, 2][0]
xbar = (xmin + xmax) / 2
ybar = (ymin + ymax) / 2
center_of_mask = [xbar, ybar]
print('xmin: {}\nymin: {}\nxmax: {}\nymax: {}'.format(xmin, ymin, xmax, ymax))
print('Center of the Mask: ', center_of_mask)
print('======================================================')
visualize_car_door.display_instances(img, r['rois'], r['masks'], r['class_ids'],
dataset_val.class_names, r['scores'], figsize=(5, 5), image_name=image_name)
<file_sep># coding: utf-8
import cv2
import numpy as np
from visualize_cv2_car_door import model, display_instances, class_names
# take the frames from video
capture = cv2.VideoCapture('IMG_5634.MOV')
size = (
int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
)
# Write the video file
codec = cv2.VideoWriter_fourcc(*'DIVX')
output = cv2.VideoWriter('videofile_masked2.avi', codec, 60.0, size)
while capture.isOpened():
# bool, and frame value
ret, frame = capture.read()
if ret:
# add mask to frame
results = model.detect([frame], verbose=0)
r = results[0]
frame = display_instances(
frame, r['rois'], r['masks'], r['class_ids'], class_names, r['scores']
)
output.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
capture.release()
output.release()
cv2.destroyAllWindows()<file_sep># coding: utf-8
# created by <NAME> on 2018.10.07
# feedback: <EMAIL>
import os
def loadim(image_path = '', ext = 'png', key_word = 'car_door'):
image_list = []
for filename in os.listdir(image_path):
if filename.endswith(ext) and filename.find(key_word) != -1:
current_path = os.path.abspath(image_path)
image_abs_path = os.path.join(current_path,filename)
image_list.append(image_abs_path)
return image_list
if __name__ == '__main__':
impath = '../data/car_door'
IMAGE_LIST = loadim(impath)
print(IMAGE_LIST,'\n')
<file_sep># coding: utf-8
# created by <NAME> on 2018.10.07
# feedback: <EMAIL>
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
# Eigen
import load_image
def object_dict(impath, scale):
# initialize the dictionary
bnd_dict = {'folder': 'FOLDER','filename':'NAME', 'path': 'PATH', 'width': 0, 'height': 0, 'depth': 0,
'xmin': 0, 'ymin': 0, 'xmax': 0, 'ymax': 0}
# read the image
img = cv2.imread(impath, -1)
img = cv2.resize(img, (0,0), fx = scale, fy = scale, interpolation = cv2.INTER_CUBIC)
rows, cols, channels = img.shape
# Initialization for the position
xmin = cols
ymin = rows
xmax = 0
ymax = 0
for i in range(rows):
for j in range(cols):
px = img[i,j]
if px[3] !=0:
if ymin > i:
ymin = i
if xmin > j:
xmin = j
if ymax < i:
ymax = i
if xmax < j:
xmax = j
# Bounding box information for .xml
bnd_dict['folder'] = impath.split(os.path.sep)[-2]
bnd_dict['filename'] = impath.split(os.path.sep)[-1]
bnd_dict['path'] = impath
bnd_dict['width'] = cols
bnd_dict['height'] = rows
bnd_dict['depth'] = channels
bnd_dict['xmin'] = xmin
bnd_dict['ymin'] = ymin
bnd_dict['xmax'] = xmax
bnd_dict['ymax'] = ymax
# IMPORTANT: .COPY()
# bnd_position.append(bnd_dict.copy())
return bnd_dict
if __name__ == '__main__':
# test
image_path_list = load_image.loadim('../data/car_door')
for image_path in image_path_list:
bp = object_dict(image_path)
print(bp)<file_sep># coding: utf-8
# # FusionNet for Car Door Detection and Pose Estimation
# @author: <NAME>
# @date: 2018.12.20
import os
import sys
import json
import numpy as np
import skimage.io
import time
import re
# from skimage.transform import resize
from skimage.color import gray2rgb
from keras.preprocessing.image import img_to_array
from keras.models import load_model
import tensorflow as tf
import argparse
import imutils
import pickle
import cv2
# Set the MRCNN_DIR variable to the directory of the Mask_RCNN
MRCNN_DIR = '../../'
sys.path.append(MRCNN_DIR)
from mrcnn.config import Config
import mrcnn.utils as utils
import time
from mrcnn import visualize_car_door
import mrcnn.model as modellib
# ## Set up logging and pre-trained model paths
# Directory to save logs and trained model
MODEL_DIR = os.path.join(MRCNN_DIR, "output")
# AttitudeNet
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-ma", "--model_a",
default="/home/hangwu/Repositories/Model_output/Attitude_CNN/attitude_cnn.h5",
# required=True,
help="path to trained attitude model model")
ap.add_argument("-mm", "--model_m",
default="/home/hangwu/Repositories/Model_output/Mask_RCNN/mask_rcnn_car_door_0250.h5",
# required=True,
help="path to trained Mask R-CNN model model")
ap.add_argument("-la", "--latitudebin",
default="/home/hangwu/Repositories/Model_output/Attitude_CNN/latitude_lb.pickle",
# required=True,
help="path to output latitude label binarizer")
ap.add_argument("-lo", "--longitudebin",
default="/home/hangwu/Repositories/Model_output/Attitude_CNN/longitude_lb.pickle",
# required=True,
help="path to output longitude label binarizer")
ap.add_argument("-r", "--renderings",
default="/home/hangwu/Repositories/Dataset/renderings_square",
# required=True,
help="path to input renderings directory")
ap.add_argument("-vj", "--val_json",
default="/home/hangwu/Repositories/Dataset/annotations/mask_rcnn/car_door_val.json",
# required=True,
help="path to validation data json annotation directory")
ap.add_argument("-vd", "--val_data",
default="/home/hangwu/Repositories/Dataset/val_data",
# required=True,
help="path to validation data directory")
ap.add_argument("-test", "--test",
# default="/media/hangwu/TOSHIBA_EXT/Dataset/test_data",
default="/home/hangwu/Repositories/Dataset/real_car_door/dataset/images",
# required=True,
help="path to test dataset directory")
ap.add_argument("-codebook", "--codebook",
# default="/media/hangwu/TOSHIBA_EXT/Dataset/test_data",
default="/home/hangwu/Repositories/AIBox/annotations/codebook/codebook.json",
# required=True,
help="path to code book directory")
args = vars(ap.parse_args())
# load the trained convolutional neural network from disk, followed
# by the latitude and longitude label binarizers, respectively
print("[INFO] loading network...")
model_attitude = load_model(args["model_a"], custom_objects={"tf": tf})
latitudeLB = pickle.loads(open(args["latitudebin"], "rb").read())
longitudeLB = pickle.loads(open(args["longitudebin"], "rb").read())
def loadim(image_path='Car_Door', ext='png', key_word='car_door'):
image_list = []
for filename in os.listdir(image_path):
if filename.endswith(ext) and filename.find(key_word) != -1:
current_path = os.path.abspath(image_path)
image_abs_path = os.path.join(current_path, filename)
image_list.append(image_abs_path)
return image_list
# Pose Estimation
# focal length (in terms of pixel) predefinition:
fx_t = 750 # [pixels]
fy_t = 735 # [pixels]
fx_r = 2943.6 # [pixels]
fy_r = 2935.5 # [pixels]
z_r = 1500 # [mm]
def get_diagonal_len(pitch, jaw, code_book):
"""get the diagonal length of the bounding box through Codebook
"""
with open(code_book) as cb:
json_data = json.load(cb)
# Codebook format: {"<latitude_1>": {"<longitude_1>": [<width_1>, <height_1>, <diagonal_length_1>]}}
diagonal_length = json_data[pitch][jaw]
return diagonal_length
def f_diagonal_calculation(d, w, h, f_x, f_y):
"""d represents the diagonal length of the bounding box,
w represents the width, and h represents the height.
"""
f_diagonal = d / np.sqrt(np.power(w/f_x, 2) + np.power(h/f_y, 2))
return f_diagonal
def distance_calculation(bbox_t,fx_t,fy_t,pitch,jaw,fx_r,fy_r,z_r):
"""d represents the diagonal length of the bounding box,
w represents the width, and h represents the height.
"""
# Unity virtual camera
# get bbox size
len_diagonal = get_diagonal_len(pitch, jaw, args["codebook"])
# width
w_r = len_diagonal[0]
# height
h_r = len_diagonal[1]
# diagonal
d_r = len_diagonal[2]
# f_diagonal calculation
f_diagonal_r = f_diagonal_calculation(d_r, w_r, h_r, fx_r, fy_r)
# real camera
w_t = bbox_t[0]
h_t = bbox_t[1]
d_t = bbox_t[2]
f_diagonal_t = f_diagonal_calculation(d_t, w_t, h_t, fx_t, fy_t)
# Distance Calculation
distance_z = z_r * f_diagonal_t / f_diagonal_r * d_r /d_t
print("==============================================")
print("estimated distance: {}".format(distance_z))
print("==============================================")
return distance_z
def pose_estimation(image, real_longitude, image_name, bbox_info):
output = imutils.resize(image, width=1000)
# cv2.imwrite(
# "/home/wu/CyMePro/Object_Detection/PoseNet/new_training_set/Results_{}_{}.png".format(image_name, time.time()),
# output)
# pre-process the image for classification
image = cv2.resize(image, (224, 224))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
# classify the input image using Keras' multi-output functionality
print("[INFO] classifying image...")
(latitudeProba, longitudeProba) = model_attitude.predict(image)
# find indexes of both the latitude and longitude outputs with the
# largest probabilities, then determine the corresponding class
# labels
latitudeIdx = latitudeProba[0].argmax()
longitudeIdx = longitudeProba[0].argmax()
latitudeLabel = latitudeLB.classes_[latitudeIdx]
longitudeLabel = longitudeLB.classes_[longitudeIdx]
# draw the latitude label and longitude label on the image
latitudeText = "latitude: {} ({:.2f}%)".format(latitudeLabel,
latitudeProba[0][latitudeIdx] * 100)
longitudeText = "longitude: {} ({:.2f}%)".format(longitudeLabel,
longitudeProba[0][longitudeIdx] * 100)
# real_longitudeText = "GT longitude: {}".format(real_longitude)
cv2.putText(output, latitudeText, (10, 25), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2)
cv2.putText(output, longitudeText, (10, 55), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2)
# cv2.putText(output, str(real_longitudeText), (10, 85), cv2.FONT_HERSHEY_SIMPLEX,
# 0.7, (0, 255, 0), 2)
# display the predictions to the terminal as well
print("[INFO] {}".format(latitudeText))
print("[INFO] {}".format(longitudeText))
# show the output image
# cv2.imshow("Output", output)
image_compare_name = 'car_door_{}_{}.png'.format(latitudeLabel, longitudeLabel)
image_compare_path = os.path.join(args["renderings"], image_compare_name)
print(image_compare_path)
image_compare = cv2.imread(image_compare_path)
image_compare = imutils.resize(image_compare, width=1000)
print(output.shape[0])
_ = output.shape[0]
if not _ == 1000:
print(output.shape)
output = cv2.resize(output, (1000, 1000))
print(image_compare.shape[0])
_ = image_compare.shape[0]
if not _ == 1000:
print(image_compare.shape)
image_compare = cv2.resize(image_compare, (1000, 1000))
try:
image_horizontal = np.hstack((output, image_compare))
cv2.imwrite("/home/hangwu/Repositories/Dataset/tmp/Results_{}_{:4.2f}.png".format(image_name, time.time()),
image_horizontal)
# cv2.imshow("Comparison", image_horizontal)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
except:
print("axis not match")
print(output.shape)
print(image_compare.shape)
# cv2.imshow("Detection", output)
# cv2.imshow("Comparison", image_compare)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
try:
# Distance Computing
distance_calculation(bbox_info,fx_t,fy_t,str(latitudeLabel),str(longitudeLabel),fx_r,fy_r,z_r)
except:
print("distance calculation failed!")
# ## Configuration
# Define configurations for training on the car door dataset.
class CarDoorConfig(Config):
"""
Configuration for training on the car door dataset.
Derives from the base Config class and overrides values specific
to the car door dataset.
"""
# Give the configuration a recognizable name
NAME = "car_door"
# Train on 1 GPU and 1 image per GPU. Batch size is 1 (GPUs * images/GPU).
GPU_COUNT = 1
IMAGES_PER_GPU = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 1 # background + 1 (car_door)
# All of our training images are 1008x756
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 512
# You can experiment with this number to see if it improves training
STEPS_PER_EPOCH = 500
# This is how often validation is run. If you are using too much hard drive space
# on saved models (in the MODEL_DIR), try making this value larger.
VALIDATION_STEPS = 5
# use resnet101 or resnet50
BACKBONE = 'resnet101'
# big object
RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128)
TRAIN_ROIS_PER_IMAGE = 32
MAX_GT_INSTANCES = 10
POST_NMS_ROIS_INFERENCE = 500
POST_NMS_ROIS_TRAINING = 1000
config = CarDoorConfig()
config.display()
# # Define the dataset
class CarPartsDataset(utils.Dataset):
def load_data(self, annotation_json, images_dir):
""" Load the coco-like dataset from json
Args:
annotation_json: The path to the coco annotations json file
images_dir: The directory holding the images referred to by the json file
"""
# Load json from file
json_file = open(annotation_json)
car_door_json = json.load(json_file)
json_file.close()
# Add the class names using the base method from utils.Dataset
source_name = "car_parts"
for category in car_door_json['categories']:
class_id = category['id']
class_name = category['name']
if class_id < 1:
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(
class_name))
return
self.add_class(source_name, class_id, class_name)
# Get all annotations
annotations = {}
for annotation in car_door_json['annotations']:
image_id = annotation['image_id']
if image_id not in annotations:
annotations[image_id] = []
annotations[image_id].append(annotation)
# Get all images and add them to the dataset
seen_images = {}
for image in car_door_json['images']:
image_id = image['id']
if image_id in seen_images:
print("Warning: Skipping duplicate image id: {}".format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print("Warning: Skipping image (id: {}) with missing key: {}".format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
image_annotations = annotations[image_id]
# Add the image using the base method from utils.Dataset
self.add_image(
source=source_name,
image_id=image_id,
path=image_path,
width=image_width,
height=image_height,
annotations=image_annotations
)
# # Create the Training and Validation Datasets
dataset_val = CarPartsDataset()
dataset_val.load_data(args["val_json"], args["val_data"])
dataset_val.prepare()
# ## Display a few images from the training dataset
class InferenceConfig(CarDoorConfig):
GPU_COUNT = 1
IMAGES_PER_GPU = 1
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 512
DETECTION_MIN_CONFIDENCE = 0.90
inference_config = InferenceConfig()
# Recreate the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=inference_config,
model_dir=MODEL_DIR)
# Get path to saved weights
# Either set a specific path or find last trained weights
# model_path = os.path.join(MRCNN_DIR, ".h5 file name here")
# model_path = model.find_last()
model_path = args["model_m"]
# Load trained weights (fill in path to trained weights here)
assert model_path != "", "Provide path to trained weights"
print("Loading weights from ", model_path)
model.load_weights(model_path, by_name=True)
# # Run Inference
# Run model.detect()
# import skimage
real_test_dir = args["test"]
image_paths = []
for filename in os.listdir(real_test_dir):
if os.path.splitext(filename)[1].lower() in ['.png', '.jpg', '.jpeg', '.JPG']:
image_paths.append(os.path.join(real_test_dir, filename))
for image_path in image_paths:
img = skimage.io.imread(image_path)
# img = imutils.resize(img, width=360)
if len(img.shape) < 3:
img = gray2rgb(img)
img_arr = np.array(img)
results = model.detect([img_arr], verbose=1)
r = results[0]
image_name = image_path.split(os.path.sep)[-1][:-4]
if len(r['rois']):
# xmin ymin
print('======================================================')
match = re.match(r'([0-9]+)(_+)([0-9]+)(_+)([0-9]+)', image_name, re.I)
first_element = match.groups()[0]
if first_element.isdigit():
real_longitude = 360 - int(match.groups()[4])
print('test image name: {} ==> Bounding box coordinates '.format(image_name), r['rois'])
xmin = r['rois'][:, 1][0]
ymin = r['rois'][:, 0][0]
xmax = r['rois'][:, 3][0]
ymax = r['rois'][:, 2][0]
xbar = (xmin + xmax) / 2
ybar = (ymin + ymax) / 2
center_of_mask = [xbar, ybar]
# Distance Calculation
bbox_width = xmax - xmin
bbox_height = ymax - ymin
bbox_diagonal = np.sqrt(np.power(bbox_width, 2) + np.power(bbox_height, 2))
# detected bounding box size
bbox_t = [bbox_width, bbox_height, bbox_diagonal]
image_center_x = img.shape[1]/2
image_center_y = img.shape[0]/2
center_of_image = [image_center_x, image_center_y]
print('Center of the image: ', center_of_image)
# "a" length
pixel_delta_u = image_center_x - xbar
# "b" length
pixel_delta_v = image_center_y - ybar
print("a: {} pixel; b: {} pixel.".format(pixel_delta_u, pixel_delta_v))
print('xmin: {}\nymin: {}\nxmax: {}\nymax: {}'.format(xmin, ymin, xmax, ymax))
print('Center of the Mask: ', center_of_mask)
print('======================================================')
visualize_car_door.display_instances(img, r['rois'], r['masks'], r['class_ids'],
dataset_val.class_names, r['scores'], figsize=(5, 5), image_name=image_name)
visualize_car_door.mask_to_squares(img, r['masks'], xmin, ymin, xmax, ymax)
mask_for_pose = visualize_car_door.mask_to_squares(img, r['masks'], xmin, ymin, xmax, ymax)
pose_estimation(mask_for_pose, real_longitude, image_name, bbox_t)
<file_sep># -*- coding: UTF-8 -*-
# 2018/10/26 by <NAME>
import numpy
import os
import random
import shutil
# get image absolut path
def loadim(image_path = 'images', ext = 'jpg', key_word = 'car_door'):
image_list = []
for filename in os.listdir(image_path):
if filename.endswith(ext) and filename.find(key_word) != -1:
current_path = os.path.abspath(image_path)
image_abs_path = os.path.join(current_path,filename)
image_list.append(image_abs_path)
return image_list
# Path
# Images
Main_Dataset_Path='/home/hangwu/Repositories/Dataset/dataset/car_door_all/image'
# Train_Dataset_Path='/home/wu/CyMePro/Dataset/train_data'
Val_Dataset_Path='/home/hangwu/Repositories/Dataset/dataset/car_door_all/split/image_val'
Test_Dataset_Path='/home/hangwu/Repositories/Dataset/dataset/car_door_all/split/image_test'
img_path_dict = {
'Main': Main_Dataset_Path,
# 'Train': Train_Dataset_Path,
'Val': Val_Dataset_Path,
'Test': Test_Dataset_Path
}
# Solid Masks
# Main_Mask_Path='/home/wu/CyMePro/Dataset/annotations/solid_masks'
# Train_Mask_Path='/home/wu/CyMePro/Dataset/annotations/train_solid_mask'
# Val_Mask_Path='/home/wu/CyMePro/Dataset/annotations/val_solid_mask'
# Test_Mask_Path='/home/wu/CyMePro/Dataset/annotations/test_solid_mask'
# mask_path_dict = {
# 'Main': Main_Mask_Path,
# 'Train': Train_Mask_Path,
# 'Val': Val_Mask_Path,
# 'Test': Test_Mask_Path
# }
# Masks
Main_Mask_ww_Path='/home/hangwu/Repositories/Dataset/dataset/car_door_all/mask_bw'
# Train_Mask_ww_Path='/home/wu/CyMePro/Dataset/annotations/train_mask'
Val_Mask_ww_Path='/home/hangwu/Repositories/Dataset/dataset/car_door_all/split/mask_val'
Test_Mask_ww_Path='/home/hangwu/Repositories/Dataset/dataset/car_door_all/split/mask_test'
mask_ww_path_dict = {
'Main': Main_Mask_ww_Path,
# 'Train': Train_Mask_ww_Path,
'Val': Val_Mask_ww_Path,
'Test': Test_Mask_ww_Path
}
# XMLs
# Main_XML_Path='/home/wu/CyMePro/Dataset/annotations/xmls'
# Train_XML_Path='/home/wu/CyMePro/Dataset/annotations/train_xml'
# Val_XML_Path='/home/wu/CyMePro/Dataset/annotations/val_xml'
# Test_XML_Path='/home/wu/CyMePro/Dataset/annotations/test_xml'
# xml_path_dict = {
# 'Main': Main_XML_Path,
# 'Train': Train_XML_Path,
# 'Val': Val_XML_Path,
# 'Test': Test_XML_Path
# }
# training portion
TrainR=0.7
# validating portion
ValR=0.2
# total num
PreImNum=100
fileIdLen=6
# image id set
ImIdSet=loadim(Main_Dataset_Path)
# print(ImIdSet)
# shuffle the list
random.shuffle(ImIdSet)
ImNum=len(ImIdSet)
# training number
TrainNum=int(TrainR*ImNum)
# validating number
ValNum=int(ValR*ImNum)
# get the first TrainNum data
TrainImId=ImIdSet[:TrainNum-1]
TrainImId.sort()
# get the val data
ValImId=ImIdSet[TrainNum:TrainNum+ValNum-1]
ValImId.sort()
# train + val = trainval
TrainValImId=list(set(TrainImId).union(set(ValImId)))
TrainValImId.sort()
# get the test
TestImId=(list(set(ImIdSet).difference(set(TrainValImId))))
TestImId.sort()
# combine the sets in dictionary
TrainValTestIds={}
# TrainValTestIds['Train']=TrainImId
TrainValTestIds['Val']=ValImId
# TrainValTestIds['trainval']=TrainValImId
TrainValTestIds['Test']=TestImId
print(TrainValTestIds.keys())
for key in TrainValTestIds.keys():
# print(key)
for value in TrainValTestIds[key]:
# print(value)
# file name
file_name_without_ext = value.split(os.path.sep)[-1][:-4]
# images
img_dest_path = img_path_dict[key]
img_dest_file = os.path.join(img_dest_path, file_name_without_ext+'.jpg')
shutil.copy2(value, img_dest_file)
# solid masks
# mask_origin_path = mask_path_dict['Main']
# mask_origin_file = os.path.join(mask_origin_path, file_name_without_ext+'.png')
# mask_dest_path = mask_path_dict[key]
# mask_dest_file = os.path.join(mask_dest_path, file_name_without_ext+'.png')
# shutil.copy2(mask_origin_file, mask_dest_file)
# masks
mask_ww_origin_path = mask_ww_path_dict['Main']
mask_ww_origin_file = os.path.join(mask_ww_origin_path, file_name_without_ext+'.png')
mask_ww_dest_path = mask_ww_path_dict[key]
mask_ww_dest_file = os.path.join(mask_ww_dest_path, file_name_without_ext+'.png')
shutil.copy2(mask_ww_origin_file, mask_ww_dest_file)
# XMLs
# xml_origin_path = xml_path_dict['Main']
# xml_origin_file = os.path.join(xml_origin_path, file_name_without_ext+'.xml')
# xml_dest_path = xml_path_dict[key]
# xml_dest_file = os.path.join(xml_dest_path, file_name_without_ext+'.xml')
# shutil.copy2(xml_origin_file, xml_dest_file)
|
79eec9f4b1dac6c085dd3783854b98d0c6c9769c
|
[
"Markdown",
"Python"
] | 23 |
Python
|
hangwudy/Mask_RCNN
|
8b5d896076b994e2f9136054114c551a8cb3119f
|
c9b5efa0307a73dd5178988981f67762eab5ae36
|
refs/heads/master
|
<file_sep>export default [
{
id: "1",
title: "<NAME>: Preparados con los mejores ingredientes, calidad y frescura.",
price: 8.50,
offerPrice: 10.00,
stock: 12,
img: "ceviche.jpg",
category: "frescos",
},
{
id: "2",
title: "<NAME>:
<div>"Deliciosos ingredientes"</div>,
price: 15.99,
offerPrice: 13.99,
stock: 12,
img: "baby.jpg",
category: "vegetable",
},
{
id: "3",
title: "abciquam feugiat beans",
price: 4.88,
offerPrice: null,
stock: 12,
img: "beans.jpg",
category: "vegetable",
},
{
id: "4",
title: "Lorem am beans dui non",
price: 1.88,
offerPrice: null,
stock: 12,
img: "beans2.jpg",
category: "vegetable",
},
{
id: "5",
title: "Berry es feugiat mollis",
price: 2.3,
offerPrice: null,
stock: 12,
img: "berry.jpg",
category: "fruits",
},
{
id: "6",
title: "berry feugiat dui non mollis",
price: 2.22,
offerPrice: null,
stock: 12,
img: "berry2.jpg",
category: "fruits",
},
{
id: "7",
title: "brussels feugiat dui non mollis",
price: 2.88,
offerPrice: null,
stock: 12,
img: "brussels.jpg",
category: "vegetable",
},
{
id: "8",
title: "carrot feugiat dui non mollis",
price: 3.88,
offerPrice: null,
stock: 12,
img: "carrot.jpg",
category: "vegetable",
},
{
id: "9",
title: "celery feugiat dui non mollis",
price: 5.88,
offerPrice: null,
stock: 12,
img: "celery.jpg",
category: "vegetable",
},
{
id: "11",
title: "cherry feugiat dui non mollis",
price: 7.88,
offerPrice: 6.88,
stock: 12,
img: "cherry.jpg",
category: "fruits",
},
{
id: "22",
title: "chicken feugiat dui non mollis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "chicken.jpg",
category: "meat",
},
{
id: "33",
title: "Aliquam feugiat non chicken",
price: 8.88,
offerPrice: null,
stock: 12,
img: "chicken2.jpg",
category: "meat",
},
{
id: "44",
title: "clemen feugiat dui",
price: 4.99,
offerPrice: null,
stock: 12,
img: "clemen.jpg",
category: "fruits",
},
{
id: "55",
title: "cod feugiat dui non",
price: 9.88,
offerPrice: null,
stock: 12,
img: "cod.jpg",
category: "meat",
},
{
id: "66",
title: "corn feugiat non mollis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "corn.jpg",
category: "vegetable",
},
{
id: "77",
title: "cucumber feugiat dui non",
price: 4.88,
offerPrice: 2.5,
stock: 12,
img: "cucumber.jpg",
category: "vegetable",
},
{
id: "88",
title: "dates feugiat non duilis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "dates.jpg",
category: "fruits",
},
{
id: "99",
title: "fresh fish feugiat dui",
price: 4.88,
offerPrice: null,
stock: 12,
img: "fish.jpg",
category: "meat",
},
{
id: "00",
title: "fish lorem ipsum",
price: 4.88,
offerPrice: null,
stock: 12,
img: "fish2.jpg",
category: "meat",
},
{
id: "111",
title: "fish non mollis feugiat dui",
price: 4.88,
offerPrice: 3.25,
stock: 12,
img: "fish3.jpg",
category: "meat",
},
{
id: "222",
title: "lemon non mollis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "lemon.jpg",
category: "fuits",
},
{
id: "333",
title: "Aliquam lime dui non mollis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "lime.jpg",
category: "fruits",
},
{
id: "444",
title: "Aliquam mango dui non",
price: 4.88,
offerPrice: null,
stock: 12,
img: "mango.jpg",
category: "fruits",
},
{
id: "555",
title: "Aliquam meat dui non mollis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "meat.jpg",
category: "meat",
},
{
id: "666",
title: "meat feugiat dui non mollis",
price: 4.88,
offerPrice: 4.0,
stock: 12,
img: "meat2.jpg",
category: "meat",
},
{
id: "777",
title: "Aliquam feugiat dui non meat",
price: 4.88,
offerPrice: null,
stock: 12,
img: "meat3.jpg",
category: "meat",
},
{
id: "888",
title: "mix vegetables feugiat dui non mollis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "mix.jpg",
category: "vegetable",
},
{
id: "999",
title: "pears feugiat dui non mollis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "pears.jpg",
category: "fruits",
},
{
id: "000",
title: "Aliquam pepper dui non mollis",
price: 4.88,
offerPrice: 3.99,
stock: 12,
img: "pepper.jpg",
category: "vegetable",
},
{
id: "1111",
title: "Aliquam salmon dui non mollis",
price: 4.88,
offerPrice: null,
stock: 12,
img: "salmon.jpg",
category: "meat",
},
{
id: "bread1",
title: "Sprouts Classic Seedsational Bread 14 oz",
price: 2.25,
offerPrice: null,
stock: 12,
img: "bread.jpg",
category: "bakery",
},
{
id: "bread2",
title: "Traditional Corn Special Bread",
price: 1.75,
offerPrice: null,
stock: 12,
img: "bread2.jpg",
category: "bakery",
},
{
id: "bread3",
title: "Sprouts Classic Seedsational Bread",
price: 2.25,
offerPrice: null,
stock: 12,
img: "bread3.jpg",
category: "bakery",
},
{
id: "toast",
title: "Oven Baked Garlic & Cheese Toast",
price: 1.7,
offerPrice: null,
stock: 12,
img: "toast.jpg",
category: "bakery",
},
{
id: "toast2",
title: "Oven Baked Italian Herb with Olive Oil Toast",
price: 2.25,
offerPrice: null,
stock: 12,
img: "toast2.jpg",
category: "bakery",
},
{
id: "cookies",
title: "Raspberry Crumble Cookies",
price: 2.25,
offerPrice: null,
stock: 12,
img: "cookies.jpg",
category: "bakery",
},
{
id: "cookies2",
title: "Chocolate Chip Cookies",
price: 3.0,
offerPrice: null,
stock: 12,
img: "cookies2.jpg",
category: "bakery",
},
{
id: "cookies3",
title: "Freshly Baked Chocolate Chip Cookie",
price: 2.5,
offerPrice: null,
stock: 12,
img: "cookies3.jpg",
category: "bakery",
},
{
id: "muffin",
title: "Thomas Cinnamon Raisin English Muffins",
price: 2.25,
offerPrice: null,
stock: 12,
img: "muffin.jpg",
category: "bakery",
},
{
id: "muffin2",
title: "Mini Zucchini & Carrot Muffin",
price: 2.25,
offerPrice: null,
stock: 12,
img: "muffin2.jpg",
category: "bakery",
},
{
id: "muffin3",
title: "Double Chocolate Oat Muffin ",
price: 2.25,
offerPrice: null,
stock: 12,
img: "muffin3.jpg",
category: "bakery",
},
{
id: "tea",
title: "Freshly Brewed Organic Green Tea",
price: 0.75,
offerPrice: null,
stock: 12,
img: "tea.jpg",
category: "drink",
},
{
id: "coffe",
title: "Fresh Grinded Frappé coffee",
price: 1.5,
offerPrice: null,
stock: 12,
img: "coffe.jpg",
category: "drink",
},
{
id: "coffe2",
title: "Caffee Nero Mocha Late",
price: 1.8,
offerPrice: null,
stock: 12,
img: "coffe2.jpg",
category: "drink",
},
{
id: "coffe3",
title: "Nescafe Clasico Instant Coffee",
price: 2.2,
offerPrice: null,
stock: 12,
img: "coffe3.jpg",
category: "drink",
},
{
id: "coffe4",
title: "Peet Coffee Decaf Major Dickason Blend",
price: 2.4,
offerPrice: 2.1,
stock: 12,
img: "coffe4.jpg",
category: "drink",
},
];
<file_sep>import fetch from "isomorphic-unfetch";
import { nanoid } from "nanoid";
//fetcher
export const fetcher = (url) => fetch(url).then((r) => r.json());
export const getFormValidations = () => {
return {
//name
name: {
required: {
value: true,
message: "Name is required",
},
maxLength: {
value: 20,
message: "Max Length 20 chars",
},
minLength: {
value: 5,
message: "Min Length 5 chars",
},
pattern: {
value: /^[A-Za-z ]{5,20}$/,
message: "Icorrect Name",
},
},
//phone
phone: {
required: {
value: true,
message: "Phone is required",
},
maxLength: {
value: 20,
message: "Max Length 20 chars",
},
minLength: {
value: 5,
message: "Min Length 5 chars",
},
pattern: {
value: /^[0-9]{5,20}$/,
message: "Icorrect Phone",
},
},
//address
address: {
required: {
value: true,
message: "Address is required",
},
maxLength: {
value: 20,
message: "Max Length 20 chars",
},
minLength: {
value: 5,
message: "Min Length 5 chars",
},
pattern: {
value: /^[0-9a-zA-Z ]{5,20}$/,
message: "Icorrect Address",
},
},
//city
city: {
required: {
value: true,
message: "City is required",
},
},
//schedule
schedule: {
required: {
value: true,
message: "Schedule is required",
},
},
//extra comment
comment: {
maxLength: {
value: 25,
message: "Max Length 25 chars",
},
},
};
};
//wsp url creator
export function getWspUrl(orderData) {
const N = process.env.NEXT_PUBLIC_MY_PHONE_NUMBER;
const ID = nanoid(8);
const { cartItems, subTotal, withDelivery, shippingCost, total, formData } = orderData;
const { name, phone, address, city, schedule, comment } = formData;
let cartListforUrl = "";
{
Object.values(cartItems).forEach((item) => {
const itemTotal = (item.offerPrice ? item.offerPrice * item.qty : item.price * item.qty).toFixed(2);
cartListforUrl += `%0A%0A - *(${item.qty})* ${item.title} --> _*$${itemTotal}*_`;
});
}
const WSP_URL = `https://api.whatsapp.com/send/?phone=${N}&text=%2A${"Order"}%3A%2A%20${ID}%0A%0A%2A${"Client"}%3A%2A%20${name}%0A%0A%2A${"Phone"}%3A%2A%20${phone}%0A%0A%2A${
withDelivery ? "Address" + "%3A%2A%20" + address + " %0A%0A%2A" : ""
}${withDelivery ? "City" + "%3A%2A%20" + city + "%0A%0A%2A" : ""}${
withDelivery ? "Schedule" + "%3A%2A%20" + schedule + "%0A%0A%2A" : ""
}${comment ? "Comment" + "%3A%2A%20" + comment + "%0A%0A%2A" : ""}${"Items List"}%3A%2A${cartListforUrl}%0A%0A%2A${
withDelivery ? "Sub Total" + "%3A%2A%20$" + subTotal + " %0A%0A%2A" : ""
}${withDelivery ? "Delivery Fee" + "%3A%2A%20$" + shippingCost + " %0A%0A%2A" : ""}${"Total"}%3A%2A%20${total}%0A%0A`;
return WSP_URL;
}
|
875111c7d0d5583c08ef151fdd3f0bab9361adf4
|
[
"JavaScript"
] | 2 |
JavaScript
|
S4ck/store
|
4a84ceae536df5aba8ba92fc4a63a2c5abf0ef41
|
365bcda4438c5aa4d917f300fecd3b45e1a42ae3
|
refs/heads/master
|
<repo_name>MichalVysin/HW_1_7<file_sep>/src/com/company/Group.java
package com.company;
public enum Group {
FAMILY ("Rodina"), WORK ("Práce"), OTHER ("Ostatní");
private final String description;
Group(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
<file_sep>/README.md
# Homework 1_7
Homework for Engeto
Java 1 - Lesson 7
Za domácí úkol vytvořte jednoduchou aplikaci reprezentující telefonní seznam. Nejprve si vytvořte několik záznamů typu Kontakt, který obsahuje:
Telefonní číslo
Jméno
Příjmení
Kategorii (RODINA, PRACE, OSTATNI)
Telefonní číslo Jméno Příjmení Kategorie
+420602111222 Jan Novak PRACE
+420212342143 Tomas Zeleny PRACE
+420602222345 Jana Novakova OSTATNI
+420602553233 Sef PRACE
+420612533434 Rodice - pevna RODINA
Vytvořte program, který bude mít následující metody:
Na základě celého telefonního čísla vyhledá Kontakt
Na základě jména nebo příjmení najde seznam záznamů
Na základě části telefonního čísla najde seznam záznamů, které obsahuje onu část telefonního čísla
|
95d92109337ed784a65da6ce3f7ab4394722f633
|
[
"Markdown",
"Java"
] | 2 |
Java
|
MichalVysin/HW_1_7
|
6a28b89e2909989c4a8aebeda83ad33a13ebd80c
|
4e212211f7f79ed61993d415834e03f84a4ac370
|
refs/heads/master
|
<file_sep>// () The League of Amazing Programmers 2013-2017
// Level 0
package _02_crazy_cat_lady;
import java.net.URI;
import javax.swing.JOptionPane;
public class CrazyCatLady {
public static void main(String[] args) {
// 1. Ask the user how many cats they have
String cats=JOptionPane.showInputDialog("How many cats do you have?");
// 2. Convert their answer into an int
int vari=Integer.parseInt(cats);
// 3. If they have 3 or more cats, tell them they are a crazy cat lady
if (vari>3) {
JOptionPane.showMessageDialog(null, "You're a crazy cat lady");
}
// 4. If they have less than 3 cats AND more than 0 cats, call the method below to show them a cat video
else if (vari<3 && vari>0) {
playVideo("https://www.youtube.com/watch?v=d7M_K62Evnk0");
}
else {
playVideo("https://www.youtube.com/watch?v=ZJT9CeEhM10");
}
// 5. If they have 0 cats, show them a video of A Frog Sitting on a Bench Like a Human
}
static void playVideo(String videoURL) {
try {
URI uri = new URI(videoURL);
java.awt.Desktop.getDesktop().browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>// Copyright (c) The League of Amazing Programmers 2013-2017
// Level 0
package _01_robot_color_chooser;
import javax.swing.JOptionPane;
import java.awt.Color;
import org.jointheleague.graphical.robot.Robot;
public class RobotColorChooser {
public static void main(String[] args) {
//1. Create a new Robot
Robot eee= new Robot();
eee.penDown();
eee.moveTo(900, 600);
//3. Ask the user what color they would like the robot to draw
for (int i = 0; i < 23; i++) {
String z=JOptionPane.showInputDialog("What color do you want. Red, Orange, yellow, green, blue, pink, gray, cyan, or magenta?");
//5. Use an if/else statement to set the pen color that the user requested
if(z.equals("red")) {
eee.setPenColor(Color.red);
}
else if(z.equals("orange")) {
eee.setPenColor(Color.orange);
}
else if(z.equals("yellow")) {
eee.setPenColor(Color.yellow);
}
else if(z.equals("green")) {
eee.setPenColor(Color.green);
}
else if(z.equals("blue")) {
eee.setPenColor(Color.blue);
}
else if(z.equals("pink")) {
eee.setPenColor(Color.pink);
}
else if(z.equals("gray")) {
eee.setPenColor(Color.gray);
}
else if(z.equals("cyan")) {
eee.setPenColor(Color.cyan);
}
else if(z.equals("magenta")) {
eee.setPenColor(Color.magenta);
}
//6. If the user doesn’t enter anything, choose a random color
else {
eee.setRandomPenColor();
}
//7. Put a loop around your code so that you keep asking the user for more colors & drawing them
//4. Set the pen width to 10
eee.setPenWidth(10);
//2. Make the robot draw a shape (this will take more than one line of code)
for (int uop = 0; uop < 4; uop++) {
eee.setSpeed(100);
eee.move(100);
eee.turn(90);
}
for (int j = 0; j < 4; j++) {
eee.setSpeed(100);
eee.move(100);
eee.turn(-90);
}
for (int lol = 0; lol < 4; lol++) {
eee.setSpeed(100);
eee.turn(90);
eee.move(100);
}
for (int oo = 0; oo < 4; oo++) {
eee.setSpeed(100);
eee.turn(-90);
eee.move(100);
for (int uoop = 0; uoop < 4; uoop++) {
eee.setSpeed(100);
eee.move(200);
eee.turn(90);
}
for (int jj = 0; jj < 4; jj++) {
eee.setSpeed(100);
eee.move(200);
eee.turn(-90);
}
for (int lool = 0; lool < 4; lool++) {
eee.setSpeed(100);
eee.turn(90);
eee.move(200);
}
for (int ooo = 0; ooo < 4; ooo++) {
eee.setSpeed(100);
eee.turn(-90);
eee.move(200);
}
}
}
}
}
<file_sep>package _07_years_alive;
public class YearsAlive {
public static void main(String[] args) {
for (int i = 0; i < 14; i++) {
System.out.println(2007+i);
}
}
}
|
3c67fa87bc768f87cd34a49093d565de936c0811
|
[
"Java"
] | 3 |
Java
|
League-Level0-Student/level-0-module-3-rudyzhangsems
|
7c898fb150fbff631a97cad3aa52e57ff219a555
|
383e28826e390bbdecfa1da0724659aad49b1304
|
refs/heads/master
|
<file_sep>Django==2.1.1
mysqlclient==1.3.12
Pillow==5.2.0
python-dotenv==0.9.1
pytz==2018.5
<file_sep>/**************************************
* Leaflet JS setup *
**************************************/
Building = function(title, lat, lon){
this.title = title;
this.latitude = lat;
this.longitude = lon;
this.log = function(){
console.log(this.title);
}
}
var planes = [
new Building("7C6807", -1.273308, 36.807241),
new Building("7C6838", -1.272938, 36.807010),
new Building("7C6CA1", -1.272949, 36.807670),
new Building("7C6CA2", -1.272514, 36.807735),
new Building("C81D9D", -1.271983, 36.807102),
new Building("C82009", -1.271940, 36.807317),
new Building("C82081", -1.272508, 36.806255),
new Building("C820AB", -1.272546, 36.806512),
new Building("C820B6", -1.273302, 36.806753),
];
var map = L.map('map').setView([-1.273354361415031, 36.80712819099427], 18);
mapLink =
'<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data& copy ; ' + mapLink,
maxZoom: 18,
}).addTo(map);
for (var i = 0; i < planes.length; i++) {
var marker = new L.marker([planes[i].latitude, planes[i].longitude])
.bindPopup('<a href="//google.com" target="_blank" >' + planes[i].title + '</a>')
.addTo(map);
marker.onClick(function (e) {
console.log("henlo");
});
planes[i].log()
}
|
fd143907353592ee7efdf34e07e111a1c2c867d8
|
[
"JavaScript",
"Text"
] | 2 |
Text
|
savatia/Project
|
6877fa1667ee2ac5d377eef45090d2cb2253158e
|
d8c22b399f8bc6e291d2cd083b3b96a05f0326e5
|
refs/heads/main
|
<repo_name>RyanWickham/Erin-McCrea-Art<file_sep>/src/components/Portfolio/PortfolioPhoto.js
import "../../index.css";
export default function PortfolioPhoto(props) {
const name = props.name;
//load the image from local file
const imgPath = props.imgPath;
const img = require(`../../Images/art/${imgPath}`).default;
return (
<div className="portfolioPhoto">
<img id="portfolioPhoto" src={img} alt={name} />
</div>
)
}
<file_sep>/src/components/NavBar/LeftNavbar.js
import '../../index.css';
import { NavLink, useLocation } from 'react-router-dom';
import SocialIcons from './SocialIcons/SocialIcons.js';
export default function LeftNavbar() {
const { pathname } = useLocation();
return(
<nav className="left-menu">
<div className="nav-heading"><NavLink to="/"><NAME> Art</NavLink></div>
<div className="vr-nav">
<ul>
<li><NavLink to="/Portfolio/acrylic" isActive={() => ['/Portfolio/acrylic', '/Portfolio/drawing'].includes(pathname)}>Portfolio</NavLink></li>
<ul className="nav-sub-list">
<li><NavLink to="/Portfolio/acrylic">- Acrylic Paintings</NavLink></li>
<li><NavLink to="/Portfolio/drawing">- Drawings</NavLink></li>
</ul>
<li><NavLink to="/ArtistStatement" isActive={() => ['/ArtistStatement', '/'].includes(pathname)}>Artist Statement</NavLink></li>
<li><NavLink to="/Commissions">Commissions / Contact</NavLink></li>
{/* <li className='socialIcons-li'><SocialIcons /></li> */}
</ul>
<div className='socialIconsDiv'><SocialIcons /></div>
</div>
</nav>
);
}<file_sep>/src/App.js
import './App.css';
import { Switch, Route } from 'react-router-dom';
import { useMediaQuery } from 'react-responsive';
import LeftNavbar from './components/NavBar/LeftNavbar.js';
import TopNavbar from './components/NavBar/TopNavbar.js';
import Portfolio from './components/Portfolio/index.js'
import ArtistStatement from './components/ArtistStatement/index.js'
import Commissions from './components/Commissions/index.js'
import PrintShopPage from './components/PrintShop/index.js';
function App() {
const isDesktopOrLaptop = useMediaQuery({ query: '(min-width: 901px)' });
//const isTabletOrMobile = useMediaQuery({ query: '(max-width: 900px)' });
return (
<div className="App" style={{height: '100%'}}>
{/* If the screen is a big screen like desktop or tablet set nevigation bar correctly */}
{ isDesktopOrLaptop ? <LeftNavbar /> : <TopNavbar />}
<main className="vr-side">
<Switch>
<Route path="/printShop/:id">
<PrintShopPage />
</Route>
<Route path="/portfolio/:pageType">
<Portfolio />
</Route>
<Route path="/artistStatement">
<ArtistStatement />
</Route>
<Route path="/commissions">
<Commissions />
</Route>
<Route path='/'>
<ArtistStatement />
</Route>
</Switch>
</main>
</div>
);
}
export default App;<file_sep>/src/components/PrintShop/index.js
import "../../index.css";
import {useParams} from 'react-router-dom';
import Quantity from './Quantity.js';
import Size from './Size.js';
//file that contains information about images
import {dataFile} from "../../Images/imageData.js";
export default function PrintShopPage() {
const { id } = useParams();
const artName = "Name";
const artDescription = "Description Description Description Description Description Description";
const imageData = dataFile.filter(data => data.imageFileName===id);
const artImage = require(`../../Images/art/${id}.${imageData.fileType}`).default;
return (
<div className="printShopPage">
<div className="pageSplitDiv">
<div className="page40WidthDiv printShopImgDiv">
<img src={artImage?artImage:''} alt=""></img>
</div>
{/* Right side of page */}
<div className="page40WidthDiv artistStatementTextDiv">
<h1 id="printPageHeading">{artName}</h1>
<p className='printPageDescription'>{artDescription}</p>
<Size />
<Quantity />
</div>
</div>
</div>
)
}<file_sep>/src/components/Backdrop/Backdrop.js
import '../../index.css';
export default function Backdrop (props) {
return (
<div className='backdrop' onClick={props.click}></div>
)
}<file_sep>/src/Images/imageData.js
export const dataFile = [
{
name: "Kookaburra",
imageFileName: "bird2",
fileType: "jpg",
description: "20 x 24” Acrylic on Canvas",
type: "acrylic"
},
{
name: "<NAME>",
imageFileName: "bird3",
fileType: "jpg",
description: "15 x 30” Acrylic on Canvas",
type: "acrylic"
},
{
name: "<NAME>",
imageFileName: "bird4",
fileType: "jpg",
description: "12 x 16” Acrylic on Canvas",
type: "acrylic"
},
{
name: "Sea Lion",
imageFileName: "seal",
fileType: "jpg",
description: "14 x 18” Acryoic on Canvas",
type: "acrylic"
},
{
name: "<NAME>",
imageFileName: "plant",
fileType: "jpg",
description: "20x 24” Acrylic on Canvas",
type: "acrylic"
},
{
name: "Rainbow Lorikeets",
imageFileName: "bird5",
fileType: "jpg",
description: "20 x 24” Acrylic on Canvas",
type: "acrylic"
},
{
name: "Wedge-Tailed Eagle",
imageFileName: "bird6",
fileType: "jpg",
description: "24 x 36” Acrylic on Canvas",
type: "acrylic"
},
{
name: "Magpie",
imageFileName: "brenda",
fileType: "jpg",
description: "20 x 24” Acrylic on Canvas",
type: "acrylic"
},
{
name: "<NAME>",
imageFileName: "bird8",
fileType: "jpg",
description: "20 x 24” Acrylic on Canvas",
type: "acrylic"
},
{
name: "Eastern Rosella",
imageFileName: "bird1",
fileType: "jpg",
description: "24 x 24” Acrylic on Canvas",
type: "acrylic"
},
]<file_sep>/src/components/NavBar/TopNavbar.js
import '../../index.css';
import { useState } from 'react';
import DrawerToggleButton from './SideDrawer/DrawerToggleButton';
import SideDrawer from './SideDrawer/SideDrawer.js';
import Backdrop from '../Backdrop/Backdrop.js';
export default function TopNavbar(props) {
const [sideDrawerOpen, setSideDrawerOpen] = useState(false);
const drawerToggleClickHandler = () => {
setSideDrawerOpen(!sideDrawerOpen);
};
const backdropClickHandler = () => {
setSideDrawerOpen(false);
}
return (
<header className='top-menu'>
<nav className='top-menu-container'>
{/* Controls the side menu when hamburger button is clicked */}
<div>
<DrawerToggleButton click={drawerToggleClickHandler}/>
<SideDrawer show={sideDrawerOpen}/>
{sideDrawerOpen && <Backdrop click={backdropClickHandler}/>}
</div>
<div className='nav-heading'><NAME></div>
</nav>
</header>
)
}<file_sep>/src/components/PrintShop/Size.js
import "../../index.css";
export default function Size() {
return (
<div className="printShopSizesDiv">
<span className="sizeSpan">
SIZE:
</span>
<span className="buttonSpan">
<button>210x297</button>
<button>297x4420</button>
<button>420x594</button>
<button>593x841</button>
</span>
</div>
)
}
<file_sep>/src/components/Commissions/index.js
import "../../index.css";
export default function ArtistStatement() {
return (
<div className="CommissionsPage">
<h1 className="pageHeading">Commissions</h1>
{/* Main text to describe the process */}
<section className='mainSection'>
<p>Commissions are available by request. If you are interested in a commissioned piece, please contact me via email.
At the bottom of the page are some standard commission sizing and prices. If you are after a custom size, multiple
subjects (more than 2) or still life/landscape artwork, please contact me via email to discuss your needs and a
quote/time frame will be supplied. Times may vary, but care will be taken to notify the client if any time-related
changes arise. Commissions are done in either graphite pencil on fine art paper or acrylic paint on canvas.</p>
<p>To achieve high-quality artwork, it is advised to supply high-quality photographs of your subjects. Photos
should not be blurred or pixelated, and close to the camera. If photos are of poor quality, the commission may
be rejected. To produce good quality photos, make sure the subject has good focus, and the lighting is not
too bright. It can help to supply several photographs to be used as references. A non-refundable deposit
of 25% of the quoted cost will be required before commencement of the artwork. Full payment will be required
at the completion of the artwork, and before postage. Postage will vary depending on the artwork.</p>
</section>
{/* Dot points of things to include in email */}
<section className='neededInfoSection'>
<h2 className='pageSubHeading'>Information Needed</h2>
<ul>
<li>What media you would like the artwork in. Currently offered is graphite on fine art paper or acrylic on canvas.</li>
<li>What size would you like the artwork?</li>
<ul>
<li>Drawings are often done in sizes such as A4, A3 etc.</li>
<li>Paintings will often be measured in inches such as 12x12” or 20x24”.</li>
</ul>
<li>For portraits, a clear and crisp reference image of the subject is required. This is especially important.
To capture the “likeness” of a subject, a clear photograph is needed. Pixelated or blurry images will not be accepted.
Please ensure you get a good clear photo if possible, supply several photos for portraits.</li>
<li>How many subjects you would like in your artwork? Each additional subject will increase the cost of the artwork.</li>
<li>An idea of what you would like to spend; this can be discussed to meet your needs. Generally, a painting will be more expensive than a drawing. The size and number of subjects will affect the pricing also.</li>
</ul>
</section>
</div>
)
}<file_sep>/src/components/Portfolio/PortfolioItem.js
import "../../index.css";
import Photo from "./PortfolioPhoto.js";
import InfoBox from "./InfoBox.js";
export default function PortfolioItem(props) {
return (
<div className="portfolioItem">
<Photo imgPath={`${props.data.imageFileName}.${props.data.fileType}`} name={props.data.name} />
<InfoBox name={props.data.name} description={props.data.description} />
</div>
)
}<file_sep>/src/components/Portfolio/InfoBox.js
import "../../index.css";
export default function PortfolioInfoBox(props) {
return (
<div className="portfolioInfoBox">
<h2 id="portfolioItemName">{props.name}</h2>
<div className="portfolioItemDescription">
<p>{props.description}</p>
</div>
</div>
)
}<file_sep>/src/components/PrintShop/Quantity.js
import "../../index.css";
export default function Quantity() {
const amount = 1;
return (
<div className="printShopQuantityDiv">
<span className="quantitySpan">
QUANTITY:
</span>
<span className="buttonSpan">
<button>-</button>
{amount}
<button>+</button>
</span>
</div>
)
}
|
fa2a524995d74a82b030494bb1ef8d5fba7700a6
|
[
"JavaScript"
] | 12 |
JavaScript
|
RyanWickham/Erin-McCrea-Art
|
26021a7eb45b634340860e53c818f3a925737eae
|
923f8665d329da99bb8dfefba8f0a2f1c340860a
|
refs/heads/master
|
<file_sep># Release Notes
## v1.1.0 - 2020-10-28
- Add CHANGELOG.md
- New set `delimiters()` method for `param` Feild
## v1.0.2 - 2020-10-28
- Improved examples/docs
- Improved README.md
- Code typos
## v1.0.1 - 2020-10-26
- Fix examples (performance page)
- Code typos
## v1.0.0 - 2020-10-26
- First release<file_sep># ItemParser
ItemParser is a simple PHP class for parsing Products and other records
with their parameters or options (like colors, sizes etc) from CSV, present results as array
or display it as html table
<p align="center"><img src="https://raw.githubusercontent.com/decss/item-parser/assets/ItemParserPromo.png" alt="ItemParser Preview"></p>
### Take a look at [live demo][demo]
See the `examples` folder for usage examples
## Features
**Parser** features:
* Parse data from csv to array
* Display parse results in table view
* Parse parameters like `size`, `color`, `material`, `category`, etc from cells like `S; M; L; XL` to array of `[id => 1, value => "S"]` items
* Detect missing parameters and give an ability to replace or ignore it
* Configure each column type and order or skip it
* Search parameters by value or aliases
* Skip specified rows or columns
**Drawer** features:
* Select, change or skip each column manually
* Display parameters as tags
* Mark tags as `ignored`, `replaced` or `not found`
* Mark cell as `valid` or `invalid`
* Shorten links and image urls
* Shorten long text
* Hide valid, invalid or custom rows
## Requirements
As noted in `composer.json` production requirements:
- php >= 5.5
- php mbstring extension
- php json extension
- php iconv extension
- parsecsv/php-parsecsv
## Installation
Using Composer run the following on the command line:
```
composer require decss/item-parser
```
Include Composer's autoloader file in your PHP script:
```php
require_once __DIR__ . '/vendor/autoload.php';
```
#### Without composer
Not recommended. To use ItemParser, you have to add a `require 'itemparser.lib.php';` line.
Note that you will need to require all ItemParser dependencies like `ParseCsv`.
## Parser result
Paeser result is an array of rows (lines). Each row matches the corresponding line in the CSV and generally looks as follows:
```php
0 => [
"row" => 1, // line number in CSV
"valid" => true, // true if all row's Fields is valid, false if any is invalid
"skip" => false, // true only if you skip this row by special method
"fields" => [] // array of row fields (cells)
]
```
Skipped rows can be both valid (`"valid" => true`) or invalid (`"valid" => false`) and vice versa.
As mentioned above, `"fields"` is an array of Field items. Each Field can be different depending on its type, config and content.
All row fields will be presented in result, even if Field was not parsed or was skipped or invalid - there is no matter.
#### Empty field
This is an example of skipped or not configured Field:
```php
14 => [
"text" => "cell text", // Original CSV cell text
"name" => null, // Field name from Parser Fields config
"type" => null // Field type
]
```
#### Text field
So there is 2 Field types: `text` and `param`. Here is example of configured `text` Field:
```php
1 => [
"text" => "V_3J689910",
"name" => "item_sku",
"type" => "text",
"valid" => true, // true if Field is not required or required and have valid "value"
"value" => "V_3J689910" // Unlike "text", "value" is the processed value of a cell.
]
```
`"value"` - is what you should to use instead of `"text"`
#### Param field and values
Next is "param" Field:
```php
3 => [
"text" => "Black; Not a color; Grey; ",
"name" => "item_color",
"type" => "param",
"valid" => false,
"value" => [
0 => [
"valid" => true, // true if param was found in Field params
"skip" => false, // true if this value was skipped in Field missings config
"replace" => false, // true if this value was replaced in Field missings config
"id" => 1, // Param ID, if it's value was found by in Field params
"value" => "Black", // Param or Replaced param value
"text" => "Black" // Param text extracted from cell text value
],
1 => [
"valid" => false,
"skip" => false,
"replace" => false,
"id" => null,
"value" => null,
"text" => "Not a color"
],
2 => ["valid" => true, "skip" => false, "replace" => false, "id" => 3, "value" => "Grey", "text" => "Grey"]
]
]
```
So you can see that `"value"` of `param` Field is an array. Here is example of both found `[0,2]` and not found `[1]` colors.
If there is 2 or more identical colors (ie `"Black; Red; Black"`) all fo them will be valid but duplicates will be skipped.
## Usage
#### Parser usage
```php
use ItemParser\Parser;
// 1. Init Parser and set CSV file path
$csvPath = 'file.csv';
$parser = new Parser($csvPath);
// 2. Config columns
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->textField('item_link');
$parser->textField('item_image1');
$parser->textField('item_image2');
// 2.1 Config param column
// Param array
$colors = [
['id' => 1, 'value' => 'Red'],
['id' => 2, 'value' => 'Green'],
['id' => 3, 'value' => 'Blue'],
['id' => 4, 'value' => 'Gold', 'alias' => ['Gold sand', 'Golden-Orange']],
];
// Param Missing - skip or replace colors, that was not found in $colors
$colorsMissing = [
'Orange' => -1, // Skip this color
'Golden' => 4, // Replace "Golden" to "Gold" (id = 4)
];
$parser->paramField('item_color', [$colors, $colorsMissing])->required();
// 3. Run parse and get results
$result = $parser->parse();
```
#### Drawer usage
```php
use ItemParser\Drawer;
// Create Drawer and config columns (optional)
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_link' => ['display' => 'link'],
'item_image1' => ['display' => 'image'],
]);
// Display results
echo '<table class="parse-table">'
. '<thead>' . $drawer->head() . '</thead>'
. '<tbody>' . $drawer->body() . '</tbody>'
. '</table>';
```
## Detailed usage
#### Create Parser and set content
```php
// Set CSV file path
$parser = new Parser('file.csv');
// or
$parser = new Parser;
$parser->setCsvPath('file.csv');
// also you can use preconfigured parseCsv class
$parseCsv = new \ParseCsv\Csv();
$parseCsv->limit = 5;
$parseCsv->delimiter = "\t";
$parser = new Parser('file.csv', $parseCsv);
// Set SCV content
$parser = new Parser;
$content = file_get_contents('file.csv');
$parser->setCsvContent($content);
```
You can access to `Csv()` instance of `ParseCsv` library and configure it directly:
```php
$csvObj = $parser->getCsvObj();
$csvObj->delimiter = ';,'; // Set CSV rows delimiter characters
```
#### Configure columns
```php
// Add text field
$parser->textField('column_name');
// Add required text field
$parser->textField('column2_name')->required();
// Add param field
$parser->paramField('item_size', [$sizes]);
// Add required param field with missing colors and set possible delimiters for params
$parser->paramField('item_color', [$colors, $colorsMissing])->required()->delimiters([';', ',', '/']);
```
See examples to get how arguments like `$colors` and `$colorsMissing` work
#### Configure parser options
```php
// Skip first 2 rows
$parser->skipRows([0,1]);
// Skip columns and set order
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
4 => 'item_size',
// 5, 6 - skip
7 => 'item_material',
8 => 'item_desc',
9 => 'item_link',
10 => 'item_image1',
11 => 'item_image2',
12 => 'item_image3',
// further will be skipped
]);
```
#### Parsing and results
```php
// Do parsing and get results
$result = $parser->parse();
// Get results after parsing
$result = $parser->result();
```
#### Use Drawer
```php
// Create Drawer and config it
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_sku' => ['title' => 'Product SKU'],
'item_price' => ['title' => 'Price'],
'item_size' => ['title' => 'Sizes'],
'item_color' => ['title' => 'Colors'],
'item_desc' => ['title' => 'Description', 'display' => 'text'],
'item_link' => ['display' => 'link'],
'item_image1' => ['display' => 'image'],
'item_image2' => ['display' => 'image'],
'item_image3' => ['display' => 'image'],
]);
// Hide valid rows
$drawer->hideValid();
// Hide invalid rows
$drawer->hideInvalid();
// Hide custom rows
drawer->hideRows([0, 6, 7, 8]);
// Display missing selects
echo $drawer->missing();
// Display table column names
echo $drawer->head();
// Display table column names with Field selects
echo $drawer->head('select');
// Display table rows
echo $drawer->body();
```
## Credits
* ItemParser is based on [ParseCsv] class.
[demo]: http://217.16.18.253/item-parser/examples/
[ParseCsv]: https://github.com/parsecsv/parsecsv-for-php<file_sep><?php
namespace ItemParser;
use ItemParser\Helpers;
abstract class FieldAbstract
{
const TYPE_TEXT = 'text';
const TYPE_PARAM = 'param';
/**
* @var string Field uniq name, required
*/
protected $name;
/**
* @var string Field type: 'text' or 'param'
*/
protected $type;
/**
* @var string Field title (for Drawing purposes)
*/
protected $title;
/**
* @var string Field display mode, empty (simple text), 'text' (cropped text) or 'link' or 'image'
*/
protected $display;
/**
* @var bool Is Field required
*/
protected $required = false;
public function __construct($name, $type = self::TYPE_TEXT, $opts = [])
{
$this->name($name);
$this->type($type);
}
/**
* Set Field name
*
* @param string $name
* @return $this
*/
public function name($name)
{
$this->name = $name;
return $this;
}
/**
* Set Field type
*
* @param string $type 'text' or 'param'
* @return $this
*/
public function type($type)
{
$this->type = $type;
return $this;
}
/**
* Set Field title (for drawing)
*
* @param string $title
* @return $this
*/
public function title($title)
{
$this->title = $title;
return $this;
}
/**
* Set Field display mode: 'text' or 'link' or 'image'
* 'text' - shorten text, 'link' and 'image' - transform URL
*
* @param string $display
* @return $this
*/
public function display($display)
{
$this->display = $display;
return $this;
}
/**
* Set is Field required or not. Required fields will be invalid if empty
*
* @param bool $required
* @return $this
*/
public function required($required = true)
{
$this->required = $required;
return $this;
}
/**
* Set Field type 'text'
*
* @return $this
*/
public function text()
{
$this->type('text');
return $this;
}
/**
* Set Field type 'param'
*
* @return $this
*/
public function param()
{
$this->type(self::TYPE_PARAM);
return $this;
}
/**
* Check Field type
*
* @param string $type Field type: 'text' or 'param'
* @return bool
*/
public function is($type)
{
if ($this->type === $type) {
return true;
}
return false;
}
/**
* Check Field is required
*
* @return bool
*/
public function isRequired()
{
return $this->required;
}
/**
* Get Field name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get Field type: 'text' or 'param'
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Get Field title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Get Field display: 'text' or 'link' or 'image'
*
* @return string
*/
public function getDisplay()
{
return $this->display;
}
/**
* Base template of parsed cell array
*
* @param string $text
* @param string $name
* @param string $type
* @return array
*/
public static function getResultArray($text, $name = null, $type = null)
{
return [
'text' => $text,
'name' => $name,
'type' => $type,
];
}
/**
* Parse cell value with it's Field config
*
* @param FieldAbstract|null $field
* @param string $text
* @return array
*/
public static function parse(FieldAbstract $field = null, $text = '')
{
$result = static::getResultArray($text);
$missing = [];
if ($field) {
list($result, $missing) = $field->parseField($text);
}
return [$result, $missing];
}
/**
* Parse cell value
*
* @param $text
* @return mixed
*/
abstract protected function parseField($text);
}<file_sep><?php
// Check if people used Composer to include this project in theirs
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
require __DIR__ . '/src/Parser.php';
require __DIR__ . '/src/Drawer.php';
require __DIR__ . '/src/FieldAbstract.php';
require __DIR__ . '/src/FieldText.php';
require __DIR__ . '/src/FieldParam.php';
require __DIR__ . '/src/Helpers.php';
} else {
require __DIR__ . '/vendor/autoload.php';
}<file_sep><?php
namespace ItemParser;
use ParseCsv\Csv;
use ItemParser\FieldAbstract as Field;
use ItemParser\Helpers;
class Parser
{
// TODO: add getMissing() method
/**
* @var \ParseCsv\Csv
*/
private $parseCsv;
/**
* @var string CSV text content
*/
private $content;
/**
* @var integer Count of parsed rows
*/
private $rowsCnt;
/**
* @var integer Total columns
*/
private $colsCnt;
/**
* @var array Parser Fields
*/
private $fields;
/**
* @var array Fields corresponding to columns
*/
private $fieldsOrder;
/**
* @var array Parser result
*/
private $result;
/**
* @var array Rows to skip (first row = 0)
*/
private $skipRows = [];
public function __construct($path = null, \ParseCsv\Csv $parseCsv = null)
{
if (!$parseCsv) {
$this->parseCsv = new Csv();
$this->parseCsv->heading = false;
$this->parseCsv->use_mb_convert_encoding = true;
} else {
$this->parseCsv = $parseCsv;
}
if ($path) {
$this->setCsvPath($path);
}
}
/**
* Add Text field to parser
*
* @param string $name Field name for input name and parse result array
* @param array $opts
* @return FieldText
*/
public function textField($name, $opts = [])
{
$field = new FieldText($name, Field::TYPE_TEXT);
$this->fieldsOrder[] = $name;
$this->fields[$name] = $field;
return $field;
}
/**
* Add Param field to parser
*
* @param string $name Field name for input name and parse result array
* @param array $params Params array like [$params, $missing] or just [$params]
* @return FieldParam
*/
public function paramField($name, $params = [])
{
$field = new FieldParam($name, Field::TYPE_PARAM, $params);
$this->fieldsOrder[] = $name;
$this->fields[$name] = $field;
return $field;
}
/**
* Set fields order to apply each field to corresponding column in CSV
*
* @param array $order
*/
public function fieldsOrder($order)
{
$this->fieldsOrder = $order;
}
/**
* Get field by index
*
* @param int $index
* @return Field
*/
public function getField($index)
{
$name = $this->fieldsOrder[$index];
return $this->fields[$name];
}
/**
* Get field by name
*
* @param string $name
* @return Field
*/
public function getFieldByName($name)
{
return $this->fields[$name];
}
/**
* Get all fields
*
* @param string $mode Get all fields or fields set by fieldsOrder()
* @return array
*/
public function getFields($mode = 'all')
{
if ($mode == 'all') {
return $this->fields;
} elseif ($mode == 'selected') {
$result = [];
foreach ($this->fields as $field) {
$name = $field->getName();
if (in_array($name, $this->fieldsOrder)) {
$result[$name] = $field;
}
}
return $result;
}
}
/**
* Skipped rows will be marked as "skip" in parse results, params will not processed
*
* @param integer|array $skipRows Rows to skip, 0 - first row, 1 - second, ...
*/
public function skipRows($skipRows)
{
if (!is_array($skipRows)) {
$skipRows = [intval($skipRows)];
}
$this->skipRows = $skipRows;
}
/**
* Get ParseCsv object
*
* @return \ParseCsv\Csv
*/
public function getCsvObj()
{
return $this->parseCsv;
}
/**
* Set CSV file path
*
* @param string $path Path to CSV file
*/
public function setCsvPath($path)
{
$content = file_get_contents($path);
$this->setCsvContent($content);
}
/**
* Set CSV file content
*
* @param string $content Raw CSV content in text format
*/
public function setCsvContent($content)
{
$encoding = Helpers::mbDetectEncoding($content);
$this->parseCsv->encoding($encoding, 'UTF-8');
$this->content = $content;
}
/**
* Parse CSV and return results
*
* @return array
*/
public function parse()
{
$this->parseCsv->auto($this->content);
$this->rowsCnt = count($this->parseCsv->data);
$this->colsCnt = count($this->parseCsv->data[0]);
$result = [];
$missing = [];
for ($r = 0; $r < $this->rowsCnt; $r++) {
$rowFields = $this->parseCsv->data[$r];
$valid = true;
$skip = in_array($r, $this->skipRows) ? true : false;
$fields = [];
foreach ($rowFields as $f => $text) {
$fieldObj = $this->getField($f);
list($fields[$f], $fieldMissing) = Field::parse($fieldObj, $text);
if (!$skip && $fieldMissing) {
Helpers::mergeMissing($missing[$fieldObj->getName()], $fieldMissing);
}
if ($fieldObj && !$fields[$f]['valid']) {
$valid = false;
}
}
$result[] = [
'row' => ($r + 1),
'valid' => $valid,
'skip' => $skip,
'fields' => $fields,
];
}
// Remove duplicates and set missing property
foreach ($missing as $name => $opts) {
$field = $this->getFieldByName($name);
$field->setMissing(array_values(array_unique($missing[$name])));
}
$this->result = $result;
return $this->result;
}
/**
* Get parse results
*
* @return array
*/
public function result()
{
return $this->result;
}
/**
* Get parsed rows count
*
* @return integer
*/
public function rows()
{
return $this->rowsCnt;
}
/**
* Get parsed cols count
*
* @return integer
*/
public function cols()
{
return $this->colsCnt;
}
}
<file_sep><?php
/**
* Nothing usefull just examples header navigation
*/
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require __DIR__ . '/../vendor/autoload.php';
} else {
require __DIR__ . '/../itemparser.lib.php';
if (file_exists(__DIR__ . '/../vendor/parsecsv/php-parsecsv/parsecsv.lib.php')) {
require __DIR__ . '/../vendor/parsecsv/php-parsecsv/parsecsv.lib.php';
} elseif (file_exists(__DIR__ . '/../../../parsecsv/php-parsecsv/parsecsv.lib.php')) {
require __DIR__ . '/../../../parsecsv/php-parsecsv/parsecsv.lib.php';
}
}
if (!function_exists('dump')) {
function dump($array) {
echo '<p>For better output run: <kbd>composer require --dev symfony/var-dumper:^3.4</kbd></p>';
echo '<pre>';
print_r($array);
echo '</pre>';
}
}
if (!function_exists('dd')) {
function dd($array) {
dump($array);
exit;
}
}
?>
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<style>
/* Example pages style */
body, table {margin: 4px;}
table {font-size: 13px;}
table td {padding: 2px 3px; border: 1px solid #666;}
select {font-size: 11px;}
.missing-tables table {display: inline-block; vertical-align: top;}
nav {position: fixed; right: 20px;}
nav ul {width: 240px;}
.content {padding-right: 280px;}
pre {
max-width: 1000px;
background: #eee;
padding: 8px 10px;
margin: 5px 0;
}
/* Drawer table style */
.parse-table thead td {font-weight: bold;}
.parse-table td.hidden {text-align: center; font-style: italic; padding: 6px 3px;}
.parse-table .tag {
vertical-align: top;
font-size: 0.9em;
display: inline-block;
border: 1px solid gray;
border-radius: 5px;
padding: 1px 4px;
margin: 0 4px 4px 0;
cursor: pointer;
min-height: 1.2em;
min-width: 1.2em;
}
.parse-table .tag {background-color: #fff; color: #000;}
.parse-table .tag.invalid {background-color: #ff372d;}
.parse-table .tag.replaced {background-color: #14ff3b;}
.parse-table .tag.skipped {background-color: #ccc; color:#666;}
.parse-table tr.skipped {background-color: #ccc; color:#666;}
.parse-table td.invalid {background-color: #ff372d;}
.parse-table td.skipped {background-color: #ccc; color:#666;}
.parse-table tr.invalid > td:first-child {background-color: #ff372d;}
/*.parse-table select option.required {background: #ff372d;}*/
.parse-table select option.required {font-weight: bold;}
.parse-table select option.selected,
.parse-table select option.required.selected {background: #d1d1d1; color: #666;}
</style>
</head>
<boddy>
<ul class="nav nav-tabs mt-2 mb-4">
<li class="nav-item"><a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Examples:</a></li>
<?php
$pages = [
'index.php' => 'Index',
'01-full.php' => '01-All features',
'02-basic.php' => '02-Basic',
'03-rows-columns.php' => '03-Rows/Columns',
'04-drawer.php' => '04-Drawer display',
'05-select-columns.php' => '05-Select columns',
'06-params.php' => '06-Missing params',
'07-aliases.php' => '07-Param aliases',
'08-performance.php' => '08-Performance',
];
foreach ($pages as $page => $name) {
echo '<li class="nav-item"><a class="nav-link ' . (stristr($_SERVER['PHP_SELF'], $page) ? 'active' : '') . '" href="' . $page . '">' . $name . '</a></li>';
}
?>
</ul><file_sep><?php
require 'inc.head.php';
use ItemParser\Drawer;
use ItemParser\Parser;
$sizes = json_decode(file_get_contents('data/psizes.json'), true);
$colors = json_decode(file_get_contents('data/pcolors.json'), true);
$csvPath = 'data/file.csv';
// 1. Init Parser and set CSV file path
$parser = new Parser($csvPath);
// 2. Config columns
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->paramField('item_color', [$colors]);
$parser->paramField('item_size', [$sizes])->required(true);
$parser->textField('item_size_text');
$parser->textField('item_collection');
$parser->textField('item_material');
$parser->textField('item_desc')->required();
$parser->textField('item_link');
$parser->textField('item_image1');
// 3. Run parse and get results
$result = $parser->parse();
// 4. Init Drawer
$drawer = new Drawer($parser);
?>
<div class="container-fluid">
<div class="row mb-4">
<div class="col-6">
<h3>Basic usage <span class="h6">(CSV file used in examples: <a href="data/file.csv">file.csv</a>)</span></h3>
<hr>
<h5>1. Set CSV file or content: </h5>
<pre>// Set filepath
$parser = new Parser('file.csv');
// or
$parser = new Parser;
$parser->setCsvPath('file.csv');
// or Set CSV content
$parser = new Parser;
$content = file_get_contents('file.csv');
$parser->setCsvContent($content);</pre>
<h4>2. Configure Fields</h4>
<p>
Each <b>Field</b> should have it's own uniq name. Field name is used as name of
associated inputs and value of <b>"name"</b> property of row's <b>"fields"</b> items (Parser results).
</p>
<p>
There are 2 field types: <b>text</b> for text data like name, price, url, description and <b>param</b>
for parameters that has their uniq id and value. See <b>2.</b> of this file source code.<br>
To add text field use <kbd>textField('field_name')</kbd> method<br>
To add param field use <kbd>paramField('field_name', [$params, $missings])</kbd>, where: <br>
<b>$params</b> is array of parameters, associated with field,<br>
<b>$missings</b> is optional array of missing parameters where replace or skip for missing param can be
defined
</p>
<p>
Field can be set as required using <kbd>required()</kbd> method. Required field id invalid if it hasn't any
value or some of field values (tags) has an error (for param fields)
</p>
<h4>3. Parsing</h4>
<p>
To get Parse results just do this: <kbd>$result = $parser->parse();</kbd> or
<kbd>$result = $parser->result();</kbd> after.
</p>
</div>
<div class="col-6">
<h3>Parser results</h3>
<?php dump($result) ?>
</div>
</div>
</div>
<h2>Drawer view</h2>
<table class="parse-table">
<thead>
<?php echo $drawer->head() ?>
</thead>
<tbody>
<?php echo $drawer->body() ?>
</tbody>
</table>
</body>
</html><file_sep><?php
require 'inc.head.php';
use ItemParser\Drawer;
use ItemParser\Helpers;
use ItemParser\Parser;
function generateParams($name, $size = 1000)
{
$params = [];
if ($name == 'size') {
$params = json_decode(file_get_contents('data/psizes.json'), true);
} elseif ($name == 'color') {
$params = json_decode(file_get_contents('data/pcolors.json'), true);
}
$steps = $size - count($params);
for ($i = 0; $i < $steps; $i++) {
$params[] = [
'id' => ($i + 20),
'value' => ucfirst($name) . ' ' . $i,
];
}
shuffle($params);
return $params;
}
function generateCsv($size = 1000)
{
$csvPath = 'data/file.csv';
$content = file_get_contents($csvPath);
$tmp = trim(substr_replace($content, null, 0, strpos($content, "\n")));
$steps = $size / count(explode(PHP_EOL, $tmp)) - 1;
for ($i = 0; $i < $steps; $i++) {
$content .= $tmp . "\r\n";
}
return $content;
}
// Generate ~1000 Sizes
$sizes = generateParams('size', 1000);
// Generate ~1000 Colors
$colors = generateParams('color', 1000);
// Generate ~1000 CSV rows
$content = generateCsv(1000);
$tStart = microtime(true);
$mStart = memory_get_usage();
// 1. Init Parser and set CSV file path
$t = microtime(true);
$parser = new Parser();
$parser->setCsvContent($content);
$time['Load CSV'] = microtime(true) - $t;
// 2.1. Set rows to skip
$parser->skipRows([0]);
// 2.2. Config columns (in any order)
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->paramField('item_color', [$colors, $_POST['parseMissing']['item_color']]);
$parser->paramField('item_size', [$sizes, $_POST['parseMissing']['item_size']])->required(true)->delimiters([';', '/']);
$parser->textField('item_size_text');
$parser->textField('item_collection');
$parser->textField('item_material');
$parser->textField('item_desc')->required();
$parser->textField('item_link');
$parser->textField('item_image1');
$parser->textField('item_image2');
$parser->textField('item_image3');
// 2.3. Set columns ordering and skip some columns
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
4 => 'item_size',
// 5, 6 - skip
7 => 'item_material',
8 => 'item_desc',
9 => 'item_link',
10 => 'item_image1',
11 => 'item_image2',
12 => 'item_image3',
// further will be skipped
]);
// 3. Run parse and get results
$t = microtime(true);
$result = $parser->parse();
$time['Parsing'] = microtime(true) - $t;
// 4. Init Drawer with options
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_sku' => ['title' => 'Prod. SKU'],
'item_price' => ['title' => 'Price'],
'item_size' => ['title' => 'Sizes'],
'item_color' => ['title' => 'Colors'],
'item_desc' => ['title' => 'Description', 'display' => 'text'],
'item_link' => ['display' => 'link'],
'item_image1' => ['title' => 'First Image', 'display' => 'image'],
'item_image2' => ['title' => 'Second Image', 'display' => 'image'],
'item_image3' => ['title' => 'Third Image', 'display' => 'image'],
]);
// Drawer render emulate
$t = microtime(true);
$drawer->missing();
$drawer->head();
$drawer->body();
$time['Drawing'] = microtime(true) - $t;
// Stats
$mEnd = memory_get_usage();
// Round time
$time['Total'] = microtime(true) - $tStart;
foreach ($time as $key => $val) {
$time[$key] = round($val, 3);
}
$stats = [
'Sizes count' => count($sizes),
'Colors count' => count($colors),
'CSV Rows' => $parser->rows(),
'Memory' => number_format(($mEnd - $mStart) / 1024, 2, '.', ' ') . ' Kb',
];
// After measuring memory AND drawer time we can hide rows
$drawer->hideRows(range(15, $parser->rows() - 10));
?>
<div class="container-fluid">
<div class="row mb-4">
<div class="col-6">
<h3>Performance <span class="h6">(CSV file used in examples: <a href="data/file.csv">file.csv</a>)</span></h3>
<hr>
<p>
Here is an example of parsing CSV with 1000 rows with 2 Param columns, configured with 1000 param values for each
</p>
<p>
First 10 lines has 15 colors and 38 sizes. All other lines are the copy of first 10. Whole 1000 lines contains about 1500 colors and 3800 sizes.<br>
Assuming that each of the <b>$sizes</b> and <b>$colors</b> arrays has 1000 items, can be concluded
that there was 1500 * 1000 + 3800 * 1000 value comparisons which gives us theoretically up to <b>5 000 000</b> comparisons or even more (and this does not include aliases)<br>
</p>
<p>
But the real number is much less due to caching and the search stops when the parameter is found.<br>
You can se how much time it takes, take a look at <b>"Parsing"</b> time (<?php echo $time['Parsing']; ?> sec)
</p>
</div>
<div class="col-6">
<h3>Statistics</h3>
<b>Usage:</b>
<?php dump($stats); ?>
<b>Time (sec):</b>
<?php dump($time); ?>
</div>
</div>
</div>
<h2>Drawer view</h2>
<form action="" method="POST">
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
Missing params and display options:
<div class="missing-tables">
<?php echo $drawer->missing() ?>
</div>
<table class="parse-table">
<thead>
<?php echo $drawer->head() ?>
</thead>
<tbody>
<?php echo $drawer->body() ?>
</tbody>
</table>
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
</form>
</body>
</html><file_sep><?php
require 'inc.head.php';
?>
<nav>
<ul class="list-group">
<li class="list-group-item"><h4>Context</h4></li>
<li class="list-group-item"><a href="#features">Features</a></li>
<li class="list-group-item"><a href="#installation">Installation</a></li>
<li class="list-group-item">
<a href="#parser-result">Parser result</a><br>
• <a class="small" href="#empty-field">Empty field</a><br>
• <a class="small" href="#text-field">Text field</a><br>
• <a class="small" href="#param-field">Param field and values</a><br>
</li>
<li class="list-group-item">
<a href="#usage">Usage</a><br>
• <a class="small" href="#parser-usage">Parser usage</a><br>
• <a class="small" href="#drawer-usage">Drawer usage</a><br>
</li>
<li class="list-group-item">
<a href="#detailed-usage">Detailed usage</a><br>
• <a class="small" href="#create-parser">Create Parser and set content</a><br>
• <a class="small" href="#configure-columns">Configure columns</a><br>
• <a class="small" href="#configure-parser">Configure parser options</a><br>
• <a class="small" href="#parsing-and-results">Parsing and results</a><br>
• <a class="small" href="#use-drawer">Use Drawer</a><br>
</li>
</ul>
</nav>
<div class="container-fluid content">
<h3>ItemParser</h3>
<p>ItemParser is a simple PHP class for parsing Products and other records
with their parameters (like colors, sizes etc) from CSV, present results as array
or display it as html table </p>
<hr>
<h3 id="features">Features</h3>
<b>Parser</b> features:
<ul>
<li>Parse data from csv to array</li>
<li>Display parse results in table view</li>
<li>Parse parameters like <i>size, color, material, category, etc</i> from cells like <i>"S; M; L; XL"</i>
to array of [id => 1, value => "S"] items</li>
<li>Detect missing parameters and give an ability to replace or ignore it</li>
<li>Configure each column type and order or skip it</li>
<li>Search parameters by value or aliases</li>
<li>Skip specified rows or columns</li>
</ul>
<b>Drawer</b> features:
<ul>
<li>Select, change or skip each column manually</li>
<li>Display parameters as tags</li>
<li>Mark tags as <i>ignored, replaced</i> or <i>not found</i></li>
<li>Mark cell as <i>valid</i> or <i>invalid</i></li>
<li>Shorten links and image urls</li>
<li>Shorten long text</li>
<li>Hide valid, invalid or custom rows</li>
</ul>
<hr>
<h3 id="installation">Installation</h3>
Using Composer run the following on the command line:
<pre><code>composer require decss/item-parser</code></pre>
Include Composer's autoloader file in your PHP script:
<pre><code>require_once __DIR__ . '/vendor/autoload.php';</code></pre>
<b>Without composer</b>
<p>
Not recommended. To use ItemParser, you have to add a
<kbd>require 'itemparser.lib.php';</kbd> line. <br>
Note that you will need to require all ItemParser dependencies like <i>ParseCsv</i>.
</p>
<hr>
<h3 id="parser-result">Parser result</h3>
<div class="mb-3">
Paeser result is an array of rows (lines). Each row matches the corresponding line in the CSV and generally looks as follows:
<pre class="mb-0"><code>0 => [
"row" => 1, // line number in CSV
"valid" => true, // <i>true</i> if all row's Fields is valid, <i>false</i> if any is invalid
"skip" => false, // <i>true</i> only if you skip this row by special method
"fields" => [] // array of row fields (cells)
]</code></pre>
Skipped rows can be both valid ("valid" => true) or invalid ("valid" => false) and vice versa.
</div>
<p>
As mentioned above, <i>"fields"</i> is an array of Field items. Each Field can be different depending on its type, config and content.<br>
All row fields will be presented in result, even if Field was not parsed or was skipped or invalid - there is no matter.
</p>
<h5 id="empty-field">Empty field</h5>
<div class="mb-3">
This is an example of skipped or not configured Field:
<pre><code>14 => [
"text" => "cell text", // Original CSV cell text
"name" => null, // Field name from Parser Fields config
"type" => null // Field type
]</code></pre>
</div>
<h5 id="text-field">Text field</h5>
<div class="mb-3">
So there is 2 Field types: <i>text</i> and <i>param</i>. Here is example of configured <i>text</i> Field:
<pre class="mb-0"><code>1 => [
"text" => "V_3J689910", //
"name" => "item_sku", //
"type" => "text", //
"valid" => true, // <i>true</i> if Field is not required or required and have valid "value"
"value" => "V_3J689910" // Unlike <i>"text"</i>, <i>"value"</i> is the processed value of a cell.
]</code></pre>
<i>"value"</i> - is what you should to use instead of <i>"text"</i><br>
</div>
<h5 id="param-field">Param field and values</h5>
<div class="mb-3">
Next is <i>"param"</i> Field:
<pre class="mb-0"><code>3 => [
"text" => "Black; Not a color; Grey; ",
"name" => "item_color",
"type" => "param",
"valid" => false,
"value" => [
0 => [
"valid" => true, // <i>true</i> if param was found in Field params
"skip" => false, // <i>true</i> if this value was skipped in Field missings config
"replace" => false, // <i>true</i> if this value was replaced in Field missings config
"id" => 1, // Param ID, if it's value was found by in Field params
"value" => "Black", // Param or Replaced param value
"text" => "Black" // Param text extracted from cell text value
],
1 => [
"valid" => false,
"skip" => false,
"replace" => false,
"id" => null,
"value" => null,
"text" => "Not a color"
],
2 => ["valid" => true, "skip" => false, "replace" => false, "id" => 3, "value" => "Grey", "text" => "Grey"]
]
]</code></pre>
So you can see that <i>"value"</i> of <i>param</i> Field is an array. Here is example of both found [0,2] and not found [1] colors.<br>
If there is 2 or more identical colors (ie "Black; Red; Black") all fo them will be valid but duplicates will be skipped.
</div>
<hr>
<h3 id="usage">Usage</h3>
<h5 id="parser-usage">Parser usage</h5>
<pre><code>use ItemParser\Parser;
// 1. Init Parser and set CSV file path
$csvPath = 'file.csv';
$parser = new Parser($csvPath);
// 2. Config columns
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->textField('item_link');
$parser->textField('item_image1');
$parser->textField('item_image2');
// 2.1 Config param column
// Param array
$colors = [
['id' => 1, 'value' => 'Red'],
['id' => 2, 'value' => 'Green'],
['id' => 3, 'value' => 'Blue'],
['id' => 4, 'value' => 'Gold', 'alias' => ['Gold sand', 'Golden-Orange']],
];
// Param Missing - skip or replace colors, that was not found in $colors
$colorsMissing = [
'Orange' => -1, // Skip this color
'Golden' => 4, // Replace "Golden" to "Gold" (id = 4)
];
$parser->paramField('item_color', [$colors, $colorsMissing])->required();
// 3. Run parse and get results
$result = $parser->parse();
</code></pre>
<br>
<h5 id="drawer-usage">Drawer usage</h5>
<pre><code>use ItemParser\Drawer;
// Create Drawer and config columns (optional)
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_link' => ['display' => 'link'],
'item_image1' => ['display' => 'image'],
]);
// Display results
echo '<table class="parse-table">'
. '<thead>' . $drawer->head() . '</thead>'
. '<tbody>' . $drawer->body() . '</tbody>'
. '</table>';
</code></pre>
<hr>
<h3 id="detailed-usage">Detailed usage</h3>
<h5 id="create-parser">Create Parser and set content</h5>
<pre><code>// Set CSV file path
$parser = new Parser('file.csv');
// or
$parser = new Parser;
$parser->setCsvPath('file.csv');
// Set SCV content
$parser = new Parser;
$content = file_get_contents('file.csv');
$parser->setCsvContent($content);
</code></pre>
<p>You can access to <i>Csv()</i> instance of <i>ParseCsv</i> library and configure it directly:</p>
<pre>$csvObj = $parser->getCsvObj();
$csvObj->delimiter = ';,'; // Set CSV rows delimiter characters
</pre>
<br>
<h5 id="configure-columns">Configure columns</h5>
<pre><code>// Add text field
$parser->textField('column_name');
// Add required text field
$parser->textField('column2_name')->required();
// Add param field
$parser->paramField('item_size', [$sizes]);
// Add required param field with missing colors and set possible delimiters for params
$parser->paramField('item_color', [$colors, $colorsMissing])->required()->delimiters([';', ',', '/']);
</code></pre>
See examples to get how arguments like <i>$colors</i> and <i>$colorsMissing</i> work<br><br>
<h5 id="configure-parser">Configure parser options</h5>
<pre><code>// Skip first 2 rows
$parser->skipRows([0,1]);
// Skip columns and set order
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
4 => 'item_size',
// 5, 6 - skip
7 => 'item_material',
8 => 'item_desc',
9 => 'item_link',
10 => 'item_image1',
11 => 'item_image2',
12 => 'item_image3',
// further will be skipped
]);
</code></pre>
<br>
<h5 id="parsing-and-results">Parsing and results</h5>
<pre><code>// Do parsing and get results
$result = $parser->parse();
// Get results after parsing
$result = $parser->result();
</code></pre>
<br>
<h5 id="use-drawer">Use Drawer</h5>
<pre><code>// Create Drawer and config it
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_sku' => ['title' => 'Product SKU'],
'item_price' => ['title' => 'Price'],
'item_size' => ['title' => 'Sizes'],
'item_color' => ['title' => 'Colors'],
'item_desc' => ['title' => 'Description', 'display' => 'text'],
'item_link' => ['display' => 'link'],
'item_image1' => ['display' => 'image'],
'item_image2' => ['display' => 'image'],
'item_image3' => ['display' => 'image'],
]);
// Hide valid rows
$drawer->hideValid();
// Hide invalid rows
$drawer->hideInvalid();
// Hide custom rows
drawer->hideRows([0, 6, 7, 8]);
// Display missing selects
echo $drawer->missing();
// Display table column names
echo $drawer->head();
// Display table column names with Field selects
echo $drawer->head('select');
// Display table rows
echo $drawer->body();
</code></pre>
</div>
</body>
</html><file_sep><?php
require 'inc.head.php';
use ItemParser\Drawer;
use ItemParser\Parser;
$sizes = json_decode(file_get_contents('data/psizes.json'), true);
$colors = json_decode(file_get_contents('data/pcolors.json'), true);
$csvPath = 'data/file.csv';
// 1. Init Parser and set CSV file path
$parser = new Parser($csvPath);
// 2.1. Set rows to skip
$parser->skipRows([0]);
// 2.2. Config columns (in any order)
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->paramField('item_color', [$colors]);
$parser->paramField('item_size', [$sizes])->required(true);
$parser->textField('item_size_text');
$parser->textField('item_collection');
$parser->textField('item_material');
$parser->textField('item_desc')->required();
$parser->textField('item_link');
$parser->textField('item_image1');
$parser->textField('item_image2');
$parser->textField('item_image3');
// 2.3. Set columns ordering and skip some columns
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
4 => 'item_size',
// 5, 6 - skip
7 => 'item_material',
8 => 'item_desc',
9 => 'item_link',
10 => 'item_image1',
11 => 'item_image2',
12 => 'item_image3',
// further will be skipped
]);
// 3. Run parse and get results
$result = $parser->parse();
// 4. Init Drawer
$drawer = new Drawer($parser);
// 4.1. Hide some rows
$drawer->hideRows([6, 7, 8]);
?>
<div class="container-fluid">
<div class="row mb-4">
<div class="col-6">
<h3>Rows & Columns <span class="h6">(CSV file used in examples: <a href="data/file.csv">file.csv</a>)</span></h3>
<hr>
<p>
You can manipulate by rows and columns in <b>Parser</b> and <b>Drawer</b>.
Drawer manipulations will have no affect to Parser results.
</p>
<h4>Parser</h4>
<p>
To skip rows you should call Parser <kbd>skipRows()</kbd> method as shown in <b>2.1.</b> of this file
source code.<br>
Skipped rows will not be excluded from the result, but all of them will have <u>skip</u> field with
<u>true</u> value.
</p>
<p>
To skip columns you need <kbd>fieldsOrder()</kbd> method. Using it you can apply configured <b>Field</b>
to any CSV column, as shown in <b>2.3.</b>
</p>
<h4>Drawer</h4>
<p>
To hide rows from a table use <kbd>hideRows()</kbd> as shown in <b>4.1.</b>
Also you can use <kbd>hideValid()</kbd> and <kbd>hideInvalid()</kbd> to hide valid or invalid rows
accordingly.
All 3 methods takes array if row(line) numbers from starting from 0.
</p>
</div>
<div class="col-6">
<h3>Parser results</h3>
<?php dump($result) ?>
</div>
</div>
</div>
<h2>Drawer view</h2>
<table class="parse-table">
<thead>
<?php echo $drawer->head() ?>
</thead>
<tbody>
<?php echo $drawer->body() ?>
</tbody>
</table>
</body>
</html><file_sep><?php
namespace ItemParser;
use ItemParser\Helpers;
class FieldParam extends FieldAbstract
{
/**
* @var array Field params (values)
*/
private $params = [];
/**
* @var array Params (values) from CSV that was not found in $params
*/
private $missing = [];
/**
* @var string[] Parameter values delimiters
*/
private $delimiters = [';', ','];
public function __construct($name, $type, $params = [])
{
parent::__construct($name, $type);
if ($params[0]) {
$this->params($params[0]);
}
if ($params[1]) {
$this->missing($params[1]);
}
}
/**
* Set params
*
* @param array $params
* @return $this
*/
public function params($params)
{
$this->params = $params;
$this->normalizeAlias();
return $this;
}
/**
* Set missing array while adding field
*
* @param array $missing
* @return $this
*/
public function missing($missing)
{
$this->missing = $missing;
return $this;
}
/**
* Set parameter values delimiters.
* If set 2 or more delimiters - the most frequently occurring in the cell will be chosen
*
* @param array|string $delimiters
* @return $this
*/
public function delimiters($delimiters)
{
if (is_string($delimiters)) {
$delimiters = [$delimiters];
}
$this->delimiters = $delimiters;
return $this;
}
/**
* Get params
*
* @return array
*/
public function getParams()
{
return $this->params;
}
/**
* Get missing array
*
* @return array
*/
public function getMissing()
{
return $this->missing;
}
/**
* Set missing after CSV was processed
*
* @param $array
*/
public function setMissing($array)
{
// Filter missing params (from $_POST) by real missing from SCV
foreach ($this->missing as $param => $val) {
if (!in_array($param, $array)) {
unset($this->missing[$param]);
}
}
foreach ($array as $param) {
if (!isset($this->missing[$param])) {
$this->missing[$param] = 0;
}
}
}
/**
* Check if Field has missing
*
* @return bool
*/
public function hasMissing()
{
return count($this->missing) ? true : false;
}
/**
* Try to search Value in $this->missing array
*
* @param $valText
* @return int|null
*/
private function findInMissing($valText)
{
foreach ($this->getMissing() as $replacement => $id) {
if ($replacement == $valText) {
if ($id == -1) {
return -1;
} elseif ($id > 0) {
return Helpers::getById($id, $this->getParams());
}
}
}
return null;
}
protected function parseField($text)
{
$result = self::getResultArray($text, $this->getName(), $this->getType());
$missing = [];
$values = [];
$textArr = Helpers::strToArray($text, $this->delimiters); // TODO: make ';' configurable
$i = 0;
foreach ($textArr as $valText) {
$valText = trim($valText);
if (!$valText) {
continue;
}
$pValid = false;
$pSkip = false;
$pReplace = false;
$param = [];
$replacement = $this->findInMissing($valText);
if ($replacement === -1) {
$pSkip = true;
} elseif ($replacement && is_array($replacement)) {
$pReplace = true;
$param = $replacement;
}
if (!$param) {
$param = Helpers::findInParams($valText, $this->getParams(), $this->getName());
}
if ($param) {
$pValid = true;
}
if (!$param || $pReplace) {
$missing[] = $valText;
}
// Always valid if skipped
// $pValid = $pSkip ? true : $pValid;
$values[$i] = [
'valid' => $pValid,
'skip' => $pSkip,
'replace' => $pReplace,
'id' => $param['id'],
'value' => $param['value'],
'text' => $valText,
];
$i++;
}
// Check and skip duplicates
$tmp = [];
foreach ($values as $i => $value) {
if ($value['valid'] == false || $value['skip'] == true) {
continue;
}
if (!in_array($value['id'], $tmp)) {
$tmp[] = $value['id'];
} else {
$values[$i]['skip'] = true;
}
}
$valid = true;
$activeValues = 0;
// Check for at least one valid and not skipped param
foreach ($values as $i => $value) {
if ($value['valid'] && !$value['skip']) {
$activeValues++;
}
if (!$value['valid'] && !$value['skip']) {
$valid = false;
}
}
// There is no one valid value on required field
if ($this->isRequired() && $activeValues == 0) {
$valid = false;
} elseif (!$this->isRequired()) {
// $valid = true;
}
$result['valid'] = $valid;
$result['value'] = $values;
return [$result, $missing];
}
/**
* Normalize $this->params aliases
*/
private function normalizeAlias()
{
foreach ($this->params as $i => $param) {
if ($param['alias']) {
foreach ($param['alias'] as $a => $alias) {
$this->params[$i]['alias'][$a] = Helpers::normalizeStr($alias);
}
}
}
}
}<file_sep><?php
namespace ItemParser;
class Helpers
{
static function mbDetectEncoding($string, $ret = null)
{
$enclist = [
'UTF-8', 'ASCII',
'Windows-1251', 'Windows-1252', 'Windows-1254',
'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', 'ISO-8859-5',
'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9', 'ISO-8859-10',
'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
];
$result = false;
foreach ($enclist as $item) {
$sample = iconv($item, $item, $string);
if (md5($sample) == md5($string)) {
if ($ret === null) {
$result = $item;
} else {
$result = true;
}
break;
}
}
return $result;
}
/**
* Convert string into array using costum delimiter
* @param string $str String to implode
* @param string|array $delimiters optional Delimiter
* @param string $filter optional Filter to apply to values ['int'|'mixed']
* @return array
*/
static function strToArray($str, $delimiters = [';', ','], $filter = 'mixed')
{
if (is_array($str)) {
return $str;
}
if (is_string($delimiters)) {
$delimiters = [$delimiters];
}
$array = array();
if (strlen($str)) {
if (count($delimiters) > 1) {
foreach ($delimiters AS $symbol) {
$num[] = substr_count($str, $symbol);
}
$delimiter = $delimiters[array_keys($num, max($num))[0]];
} else {
$delimiter = $delimiters[0];
}
$arr = stristr($str, $delimiter) ? explode($delimiter, $str) : array($str);
foreach ($arr as $value) {
$value = ($filter == 'int') ? intval($value) : $value;
if (isset($value)) {
$array[] = $value;
}
}
}
return $array;
}
public static function findInParams($text, $params, $name = 0)
{
static $cache = [];
static $results = [];
if (isset($results[$name][$text])) {
return $results[$name][$text];
}
$results[$name][$text] = false;
if (!$cache[$text]) {
$cache[$text] = self::normalizeStr($text);
}
foreach ($params as $param) {
$value = $param['value'];
if (!$cache[$value]) {
$cache[$value] = self::normalizeStr($value);
}
if ($cache[$text] == $cache[$value]) {
$results[$name][$text] = $param;
}
if ($param['alias'] && in_array($cache[$text], $param['alias'])) {
$results[$name][$text] = $param;
}
}
return $results[$name][$text];
}
public static function normalizeStr($str)
{
static $cache = [];
if (!$cache[$str]) {
$res = mb_strtolower(trim($str));
$res = str_replace('ё', 'е', $res);
$res = preg_replace(['~\s{2,}~', '~[\t\n]~'], ' ', $res);
$cache[$str] = $res;
}
return $cache[$str];
}
public static function mergeMissing(&$rowOpts, $fieldOpts)
{
if (!$fieldOpts) {
return false;
}
if (!$rowOpts) {
$rowOpts = $fieldOpts;
} else {
$rowOpts = array_merge($rowOpts, $fieldOpts);
}
return true;
}
public static function getById($id, $array)
{
foreach ($array as $item) {
if ($id && $id == $item['id']) {
return $item;
}
}
return null;
}
}<file_sep><?php
require 'inc.head.php';
use ItemParser\Drawer;
use ItemParser\Parser;
$sizes = json_decode(file_get_contents('data/psizes.json'), true);
$colors = json_decode(file_get_contents('data/pcolors.json'), true);
$csvPath = 'data/file.csv';
// 1. Init Parser and set CSV file path
$parser = new Parser($csvPath);
// 2.1. Set rows to skip
$parser->skipRows([0]);
// 2.2. Config columns (in any order)
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->paramField('item_color', [$colors]);
$parser->paramField('item_size', [$sizes])->required(true);
$parser->textField('item_size_text');
$parser->textField('item_collection');
$parser->textField('item_material');
$parser->textField('item_desc')->required();
$parser->textField('item_link');
$parser->textField('item_image1');
$parser->textField('item_image2');
$parser->textField('item_image3');
// 2.3. Set columns ordering and skip some columns
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
4 => 'item_size',
// 5, 6 - skip
7 => 'item_material',
8 => 'item_desc',
9 => 'item_link',
10 => 'item_image1',
11 => 'item_image2',
12 => 'item_image3',
// further will be skipped
]);
// 3. Run parse and get results
$result = $parser->parse();
// 4. Init Drawer with options
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_sku' => ['title' => 'Prod. SKU'],
'item_price' => ['title' => 'Price'],
'item_size' => ['title' => 'Sizes'],
'item_color' => ['title' => 'Colors'],
'item_desc' => ['title' => 'Description', 'display' => 'text'],
'item_link' => ['display' => 'link'],
'item_image1' => ['title' => 'First Image', 'display' => 'image'],
'item_image2' => ['title' => 'Second Image', 'display' => 'image'],
'item_image3' => ['title' => 'Third Image', 'display' => 'image'],
]);
// Change max text length for ['display' => 'text'] cells
$drawer->setTextLen(30);
// Disable text crop fro skipped columns
// $drawer->cropSkipped(false);
?>
<div class="container-fluid">
<div class="row mb-4">
<div class="col-6">
<h3>Drawer display <span class="h6">(CSV file used in examples: <a href="data/file.csv">file.csv</a>)</span></h3>
<hr>
For better displaying cells with links, images and text you can set appropriate display options.
It can be done by passing 2nd argument to Drawer(). Also you can set column title like shown below:
<pre>$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'], // Set column title
'item_desc' => ['title' => 'Description', 'display' => 'text'], // Crop text and set column title
'item_link' => ['display' => 'link'], // Display cell as link
'item_image1' => ['display' => 'image'], // Display cell as image
'item_image2' => ['display' => 'image'], // Display cell as image
'item_image3' => ['display' => 'image'], // Display cell as image
]);</pre>
<p>
<b>['title' => 'Product Name']</b> - Set column title<br>
<b>['display' => 'text']</b> - cell text will be cropped (to 50 chars by default).
Crop length can be set by <kbd>$drawer->setTextLen($len);</kbd><br>
<b>['display' => 'link']</b> - "Link" will be displayed instead of cell value (url)<br>
<b>['display' => 'image']</b> - Drawer will try to get image or file name and display it only<br>
</p>
<p>Note that all skipped columns ("image 4" in our case) is cropped by default. This behaviour can be
disabled
by <kbd>$drawer->cropSkipped(false);</kbd></p>
</div>
<div class="col-6">
<h3>Parser results</h3>
<?php dump($result) ?>
</div>
</div>
</div>
<h2>Drawer view</h2>
<table class="parse-table">
<thead>
<?php echo $drawer->head() ?>
</thead>
<tbody>
<?php echo $drawer->body() ?>
</tbody>
</table>
</body>
</html><file_sep><?php
require 'inc.head.php';
use ItemParser\Drawer;
use ItemParser\Parser;
$sizes = json_decode(file_get_contents('data/psizes.json'), true);
$colors = json_decode(file_get_contents('data/pcolors.json'), true);
$csvPath = 'data/file.csv';
$colorsMissing = $_POST['parseMissing']['item_color'];
$sizesMissing = $_POST['parseMissing']['item_size'];
if (!$sizesMissing) {
$sizesMissing = [
"5-6" => 0,
"6-7" => 0,
"7 (S)" => 4,
"8 (S)" => 5,
"10 (M)" => 7,
"16 (XL)" => -1,
];
}
// 1. Init Parser and set CSV file path
$parser = new Parser($csvPath);
// 1.1. Get ParseCsv object and configure it directly
$parser->getCsvObj()->delimiter = ';,';
// 2.1. Set rows to skip
$parser->skipRows([0]);
// 2.2. Config columns
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->paramField('item_color', [$colors, $colorsMissing]);
$parser->paramField('item_size', [$sizes, $sizesMissing])->required(true)->delimiters([';', '/']);;
$parser->textField('item_material');
$parser->textField('item_desc')->required();
$parser->textField('item_collection');
$parser->textField('item_link');
$parser->textField('item_image1');
$parser->textField('item_image2');
$parser->textField('item_image3');
// 2.3. Set columns order
if ($_POST['parseOrdering']) {
$parser->fieldsOrder($_POST['parseOrdering']);
} else {
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
4 => 'item_size',
// 5, 6 - skip
7 => 'item_material',
8 => 'item_desc',
9 => 'item_link',
10 => 'item_image1',
11 => 'item_image2',
12 => 'item_image3',
// further will be skipped
]);
}
// 3. Run parse and get results
$result = $parser->parse();
// 4.1. Init Drawer
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_sku' => ['title' => 'Product SKU'],
'item_price' => ['title' => 'Price'],
'item_size' => ['title' => 'Sizes'],
'item_color' => ['title' => 'Colors'],
'item_desc' => ['title' => 'Description', 'display' => 'text'],
'item_link' => ['display' => 'link'],
'item_image1' => ['display' => 'image'],
'item_image2' => ['display' => 'image'],
'item_image3' => ['display' => 'image'],
]);
// 4.2. Set hidden rows
if ($_POST['parseHide'] == 'valid') {
$drawer->hideValid();
} elseif ($_POST['parseHide'] == 'invalid') {
$drawer->hideInvalid();
} elseif (!$_POST['parseHide'] || $_POST['parseHide'] == 'custom') {
$drawer->hideRows([0, 6, 7, 8]);
}
// Change max text length for ['display' => 'text'] cells
$drawer->setTextLen(55);
// Disable text crop fro skipped columns
// $drawer->cropSkipped(false);
?>
<div class="container-fluid">
<div class="row mb-4">
<div class="col-6">
<h3>All features <span class="h6">(CSV file used in examples: <a href="data/file.csv">file.csv</a>)</span></h3>
<hr>
<p>Showcase of full-featured <b>Parser</b> and <b>Drawer</b> class</p>
<p>See course for better understanding</p>
<p>At the end of the source code of this file, you can find a JS script that prohibits the selection of multiple columns with the same name and marks selected options</p>
</div>
<div class="col-6">
<h3>Parser results</h3>
<?php dump($result) ?>
</div>
</div>
</div>
<h2>Drawer view</h2>
<form action="" method="post">
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
Missing params and display options:
<div class="missing-tables">
<?php echo $drawer->missing() ?>
<div style="display: inline-block">
<label class="mb-0"><input type="radio" name="parseHide"
value="all" <?php echo($_POST['parseHide'] == 'all' ? 'checked' : '') ?>> Show
all rows</label><br>
<label class="mb-0"><input type="radio" name="parseHide"
value="valid" <?php echo($_POST['parseHide'] == 'valid' ? 'checked' : '') ?>>
Hide valid</label><br>
<label class="mb-0"><input type="radio" name="parseHide"
value="invalid" <?php echo($_POST['parseHide'] == 'invalid' ? 'checked' : '') ?>>
Hide invalid</label><br>
<label class="mb-0"><input type="radio" name="parseHide"
value="custom" <?php echo(!$_POST['parseHide'] || $_POST['parseHide'] == 'custom' ? 'checked' : '') ?>>
Hide custom (1, 7-9)</label><br>
</div>
</div>
Results:
<table class="parse-table">
<thead>
<?php echo $drawer->head('select') ?>
</thead>
<tbody>
<?php echo $drawer->body() ?>
</tbody>
</table>
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse">
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="<KEY>
crossorigin="anonymous"></script>
<script>
const parserSelectName = '.parse-table select[name^="parseOrdering"]';
function updateParserSelects(el) {
let selectList = $(parserSelectName);
// Unset selected value in other select boxes
if ($(el) && $(el).val()) {
selectList.each(function() {
if ($(el).attr('name') !== $(this).attr('name') && $(el).val() === $(this).val()) {
$(this).val('');
}
});
}
// Update 'selected' option's class
selectList.find('option').removeClass('selected');
selectList.each(function(i, select) {
if ($(select).val()) {
selectList.find('option[value="' + $(select).val() + '"]').addClass('selected');
}
});
}
$(function () {
// Update selects first time on page load
updateParserSelects();
// Ser onChange listener
$('body').on('change', parserSelectName, function() {
updateParserSelects(this);
});
});
</script>
</body>
</html><file_sep><?php
namespace ItemParser;
use ItemParser\Helpers;
class FieldText extends FieldAbstract
{
protected function parseField($text)
{
$result = self::getResultArray($text, $this->getName(), $this->getType());
$valid = true;
$value = trim($text);
if ($this->isRequired() && !$value) {
$valid = false;
}
$result['valid'] = $valid;
$result['value'] = $value;
return [$result, null];
}
}<file_sep><?php
require 'inc.head.php';
use ItemParser\Drawer;
use ItemParser\Parser;
$colors = [
// ['id' => 1, 'value' => 'Black',],
// ['id' => 2, 'value' => 'Blue',],
// ['id' => 3, 'value' => 'Grey',],
// ['id' => 4, 'value' => 'Orange',],
// ['id' => 5, 'value' => 'Red',],
[
'id' => 5,
'value' => 'Gold',
'alias' => ['Golden', 'Golden-ORANGE']
],
];
$csvPath = 'data/file.csv';
// Get missings configs
$colorsMissing = $_POST['parseMissing']['item_color'];
// 1. Init Parser and set CSV file path
$parser = new Parser($csvPath);
// 2.1. Set rows to skip
$parser->skipRows([0]);
// 2.2. Config columns (in any order)
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->paramField('item_color', [$colors, $colorsMissing]);
// 2.3. Set columns ordering and skip some columns
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
// further will be skipped
]);
// 3. Run parse and get results
$result = $parser->parse();
// 4. Init Drawer with options
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_sku' => ['title' => 'Prod. SKU'],
'item_price' => ['title' => 'Price'],
'item_size' => ['title' => 'Sizes'],
'item_color' => ['title' => 'Colors'],
]);
// 4.1. Hide some rows and set crop lengths
$drawer->hideRows([6, 7, 8, 9, 10]);
$drawer->setTextLen(10);
?>
<div class="container-fluid">
<div class="row mb-4">
<div class="col-6">
<h3>Param aliases <span class="h6">(CSV file used in examples: <a href="data/file.csv">file.csv</a>)</span></h3>
<hr>
In this example we use aliases to find values (colors) that are slightly different but but
logically the same.<br>
Lines 5 and 6 has <b>Golden</b> and <b>Golden-orange</b> cell values, but gold color param was formed with <b>alias</b> field:
<pre>[
'id' => 5,
'value' => 'Gold',
'alias' => ['Golden', 'Golden-ORANGE']
],</pre>
<p>
So 'gold', 'golden' and 'golden-orange' values will be considered as <b>Gold</b> with id = 5.<br>
Parameter values search are case-insensitive
</p>
</div>
<div class="col-6">
<h3>Parser results</h3>
<?php dump($result) ?>
<b>Post array:</b>
<?php dump($_POST) ?>
</div>
</div>
</div>
<h2>Drawer view</h2>
<form action="" method="POST">
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
Missing params and display options:
<div class="missing-tables">
<?php echo $drawer->missing() ?>
</div>
<table class="parse-table">
<thead>
<?php echo $drawer->head() ?>
</thead>
<tbody>
<?php echo $drawer->body() ?>
</tbody>
</table>
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
</form>
</body>
</html><file_sep><?php
require 'inc.head.php';
use ItemParser\Drawer;
use ItemParser\Parser;
$sizes = json_decode(file_get_contents('data/psizes.json'), true);
$colors = json_decode(file_get_contents('data/pcolors.json'), true);
$csvPath = 'data/file.csv';
// 1. Init Parser and set CSV file path
$parser = new Parser($csvPath);
// 2.1. Set rows to skip
$parser->skipRows([0]);
// 2.2. Config columns (in any order)
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->paramField('item_color', [$colors]);
$parser->paramField('item_size', [$sizes])->required(true);
$parser->textField('item_size_text');
$parser->textField('item_collection');
$parser->textField('item_material');
$parser->textField('item_desc')->required();
$parser->textField('item_link');
$parser->textField('item_image1');
$parser->textField('item_image2');
$parser->textField('item_image3');
// 2.3. Set columns ordering and skip some columns
if ($_POST['parseOrdering']) {
$parser->fieldsOrder($_POST['parseOrdering']);
} else {
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
4 => 'item_size',
// 5, 6 - skip
7 => 'item_material',
8 => 'item_desc',
9 => 'item_link',
10 => 'item_image1',
11 => 'item_image2',
12 => 'item_image3',
// further will be skipped
]);
}
// 3. Run parse and get results
$result = $parser->parse();
// 4. Init Drawer with options
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_sku' => ['title' => 'Prod. SKU'],
'item_price' => ['title' => 'Price'],
'item_size' => ['title' => 'Sizes'],
'item_color' => ['title' => 'Colors'],
'item_desc' => ['title' => 'Description', 'display' => 'text'],
'item_link' => ['display' => 'link'],
'item_image1' => ['title' => 'First Image', 'display' => 'image'],
'item_image2' => ['title' => 'Second Image', 'display' => 'image'],
'item_image3' => ['title' => 'Third Image', 'display' => 'image'],
]);
?>
<div class="container-fluid">
<div class="row mb-4">
<div class="col-6">
<h3>Select columns <span class="h6">(CSV file used in examples: <a href="data/file.csv">file.csv</a>)</span></h3>
<hr>
<p>
To make available manual column selection 3 steps are required: <br>
1. Wrap table with form<br>
2. Draw table head with column <i>selects</i> <kbd>echo $drawer->head('select');</kbd><br>
3. Set new fields order by calling <kbd>$parser->fieldsOrder($_POST['parseOrdering']);</kbd>
</p>
<p>
By default names of select elements is <b>parseOrdering</b>. If you need to set another name, you can do
it by calling
<kbd>$drawer->setOrderInputName($name)</kbd>
</p>
</div>
<div class="col-6">
<h3>Parser results</h3>
<?php dump($result) ?>
<b>Post array:</b>
<?php dump($_POST) ?>
</div>
</div>
</div>
<h2>Drawer view</h2>
<form action="" method="POST">
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
<table class="parse-table">
<thead>
<?php echo $drawer->head('select') ?>
</thead>
<tbody>
<?php echo $drawer->body() ?>
</tbody>
</table>
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
</form>
</body>
</html><file_sep><?php
require 'inc.head.php';
use ItemParser\Drawer;
use ItemParser\Parser;
$sizes = json_decode(file_get_contents('data/psizes.json'), true);
$colors = json_decode(file_get_contents('data/pcolors.json'), true);
$csvPath = 'data/file.csv';
// Get missings configs
$colorsMissing = $_POST['parseMissing']['item_color'];
$sizesMissing = $_POST['parseMissing']['item_size'];
if (!$sizesMissing) {
$sizesMissing = [
"5-6" => 0,
"6-7" => 3,
"7 (S)" => 4,
"8 (S)" => 5,
"10 (M)" => 7,
"16 (XL)" => -1,
];
}
// 1. Init Parser and set CSV file path
$parser = new Parser($csvPath);
// 2.1. Set rows to skip
$parser->skipRows([0]);
// 2.2. Config columns (in any order)
$parser->textField('item_name')->required();
$parser->textField('item_sku')->required();
$parser->textField('item_price')->required();
$parser->paramField('item_color', [$colors, $colorsMissing]);
$parser->paramField('item_size', [$sizes, $sizesMissing])->required(true)->delimiters([';', '/']);
$parser->textField('item_size_text');
$parser->textField('item_collection');
$parser->textField('item_material');
$parser->textField('item_desc')->required();
$parser->textField('item_link');
$parser->textField('item_image1');
$parser->textField('item_image2');
$parser->textField('item_image3');
// 2.3. Set columns ordering and skip some columns
$parser->fieldsOrder([
0 => 'item_name',
1 => 'item_sku',
2 => 'item_price',
3 => 'item_color',
4 => 'item_size',
// 5, 6 - skip
7 => 'item_material',
8 => 'item_desc',
9 => 'item_link',
10 => 'item_image1',
11 => 'item_image2',
12 => 'item_image3',
// further will be skipped
]);
// 3. Run parse and get results
$result = $parser->parse();
// 4. Init Drawer with options
$drawer = new Drawer($parser, [
'item_name' => ['title' => 'Product Name'],
'item_sku' => ['title' => 'Prod. SKU'],
'item_price' => ['title' => 'Price'],
'item_size' => ['title' => 'Sizes'],
'item_color' => ['title' => 'Colors'],
'item_desc' => ['title' => 'Description', 'display' => 'text'],
'item_link' => ['display' => 'link'],
'item_image1' => ['title' => 'First Image', 'display' => 'image'],
'item_image2' => ['title' => 'Second Image', 'display' => 'image'],
'item_image3' => ['title' => 'Third Image', 'display' => 'image'],
]);
// 4.1. Hide some rows
$drawer->hideRows([0, 1, 2, 6, 7, 8]);
?>
<div class="container-fluid">
<div class="row mb-4">
<div class="col-6">
<h3>Missing params <span class="h6">(CSV file used in examples: <a href="data/file.csv">file.csv</a>)</span></h3>
<hr>
<p>
Here you can see how parameters replacement works.
If column was configured as Param Field - parser will extract values from cell
and search it in param array, that was configured to that Fields (i.e. $colors, $sizes)
</p>
<p>
Values are displayed in Drawer table as tags. Value can be found (white tag), not found (red tag), skipped (gray tag) or replaced (green tag) with existing param.
It can be configured by passing missing array when field is configured (you can see it in <b>2.2.</b> of this file source code)
</p>
<p>
Note that if Field is required and has no one valid values - Field will be invalid
</p>
<p>
By default cell values separated by one of <kbd>;</kbd> or <kbd>,</kbd> chars. You can define your own delimiters by calling Field's <kbd>delimiters(string|array)</kbd> method:
</p>
<pre>$parser->paramField('name', [$params])->delimiters([';', '/']);</pre>
<p>
If you set more than one delimiter - the most common character will be used (delimiter frequency calculated for each cell separately).
You can see how custom delimiter <kbd>/</kbd> works at <b>6</b> line
</p>
</div>
<div class="col-6">
<h3>Parser results</h3>
<?php dump($result) ?>
<b>Post array:</b>
<?php dump($_POST) ?>
</div>
</div>
</div>
<h2>Drawer view</h2>
<form action="" method="POST">
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
Missing params and display options:
<div class="missing-tables">
<?php echo $drawer->missing() ?>
</div>
<table class="parse-table">
<thead>
<?php echo $drawer->head() ?>
</thead>
<tbody>
<?php echo $drawer->body() ?>
</tbody>
</table>
<input type="submit" class="btn btn-success btn-lg btn-block" value="Apply and parse"><br>
</form>
</body>
</html><file_sep><?php
namespace ItemParser;
use ItemParser\Parser;
use ItemParser\FieldAbstract as Field;
use ItemParser\FieldParam;
class Drawer
{
/**
* @var \ItemParser\Parser
*/
private $parser;
private $options;
private $hidden = [];
private static $orderInput = 'parseOrdering';
private static $missingInput = 'parseMissing';
private static $textLen = 50;
private static $cropSkipped = true;
public function __construct(Parser $parser, $options = [])
{
if ($parser) {
$this->setParser($parser);
}
if ($options) {
$this->options = $options;
foreach ($options as $name => $option) {
$field = $this->parser->getFieldByName($name);
if ($field) {
$field->title($option['title']);
$field->display($option['display']);
}
}
}
}
public function setParser(Parser $parser)
{
$this->parser = $parser;
}
public function setTextLen($len)
{
self::$textLen = intval($len);
}
public function cropSkipped($crop = true)
{
self::$cropSkipped = $crop;
}
/**
* Set name attribute value for ordering select
*
* @param string $name ordering Select element name
*/
public function setOrderInputName($name)
{
self::$orderInput = $name;
}
/**
* Set name attribute value for missing select
*
* @param string $name missing Select element name
*/
public function setMissingInputName($name)
{
self::$missingInput = $name;
}
public function head($format = 'html', $opts = [])
{
$result = null;
$items = [];
$parser = $this->parser;
for ($i = 0; $i < $parser->cols(); $i++) {
$field = $parser->getField($i);
$fieldName = self::fieldName($field);
$items[] = [
'index' => $i,
'value' => (string)$fieldName,
];
}
if ($format == 'html') {
$result .= '<td>#</td>';
foreach ($items as $item) {
$result .= '<td>' . $item['value'] . '</td>';
}
$result = '<tr>' . $result . '</tr>';
} elseif ($format == 'select') {
$result .= '<td>#</td>';
for ($i = 0; $i < $parser->cols(); $i++) {
$result .= '<td>' . $this->drawSelect($i) . '</td>';
}
$result = '<tr>' . $result . '</tr>';
} elseif ($format == 'json') {
$result = json_encode($items);
} elseif ($format == 'array') {
$result = $items;
}
return $result;
}
public function body()
{
$parser = $this->parser;
$res = $parser->result();
$hidden = [];
for ($r = 0; $r < $parser->rows(); $r++) {
if (in_array($r, $this->hidden)) {
$hidden['cnt']++;
$hidden['min'] = !$hidden['min'] ? $res[$r]['row'] : $hidden['min'];
$hidden['max'] = $res[$r]['row'];
continue;
}
if ($hidden) {
$result .= self::drawHiddenRow($hidden, $parser->cols());
}
$cells = '<td>' . $res[$r]['row'] . '</td>';
$valid = true;
for ($i = 0; $i < $parser->cols(); $i++) {
$field = $parser->getField($i);
$value = $res[$r]['fields'][$i];
$cells .= self::drawCell($value, $field, ['skipRow' => $res[$r]['skip']]);
}
$trCls = null;
if ($res[$r]['skip']) {
$trCls = 'skipped';
} elseif (!$res[$r]['valid']) {
$trCls = 'invalid';
}
$result .= '<tr' . ($trCls ? ' class="' . $trCls . '"' : '') . '>' . $cells . '</tr>';
}
if ($hidden) {
$result .= self::drawHiddenRow($hidden, $parser->cols());
}
return $result;
}
private static function drawHiddenRow(&$hidden, $cols)
{
if ($hidden['min'] != $hidden['max']) {
$num = $hidden['min'] . '..' . $hidden['max'];
} else {
$num = $hidden['min'];
}
$result = '<tr><td>' . $num . '</td><td class="hidden" colspan="' . ($cols) . '">'
. '... hidden <b>' . $hidden['cnt'] . '</b> line(s) ...</td></tr>';
$hidden = [];
return $result;
}
public function missing()
{
$table = '';
$fields = $this->parser->getFields('selected');
foreach ($fields as $field) {
if ($field instanceof FieldParam && $field->hasMissing()) {
$table .= '<table>';
$table .= '<tr><td colspan="2"><b>' . self::fieldName($field) . '</b></td></tr>';
foreach ($field->getMissing() as $name => $value) {
$table .= '<tr><td>' . $name . '</td>'
. '<td>' . self::drawValues($field, $name, $value) . '</td></tr>';
}
$table .= '</table>';
}
}
return $table;
}
public function hideValid()
{
foreach ($this->parser->result() as $r => $row) {
if ($row['valid']) {
$rows[] = $r;
}
}
$this->hideRows($rows);
}
public function hideInvalid()
{
foreach ($this->parser->result() as $r => $row) {
if (!$row['valid']) {
$rows[] = $r;
}
}
$this->hideRows($rows);
}
/**
* Set rows that will not be displayed
*
* @param array $rows
*/
public function hideRows($rows)
{
if ($rows && !is_array($rows)) {
$rows = [$rows];
}
$this->hidden = $rows;
}
private static function drawValues(FieldParam $field, $name, $value)
{
$options = '<option value="0">-</option>'
. '<option value="-1" ' . ($value == -1 ? 'selected' : '') . '>-- Skip --</option>';
foreach ($field->getParams() as $param) {
$select = $param['id'] == $value ? 'selected' : '';
$options .= '<option value="' . $param['id'] . '" ' . $select . '>' . $param['value'] . '</option>';
}
$name = htmlspecialchars($name);
$select = '<select name="' . self::$missingInput . '[' . $field->getName() . '][' . $name . ']">'
. $options
. '</select>';
return $select;
}
private function drawSelect($index)
{
$parser = $this->parser;
$currentField = $parser->getField($index);
$options = '';
foreach ($parser->getFields() as $field) {
$optCls = '';
$selected = $field === $currentField ? 'selected' : '';
$name = self::fieldName($field);
if ($field->isRequired()) {
$name .= ' *';
$optCls = 'class="required"';
}
$options .= "<option value=\"{$field->getName()}\" {$optCls} {$selected}>{$name}</option>";
}
$select = '<select name="' . self::$orderInput . '[' . $index . ']">'
. '<option value="">-</option>'
. $options
. '</select>';
return $select;
}
private static function drawCell($value, Field $field = null, $opts = [])
{
$tdCls = null;
if (!$field || $opts['skipRow']) {
$text = $value['text'];
if (self::$cropSkipped) {
$text = self::drawCellText($text, 'text');
}
$tdCls = 'skipped';
} elseif ($field) {
if ($field->is(Field::TYPE_TEXT)) {
$text = self::drawCellText($value['value'], $field->getDisplay());
} elseif ($field->is(Field::TYPE_PARAM)) {
$text = self::drawTags($value['value']);
}
if (!$value['valid']) {
$tdCls = 'invalid';
}
}
return '<td' . ($tdCls ? ' class=' . $tdCls : '') . '>' . $text . '</td>';
}
private static function drawCellText($value, $display)
{
$text = '';
if ($display == 'link') {
if ($value) {
$text = '<a href="' . $value . '" target="_blank">Link</a>';
}
} elseif ($display == 'image') {
if (filter_var($value, FILTER_VALIDATE_URL)) {
$link = basename(parse_url($value, PHP_URL_PATH));
} else {
$link = $value;
}
$text = '<a href="' . $value . '" target="_blank">' . $link . '</a>';
} elseif ($display == 'text') {
if (mb_strlen($value) > self::$textLen) {
$text = substr($value, 0, self::$textLen) . ' ...';
} else {
$text = $value;
}
} else {
$text = $value;
}
return $text;
}
private static function drawTags($items)
{
$tags = '';
foreach ($items as $item) {
$tagCls = self::getTagCls($item);
if ($item['valid']) {
$text = $item['value'];
} else {
$text = $item['text'];
}
$tags .= '<span class="tag' . ($tagCls ? ' ' . $tagCls : '') . '">' . $text . '</span>';
}
return $tags;
}
private static function getTagCls($item)
{
$tagCls = null;
if ($item['skip']) {
$tagCls = 'skipped';
} elseif ($item['replace']) {
$tagCls = 'replaced';
} elseif (!$item['valid']) {
$tagCls = 'invalid';
}
return $tagCls;
}
private static function fieldName(Field $field = null)
{
if ($field) {
return $field->getTitle() ? $field->getTitle() : $field->getName();
}
return '';
}
}
|
75f3c5b9ccae31d5aba9961842b100a3b647f7fa
|
[
"Markdown",
"PHP"
] | 19 |
Markdown
|
decss/item-parser
|
5a10d4df83b69abf690d1410ba5733dda25dce44
|
455010771d94a8d1353ac860e7fe9ac0221dff8e
|
refs/heads/master
|
<file_sep>package com.bhanu.turnstile.state;
import com.bhanu.turnstile.TurnstileFsm;
/**
* this state is used by complicated fsm , after the single coin it moves to
* this state
*
* @author Dev-il
*
*/
public class TurnstileIntermidiateLockedState implements TurnstileState {
private TurnstileLockedState lockedState;
@Override
public void coin(TurnstileFsm fsm) {
init();
lockedState.coin(fsm);
}
@Override
public void pass(TurnstileFsm fsm) {
init();
lockedState.pass(fsm);
}
private void init() {
if (this.lockedState == null) {
lockedState = new TurnstileLockedState();
}
}
}
<file_sep>package com.bhanu.turnstile.state;
import com.bhanu.turnstile.TurnstileFsm;
public class TurnstileLockedState implements TurnstileState{
private TurnstileUnLockedState unLockedState ;
@Override
public void coin(TurnstileFsm fsm) {
if(unLockedState==null) {
unLockedState = new TurnstileUnLockedState();
}
fsm.setState(unLockedState);
fsm.unLock();
}
@Override
public void pass(TurnstileFsm fsm) {
fsm.setState(this);
fsm.alarm();
}
}
<file_sep>package com.bhanu.turnstile;
public class SimpleTurnstileFsm extends TurnstileFsm{
private String actions="";
@Override
public void lock() {
actions=actions+"L";
}
@Override
public void unLock() {
actions=actions+"U";
}
@Override
public void thankYou() {
actions=actions+"T";
}
@Override
public void alarm() {
actions=actions+"A";
}
public String getActions() {
return actions;
}
}
<file_sep># turnstile
turnstile state pattren
A state pattren example which simulates a trunstile mechanism.
<file_sep>package com.bhanu.turnstile.state;
import com.bhanu.turnstile.TurnstileFsm;
public interface TurnstileState {
public void coin(TurnstileFsm fsm);
public void pass(TurnstileFsm fsm);
}
|
0930225262e2b7f97ed1b9ac48cf59ce55a94b0b
|
[
"Markdown",
"Java"
] | 5 |
Java
|
bhanuunrivalled/turnstile
|
84798a31f8eb28e201c10adc233dcfeba1af5564
|
b1d19208ff5682ee174ad8691fb13b15aac1b97b
|
refs/heads/master
|
<repo_name>sincezhg/Demo<file_sep>/CoreAPI/CoreWeb/Models/UserInfo.cs
using System;
namespace CoreWeb.Models
{
public class UserInfo
{
public UserInfo()
{
}
public UserInfo(int UserID, string UserName, string Phone, string Address)
{
_UserID = UserID;
_UserName = UserName;
_Phone = Phone;
_Address = Address;
}
private int _UserID;
private string _UserName;
private string _Phone;
private string _Address;
public int UserID { get => _UserID; set => _UserID = value; }
public string UserName { get => _UserName; set => _UserName = value; }
public string Address { get => _Address; set => _Address = value; }
public string Phone { get => _Phone; set => _Phone = value; }
}
}
<file_sep>/CoreAPI/CoreAPI/Controllers/ValuesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace CoreAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
static IEnumerable<string> GetNames()
{
string[] names =
{
"Archimedes", "Pythagoras", "Euclid", "Socrates", "Plato"
};
return from name in names
select name;
}
}
}
<file_sep>/CoreAPI/CoreWeb/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreWeb.Models;
namespace CoreWeb.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public IActionResult UserList()
{
List<UserInfo> users = LoadUser();
return View();
}
public List<UserInfo> LoadUser()
{
List<UserInfo> users = new List<UserInfo>()
{
new UserInfo(1,"jack","1863123335","123"),
new UserInfo(2,"lucy","1863123335","123"),
new UserInfo(3,"lily","1863123335","123"),
new UserInfo(4,"nick","1863123335","123"),
new UserInfo(5,"james","1863123335","123"),
new UserInfo(6,"jason","1863123335","123"),
new UserInfo(7,"cherry","1863123335","123"),
};
return users;
}
}
}
|
ce0bfe981a6174c20dd805a42b597d1eb238caf9
|
[
"C#"
] | 3 |
C#
|
sincezhg/Demo
|
91343d4a0881c81980a55b6e3a22f35156063174
|
38d4cd28e186683afb030fd32dc3ac7e0b582928
|
refs/heads/master
|
<repo_name>developerbch/Test1<file_sep>/Day5/src/ArraylistEx.java
import java.util.*;
public class ArraylistEx {
List<Dataclass> li;
ArraylistEx() {
new ArrayList<Dataclass>();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArraylistEx ar = new ArraylistEx();
int choice;
System.out.println("--------------------");
System.out.println("--- 종합 정보 시스템 ----");
System.out.println("--1. 추가 ----");
System.out.println("--2. 수정 ----");
System.out.println("--3. 삭제 ----");
System.out.println("--4. 전체 출력 ----");
System.out.println("--5. 종료 ----");
System.out.println("--------------------");
choice = sc.nextInt();
if(choice == 1) {
System.out.println("이름을 입력해주세요 : ");
}
}
}
|
99b8abe1399c6d2f9ae64f495cba3a3139a9311f
|
[
"Java"
] | 1 |
Java
|
developerbch/Test1
|
71bad754fdc523c3ed229678991a92a169cc72cd
|
332bca6ca0a905375eb2302f905e9415b7630520
|
refs/heads/master
|
<file_sep>using System;
namespace DataMapper
{
public class Copy : ICopy
{
public int CopyId { get; set; }
public bool Available { get; set; }
public int MovieId { get; set; }
public Copy(int copyId,bool available,int movieId)
{
CopyId = copyId;
Available = available;
MovieId = movieId;
}
}
}
<file_sep>using System;
namespace DataMapper
{
public interface IMovieMapper
{
void Delete();
void Update(int movieId,string title,int year,int ageRestriction,float price);
void Read();
void Save(IMovie entity);
void Insert();
}
}
<file_sep>using System;
using Npgsql;
namespace DataMapper
{
public class CopyMapper : ICopyMapper
{
private ICopy _instance { get; set; }
public void Delete()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand delete = new NpgsqlCommand($"DELETE FROM copies WHERE copy_id={_instance.CopyId} AND available={_instance.Available} AND movie_id={_instance.MovieId}", connection);
connection.Open();
delete.ExecuteNonQuery();
connection.Close();
}
}
public void Update(int copyId, bool available, int movieId)
{
using(NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand update = new NpgsqlCommand($"UPDATE copies SET copy_id={copyId},available={available},movie_id={movieId} WHERE copy_id={_instance.CopyId} AND available={_instance.Available} AND movie_id={_instance.MovieId}", connection);
connection.Open();
update.ExecuteNonQuery();
_instance.MovieId = movieId;
_instance.CopyId = copyId;
_instance.Available = available;
connection.Close();
}
}
public void Read()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand read = new NpgsqlCommand($"SELECT * FROM copies WHERE copy_id={_instance.CopyId} AND available={_instance.Available} AND movie_id={_instance.MovieId}", connection);
connection.Open();
NpgsqlDataReader reader = read.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine($"CopyID-{reader[0]},Available-{reader[1]},MovieID-{reader[2]}");
}
}
connection.Close();
}
}
public void Save(ICopy entity)
{
_instance = entity;
}
public void Insert()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand insert = new NpgsqlCommand($"INSERT INTO copies VALUES ({_instance.CopyId},{_instance.Available},{_instance.MovieId})",connection);
connection.Open();
insert.ExecuteNonQuery();
connection.Close();
}
}
}
}
<file_sep>using System;
using Npgsql;
using System.Collections.Generic;
namespace ActiveRecordLibrary
{
public class MovieRecord
{
public int MovieId { get; private set; }
public string Title { get; private set; }
public int Year { get; private set; }
public float Price { get; private set; }
public int NumberOfAvailableCopies => GetCountOfAvailableCopies();
public int NumberOfAllCopies => GetCountOfAllCopies();
public string AvailableACopiesFromTotalCopies => $"{NumberOfAvailableCopies}/{NumberOfAllCopies}";
public MovieRecord(int movieId, string title, int year, float price)
{
MovieId = movieId;
Title = title;
Year = year;
Price = price;
}
public void RemoveThisMovieFromDatabase()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand check = new NpgsqlCommand($"SELECT COUNT(movie_id) FROM movies WHERE movie_id={MovieId}");
int count = int.Parse(Convert.ToString(check.ExecuteReader()[0]));
if (count != 0)
{
NpgsqlCommand remove = new NpgsqlCommand($"DELETE FROM movies WHERE movie_id={MovieId}");
remove.ExecuteNonQuery();
}
else
Console.WriteLine("Sorry.There aren't any movies in the database with this identifier.");
}
}
public void Rent(int clientId)
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
if (NumberOfAvailableCopies != 0)
{
NpgsqlCommand getMaxId = new NpgsqlCommand($"SELECT MAX(copy_id) FROM copies WHERE movie_id={MovieId} AND available=true");
NpgsqlDataReader reader = getMaxId.ExecuteReader();
int copyId = int.Parse(Convert.ToString(reader[0]));
NpgsqlCommand insert = new NpgsqlCommand($"INSERT INTO rentals(copy_id, client_id, date_of_rental, date_of_return) VALUES({copyId}, {clientId}, NOW(), NULL)");
insert.ExecuteNonQuery();
NpgsqlCommand update = new NpgsqlCommand($"UPDATE copies SET available = false WHERE copy_id={copyId}");
update.ExecuteNonQuery();
}
else
Console.WriteLine("Sorry , we haven't any available copies of this movie.");
}
}
private int GetCountOfAvailableCopies()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand count = new NpgsqlCommand($"SELECT COUNT(copy_id) FROM copies WHERE movie_id={MovieId} AND available=true");
NpgsqlDataReader reader = count.ExecuteReader();
int result = int.Parse(Convert.ToString(reader[0]));
return result;
}
}
private int GetCountOfAllCopies()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand count = new NpgsqlCommand($"SELECT COUNT(copy_id) FROM copies WHERE movie_id={MovieId}");
NpgsqlDataReader reader = count.ExecuteReader();
int result = int.Parse(Convert.ToString(reader[0]));
return result;
}
}
public void InsertThisCopyToDatabase()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand insert = new NpgsqlCommand($"INSERT INTO movies (movie_id,title,year,price) VALUES({MovieId},'{Title}',{Year},{Price})");
insert.ExecuteNonQuery();
}
}
public static MovieRecord GetMovieById(int id)
{
MovieRecord result = null;
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = razumovsky123; Database = MoviesCodeFirst;"))
{
NpgsqlCommand select = new NpgsqlCommand($"SELECT movie_id,title,year,price FROM movies WHERE copy_id={id}", connection);
NpgsqlDataReader reader = select.ExecuteReader();
List<string> movieData = new List<string>();
int i = 0;
while (reader.Read())
{
i++;
movieData.Add(Convert.ToString(reader[i]));
}
result = new MovieRecord(int.Parse(movieData[0]), Convert.ToString(movieData[1]), int.Parse(movieData[2]), float.Parse(movieData[2]));
}
return result;
}
}
}
<file_sep>using System;
using Npgsql;
namespace Task1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;");
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM movies", connection);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
Console.WriteLine($"Movie id-{reader[0]},Title-{reader[1]},Year-{reader[2]},Age restriction-{reader[3]},Price-{reader[4]}\n\n");
connection.Close();
Console.WriteLine("Do you want to make a new movie?Yes-1,No-0");
string answer = Console.ReadLine();
if (answer == "1")
{
NpgsqlConnection addConnection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;");
addConnection.Open();
Console.Write("Movie id:");
int movieId = Convert.ToInt32(Console.ReadLine());
Console.Write("Title:");
string title = Console.ReadLine();
Console.Write("Year:");
int year = Convert.ToInt32(Console.ReadLine());
Console.Write("Age Restriction:");
int ageRestriction = Convert.ToInt32(Console.ReadLine());
Console.Write("Price:");
float price = float.Parse(Console.ReadLine());
NpgsqlCommand add =new NpgsqlCommand($"INSERT INTO movies (movie_id,title,year,age_restriction,price) VALUES({movieId},'{title}',{year},{ageRestriction},{price})", addConnection);
add.ExecuteNonQuery();
Console.Read();
addConnection.Close();
Console.Clear();
continue;
}
Console.Clear();
continue;
}
}
}
}
<file_sep>using System;
namespace DataMapper
{
public interface ICopy
{
int CopyId { get; set; }
bool Available { get; set; }
int MovieId { get; set; }
}
}
<file_sep>using System;
namespace DataMapper
{
public interface ICopyMapper
{
void Delete();
void Update(int movieId,bool available,int copyId);
void Read();
void Save(ICopy entity);
void Insert();
}
}
<file_sep>using System;
using Npgsql;
namespace Task1
{
class Program
{
static void Main(string[] args)
{
NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;");
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT title,first_name,last_name FROM starring s JOIN actors act ON act.actor_id=s.actor_id JOIN movies m On m.movie_id=s.movie_id", connection);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
Console.WriteLine($"Title-{reader[0]},Movie_id-{reader[1]},Age restriction-{reader[2]},Year-{reader[3]},Firstname-{reader[4]},Lastname-{reader[5]}");
connection.Close();
}
}
}
<file_sep>using System;
using Npgsql;
using System.Collections.Generic;
namespace ActiveRecordLibrary
{
public class CopyRecord
{
public int CopyId { get; private set; }
public int MovieId { get; private set; }
public bool Available { get; private set; }
public CopyRecord(int copyId, int movieId, bool available)
{
CopyId = copyId;
MovieId = movieId;
Available = available;
}
public void RemoveThisCopyFromDatabase()
{
using(NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand check = new NpgsqlCommand($"SELECT COUNT(copy_id) FROM copies WHERE copy_id={CopyId}");
int count = int.Parse(Convert.ToString(check.ExecuteReader()[0]));
if (count != 0)
{
NpgsqlCommand remove = new NpgsqlCommand($"DELETE FROM copies WHERE copy_id={CopyId} AND available={Available} AND movie_id={MovieId}");
remove.ExecuteNonQuery();
}
else
Console.WriteLine("Sorry.There aren't any copies in the database with this identifier.");
}
}
public void InsertThisCopyToDatabase()
{
using(NpgsqlConnection connection=new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand insert = new NpgsqlCommand($"INSERT INTO copies (copy_id,available,movie_id) VALUES({CopyId},{Available},{MovieId})");
insert.ExecuteNonQuery();
}
}
public static CopyRecord GetCopyById(int id)
{
CopyRecord result = null;
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand select = new NpgsqlCommand($"SELECT copy_id,available,movie_id FROM copies WHERE copy_id={id}",connection);
NpgsqlDataReader reader = select.ExecuteReader();
List<string> copyData = new List<string>();
int i = 0;
while (reader.Read())
{
i++;
copyData.Add(Convert.ToString(reader[i]));
}
result = new CopyRecord(int.Parse(copyData[0]), int.Parse(copyData[1]), bool.Parse(copyData[2]));
}
return result;
}
}
}
<file_sep>using System;
using Npgsql;
namespace Task1
{
class Program
{
static void Main(string[] args)
{
NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;");
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM copies c JOIN movies m ON m.movie_id=c.copy_id", connection);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
Console.WriteLine($"Title-{reader[0]},Movie_id-{reader[1]},Age restriction-{reader[2]},Year-{reader[3]},Firstname-{reader[4]},Lastname-{reader[5]},Copy_id-{reader[6]},Available-{reader[7]}\n\n");
connection.Close();
}
}
}
<file_sep>using System;
namespace DataMapper
{
public interface IMovie
{
public int MovieId { get; set; }
public string Title { get; set; }
public int Year { get; set; }
public int AgeRestriction { get; set; }
public float Price { get; set; }
}
}
<file_sep>using System;
using Npgsql;
namespace ActiveRecord
{
class Program
{
static void Main(string[] args)
{
NpgsqlConnection conn = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;");
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT m.movie_id,title,year,age_restriction,price,COUNT(cop.copy_id) AS count FROM movies m JOIN copies cop ON cop.copy_id=m.movie_id GROUP BY m.movie_id");
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
Console.WriteLine($"Movie id-{reader[0]},Title-{reader[1]},Year-{reader[2]},Age restriction-{reader[3]},Price-{reader[4]},Count of copies-{reader[5]}");
conn.Close();
}
}
}
<file_sep>using System;
using Npgsql;
namespace Task1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;");
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM copies", connection);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
Console.WriteLine($"Copy id-{reader[0]},Available-{reader[1]},Movie id-{reader[2]}\n\n");
connection.Close();
Console.WriteLine("Do you want to make a new copy?Yes-1,No-0");
string answer = Console.ReadLine();
if (answer == "1")
{
NpgsqlConnection addConnection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;");
addConnection.Open();
Console.Write("Movie id:");
int movieId = Convert.ToInt32(Console.Read());
Console.Write("Copy id:");
int copyId = Convert.ToInt32(Console.Read());
Console.Write("Available:");
bool available = Convert.ToBoolean(Console.Read());
addConnection.Open();
NpgsqlCommand add =new NpgsqlCommand($"INSERT INTO copies (copy_id,available,movie_id) VALUES({copyId},{available},{movieId})", addConnection);
add.ExecuteNonQuery();
Console.Read();
addConnection.Close();
Console.Clear();
continue;
}
Console.Clear();
continue;
}
}
}
}
<file_sep>using System;
using Npgsql;
namespace DataMapper
{
public class MovieMapper : IMovieMapper
{
private IMovie _instance { get; set; }
public void Delete()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand delete = new NpgsqlCommand($"DELETE FROM movies WHERE movie_id={_instance.MovieId} AND title='{_instance.Title}' AND year={_instance.Year}", connection);
connection.Open();
delete.ExecuteNonQuery();
connection.Close();
}
}
public void Update(int movieId, string title, int year, int ageRestriction, float price)
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand update = new NpgsqlCommand($"UPDATE movies SET movie_id={movieId},title='{title}',year={year},age_restriction={ageRestriction},price={price} WHERE movie_id={_instance.MovieId} AND title='{_instance.Title}' AND year={_instance.Year}", connection);
connection.Open();
update.ExecuteNonQuery();
_instance.MovieId = movieId;
_instance.Year = year;
_instance.Title = title;
_instance.MovieId = movieId;
connection.Close();
}
}
public void Read()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand read = new NpgsqlCommand($"SELECT * FROM movies WHERE movie_id={_instance.MovieId}", connection);
connection.Open();
NpgsqlDataReader reader = read.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine($"ID-{reader[0]},Title-{reader[1]},Year-{reader[2]},Age restriction-{reader[3]},Price-{reader[4]}");
}
}
connection.Close();
}
}
public void Save(IMovie entity)
{
_instance = entity;
}
public void Insert()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = 127.0.0.1; User Id = postgres; Password = <PASSWORD>; Database = MoviesCodeFirst;"))
{
NpgsqlCommand insert = new NpgsqlCommand($"INSERT INTO movies VALUES ({_instance.MovieId},'{_instance.Title}',{_instance.Year},{_instance.AgeRestriction},{_instance.Price})", connection);
connection.Open();
insert.ExecuteNonQuery();
connection.Close();
}
}
}
}
<file_sep>using System;
using DataMapper;
namespace DataMapperTest
{
class Program
{
static void Main(string[] args)
{
Movie movie = new Movie(21, "Razumovsky", 1994, 27, 27);
MovieMapper mapper = new MovieMapper();
mapper.Save(movie);
mapper.Insert();
mapper.Read();
mapper.Update(22, "Razumovsky Top!", 1994, 27, 27);
mapper.Read();
mapper.Delete();
movie.MovieId = 21;
movie.Year = 2021;
movie.Title = "Razumovsky eats potatoes";
movie.Price = 100;
movie.AgeRestriction= 12;
mapper.Insert();
mapper.Read();
Console.Read();
Copy copy = new Copy(21,true,5);
CopyMapper copyMapper = new CopyMapper();
copyMapper.Save(copy);
copyMapper.Insert();
copyMapper.Read();
copyMapper.Update(22,false,8);
copyMapper.Read();
copyMapper.Delete();
copy.MovieId = 6;
copy.Available = true;
copy.CopyId = 23;
copyMapper.Insert();
copyMapper.Read();
Console.Read();
}
}
}
|
efb141e6d66149999465c094af8ff10ece49acf8
|
[
"C#"
] | 15 |
C#
|
kolbasator/ADO.NET
|
c04f14a9ebd659bb1ac60467183c4e144e8b4822
|
6f55a2adbd850c1f0b36ef3fadd0c360e5460563
|
refs/heads/master
|
<file_sep>package com.zc741.navigationdrawer;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("标题");
toolbar.inflateMenu(R.menu.base_toolbar_menu);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
searchPopup();
break;
case R.id.action_notification:
Toast.makeText(MainActivity.this, "notification", Toast.LENGTH_SHORT).show();
break;
case R.id.action_item1:
Toast.makeText(MainActivity.this, "设置", Toast.LENGTH_SHORT).show();
break;
case R.id.action_item2:
Toast.makeText(MainActivity.this, "模式", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
assert fab != null;
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
// startActivity(new Intent(MainActivity.this, CoordinatorLayoutActivity.class));
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//TextInputLayout
final TextInputLayout textInputLayout = (TextInputLayout) findViewById(R.id.textInputLayout);
EditText editText = textInputLayout.getEditText();
textInputLayout.setHint("请输入用户名");
assert editText != null;
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() < 6) {
textInputLayout.setError("错误!用户名小于6位");
textInputLayout.setErrorEnabled(true);
} else {
textInputLayout.setErrorEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() < 6) {
textInputLayout.setError("错误!用户名小于6位");
textInputLayout.setErrorEnabled(true);
} else {
textInputLayout.setErrorEnabled(false);
}
}
});
//another
final TextInputLayout textInputLayout1 = (TextInputLayout) findViewById(R.id.textInputLayout1);
EditText editText1 = textInputLayout1.getEditText();
textInputLayout1.setHint("请输入密码");
assert editText1 != null;
editText1.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() < 6) {
textInputLayout.setError("错误!用户名小于6位");
textInputLayout.setErrorEnabled(true);
} else {
textInputLayout.setErrorEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() < 6) {
textInputLayout1.setError("错误!密码少于6位");
textInputLayout1.setErrorEnabled(true);
} else {
textInputLayout1.setErrorEnabled(false);
}
}
});
}
private void searchPopup() {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.search_popue, null);
PopupWindow popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
popupWindow.setAnimationStyle(R.style.searchPopup);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true);
WindowManager.LayoutParams params = getWindow().getAttributes();//创建当前界面的一个参数对象
params.alpha = 0.8f;
getWindow().setAttributes(params);//把该参数对象设置进当前界面中
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.alpha = 1.0f;//设置为不透明,即恢复原来的界面
getWindow().setAttributes(params);
}
});
//第一个参数为父View对象,即PopupWindow所在的父控件对象,第二个参数为它的重心,后面两个分别为x轴和y轴的偏移量
popupWindow.showAtLocation(inflater.inflate(R.layout.activity_main, null), Gravity.TOP, 0, 0);
//键盘弹出
EditText edit_search = (EditText) view.findViewById(R.id.edit_search);
edit_search.setFocusable(true);
edit_search.requestFocus();
InputMethodManager inputMethodManager = (InputMethodManager) edit_search.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
}
//处理键盘监听 点击除EditText区域之外键盘消失
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View view = getCurrentFocus();
if (isShouldHideInput(view, ev)) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (im != null) {
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
return super.dispatchTouchEvent(ev);
}
//
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
private boolean isShouldHideInput(View view, MotionEvent ev) {
if (view != null && (view instanceof EditText)) {
int[] leftTop = {0, 0};
//获取输入框当前位置
view.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + view.getHeight();
int right = left + view.getWidth();
if (ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom) {
//点击的是输入框 保留点击EditText事件
return false;
} else {
return true;
}
}
return false;
}
//设置监听
public void turn_to_another(View view) {
startActivity(new Intent(this, ScrollingActivity.class));
}
public void turn_to_another1(View view) {
startActivity(new Intent(this, TabLayoutActivity.class));
}
public void turn_to_another2(View view) {
startActivity(new Intent(this, CoordinatorLayoutActivity.class));
}
public void turn_to_another3(View view) {
startActivity(new Intent(this, NestedScrollViewViewPager.class));
}
public void turn_to_another4(View view) {
startActivity(new Intent(this, BottomSheetActivity.class));
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
<file_sep># NavigationDrawer
组合四种不同的页面布局
### Scrolling和ToolBar

### ToolBar、Tabayout和ViewPager

### CoordinatorLayout、ToolBar、TabLayout和ViewPager

### NestedScrollView、CollapsingToolbarLayout、TabLayout、ViewPager

### 利用SlidingMenu实现微信右滑关闭当前页面
1. 相关文件
1. BaseActivity.java (其他Activity继承BaseActivity即可)
2. AndroidManifest.xml相关注册的Activity的主题更改
3. style主题页面的修改
4. anim动画文件
5. slide_shadow.xml文件
6. 使用时注意以上相关文件
注:
最终效果可以查看:http://www.zc741.com/index.php?controller=post&action=view&id_post=17
<file_sep>package com.zc741.navigationdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
*
* Created by jiae on 2016/5/6.
*/
public class ResumeAdapter extends FragmentPagerAdapter {
public ResumeAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (0 == position) {
fragment = new ResumeBasicFragment();
} else if (1 == position) {
fragment = new ResumeSkillFragment();
} else if (2 == position) {
fragment = new ResumeWorksExperienceFragment();
} else if (3 == position) {
fragment = new ResumeProjectsExperienceFragment();
}
return fragment;
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "TAB 1";
case 1:
return "TAB 2";
case 2:
return "TAB 3";
case 3:
return "TAB 4";
}
return null;
}
}
<file_sep>package com.zc741.navigationdrawer;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class NestedScrollViewViewPager extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_nested_scroll_view_view_pager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.mipmap.ic_arrow_back);
toolbar.inflateMenu(R.menu.base_toolbar_menu);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(getApplicationContext(), "search", Toast.LENGTH_SHORT).show();
break;
case R.id.action_notification:
Toast.makeText(getApplicationContext(), "notification", Toast.LENGTH_SHORT).show();
break;
case R.id.action_item1:
Toast.makeText(getApplicationContext(), "设置", Toast.LENGTH_SHORT).show();
break;
case R.id.action_item2:
Toast.makeText(getApplicationContext(), "模式", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
// TabLayout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
// ViewPager
ViewPager mPager = (ViewPager) findViewById(R.id.myViewPager);
ResumeAdapter mPagerAdapter = new ResumeAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
tabLayout.setupWithViewPager(mPager);
// ViewPager切换时NestedScrollView滑动到顶部
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
((NestedScrollView) findViewById(R.id.nestedScrollView)).setFillViewport(true);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
<file_sep>package com.zc741.navigationdrawer;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class TabLayoutActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_tab_layout);
Toolbar tabToolbar = (Toolbar) findViewById(R.id.tab_toolbar);
tabToolbar.setTitle("Tabs");
tabToolbar.setTitleTextColor(Color.WHITE);
tabToolbar.setNavigationIcon(R.mipmap.ic_arrow_back);
tabToolbar.inflateMenu(R.menu.base_toolbar_menu);
tabToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
tabToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(TabLayoutActivity.this, "search", Toast.LENGTH_SHORT).show();
break;
case R.id.action_notification:
Toast.makeText(TabLayoutActivity.this, "notification", Toast.LENGTH_SHORT).show();
break;
case R.id.action_item1:
Toast.makeText(TabLayoutActivity.this, "设置", Toast.LENGTH_SHORT).show();
break;
case R.id.action_item2:
Toast.makeText(TabLayoutActivity.this, "模式", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setTabMode(TabLayout.MODE_FIXED);//设置tabs是否滚动,数量少不滚动
tabLayout.setTabTextColors(Color.WHITE, Color.LTGRAY);
final List<MyFragment> myFragments = new ArrayList<>();
final List<String> tabtitles = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
tabtitles.add("Tab" + i);
myFragments.add(MyFragment.newInstance("Fragment" + i));
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setOffscreenPageLimit(myFragments.size());
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public CharSequence getPageTitle(int position) {
return tabtitles.get(position);
}
@Override
public int getCount() {
return myFragments.size();
}
@Override
public Fragment getItem(int position) {
return myFragments.get(position);
}
});
tabLayout.setupWithViewPager(viewPager);
}
}
|
70a4a5cc2df800617fe7a965dd2280cc845f64d4
|
[
"Markdown",
"Java"
] | 5 |
Java
|
zhouchong741/NavigationDrawer
|
7415cd0c4ec877edab0538fda3b197ead1cc0be3
|
9a04d1a5366e6534e9de16f238e206831c251a3f
|
refs/heads/master
|
<file_sep>
public class Encryption {
// method takes in text and a password and shifts each letter in text according to the letters in password
public static String encrypt(String text, String password){
char[] letters = password.toCharArray(); // translate the password param to char array for easier manipulation
int[] shiftNums = new int[letters.length]; // array to hold shift values for each letter
for(int i = 0 ; i < letters.length; i++){
if(Character.isUpperCase(letters[i])){
shiftNums[i] = ((int) letters[i]) - 64; // subtracting 64 puts Ascii number for position in alphabet for uppercase letters
}
else{
shiftNums[i] = ((int) letters[i]) - 96; // similar idea for lower case letters
}
}
// created Iterator inner class to handle the arrays iteration
ShiftNumIterator iterator = new ShiftNumIterator(shiftNums);
// copied the string into a stringbuilder for mutability
StringBuilder encryptedString = new StringBuilder(text);
char setChar; // variable will hold shifted char that I aim to place in StringBuilder
for(int i = 0; i < encryptedString.length(); i++){
// ignore characters that are not letters
if(!Character.isLetter(encryptedString.charAt(i))){
continue;
}
else if(Character.isUpperCase(encryptedString.charAt(i))){
int code = encryptedString.charAt(i) + shiftNums[iterator.getIndex()];
// if statement checks to see if the ascii value is greater than 90 which is the upper case letter for 'Z'.
//Subtracts 26 to get a letter
if(code > 90){
code -= 26;
}
setChar = (char) code;
encryptedString.setCharAt(i, setChar);
}
else{
int code = encryptedString.charAt(i) + shiftNums[iterator.getIndex()];
// thes is does the same thing but with lower case values
if(code > 122){
code -= 26;
}
setChar = (char) code;
encryptedString.setCharAt(i, setChar);
}
}
return encryptedString.toString();
}
// method reverses the operaton done by the encrypt method
public static String decrypt(String cipher, String password){
// similar tactics as uses in encrypt to get the shift amounts from the letters
char[] letters = password.toCharArray();
int[] shiftNums = new int[letters.length];
for(int i = 0 ; i < letters.length; i++){
if(Character.isUpperCase(letters[i])){
shiftNums[i] = ((int) letters[i]) - 64;
}
else{
shiftNums[i] = ((int) letters[i]) - 96;
}
}
// Made another instance of the iterator class I wrote for the shiftNums array
ShiftNumIterator iterator = new ShiftNumIterator(shiftNums);
StringBuilder encryptedString = new StringBuilder(cipher);
char setChar;
// similar for loop to the one in encrypt but reversed
for(int i = 0; i < cipher.length(); i++){
if(!Character.isLetter(cipher.charAt(i))){
continue;
}
else if(Character.isUpperCase(cipher.charAt(i))){
int code = (int) cipher.charAt(i) - shiftNums[iterator.getIndex()];
if(code < 65){
code += 26;
}
setChar = (char) code;
encryptedString.setCharAt(i, setChar);
}
else{
int code = (int) cipher.charAt(i) - shiftNums[iterator.getIndex()];
if(code < 97){
code += 26;
}
setChar = (char) code;
encryptedString.setCharAt(i, setChar);
}
}
return encryptedString.toString();
}
}
// innter class shift iterator to ensure that the array indexes in shiftnums would be circular
class ShiftNumIterator{
int iterator;
int maxSize;
public ShiftNumIterator(int[] array){
maxSize = array.length - 1;
}
public void increment(){
iterator++;
if(iterator > maxSize){
iterator = 0;
}
}
public int getIndex(){
int returner = iterator;
increment();
return returner;
}
}
<file_sep># MessageEncryptor
A Java Swing App that can take in text input for you and perform a keyword cipher based on a specified keyword. It also allows you to import whole text files and do the same thing.
MessageEncryptor allows you to take makes use of keyword ciphers to be able to encrypt messages that you directly type into the
Single tab or that you import as a whole text file to encrypt with a keyword of your choice in the File Tab.
Please note that this program was built for fun and the encryptions can easily be cracked.
This is my first real project on Github! Feel free to pull and do with it as you wish. Any feedback will be greatly appreciated. (I know my code isn't the most organized lol)
Enjoy my program!
|
82bcaeb37836f68eb0f00475d8b217756acd25a8
|
[
"Markdown",
"Java"
] | 2 |
Java
|
TheBoJohnson/MessageEncryptor
|
660b0d294fba5a37b1479c222ce3fef955cd7c28
|
2aabc88b4402d43792b62c01e14ff25c1e82d028
|
refs/heads/master
|
<repo_name>faizandroid01/AngularProjects<file_sep>/cross-component-ex/src/app/cockpit/cockpit.component.html
<div class="row">
<div class="col-xs-12">
<p> Add New Server or blueprints !</p>
<label> Server Name </label>
<!-- <input type="text" class="form-control" [(ngModel)]="newServerName"> -->
<!-- Through local Reference -->
<input type="text" class="form-control" #serverInputName>
<label> Server Content </label>
<input type="text" class="form-control" #serverInputContent>
<br>
<button class="btn btn-primary" (click)="onAddServer(serverInputName)">
Add Server
</button>
<button class="btn btn-primary" (click)="onAddBlueprint(serverInputName)">
Add Server Blueprint
</button>
</div>
</div><file_sep>/first-ang-project/src/app/app.component.ts
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
status = 'InActive';
userName = '<NAME>';
role = 'Front Office';
dept = 10;
constructor() {
// setTimeout(() => {
// this.status = 'Active';
// }, 2000);
this.status = Math.random() > 0.5 ? 'Active' : 'InActive';
}
getColor() {
return this.status === 'Active' ? 'green' : 'red';
}
}
<file_sep>/first-ang-project/e2e/src/app.e2e-spec.ts
import {Page} from './.po';
import {browser, logging} from 'protractor';
describe('workspace-project ', () => {
let page: Page;
beforeEach(() => {
page = new Page();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('first-ang-project is running!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
<file_sep>/cross-component-ex/src/app/cockpit/cockpit.component.ts
import { Component, OnInit, EventEmitter, Output, ViewEncapsulation, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-cockpit',
templateUrl: './cockpit.component.html',
styleUrls: ['./cockpit.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CockpitComponent implements OnInit {
//These below are the events which we will be transmitted back to
//Outer component inner Add server methods Hen decoratoe used will be @Output ;
@Output() serverCreated = new EventEmitter<{ serverName: string, serverContent: string }>();
@Output('bpCreated') blueprintCreated = new EventEmitter<{ serverName: string, serverContent: string }>();;
//newServerName = '';
//newServerContent = '';
@ViewChild('serverInputContent', { static: true }) serverContentInput: ElementRef;
constructor() { }
ngOnInit() {
}
onAddServer(nameInputVal: HTMLInputElement) {
this.serverCreated.emit({
//serverName: this.newServerName,
serverName: nameInputVal.value,
//serverContent: this.newServerContent
serverContent: this.serverContentInput.nativeElement.value
});
}
onAddBlueprint(nameInputVal: HTMLInputElement) {
this.blueprintCreated.emit({
//serverName: this.newServerName,
serverName: nameInputVal.value,
// serverContent: this.newServerContent
serverContent: this.serverContentInput.nativeElement.value
});
}
}
<file_sep>/first-ang-project/src/app/test/test.component.ts
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
isToggleOn = false;
toggleCount = 1;
logs = [];
date: Date = new Date();
constructor() {
}
ngOnInit() {
}
toggleDisplay() {
this.logs.push(this.toggleCount++ + '..........' + new Date());
this.isToggleOn = !this.isToggleOn;
}
}
<file_sep>/sec-ang-project/src/app/recipes/recipe-list/recipe-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipes.model';
@Component({
selector: 'app-recipe-list',
templateUrl: './recipe-list.component.html',
styleUrls: ['./recipe-list.component.css']
})
export class RecipeListComponent implements OnInit {
recipes: Recipe[] = [
new Recipe('Masala Dosa', 'Spicy South Indian Dish.', 'https://lh3.googleusercontent.com/proxy/tH_iag031ey5_j1rjig2BssDRLOf6pE0UegFM_H-tUZAi4XCo-ZdBLxAhjNTzj3oLbl4ivc7yB0PJB1v65ACHHgZsYAkWDhi3xXAEh82OcpjUzBK7bWVjZWbmuIJs-R3EX9UoH3Yamuo65keZEt2Si4lhi-Vc20KZv9dxmLYyxgOkHYEtax-o8ah9lNz6t2kcg8dGJ2AYkkJ'),
new Recipe('Pizza', 'Peppy Paneer \' Dominos', 'https://d2mekbzx20fc11.cloudfront.net/uploads/web.Mediterranean-Lamb_2018_600x600.png'),
new Recipe('Death By Choclate', 'Polar bear Delicious', 'https://cdn.shopify.com/s/files/1/0918/2274/products/death-by-chocolate-cake-chocolate-cake-ennoble-eat-cake-today-birthday-cake-delivery-klpjmalaysia-583920_grande.jpg?v=1578916850'),
new Recipe('Gazar Ka Halwa', 'Delicious Carrot Grind', 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/42/Gajjar_ka_halwa_%28carrot_halwa%29.JPG/1200px-Gajjar_ka_halwa_%28carrot_halwa%29.JPG')
]
constructor() { }
ngOnInit() {
}
}
<file_sep>/first-ang-project/src/app/servers/servers.component.ts
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
allowNewServer = false;
serverName = '';
listOfServers = ['Server 1 '];
serverCreationStatus = 'No server Created';
serverCreated = false;
constructor() {
setTimeout(() => {
this.allowNewServer = true;
}, 2000);
}
allowedToAddServer() {
if (this.allowNewServer && this.serverName.toString().length !== 0) {
return true;
}
return false;
}
ngOnInit() {
}
onServerCreated() {
this.serverCreated = true;
this.serverCreationStatus = 'Server Created Successfully & the name of server is ' + this.serverName;
this.listOfServers.push(this.serverName);
}
onUpdateServerName(event: Event) {
this.serverName = (event.target as HTMLInputElement).value;
}
onResetClicked() {
this.serverName = '';
}
}
|
9e09816a6f715475b8579e760a32ef70681d9093
|
[
"TypeScript",
"HTML"
] | 7 |
HTML
|
faizandroid01/AngularProjects
|
5914113eb324c5f9699c8c84a4ca76bf70ca5317
|
1b793bb8a648f321bd3a579a88b8ca25b3de8006
|
refs/heads/master
|
<file_sep><?php
/**
* Used to set up custom parameters during WordPress install process
* Must be in the same DIR as the Phing build script
*
* Only run when using "phing wp-install" or "phing wp-install-only".
*
* @internal This file uses build.properties settings
*
* @package WordPhing
*/
// Add custom install code here
//Example: remove Hello Dolly
delete_plugins(array('hello.php'));
?><file_sep>WordPhing
=========
WordPress build script using [Phing](http://www.phing.info/).
- Automated installing and working with WordPress.
- Simple config file and commands to run
*Phing has no dependencies other than PHP, so it will run anywhere PHP does (unlike Apache Ant/Cappicino/Rails/Grunt/, etc). It should work right out of the box on most PHP stacks. Some of the advanced options might require additional installations of PHP/PEAR packages*
## Features
**Installation**
- Creation of a new database (optional)
- Downloads and installs WordPress (latest stable or nightly)
- Download and installs plugins and/or themes (http transfer / zip format)
- Appends info to your wp-config automatically
- Runs the WP install script (by-passes the 5 minute install)
- Custom install parameters (optional via `boot.php`)
**Build Automation:**
- SQL Export
- Git
- PHP Documentor 2
- FTP
- Minify js
- Zips or Gzips
**Runtime Automation:**
- Allows you to run scripts on a WordPress install (optional via `run.php`),
- For example: delete 1000 posts belonging to a category.
- Still in *beta* please do not run on live site
##Basic Usage
WordPhing is meant to be a base script to install and work with WordPress. Phing makes it easy to tailored the build script for each individual person's or company's development process.
It is painless to add any command line execution you want into the build file, use a built in [Phing Task](http://www.phing.info/docs/guide/stable/) or extend the code to include your own [Tasks](http://www.phing.info/docs/guide/stable/chapters/ExtendingPhing.html).
Since Phing is build with PHP it makes working with the build files easier for developers who are used to PHP syntax and operations.
##Basic Instructions
Open build.properties and fill it out and also read the comments:)
Main Command options
- `"phing wp-install"` Creates a database and installs WordPress
- `"phing wp-install-only"` Installs just WordPress (will not create the db)
- `"phing wp-clean-all"` Deletes WP directory and database
- `"phing wp-doc"` Runs PHP Documentor 2
- `"phing wp-run"` Runs custom script on WP
- `"phing help"` Command line options
Move Commands
- `"phing wp-ftp"` FTP upload - commented out by default
- `"phing wp-db-dump"` Export DB *.sql
- `"phing wp-direct-move"` ..not tested yet
- `"phing wp-ssh-move"` ..not tested yet
Git Commands
- `"phing wp-git-init"` Initialize a git repo
- `"phing wp-git-commit"` Prompts for a commit msg - also takes commit options (-A for example)
- `"phing wp-git-clone"`, `"phing wp-git-pull"`, `"phing wp-git-push"`, `"phing wp-git-branch"`
Other Commands
- `"phing wp-min-js"` Minify JS
- `"phing wp-zip"` Creates a zip from directory
- `"phing wp-zip-file"` Creates a zip from file
- `"phing wp-gzip"` Creates a gzip
- `"phing wp-gzip-file"` Creates a gzip from a file
- `"phing wp-clean-files"` Deletes WP files
- `"phing wp-clean-database"` Deletes WP Database
Commands are chainable , for example `"phing wp-install wp-git-init"`
##Advanced Instructions
- `boot.php` can be run during the install process to customize installation.
- `run.php` can be run via the `phing wp-run` command on an existing WordPress install
Both files are run from the WordPhing build file root and not the WordPress install root and require `build.properties` to be properly filled out. You can change the location to to run from the WordPress root in `build.xml`.
##Notes
The file/dir permissions (`chown/chmod`) are commented out by default to prevent issues on Windows ( see line 567 in build.xml to uncomment).
If there are problems during install you can run WordPhing in debug and verbose modes or both.
For example: `"phing wp-install -verbose -debug"`
The install build will not overwrite existing directories or existing databases. It will also Delete the readme.html and wp-sample-config.php
##Reports
PHP reports (PhpCodeSniffer, Copy-Paste detection and PHPMess) have been removed from WordPhing and left in /codesniffing. It was getting to complicated and I think this is better handled by an IDE.
##Requires
PHP 5.2 + & Phing.
- PHP Documentor 2 requires the latest Phing and the XSL PHP extension. You should use the latest build found here: [http://www.phpdoc.org/](http://www.phpdoc.org/)
- FTP requires Net_FTP [http://pear.php.net/package/Net_FTP](http://pear.php.net/package/Net_FTP)
##Todo
- Whole site migration
- SVN support
- Add backups via Rsync and Amazon
- Better CSS/JS minify via node, java or ruby?
##Install
First check in your PHP/PEAR folder to see if /Phing is alredy there. For the latest release it's recommend you run `"pear upgrade phing/phing"`.
This script will eventually might require some optional libraries , so you can run `"pear install --alldeps phing/phing"` to get them.
- If PEAR/phing is not included in your stack.
http://www.phing.info/docs/guide/stable/chapters/Setup.html#SystemRequirements
- PEAR package
http://pear.phing.info/
Why Phing? Because it's built with PHP.
https://github.com/phingofficial/phing<file_sep><?php
/**
* Used to run any script on WordPress.
* Must be in the same DIR as the Phing build script
*
* Use "phing wp-run" to run script
* See http://codex.wordpress.org/Function_Reference for Examples
*
*
* @internal This file uses build.properties settings
*
* @package WordPhing
*/
//Example: to create 35 posts on the fly
for ($k = 0 ; $k < 35; $k++){
// Create post object
$my_post = array(
'post_title' => $k . '- Posts',
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(1)
);
// Insert the post into the database
wp_insert_post( $my_post );
}
?>
|
0cba3e3d1e44eb97bed685bc4230ec87b02b347d
|
[
"Markdown",
"PHP"
] | 3 |
PHP
|
psad73/WordPhing
|
5a1574444ab6fdf4272942e4790efcdbfb39f498
|
b4540eb93b6c400988a36863abe123fcb09cd0a9
|
refs/heads/master
|
<file_sep>class RenameColumnCityNameinCitiesToName < ActiveRecord::Migration[5.0]
def change
rename_column :cities, :city_name, :name
end
end
<file_sep>namespace :app_scraper do
task fetch: :environment do
require "nokogiri"
require "open-uri"
require "pry"
url = "https://hermes.goibibo.com/hotels/v2/search/data/v3/6771549831164675055/20170126/20170127/1-1_0?s=popularity&cur=INR&f={}&pid=0"
doc = Nokogiri::HTML(open(url))
doc.each do |entry|
binding.pry
Hotel.create(hotel_name: entry.content[0])
end
end
end
<file_sep>class AddColumnToHotels < ActiveRecord::Migration[5.0]
def change
add_column :hotels, :city_id, :integer
end
end
<file_sep>namespace :app_scraper do
task fetch: :environment do
require "nokogiri"
require "open-uri"
require "pry"
url = "https://hermes.goibibo.com/hotels/v2/search/data/v3/6771549831164675055/20170126/20170127/1-1_0?s=popularity&cur=INR&f={}&pid=0"
doc = Nokogiri::HTML(open(url))
JSON.parse(doc.text)['data'].each do |entry|
entry['hn']
entry['spr']
c = City.find(4)
c.hotels.create(:hotel_name => entry['hn'], :cost => entry['spr'])
end
end
end
<file_sep>class AddAreaCoveredPoolToHotels < ActiveRecord::Migration[5.0]
def change
add_column :hotels, :area_covered_pool, :integer
end
end
<file_sep>class Facility < ApplicationRecord
has_and_belongs_to_many :hotels
end
<file_sep>require 'HTTParty'
require 'Nokogiri'
require 'JSON'
require 'Pry'
page = HTTParty.get('https://www.goibibo.com/hotels/find-hotels-in-Bangalore/6771549831164675055/6771549831164675055/%7B%22ci%22:%2220170126%22,%22co%22:%2220170127%22,%22r%22:%221-1_0%22%7D/?{}&sec=dom')
parse_page = Nokogiri::HTML(page)
Pry.start(binding)
<file_sep>class Hotel < ApplicationRecord
belongs_to :city
has_and_belongs_to_many :facilities
end
<file_sep>class HotelsController < ApplicationController
def new
end
def show
@facilities = Facility.find(12)
@hotels = @facilities.hotels.all
# @max = Hotel.maximum("area_covered_pool")
@disc = Hotel.where(city: "Bangalore")
@values_aw = @disc.order('area_covered_pool DESC')
@bigpool = Hotel.first
# @use = Hotel.order('area_covered_pool DESC')
# @value = Hotel.first
@cost = Hotel.order('cost ASEC')
@costValue = Hotel.last
@star_ratings = Hotel.where(star_rating: "3")
@values = @star_ratings.average("cost")
end
# We'll just try to render the array and see what happens
end
<file_sep>class FacilitiesController < ApplicationController
def new
end
end
<file_sep>Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :cities
get 'cities/new'
root 'cities#new'
resources :hotels
get 'hotels/show'
root 'hotels#show'
end
<file_sep>class CreateJoinTable < ActiveRecord::Migration[5.0]
def change
create_join_table :hotels, :facilities do |t|
t.index :hotel_id
t.index :facility_id
end
end
end
<file_sep>class CitiesController < ApplicationController
def new
end
end
|
8153f83bbcc27aa2c76272ee0b4bf6eddf325cda
|
[
"Ruby"
] | 13 |
Ruby
|
koshtubh1095/Associations_prac
|
6dd18fb46b911e468e93268e330776b84a4b1aa6
|
59a8f06a16d7059a1dc9c240812390e435249cdd
|
refs/heads/master
|
<file_sep># define a class
class Image
# this method build on a array contain 4 array with 4 items in each array.
# name blur
def initialize(image)
@image = image
end
# this method is to locate where is the ones in row.
def get_ones
ones = []
@image.each_with_index do |row, i|
row.each_with_index do |x, col|
if x == 1
ones << [i, col]
end
end
end
ones
end
# this method is to build command to blur [] next to ones
def blur!
ones = get_ones
@image.each_with_index do |row, i|
row.each_with_index do |x, col|
ones.each do |found_i, found_col|
if i == found_i && col == found_col
@image[i -1][col] = 1 unless i == 0
@image[i +1][col] = 1 unless i >= 3
@image[i][col -1] = 1 unless col == 0
@image[i][col +1] = 1 unless col >= 3
end
end
end
end
end
# this method define image
# need method in class to output image of array
def output_image
@image.each { |image| puts image.join() }
end
end
#test
image = Image.new([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
# output_image
puts
image.blur!
image.output_image
|
f1317998e1294487aa71cefa68bece030470b10f
|
[
"Ruby"
] | 1 |
Ruby
|
powaileung/blur1
|
a2700a3246f0e61d7109efdb7f6165a73b9fcecf
|
c9d323a6e61c4926c070e6c48932eded95d5a536
|
refs/heads/master
|
<repo_name>cantorsdustbunnies/Synes-thizer<file_sep>/src/options_page/components/OptionBar/Card/index.js
import React from 'react';
import styled from 'styled-components';
const CardWrapper = styled.div`
color: white;
width: 85%;
margin: 0 auto;
border-bottom: 1px dashed #f1f1f1a2;
padding-bottom: 20px;
`;
const CardTitle = styled.p`
margin-left: 20px;
font-weight: 100;
font-family: 'Amiri', serif;
`;
const Content = styled.div`
width: 100%;
position: relative;
text-align: right;
`;
export default ({ title = 'test', children }) => {
return (
<CardWrapper>
<CardTitle> {title}: </CardTitle>
<Content>{children}</Content>
</CardWrapper>
);
};
<file_sep>/src/options_page/components/Grid/index.js
import React, { Component } from 'react';
import styled from 'styled-components';
const GridWrapper = styled.div`
display: flex;
flex-wrap: wrap;
max-height: 350px;
`;
const GridItem = styled.div`
color: ${props => props.color || 'black'}
background-color: ${props => props.background || 'white'}
width: 40px;
height: 40px;
display: flex;
justify-content: center;
align-items: center;
margin: 1.25px;
`;
const defaultGraphemes = 'abcdefghijklmnopqrstuvwxyz0123456789'.split('');
class Grid extends Component {
constructor(props) {
super(props);
this.state = {
selected: '',
graphemes: props.graphemes || defaultGraphemes,
};
}
createGridItems() {
const { graphemes } = this.state;
return graphemes.map(
grapheme =>
grapheme.match(/[a-z]/) ? (
<GridItem key={grapheme}>
{grapheme.toUpperCase()}
{grapheme}
</GridItem>
) : (
<GridItem key={grapheme}> {grapheme} </GridItem>
)
);
}
render() {
return <GridWrapper>{this.createGridItems()}</GridWrapper>;
}
}
export default Grid;
<file_sep>/src/chrome_extension/background/index.js
import { fisherPrice, unstyled } from '../themes';
// For testing purposes only
chrome.storage.sync.clear();
//
const default_themes = {
fisherPrice: {
name: 'Fisher Price',
data: fisherPrice,
isDefault: true,
},
unstyled: {
name: 'Unstyled',
data: unstyled,
isDefault: true,
},
};
const default_graphemes = 'abcdefghijklmnopqrstuvwxyz0123456789'.split('');
const selected_theme = default_themes.fisherPrice;
const default_state = {
default_themes,
default_graphemes,
selected_theme,
user_themes: {},
user_graphemes: [],
allow_background_edit: false,
background_color: '#ffffffff',
};
// populates state if it doesn't exist, otherwise calls for it.
chrome.storage.sync.get({ state: default_state }, data => {
chrome.storage.sync.set({ state: data.state }, () => {});
});
//passes state to content script for futher processing.
chrome.browserAction.onClicked.addListener(buttonClicked);
function buttonClicked(tab) {
chrome.storage.sync.get('state', data => {
chrome.tabs.sendMessage(tab.id, data);
});
}
<file_sep>/src/options_page/components/OptionBar/index.js
import React from 'react';
import styled from 'styled-components';
import Card from './Card';
import Grid from '../Grid';
let OptionsWrapper = styled.div`
width: 300px;
height: calc(100vh - 56px);
background-color: #232323;
padding-top: 20px;
`;
let ColorPickerWrapper = styled.div`
width: 100px;
height: 25px;
border: 1px solid white;
display: inline-block;
`;
let ColorPickerColor = styled.div`
width: 90px;
height: 15px;
background-color: white;
margin: 5px;
`;
let Selector = styled.select``;
const NewTheme = styled.button`
width: 100%
margin-top: 20px;
background-color: inherit;
color: white;
border: 1px solid white;
`;
export default () => {
return (
<OptionsWrapper>
<Card title="Current Theme">
<Selector>
<option> Fisher Price </option>
<option> Unstyled </option>
</Selector>
</Card>
<Card title="Graphemes">
<Grid />
<NewTheme> Create New </NewTheme>
</Card>
<Card title="Allow app to change the background color on pages I visit">
<input type="checkbox" />
</Card>
<Card title="Background Color">
<ColorPickerWrapper>
<ColorPickerColor />
</ColorPickerWrapper>
</Card>
</OptionsWrapper>
);
};
<file_sep>/src/options_page/components/Header/index.js
import React from 'react';
import styled from 'styled-components';
import logo from '../../../chrome_extension/images/S.png';
const Header = styled.header`
height: 56px;
background-color: #232323;
display: flex;
align-items: center;
font-family: 'Roboto', sans-serif;
`;
const Logo = styled.img`
margin-left: 20px;
width: 30px;
height: 30px;
`;
const Title = styled.span`
font-size: 30px;
color: #f1f1f1f2;
margin-left: 20px;
`;
export default () => {
return (
<Header>
<Logo src={logo} />
<Title>Synes-thizer </Title>
</Header>
);
};
<file_sep>/src/options_page/App.js
/* global chrome */
import React, { Component } from 'react';
import styled from 'styled-components';
import Header from './components/Header';
import OptionBar from './components/OptionBar';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: undefined,
};
}
render() {
console.log(this.state.data);
return (
<div>
<Header />
<OptionBar />
</div>
);
}
}
export default App;
|
bf6191772b8720057e19a6b8d67de7ac7d13be5d
|
[
"JavaScript"
] | 6 |
JavaScript
|
cantorsdustbunnies/Synes-thizer
|
52d64f6af77a7386cb8d138d1db04ebc1e3027c1
|
07537694dc92d514e0e4558a6ac1008351bdca23
|
refs/heads/master
|
<file_sep>package mx.sindelantal.service;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import mx.sindelantal.utils.SongTypeEnum;
/**
* @author <NAME>
*
*/
@Service
public class SongService implements SongInterface{
protected static final Logger LOG = LogManager.getLogger();
@Override
public String findByTemperature(Double double1) {
LOG.info("FIND BY {}",double1);
CheckTemperature ckTemp = (n)->
n<10?SongTypeEnum.TYPE_CLASSICAL:
n>=10 && n<=14?SongTypeEnum.TYPE_ROCK:
n>=15 &&n<=30?SongTypeEnum.TYPE_POP:
SongTypeEnum.TYPE_PARTY;
return ckTemp.checTemperature(double1).getString();
}
interface CheckTemperature{
SongTypeEnum checTemperature(Double temperature);
}
}
<file_sep>FROM java:8
VOLUME /tmp
ADD target/SinDelantal-0.0.1-SNAPSHOT.jar SinDelantal.jar
RUN bash -c 'touch /SinDelantal.jar'
ENV JAVA_OPTS=""
ENTRYPOINT ["sh","-c","java $JAVA_OPTS -jar /SinDelantal.jar"]
MAINTAINER <EMAIL><file_sep>package mx.sindelantal.utils;
/**
* @author <NAME>
*
*/
public enum SongTypeEnum {
TYPE_PARTY("1LwBQqaMFewXbY7uSgKESN"),
TYPE_POP("6R4skbYOSaqJ6Qpm5zYWuW"),
TYPE_ROCK("3S0sKv0JifwzAF2mH2WFSE"),
TYPE_CLASSICAL("1ti3RTaWsi3wDB9sPVaoRE");
private String key;
private SongTypeEnum(String key){
this.key = key;
}
public String getString() {
return key;
}
}
<file_sep>package mx.sindelantal.api;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import mx.sindelantal.model.ClientInformation;
import mx.sindelantal.service.SongService;
/**
* @author <NAME>
*
*/
@Controller
public class SongController {
protected static final Logger LOG = LogManager.getLogger();
@Autowired
private SongService songService;
@RequestMapping(value = "/temperature", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<String> listAllUsers(@RequestBody ClientInformation clientInfo) {
String playlistsKey = songService.findByTemperature(clientInfo.getTemperature());
return new ResponseEntity<String>(playlistsKey, HttpStatus.OK);
}
@ExceptionHandler
void handleIllegalArgumentException(IllegalArgumentException e, HttpServletResponse response) throws IOException {
LOG.error("ERROR {}",e.getMessage());
response.sendError(HttpStatus.BAD_REQUEST.value());
}
}
<file_sep>package mx.sindelantal.service;
/**
* @author <NAME>
*
*/
public interface SongInterface {
/**
* @param temperature
* @return String Key
*/
public String findByTemperature(Double temperature);
}
|
fdd9b641fb100d78f420ca01c885d4d04a439d75
|
[
"Java",
"Dockerfile"
] | 5 |
Java
|
laliento/SinDelantal
|
9f4d7c0110a3321c0f1d7fb696b0ffde9b2c1bac
|
f56e1033df93bd0a2e3a65ea265ddf07a15329e5
|
refs/heads/master
|
<repo_name>micloudon/carApi<file_sep>/restfulApi/models.py
from django.db import models
class Car(models.Model):
id = models.IntegerField(primary_key=True)
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField()
fuelType = models.CharField(max_length=299)
horsePower = models.IntegerField(null=True, blank=True)
cylinders = models.IntegerField(null=True, blank=True)
driveTrain = models.CharField(max_length=299)
numDoors = models.IntegerField(null=True, blank=True)
size = models.CharField(max_length=299)
style = models.CharField(max_length=299)
highwayMpg = models.IntegerField()
cityMpg = models.IntegerField()
msrp = models.IntegerField()
<file_sep>/restfulApi/migrations/0001_initial.py
# Generated by Django 3.2.3 on 2021-05-26 23:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
('id', models.IntegerField(primary_key=True, serialize=False)),
('make', models.CharField(max_length=100)),
('model', models.CharField(max_length=100)),
('year', models.IntegerField()),
('fuelType', models.CharField(max_length=299)),
('horsePower', models.IntegerField(blank=True, null=True)),
('cylinders', models.IntegerField(blank=True, null=True)),
('driveTrain', models.CharField(max_length=299)),
('numDoors', models.IntegerField(blank=True, null=True)),
('size', models.CharField(max_length=299)),
('style', models.CharField(max_length=299)),
('highwayMpg', models.IntegerField()),
('cityMpg', models.IntegerField()),
('msrp', models.IntegerField()),
],
),
]
<file_sep>/restfulApi/urls.py
from django.urls import path
from .views import home, api, car_list, car_detail, car_detail_make, car_detail_model, car_detail_year
urlpatterns = [
path('', home),
path('api/', api),
path('api/all', car_list),
path('api/<int:pk>/', car_detail),
path('api/<str:make>/', car_detail_make),
path('api/<str:make>/<str:model>/', car_detail_model),
path('api/<str:make>/<str:model>/<int:year>', car_detail_year),
]<file_sep>/restfulApi/admin.py
from django.contrib import admin
from .models import Car
from import_export.admin import ImportExportModelAdmin
@admin.register(Car)
class ViewAdmin(ImportExportModelAdmin):
pass
<file_sep>/restfulApi/serializer.py
from rest_framework import fields, serializers
from .models import Car
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ['id', 'make', 'model', 'year', 'fuelType', 'horsePower',
'cylinders', 'driveTrain', 'numDoors', 'size', 'style', 'highwayMpg', 'cityMpg', 'msrp']
<file_sep>/README.md
# Car Api
## Live Site:
https://pacific-taiga-60618.herokuapp.com/api/ford/f-150/2017
(Clicking this link will bring up serveral JSON objects containing data that relates to Ford F-150's from the year 2017,
read *access data using urls paths* below and try putting some different values in the url)
### This Api is Restful
### It serves over 6000 articles of car data in the form of Json objects
**Access data using urls paths:**
**/api/** check site Health
**/api/all** get all data
**/api/id** get a single data object by a numerical id (all the data has ordered numberic values ranging from 1-6516), so /api/100, would grab the 100th object of data.
**/api/make/** grabs all data objects associated with certain make of car
**/api/make/model/** grabs all data objects associated with certain make and model of car
**/api/make/model/year/** grabs all data objects associated with certain make, model and year of car
I used django-import-export to import a csv file into a mysql database, specifically using the import function in the django admin panel
**Some commands to help you get rolling:**
create a virtual environment:
> python3 -m venv
Activate Virtual environment:
>source venv/bin/activate
Install the specified requirements:
>pip install -r requirements.txt
Write a requirements.txt file:
>pip freeze > requirements.txt
Run dev server:
>python manage.py runserver
Migrate to database:
>python manage.py migrate
Commit updates to database:
>python manage.py makemigrations
Intergated Cli tool for testing:
>python manage.py shell
For deployment I used an AWS ec2 instance that runs ubuntu 18.04, which serves data to a mysql database that is hosted on AWS RDS.
I used nginx and uwsgi (uwsgi is similar to gunicorn) to serve to website.
(I moved my deployment to Heroku, so this isn't needed, but it still helpful in linux server deploy scenarios)
**Here is my nginx conf file*:*
upstream django {
server unix:///home/ubuntu/carApi/djangoApi.sock;
}
server {
listen 80;
server_name ec2-54-245-43-7.us-west-2.compute.amazonaws.com www.ec2-54-245-43-7.us-west-2.compute.amazonaws.com;
charset utf-8;
client_max_body_size 75M;
location /static {
alias /home/ubuntu/carApi/static;
}
location / {
uwsgi_pass django;
include /home/ubuntu/carApi/uwsgi_params;
}
}
<file_sep>/requirements.txt
asgiref==3.3.4
defusedxml==0.7.1
diff-match-patch==20200713
dj-database-url==0.5.0
Django==3.2.3
django-cors-headers==3.7.0
django-filter==2.4.0
django-import-export==2.5.0
djangorestframework==3.12.4
et-xmlfile==1.1.0
gunicorn==20.1.0
importlib-metadata==4.0.1
Markdown==3.3.4
MarkupPy==1.14
mysqlclient==2.0.3
odfpy==1.4.1
openpyxl==3.0.7
protobuf==3.17.1
psycopg2-binary==2.8.6
python-decouple==3.4
pytz==2021.1
PyYAML==5.4.1
six==1.16.0
sqlparse==0.4.1
tablib==3.0.0
typing-extensions==3.10.0.0
xlrd==2.0.1
xlwt==1.3.0
zipp==3.4.1
<file_sep>/restfulApi/views.py
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, request
from rest_framework import serializers
from rest_framework.parsers import JSONParser
from .models import Car
from .serializer import CarSerializer
def home(request):
return HttpResponse("Site is Healthy")
def api(request):
return HttpResponse("Site is Healthy, add all to url to see all JSON objects or add a number to get a specific object")
def car_list(request):
if request.method == 'GET':
cars = Car.objects.all()
serializer = CarSerializer(cars, many=True)
return JsonResponse(serializer.data, safe=False)
def car_detail(request, pk):
try:
car = Car.objects.get(pk=pk)
except Car.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = CarSerializer(car)
return JsonResponse(serializer.data)
def car_detail_make(request, make):
try:
car = Car.objects.filter(make=make)
except Car.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = CarSerializer(car, many=True)
return JsonResponse(serializer.data, safe=False)
def car_detail_model(request, make, model):
try:
car = Car.objects.filter(make=make, model=model)
except Car.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = CarSerializer(car, many=True)
return JsonResponse(serializer.data, safe=False)
def car_detail_year(request, make, model, year):
try:
car = Car.objects.filter(make=make, model=model, year=year)
except Car.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = CarSerializer(car, many=True)
return JsonResponse(serializer.data, safe=False)
|
e42e134f0e996d4cee9e65b0152b843190573482
|
[
"Markdown",
"Python",
"Text"
] | 8 |
Python
|
micloudon/carApi
|
5104bf0ce6d4c9b88d9e99d6ab1e413c270bf2fc
|
7b27c4c46696109304de750a78159cad67b58ea9
|
refs/heads/main
|
<file_sep>""" form classes for the enquiry creator """
from django.core.validators import RegexValidator
from django import forms
from django.utils import timezone
from django.conf import settings
class CustomerDetailsForm(forms.Form):
""" Page 1 of the Initial Enquiry journey """
# Custom Regex validation for telephone number
phone_regex = RegexValidator(regex=r'^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$',
message="Provide a valid UK Phone Number.")
first_name = forms.CharField(max_length=40, label="First Name")
last_name = forms.CharField(max_length=40, label="Last Name")
building = forms.CharField(max_length=50, required=False, label="Building and Street")
street = forms.CharField(max_length=50, required=False, label="Street")
town = forms.CharField(max_length=50, required=False, label="Town")
county = forms.CharField(max_length=50, required=False, label="County")
postcode = forms.CharField(max_length=10, required=False, label="Postcode")
telephone_number = forms.CharField(validators=[phone_regex], max_length=17, label="Telephone Number", widget=forms.TextInput(attrs={'type': 'tel'}))
email_address = forms.EmailField(max_length=254, required=False, label="Email Address", widget=forms.TextInput(attrs={'type': 'email'}))
MORNING = 'M'
EARLY_AFTERNOON = 'EA'
LATE_AFTERNOON = 'LA'
SATURDAY = 'S'
PREFERRED_TIME_TO_CONTACT_CHOICES = [
(MORNING, '9am - 12pm (Mon-Fri)'),
(EARLY_AFTERNOON, '12pm - 3pm (Mon-Fri)'),
(LATE_AFTERNOON, '3pm - 5pm (Mon-Fri)'),
(SATURDAY, '9am - 2pm (Sat)'),
]
preferred_time_to_contact = forms.ChoiceField(
widget=forms.RadioSelect,
choices=PREFERRED_TIME_TO_CONTACT_CHOICES,
label="Preferred Time to Call"
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Override default "required" validation message to mention the field name
for field in self.fields.values():
field.error_messages = {'required' : f'{field.label} is required'}
class PropertyDetailsForm(forms.Form):
""" Page 2 of the Initial Enquiry journey """
ltv_value = forms.FloatField(max_value=100, min_value=0, label="LTV")
annual_income = forms.IntegerField(label="Annual Income", widget=forms.TextInput(attrs={'type': 'number'}))
loan_amount = forms.IntegerField(label="Loan Amount", widget=forms.TextInput(attrs={'type': 'number'}))
property_value = forms.IntegerField(label="Property Value", widget=forms.TextInput(attrs={'type': 'number'}))
NEW_HOUSE = 'NH'
REMORTGAGE = 'RM'
MORTGAGE_TYPE_CHOICES = [
(NEW_HOUSE, 'New House'),
(REMORTGAGE, 'Remortgage'),
]
mortgage_type = forms.ChoiceField(
widget=forms.RadioSelect,
choices=MORTGAGE_TYPE_CHOICES,
label="Mortgage Type"
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Override default "required" validation message to mention the field name
for field in self.fields.values():
field.error_messages = {'required' : f'{field.label} is required'}
def clean_ltv_value(self):
""" Validates LTV against MAX_LTV """
max_ltv = 80
ltv = self.cleaned_data['ltv_value']
if ltv > max_ltv:
raise forms.ValidationError("LTV is too high, consider reducing your Loan Amount")
return ltv
class EnquiryForm(forms.Form):
""" Final full enquiry model """
# class Meta:
# model = Enquiry
# fields = ['first_name', 'last_name', 'building', 'street', 'town', 'county', 'postcode', 'telephone_number', 'email', 'preferred_time_to_contact',
# 'annual_income', 'loan_amount', 'property_value', 'mortgage_type' ]
date_created = forms.DateField(initial=timezone.now, label="Date Created")
has_been_contacted = forms.BooleanField(initial=False, label="Has been Contacted?")
<file_sep>{% extends "_layout.html" %}
{% block title %}Internal Server Error{% endblock %}
{% block content %}
<div class="container">
<h1>There was a problem</h1>
<p>We may be experiencing technical difficulties. We apologise for the inconvenience.</p>
<p>If you would like to try again then please <a href="{% url 'customer_details' %}">click here</a>. Alternatively, you can call us on 0345 606 4488 to book an appointment with one of our qualified mortgage advisers.</p>
</div>
{% endblock %}<file_sep>{% extends "_layout.html" %}
{% block title %}Login{% endblock %}
{% block content %}
<div class="container">
<h1>Adviser Login</h1>
<form name="odip-form" method="POST">
{% csrf_token %}
{% if form.errors %}
<div class="error-summary" tabindex="-1">
<h2>There's been a problem</h2>
<ul>
{% for key, value in form.errors.items %}
<li>{{ value }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<div class="field">
<label class="field-label">{{ form.username.label }}</label>
{{ form.username }}
</div>
<div class="field">
<label class="field-label">{{ form.password.label }}</label>
<span class="field-error field-validation-valid"></span>
{{ form.password }}
</div>
<div class="field">
<button type="submit" id="submit">Login</button>
</div>
</form>
</div>
{% endblock %}<file_sep>""" Provider objects for building data sets """
class EnquiryProvider:
""" Stores a dictionary list of form values to be retrieved later """
def __init__(self):
self.data = {}
def add(self, data_to_add):
""" Add a dictionary object to the existing list """
if not isinstance(data_to_add, dict):
raise TypeError("Object must be a Dictionary")
self.data.update(data_to_add)
def get_list(self):
""" Return the list as a dictionary object """
return self.data
def get_list_with_string_values(self):
""" Return the list as a dictionary object with string values"""
working_list = self.data.items()
list_with_string_values = {str(key): str(value) for key, value in working_list}
return list_with_string_values
def __str__(self):
return str(self.data)
def __repr__(self):
return "EnquiryProvider()"
<file_sep>
from django.urls import path
from .views import (
customer_details,
property_details,
calculate_ltv,
thank_you,
)
urlpatterns = [
path('yourdetails/', customer_details, name='customer_details'),
path('propertydetails/', property_details, name='property_details'),
path('ajax/calculate_ltv/', calculate_ltv, name='calculate_ltv'),
path('thankyou/', thank_you, name='thank_you'),
]
<file_sep>{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Newcastle Building Society - Request for Online Decision in Principle</title>
</head>
<body>
<header>
<div style="width: 200px; padding-bottom: 20px;">
<svg id="nbs_logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 180 78"><style>.st0{fill-rule:evenodd;clip-rule:evenodd;fill:#7B9E03;} .st1{fill:#7B9E03;} .st2{fill:#005488;} .st3{fill-rule:evenodd;clip-rule:evenodd;fill:#005488;}</style><path class="st0" d="M66.9 73.2v-3.6h2.7c1.6 0 2.4.5 2.4 1.7s-.7 1.9-2.2 1.9h-2.9zm0-4.7v-3.2h2.6c1.4 0 2 .5 2 1.5 0 1.1-.7 1.6-2.1 1.6h-2.5v.1zm-1.4 6h4.4c2.2 0 3.5-1.2 3.5-3.1 0-1.3-.7-2.3-2-2.5 1-.4 1.5-1.2 1.5-2.2 0-1.7-1.1-2.5-3.2-2.5h-4.2v10.3z"/><path class="st1" d="M76 67h-1.3v4.9c0 .7 0 1.3.3 1.8.4.6 1.2 1 2.3 1 1.1 0 2-.4 2.5-1.3v1.1H81V67h-1.3v4c0 1.7-.8 2.5-2.2 2.5-1.2 0-1.5-.6-1.5-2V67z"/><path class="st0" d="M82.8 74.5h1.3V67h-1.3v7.5zm0-8.9h1.3v-1.4h-1.3v1.4z"/><path class="st1" d="M85.9 74.5h1.3V64.1h-1.3v10.4z"/><path class="st0" d="M95.6 64.1h-1.2v3.7c-.6-.8-1.4-1.2-2.5-1.2-2 0-3.3 1.5-3.3 4s1.3 4 3.3 4c1 0 1.8-.4 2.5-1.2v1h1.2V64.1zm-1.2 6.6c0 1.9-.8 2.9-2.2 2.9-1.4 0-2.2-1-2.2-2.8 0-1.9.8-3 2.2-3 1.4 0 2.2 1 2.2 2.9zM97.4 74.5h1.3V67h-1.3v7.5zm0-8.9h1.3v-1.4h-1.3v1.4z"/><path class="st1" d="M105.5 74.5h1.3V70v-.4c0-.7 0-1.3-.3-1.8-.4-.7-1.2-1-2.3-1-1.1 0-1.8.4-2.4 1.3V67h-1.2v7.5h1.3v-4.3c0-1.5.8-2.3 2.2-2.3 1.2 0 1.5.6 1.5 2v4.6h-.1z"/><path class="st0" d="M113.9 73.6v1c0 1.4-.6 2-2.2 2-1.3 0-2-.4-2-1.2h-1.2v.1c0 1.4 1.2 2.2 3.2 2.2 2.5 0 3.5-1 3.5-3.3V67H114v1c-.6-.7-1.2-1.2-2.4-1.2-2 0-3.4 1.6-3.4 4 0 2.5 1.4 4 3.4 4 .9-.1 1.7-.5 2.3-1.2zm-2.2-5.8c1.5 0 2.3 1 2.3 2.9s-.7 2.8-2.3 2.8c-1.4 0-2.2-1-2.2-2.9 0-1.7.8-2.8 2.2-2.8z"/><path class="st1" d="M120.6 71.1c.1 2.4 1.6 3.7 4.1 3.7 2.5 0 4-1.3 4-3.3 0-.8-.3-1.5-.9-2-.6-.5-1.4-.7-2.4-.9-2.2-.5-3.1-.6-3.1-1.9 0-1 .9-1.7 2.3-1.7 1.5 0 2.4.8 2.5 2.1h1.3c0-2.1-1.4-3.3-3.7-3.3-2.3 0-3.7 1.3-3.7 3.1s1.2 2.3 3.5 2.9c1.9.4 2.8.6 2.8 1.9 0 1.1-1 1.9-2.6 1.9s-2.7-1-2.7-2.5h-1.4z"/><path class="st0" d="M129.8 70.7c0 2.6 1.3 4 3.6 4s3.6-1.5 3.6-4c0-2.6-1.3-4-3.6-4s-3.6 1.5-3.6 4zm1.3 0c0-1.9.8-2.9 2.3-2.9 1.5 0 2.3 1 2.3 2.9s-.8 2.9-2.3 2.9c-1.5 0-2.3-1-2.3-2.9z"/><path class="st1" d="M143.6 69.5h1.3c-.1-1.7-1.3-2.8-3.2-2.8-2.1 0-3.5 1.5-3.5 4s1.3 4 3.3 4c2 0 3.2-1.1 3.3-2.9h-1.2c-.2 1.2-.9 1.8-2.1 1.8-1.3 0-2.1-1-2.1-2.9s.8-2.9 2.1-2.9 2 .6 2.1 1.7z"/><path class="st0" d="M146.1 74.5h1.3V67h-1.3v7.5zm0-8.9h1.3v-1.4h-1.3v1.4zM154.4 72.1c-.2 1-.9 1.5-1.9 1.5-1.3 0-2.1-.9-2.2-2.5h5.4v-.6c0-2.5-1.3-3.8-3.4-3.8-2.1 0-3.4 1.5-3.4 4.1 0 2.5 1.3 3.9 3.4 3.9 1.8 0 3-1 3.3-2.7h-1.2v.1zm-4.1-2.1c.1-1.4.9-2.2 2.1-2.2 1.3 0 2 .8 2 2.2h-4.1z"/><path class="st1" d="M158.7 72.6V68h1.4v-1h-1.4v-2.1h-1.3V67h-1.1v1h1.1v5c0 1.2.4 1.6 1.6 1.6.3 0 .6 0 1-.1v-1.1h-.7c-.5 0-.6-.2-.6-.8zM166.1 67l-2.1 6-2.1-6.1h-1.4l2.9 8-.3.9c-.2.4-.5.6-.9.6-.3 0-.5 0-.7-.1v1.2c.2.1.5.1.8.1 1.3 0 1.7-.6 2.2-2l3.2-8.7h-1.6v.1zM0 23.7v53.1h53.3V32.5h-5.7v-8.8H0z"/><path class="st2" d="M47.6 0v23.7h9v9h8.7v-9.2h8.8v9.2h6V0H47.6z"/><path class="st1" d="M83.2 23.5h8.5v9h-8.5v-9z"/><path class="st2" d="M65.3 58.7h3.6V46.5l7.2 12.2h3.8V40.9h-3.6v12.2l-7.2-12.2h-3.8v17.8z"/><path class="st3" d="M85.8 50.8c.1-1.8 1.1-2.7 2.6-2.7 1.6 0 2.5.9 2.6 2.7h-5.2zm5.1 3.9c-.4 1-1.2 1.5-2.4 1.5-1.7 0-2.6-1.1-2.7-3.1h8.8v-.9c0-4.5-2.3-7-6.3-7-3.8 0-6.1 2.6-6.1 6.9 0 4.4 2.4 7.1 6.2 7.1 3.1 0 5.4-1.7 6.1-4.4h-3.6v-.1z"/><path class="st2" d="M98.7 58.7h3.6l2-9.4 2.1 9.4h3.5l3.7-13.1h-3.4l-2.2 9.1-1.9-9.1h-3.6l-1.8 9.1-2.1-9.1H95l3.7 13.1zM122.7 53.8c-.2 1.6-1 2.3-2.3 2.3-1.7 0-2.6-1.4-2.6-3.9 0-2.7.8-4.1 2.6-4.1 1.3 0 2.1.8 2.3 2.2h3.5c-.2-3.2-2.4-5.1-5.8-5.1-3.9 0-6.2 2.6-6.2 7s2.3 7 6.1 7c3.4 0 5.7-2.1 6-5.4h-3.6z"/><path class="st3" d="M135.4 52.2v1.2c0 1.9-1.2 3-3.1 3-1.1 0-1.7-.6-1.7-1.6s.5-1.4 1.7-1.8c.6-.1 1.7-.1 3.1-.8zm0 4.9c0 .6.1 1.2.4 1.6h3.7v-.6c-.6-.3-.7-.9-.7-1.8v-7.5c0-2.4-2-3.7-5.7-3.7-3.4 0-5.4 1.7-5.4 4.3v.2h3.3v-.2c0-1 .8-1.6 2.2-1.6 1.5 0 2.2.4 2.2 1.5 0 1.3-.9 1.1-3.7 1.5-3.1.5-4.4 1.6-4.4 4.2 0 2.7 1.5 4.2 4 4.2 1.8 0 3.2-.8 4.1-2.1z"/><path class="st2" d="M140.3 54.4v.1c0 2.8 2.1 4.6 5.8 4.6 4 0 6.2-1.6 6.2-4.6 0-2.4-1.5-3.2-4.5-3.9-2.5-.6-3.6-.7-3.6-1.6 0-.8.6-1.2 2-1.2s2.2.6 2.3 1.8h3.4c-.1-2.8-2.2-4.5-5.7-4.5-3.4 0-5.4 1.7-5.4 4.4 0 2.2 1.5 3.2 4.5 4 2.3.6 3.5.5 3.5 1.7 0 .8-.7 1.3-2.1 1.3-1.8 0-2.7-.6-2.7-2h-3.7v-.1zM159.9 58.8v-2.6h-.9c-.9 0-1.2-.1-1.2-.8V48h2v-2.5h-2V42h-3.5v3.6h-1.7V48h1.7v7.1c0 2.7.6 3.7 3.5 3.7.5.1 1.1 0 2.1 0zM162 58.7h3.6V40.9H162v17.8z"/><path class="st3" d="M171.2 50.8c.1-1.8 1.1-2.7 2.6-2.7 1.6 0 2.5.9 2.6 2.7h-5.2zm5.1 3.9c-.4 1-1.2 1.5-2.4 1.5-1.7 0-2.6-1.1-2.7-3.1h8.8v-.9c0-4.5-2.3-7-6.3-7-3.8 0-6.1 2.6-6.1 6.9 0 4.4 2.4 7.1 6.2 7.1 3.1 0 5.4-1.7 6.1-4.4h-3.6v-.1z"/></svg>
</div>
</header>
<div>
<p>
Dear {{ first_name }},
</p>
<p>
Thank you for your enquiry. A Mortgage Adviser will be in touch soon and will attempt to call
{% if preferred_time_to_contact == 'M' %}
<span style="font-weight: bolder;">in the morning</span>,
{% elif preferred_time_to_contact == 'EA' %}
<span style="font-weight: bolder;">early afternoon</span>,
{% elif preferred_time_to_contact == 'LA' %}
<span style="font-weight: bolder;">late afternoon</span>,
{% elif preferred_time_to_contact == 'S' %}
on <span style="font-weight: bolder;">Saturday</span>,
{% endif %}
as specified.
</p>
<p>
In the meantime, if you have any further questions or concerns then you can contact us using the links below.
</p>
<p>
Kind Regards,<br>
Newcastle Building Society
</p>
</div>
<footer>
<div>
<ul>
<li><a href="https://www.newcastle.co.uk/faqs/legal-information/" target="_blank">Legal information</a></li>
<li><a href="http://www.newcastle.co.uk/contact" target="_blank">Contact Us</a></li>
<li><a href="https://www.newcastle.co.uk/complaints/" target="_blank">Complaints</a></li>
</ul>
<p>
© Newcastle Building Society. All Rights Reserved. <br />
<address>Principal Office, Portland House, New Bridge Street, Newcastle upon Tyne, NE1 8AL.</address>
Newcastle Building Society is authorised by the Prudential Regulation Authority and regulated by the Financial Conduct Authority and the Prudential Regulation Authority.<br />
Newcastle Building Society is registered on the Financial Services Register under the firm reference number 156058.
</p>
</div>
</footer>
</body>
</html><file_sep>
from django.shortcuts import render, redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, UpdateView
from django.conf import settings
from django.http import JsonResponse
from .forms import CustomerDetailsForm, PropertyDetailsForm, EnquiryForm
from .helpers.providers import EnquiryProvider
from requests import post
import json
ODIP_API_ENDPOINT = "http://ec2-35-178-182-161.eu-west-2.compute.amazonaws.com/send-enquiry"
LTVCALCULATOR_API_ENDPOINT = "https://eposdjjkpd.execute-api.eu-west-2.amazonaws.com/dev/ltv-calculator-v1"
def customer_details(request):
""" Customer Details form, first page of Enquiry """
# Set initial response code for testing purposes
response_code = 200
if request.method == "POST":
form = CustomerDetailsForm(request.POST, use_required_attribute=False)
if form.is_valid():
# Save to the session to be retreived later
request.session["customer_details"] = form.cleaned_data
return redirect("property_details")
response_code = 400
else:
form = CustomerDetailsForm(use_required_attribute=False)
context = {
"form": form
}
return render(request, "customer_details.html", context, status=response_code)
def property_details(request):
""" Property Details form, second page of Enquiry """
# Set initial response code for testing purposes
response_code = 400
# Session check to verify journey integrity
if not "customer_details" in request.session:
return redirect("customer_details")
if request.method =="POST":
form = PropertyDetailsForm(request.POST, use_required_attribute=False)
if form.is_valid():
property_details_data = form.cleaned_data
customer_details_data = request.session["customer_details"]
# Consolidate data from other pages to prep for db entry
enquiry_data = EnquiryProvider()
enquiry_data.add(property_details_data)
enquiry_data.add(customer_details_data)
# Convert all values to string before sending to API
string_data = enquiry_data.get_list_with_string_values()
# Post the data to the API
response = post(ODIP_API_ENDPOINT, json = string_data)
print(response.text)
return redirect("thank_you")
else:
# Generate a new form page and set response code
form = PropertyDetailsForm(use_required_attribute=False)
response_code = 200
context = {
"form": form
}
return render(request, "property_details.html", context, status=response_code)
def calculate_ltv(request):
loan_amount = int(request.GET.get('loanamount', None))
property_value = int(request.GET.get('propertyvalue', None))
property_data = {
"loan_amount": loan_amount,
"property_value": property_value
}
# Send data to the LTV Calculator API
response = post(LTVCALCULATOR_API_ENDPOINT, json = property_data)
# Map the response data to usable values
ltv_data = response.json()
ltv_value = ltv_data['body']['ltv_percentage']
ltv_acceptable = ltv_data['body']['is_acceptable']
# Check if the value is within specified acceptance criteria
if ltv_acceptable:
ltv_css = "ltv_acceptable"
visibility_css = "hidden"
else:
ltv_css = "ltv_unacceptable"
visibility_css = "visible"
data = {
'ltv': ltv_value,
'ltv_css': ltv_css,
'visibility_css': visibility_css,
}
return JsonResponse(data)
def thank_you(request):
""" Page displayed on submission complete """
# Session check to verify journey integrity
if not "customer_details" in request.session:
return redirect("customer_details")
# Clean the session
del request.session["customer_details"]
return render(request, "thank_you.html")
def error_404(request, exception):
""" Custom 404 error handler """
return render(request, 'error/404.html', status=404)
def error_500(request):
""" Custom 500 error handler """
return render(request, 'error/500.html', status=500)
<file_sep>from django.apps import AppConfig
class InitialEnquiryConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'initial_enquiry'
<file_sep>cd /home/ubuntu/odipweb/oDipUI
source env/bin/activate
rm -r static
python manage.py collectstatic
sudo systemctl restart gunicorn<file_sep>aniso8601==9.0.1
asgiref==3.3.4
certifi==2021.5.30
chardet==4.0.0
click==8.0.1
colorama==0.4.4
Django==3.2.4
environ==1.0
idna==2.10
itsdangerous==2.0.1
Jinja2==3.0.1
MarkupSafe==2.0.1
pytz==2021.1
requests==2.25.1
six==1.16.0
sqlparse==0.4.1
urllib3==1.26.5
Werkzeug==2.0.1
<file_sep># oDip Web UI v1.1
Repurposed from previous assignment to serve as a UI that sends a JSON object to the oDip API service.
## Pipeline Details
### Main.yml:
- Integration:
- Sets up Python v3.9
- Installs Safety and Bandit manually (not contained within Requirements file, personal choice for the developer over whether to run these modules locally)
- Bandit job currently skipped due to existence of django Secret Key in source code, Bandit will not pass with the existence of this key - (This would be fixed at a later date and would not exist in a production environment. Out of scope for this assignment)
* Deploy:
* Needs Integration to complete
* Configures AWS Credentials using GitHub Secrets
* Creates a CodeDeploy Deployment object using AWS CLI and sends to pre-defined application on CodeDeploy
### Appspec.yml
* After-Install:
* Removes static files
* Runs `collectstatic` command through django app
* Restarts GUnicorn
|
57c5b1af3f5354c53e3ee3c298ff31e0e24a179b
|
[
"HTML",
"Markdown",
"Python",
"Text",
"Shell"
] | 11 |
Python
|
eddylongshanks/CETM67-Assignment2-oDipUI
|
fdb025bac853177e8fd9831173a150a25af8e840
|
6a9090ed5b84a7a405588886bfd3a8df57be3adb
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 16:52:25 2018
@author: cecidip
The EnKF.
Ref: Evensen, Geir. (2009):
"The ensemble Kalman filter for combined state and parameter estimation."
"""
import numpy as np
import seaborn as sns
sns.set_style("whitegrid")
import hypo #https://github.com/groupeLIAMG/hypopy/blob/master/hypo.py
import multiprocessing as mp
from numpy.random import multivariate_normal
from common import * # https://github.com/nansencenter/DAPPER
from functions import *
from tqdm import tqdm #https://github.com/tqdm/tqdm/tree/master/tqdm
def fore_step(E, hyp, rcv):
"""FORECAST STEP"""
N,m=E.shape #num of enseble members
#centro=np.mean(ms[:,2:],axis=0) #basado en los ms
centro=ms[2:]
hyp = np.kron(hyp,np.ones((nsta,1)))
rcv_data = np.kron(np.ones((nev,1)), rcv)
Ef=np.zeros((E.shape))
hE=np.zeros((N,len(tt))) # Compute times with inverted hypocentre locations (hE)
for j in tqdm(range(N)):
Ef[j,:]=esfera(g,centro,E[j,:],pp=np.random.uniform(-0.1,0.1),rr=np.random.uniform(0,60))
slowness = 1./Ef[j,:]
hE[j,:] = g.raytrace(slowness, hyp, rcv_data)-hyp[:,1]
return Ef,hE,N,slowness,rcv_data,hyp
#%%
def analysis_step(Ef, hE, R, N):
"""ANALYSIS STEP"""
# Reference: <NAME>
# https://github.com/nansencenter/DAPPER/blob/master/da_methods/da_methods.py
mu = mean(Ef,0) #ensemble mean
A = Ef - mu #enesemble anomaly
hx = mean(hE,0)
Y = hE-hx #anomalies of the observed ensemble
D = multivariate_normal([0]*len(tt), R, N) #https://github.com/rlabbe/Kalman-anYd-Bayesian-Filters-in-Python/blob/master/Appendix-E-Ensemble-Kalman-Filters.ipynb
C = Y.T @ Y +( R*(N-1))
YC = mrdiv(Y, C)
KG = A.T @ YC
dE = (KG @ ( tt + D - hE ).T).T
Ea = Ef + dE
return Ea
#%%
def tt_error(Ea,slowness,hyp,rcv_data,hE,N):
"""CONTROL INVERSION - compute tt with analysed models to check if they improved"""
hEa=np.zeros((N,len(tt)))
for j in tqdm(range(N)):
slowness = 1./Ea[j,:]
hEa[j,:] = g.raytrace(slowness, hyp, rcv_data)-hyp[:,1]
err_for = abs(tt- np.mean(hE,axis=0))
err_ana = abs(tt- np.mean(hEa,axis=0))
deltaTT=plt.figure()
plt.plot(err_for,'o-')#,label=r'$\|\|\Delta tt fore\|\|$ = {0:6.5f}'.format(np.mean(err_for)))
plt.plot(err_ana,'r*-')#,label=r'$\|\|\Delta tt analysed\|\|$ = {0:6.5f}'.format(np.mean(err_ana)))
plt.ylabel('tt',fontsize=18)
plt.xlabel('Ray num',fontsize=18)
plt.tick_params(labelsize=15)
plt.legend()
plt.show()
return hEa
#%%
if __name__ == '__main__':
## GRID
xmin = 9600
xmax = 10440
ymin = 10036
ymax = 10416
zmin = 2626
zmax = 3206
dx = 20 # grid cell size, we use cubic cells here
x = np.arange(xmin, xmax+1, dx)
y = np.arange(ymin, ymax+1, dx)
z = np.arange(zmin, zmax+1, dx)
nthreads= mp.cpu_count() #use all the CPUs for parallel task
g = hypo.Grid3D(x, y, z, nthreads)
step_i =1 #change for each step
step = str(step_i)
step_prev = str(step_i-1)
#%%
""" imput files """
## Receivers
rcv=np.loadtxt(open("example/rcvRND.txt"), skiprows=1)
## Observed times
tt=np.loadtxt(open("example/tt_synth" + step + ".txt"))
## Hypos
hyp=np.loadtxt(open("example/h_true" + step + ".txt"))
## Previews (or initial) V models, by SGS :
#E=np.loadtxt(open("E100.txt")).T #ensemble de V
E=np.loadtxt(open("example/Ea"+step_prev+".txt"))
# true V for RMSE
Vtrue=np.loadtxt(open("example/Vtrue" + step + ".txt"))
# microseisms coordinates
ms=np.loadtxt(open("example/hinit" + step + ".txt"))
#%%
ircv = np.arange(rcv.shape[0]).reshape(-1,1) # vector of rcv indices
nsta = rcv.shape[0]
nev=1
#nev=len(hyp)
## Errors:
std_noise = 1.e-3
R=np.eye((len(tt))) * std_noise**2
#%%
"""Perform EnKF"""
Ef,hE, N , slowness, rcv_data,hyp= fore_step(E, hyp, rcv) #forecast step
Ea= analysis_step(Ef, hE, R, N) #Analysis step
hEa= tt_error(Ea,slowness, hyp,rcv_data,hE,N) #Control travel times
#%%
""" SAVE RESULTS"""
#slices of E before the forecast
fig=plot_rnSGS(g,E)
fig.savefig("example/rnEa" + step + ".png")
#slices de Ef
fig=plot_rnSGS(g,Ef)
fig.savefig("example/rnEf" + step + ".png")
#slices E
fig=plot_rnSGS(g,Ea)
fig.savefig("example/rnEa" + step + ".png")
#analysed ensembles Ea
np.savetxt("example/Ea" + step + ".txt", Ea)
#plots Ef Ea and dif
g.toXdmf(np.mean(Ef,axis=0), "Vp_forcasted" + step , "example/Vp_forcasted" + step )
g.toXdmf(np.mean(Ea,axis=0), "Vp_analysed" + step, "example/Vp_analysed" + step)
g.toXdmf(np.abs(np.mean(Ea,axis=0)-np.mean(Ef,axis=0)), "Vpa-Vpf" + step , "example/Vpa-Vpf" + step)
# tt analysed hEa and forecasted hE
np.savetxt("example/hE" + step + ".txt", hE)
np.savetxt("example/hEa" + step + ".txt", hEa)
<file_sep># EnKF
The Ensemble Kalman filter applied to microseismic data for updating 3D velocity models
! STILL UNDER TEST IN SYNTHETICS !
Requirements
Development is made with python version 3.6
You need to add this to you PYTHONPATH:
https://github.com/groupeLIAMG/hypopy
Note: You need to compile the python wrapper for the C++ raytracing code in https://github.com/groupeLIAMG/ttcr and add it to your PYTHONPATH to be able to run hypo.py
If you have VTK compiled with python on your system, it is possible to save velocity models and raypaths for posterior visualization (e.g. in paraview).
References:
@inproceedings{dip2019microseismic,
title={Microseismic Monitoring of Mines in Real Time with Ensemble Kalman Filter},
author={<NAME> and <NAME> and <NAME>},
booktitle={81st EAGE Conference and Exhibition 2019},
year={2019}
}
@Book{evensen2009data,
title = {Data assimilation: the ensemble Kalman filter},
publisher = {Springer Science \& Business Media},
year = {2009},
author = {<NAME>},
}
@InProceedings{raanes2016intro2,
author = {<NAME>.},
title = {Introduction to Data Assimilation and the Ensemble {K}alman Filter. {S}econd edition.},
year = {2016},
month = {October},
organization = {Nansen Environmental and Remote Sensing Center},
}
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 11 10:12:44 2018
@author: cecidip
"""
import numpy as np
import matplotlib.pyplot as plt
def plot_rnSGS(g,E,):
"""
Plots slices of randomly chosen ensemble members
If you wanna save the plot call the funtion as:
fig=plot_rnSGS(g,E)
fig.savefig("somefile.png")
"""
x=g.x
y=g.y
z=g.z
N=len(E) #
Vrn1 = E[np.random.randint(N),:].reshape(g.shape)
Vrn2 = E[np.random.randint(N),:].reshape(g.shape)
Vrn3 = E[np.random.randint(N),:].reshape(g.shape)
Vrn4 = E[np.random.randint(N),:].reshape(g.shape)
fig=plt.figure(figsize=(10,8))
plt.subplot(221)
plt.pcolor(x,z,np.squeeze(Vrn1[:,10,:].T), cmap='jet'), plt.gca().invert_yaxis()
plt.xlabel('X')
plt.ylabel('Z')
plt.colorbar()
plt.subplot(222)
plt.pcolor(x,z,np.squeeze(Vrn2[:,10,:].T), cmap='jet'), plt.gca().invert_yaxis()
plt.xlabel('Y')
plt.ylabel('Z')
plt.colorbar()
plt.subplot(223)
plt.pcolor(x,z,np.squeeze(Vrn3[:,10,:].T), cmap='jet'), plt.gca().invert_yaxis()
plt.xlabel('X')
plt.ylabel('Y')
plt.colorbar()
plt.subplot(224)
plt.pcolor(x,z,np.squeeze(Vrn4[:,10,:].T), cmap='jet'), plt.gca().invert_yaxis()
plt.xlabel('X')
plt.ylabel('Y')
plt.colorbar()
plt.suptitle('rnV_Ee')
plt.show()
return fig
def esfera(g,centro,V,pp=0.05, rr=120):
#centro: centre of the sphere
#rr:radius of the sphere
#pp: % of Velocity change
#V: velocity model
corr= np.ones((g.shape))
mm=-pp/rr
x0=centro[0]
y0=centro[1]
z0=centro[2]
#x0=sum(hyp[:,2])/nev
#y0=sum(hyp[:,3])/nev
#z0=sum(hyp[:,4])/nev
for i in range(0,g.x.size):
for j in range(0,g.y.size):
for k in range(0,g.z.size):
x=g.x[i]
y=g.y[j]
z=g.z[k]
dis=np.sqrt((x-x0)**2+(y-y0)**2+(z-z0)**2)
if dis<=rr:
corr[i,j,k]= (1+pp)#+mm*dis#+4*np.random.randn(1))
corrV=corr.flatten()
#g.toXdmf(corrV, 'esfera2', 'esfera2')
return V*corrV
def stats(E,Vtrue):
#Tarrahi2015:"Integration of microseismic monitoring data ..Kalman filter"
N,m=E.shape #num of esemble members
tmp=np.sum((E-Vtrue)**2,axis=0)
RMSE=np.sum(np.sqrt(tmp/N))/m
vmean=np.sum(E,axis=0)/N
tmp1=np.sum((E-vmean)**2,axis=0)
Sp=np.sum(np.sqrt(tmp1/N))/m
return (RMSE,Sp)
|
0bd29358fe1fee91110ad6cfd993f4349bcb5db1
|
[
"Markdown",
"Python"
] | 3 |
Python
|
groupeLIAMG/EnKF
|
bfdeb719f11f3aef35565f9828af8090ab6fb58e
|
4670b780d66d2765e6ca18c44dad0d23798be399
|
refs/heads/master
|
<repo_name>nikolay1962/MessengerTest<file_sep>/src/main/java/my/messages/IOUtils.java
package my.messages;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
public class IOUtils {
Scanner scanner;
public IOUtils() {
this.scanner = new Scanner(System.in);
}
public boolean fileExists(String filename) {
Path path = Paths.get(filename);
return fileExists(path);
}
public boolean fileExists(Path path) {
return Files.exists(path);
}
public void writeMessage(String message) {
System.out.println(message);
}
public String readNextLine() {
return scanner.nextLine();
}
public int getPositiveInteger(String request) {
int integer = 0;
while (integer < 1 || integer > 100) {
writeMessage(request);
try {
integer = Integer.parseInt(scanner.nextLine());
} catch (Exception e) {
integer = 0;
}
}
return integer;
}
public int getIntegerWithinBounds(String request, int lower, int upper) {
int integer = lower - 1;
while (integer < lower || integer > upper) {
writeMessage(request);
try {
integer = Integer.parseInt(scanner.nextLine());
} catch (Exception e) {
integer = lower - 1;
}
}
return integer;
}
public String getNotEmptyString(String request) {
String input = "";
while (input.isEmpty()) {
System.out.print(request);
input = scanner.nextLine();
}
return input;
}
public String getValidEmail(String message) {
while (true) {
writeMessage(message);
String email = readNextLine();
if (email == null || email.isEmpty()) {
return null;
}
if (!email.contains("@")) {
continue;
}
return email;
}
}
public boolean sendMessage(String currentUserEmail, String filename, String message) {
// String filename = UserServices.PREFIX_SUFFIX[0] + recepient + UserServices.PREFIX_SUFFIX[1];
if (!fileExists(filename) && !createFile(filename)) {
return false;
}
try(FileWriter fw = new FileWriter(filename, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.print(LocalDateTime.now().toString() + "; from " + currentUserEmail + "; ");
out.println(message);
} catch (IOException e) {
return false;
}
return true;
}
private boolean createFile(String filename) {
Path filePath = Paths.get(filename);
try {
Files.createFile(filePath);
return true;
} catch (IOException e) {
return false;
}
}
public Properties getProperties(String email) {
Properties config = new Properties();
Path userData = Paths.get(email);
try (InputStream stream = Files.newInputStream(userData)) {
config.load(stream);
} catch (IOException e) {
return null;
}
return config;
}
public boolean saveUserData(User user) {
Path userFile = Paths.get(user.getEmail());
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(user.getEmail());
LocalDateTime currentMoment = LocalDateTime.now();
// set the properties value
prop.setProperty("email", user.getEmail());
prop.setProperty("name", user.getName());
prop.setProperty("password", <PASSWORD>());
prop.setProperty("age", String.valueOf(user.getAge()));
prop.setProperty("lastLogoutTime", currentMoment.format(UserServices.FORMATTER));
prop.setProperty("lastTimeOfMessageGet", Long.toString(user.getLastTimeOfMessageGet()));
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
return false;
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public boolean checkIfHaveNewMessages(String incomingMessages, long lastMessageMillis) {
File file = new File(incomingMessages);
return file.lastModified() > lastMessageMillis;
}
public void displayToUser(Chat chat) {
//read all lines from message file
Path messages = Paths.get(chat.getMessageFile());
// variable to compare times;
String timeOfLastPrintedMessage = Instant.ofEpochMilli(chat.getLastTimeOfMessageGet()).atZone(ZoneId.systemDefault()).toLocalDateTime().toString();
try {
List<String> lines = Files.readAllLines(messages);
boolean printChatName = true;
for (String line : lines) {
if (line.indexOf(';') > 0) {
String timeOfMessage = line.substring(0, line.indexOf(';'));
if (timeOfLastPrintedMessage.compareTo(timeOfMessage) < 0) {
//display to user.
if (printChatName) {
printChatName = false;
writeMessage("<++++++++++ " + chat.getName() + " ++++++++++>");
}
writeMessage('\t' + line);
timeOfLastPrintedMessage = timeOfMessage;
}
}
}
} catch (IOException e) {
System.out.println(e);
}
//change lastTimeOfMessageGet in user data
chat.setLastTimeOfMessageGet(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
}
public String getInputFromUser() {
return scanner.nextLine();
}
}
|
c829afb2202f533c796b6d62094fd2fe655391c3
|
[
"Java"
] | 1 |
Java
|
nikolay1962/MessengerTest
|
ed3bf6fcda6fb90ade616aa7434fe078cc76fce8
|
a4075ac88be948c9f65e9a06127b91bc2ff932e1
|
refs/heads/master
|
<repo_name>alexgincho/Practica_Nro2<file_sep>/Practica_Nro2/Models/Usuario.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Practica_Nro2.Models
{
public class Usuario
{
public string Nombre { get; set; }
public string ApellidoPaterno { get; set; }
public string ApellidoMaterno { get; set; }
public string Telefono { get; set; }
public string Distrito { get; set; }
public string Direccion { get; set; }
public Mascota Mascota { get; set; }
}
}
<file_sep>/Practica_Nro2/Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Practica_Nro2.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace Practica_Nro2.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
ViewBag.ListaMascotas = GetMascotas();
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public IActionResult Registro()
{
Usuario usuario = new Usuario();
return View(usuario);
}
[HttpPost]
public IActionResult Registro(Usuario Usuario)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View();
}
// Creando Listado de Mascotas para los Cards
public List<Mascota> GetMascotas()
{
List<Mascota> Mascotas = new List<Mascota>();
Mascotas.Add(new Mascota { Raza = "Pastor Aleman", Tipo = "Perro", Descripcion= "El pastor alemán u ovejero es una raza canina que proviene de Alemania.", Foto= "https://upload.wikimedia.org/wikipedia/commons/9/94/Cane_da_pastore_tedesco_adulto.jpg" });
Mascotas.Add(new Mascota { Raza = "Siamés", Tipo = "Gato", Descripcion = "El siamés moderno es una raza de gato proveniente del antiguo reino de Siam", Foto = "https://www.fanaticosdelasmascotas.cl/wp-content/uploads/2020/11/gatos_siames-siam%EF%BC%B4-liliy2025-Pixabay_portada.jpg" });
Mascotas.Add(new Mascota { Raza = "Husky Siberiano", Tipo = "Perro", Descripcion = "El husky siberiano es una raza de perro de trabajo originaria del noreste de Siberia.", Foto = "https://www.animalfiel.com/wp-content/uploads/2020/07/tipos-de-husky-siberiano.png" });
return Mascotas;
}
}
}
|
51f1e879a7657badef947c0ee0f3b709c13af296
|
[
"C#"
] | 2 |
C#
|
alexgincho/Practica_Nro2
|
f7de4593dd47ff9ba831f6699e1e6c4e61f61ead
|
69eccad03f5df88c1b7174d80b8cc3b5f91a3c84
|
refs/heads/master
|
<file_sep>
all: funcs.o main.o
gcc -o program funcs.o main.o
main.o: main.c headers.h
gcc -c main.c headers.h
funcs.o: funcs.c headers.h
gcc -c funcs.c
run:
./program
<file_sep>#include<stdio.h>
#include <stdlib.h>
#include "headers.h"
#include <time.h>
#include <string.h>
void main(){
struct ppg kd;
strcpy(kd.name, "Durant");
kd.points = 27;
display(kd);
printf("\nExample 1 of random player:\n");
display(example());
printf("\nExample 2 of random player:\n");
display(example());
modify(&kd, "Williamson", 40);
printf("\nAfter Modifying Durant\n");
display(kd);
}
<file_sep>
struct ppg{char name[64]; int points;};
void display(struct ppg player);
struct ppg example();
void modify(struct ppg *player, char *newName, int newPoints);
<file_sep>#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include "headers.h"
#include <time.h>
void display(struct ppg player){
printf ("Player name: %s | Points Per Game: %d\n", player.name,player.points);
}
struct ppg example(){
struct ppg randomPlayer;
char names[5][13] = {"James", "Irving", "Antetokounmpo", "George", "Leonard"};
int points[5] = {35, 30, 25, 29, 28};
strcpy(randomPlayer.name , names[rand() % 5]); // assigns randomPlayer random name from array names
randomPlayer.points = points[rand() % 5];// assigns randomPlayer random points from array points
return randomPlayer;
}
void modify(struct ppg *player, char *newName, int newPoints){
strcpy(player->name, newName); // asssigns player new name
player->points = newPoints; // assisngs player new points
}
|
7ee1d47a752ff669b44e4aa1e33ccc3455b3699e
|
[
"C",
"Makefile"
] | 4 |
Makefile
|
KennethChin0/struct
|
722f90058e3f450e90dc3904d8caf59c7f9e3709
|
9ef2635eb633e756fa2cb7b208a891fc271f9213
|
refs/heads/main
|
<repo_name>mherzog01/util<file_sep>/sh/gcp/install_gcsfuse.sh
# https://gist.github.com/korakot/f3600576720206363c734eca5f302e38
# https://github.com/GoogleCloudPlatform/gcsfuse/blob/master/docs/installing.md
echo "deb http://packages.cloud.google.com/apt gcsfuse-bionic main" > /etc/apt/sources.list.d/gcsfuse.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -
apt -qq update
apt -qq install gcsfuse<file_sep>/sh/gcp/mk_bucket_dirs.sh
# 1. Mount $BUCKET_NAME at $MOUNT_PT
# 2. Run this script
MOUNT_PT=${1:-$HOME/mnt}
BUCKET_NAME=$2
DEL_OUTFILE=${3:-y} # Set to y or n
echo "Reading objects in $BUCKET_NAME"
OUTFILE=dir_names.txt
gsutil ls -r gs://$BUCKET_NAME/** | while read BUCKET_OBJ
do
dirname "$BUCKET_OBJ"
done | sort -u > $OUTFILE
echo "Processing directories found"
cat $OUTFILE | while read DIR_NAME
do
LOCAL_DIR=`echo "$DIR_NAME" | sed "s=gs://$BUCKET_NAME/==" | sed "s=gs://$BUCKET_NAME=="`
#echo $LOCAL_DIR
TARG_DIR="$MOUNT_PT/$LOCAL_DIR"
if ! [ -d "$TARG_DIR" ]
then
echo "Creating $TARG_DIR"
mkdir -p "$TARG_DIR"
fi
done
if [ $DEL_OUTFILE = "y" ]
then
rm $OUTFILE
fi
echo "Process complete"
|
b71dd9f25c6bde3cdbfb5cde4ca3ff773c200d02
|
[
"Shell"
] | 2 |
Shell
|
mherzog01/util
|
e0095b643c57f6248e16f94d5d553f6f4a81a4cb
|
d458a31a1ec1dbc8a6634d5defb0316285a7e6c6
|
refs/heads/main
|
<file_sep>[](https://travis-ci.com/dskyiocom/renew-letsencrypt)
# Summary
Renews mounted Let's Encrypt certificates.
Complements https://hub.docker.com/r/dskyiocom/nginx-alpine-letsencrypt
# Source code
https://github.com/dskyiocom/renew-letsencrypt
# Tags
- `latest`
# How to use this image
You need to agree to the ACME server's Subscriber Agreement by setting `ACCEPT_TOS` to `true`.
Setting `NGINX_CONTAINER` triggers `docker kill -s HUP "$NGINX_CONTAINER"`.
By default renewals are attempted at container start and every 10 days. To adjust the interval `INTERVAL` can be set.
```console
docker run -e ACCEPT_TOS=true -v "$PWD/certs:/etc/letsencrypt" -v /var/run/docker.sock:/var/run/docker.sock dskyiocom/renew-letsencrypt
```
<file_sep>FROM alpine
COPY entrypoint.sh /work/
ENTRYPOINT sh entrypoint.sh
EXPOSE 80
RUN apk add docker certbot
WORKDIR /work
<file_sep>#!/bin/sh
[ "$AGREE_TOS" = true ] || exit 1
while :; do
certbot renew --agree-tos -n --standalone
[ -n "$NGINX_CONTAINER" ] && docker kill -s HUP "$NGINX_CONTAINER"
[ -z "$INTERVAL" ] && INTERVAL=864000
sleep "$INTERVAL"
done
|
c7f62d2d6565c745c1893cc14fea3d230a4ef53d
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 3 |
Markdown
|
dskyiocom/renew-letsencrypt
|
78d7dc06bc9243171b84ab08189bafc9218a102d
|
c757e510e4da60c911b5e275a126b6ec2f8deea8
|
refs/heads/master
|
<repo_name>vitamincc/Hadoop-Pairs-vs.-Stripes-Conditional-Probability-Lift<file_sep>/pair_mapper.py
#!/usr/bin/env python
from operator import itemgetter
import string
import sys
import csv
from itertools import combinations
from collections import defaultdict
userMovies = defaultdict(list)
with open('rating03.csv', 'rb') as csvfile:
csvReader = csv.reader(csvfile)
csvReader.next()
for row in csvReader:
if float(row[2]) >= 4.0 :
userMovies[row[0]].append(row[1])
for user, movieList in userMovies.items():
for m1, m2 in combinations(movieList, 2):
print '%s\t%s\t%s' % (m1, m2, 1)
<file_sep>/README.md
# Hadoop-Pairs-vs.-Stripes-Conditional-Probability-Lift
1.Write a job to compute the frequency of co-occurrence for every pair of movies that receive a "High" ranking from the same user (the frequency is the number of users that give this ranking to both of the movies). High ranking corresponds to a 4 or a 5 ranking in the ratings file. You must do this using the 'pairs' and the 'stripes' approach explained in class. Use different sizes of the dataset to obtain a graph similar to the Figure in the slides. Then, output the 20 frequent pairs by using the movie names in the movie data file (not the IDs) You must produce two implementations of this: One in Hadoop MapReduce, one in SPARK. Compare the times for both
2.Modify your program above to compute the conditional probability P(B/A) where A,B are movies. Use the 'stripes' approach to do this. And output the names (both A and B) of the movies whose conditional probability exceeds 0.8. (This can be used as a primitive way to recommend movie B to customers that rent movie A and like it.). Graph the time needed for this vs. size of the dataset. Do this on SPARK
3.Further modify your SPARK program to compute the lift between two movies. (Recall that lift(AB)=P(AB)/(P(A)*P(B))=P(A|B)/P(A)) Again, plot the time vs. size graph, and output pairs whose lift is greater than 1.6 (What does this mean?)
<file_sep>/pair_reducer.py
#!/usr/bin/env python
from operator import itemgetter
import sys
import collections
import csv
freq = collections.defaultdict(int)
for line in sys.stdin:
#remove leading and trailing whitespace
line = line.strip()
#parse the input we got from mapper.py
words = line.split('\t', 2)
if (len(words) != 3) :
print words
try:
mv1 = int(words[0])
mv2 = int(words[1])
count = int(words[2])
pair = (mv1, mv2) if mv1 < mv2 else (mv2, mv1)
freq[pair] = freq.get(pair, 0) + 1
except ValueError:
pass
movieNames = {}
with open('movies1.csv', 'rb') as csvfile:
csvReader = csv.reader(csvfile)
csvReader.next()
for row in csvReader:
movieNames[int(row[0])] = row[1]
count = 0
for pair, freqcount in sorted(freq.iteritems(), key=lambda (k,v): (v,k), reverse=True):
count += 1
if count <= 20:
print '%s\t%s\t%s' % (movieNames[pair[0]], movieNames[pair[1]], freqcount)
<file_sep>/split_rating.R
setwd("/Users/xucc/Documents/GMU/CS657/assigns/assign2")
mydata <- read.csv("ratings1.csv")
rows <- nrow(mydata)
head(mydata)
set.seed(0)
index03 <- sample(rows, 0.03*rows, replace = FALSE)
rating03 <- mydata[index03,]
index06 <- sample(rows, 0.06*rows, replace = FALSE)
rating06 <- mydata[index06,]
index09 <- sample(rows, 0.09*rows, replace = FALSE)
rating09 <- mydata[index09,]
index12 <- sample(rows, 0.12*rows, replace = FALSE)
rating12 <- mydata[index12,]
index2 <- sample(rows, 0.1*rows, replace = FALSE)
rating2 <- mydata[index2,]
index15 <- sample(rows, 0.15*rows, replace = FALSE)
rating15 <- mydata[index15,]
index18 <- sample(rows, 0.18*rows, replace = FALSE)
rating18 <- mydata[index18,]
index21 <- sample(rows, 0.21*rows, replace = FALSE)
rating21 <- mydata[index21,]
index24 <- sample(rows, 0.24*rows, replace = FALSE)
rating24 <- mydata[index24,]
index27 <- sample(rows, 0.27*rows, replace = FALSE)
rating27 <- mydata[index27,]
index4 <- sample(rows, 0.2*rows, replace = FALSE)
rating4 <- mydata[index4,]
index5 <- sample(rows, 0.25*rows, replace = FALSE)
rating25 <- mydata[index5,]
index6 <- sample(rows, 0.3*rows, replace = FALSE)
rating6 <- mydata[index6,]
index7 <- sample(rows, 0.7*rows, replace = FALSE)
rating7 <- mydata[index7,]
index8 <- sample(rows, 0.8*rows, replace = FALSE)
rating8 <- mydata[index8,]
index5 <- sample(rows, 0.5*rows, replace = FALSE)
rating5 <- mydata[index5,]
index6 <- sample(rows, 0.6*rows, replace = FALSE)
rating6 <- mydata[index6,]
write.csv(rating1, "rating1.csv", row.names = F)
write.csv(rating2, "rating2.csv", row.names = F)
write.csv(rating3, "rating3.csv", row.names = F)
write.csv(rating4, "rating4.csv", row.names = F)
write.csv(rating5, "rating5.csv", row.names = F)
write.csv(rating6, "rating6.csv", row.names = F)
write.csv(rating03, "rating03.csv", row.names = F)
write.csv(rating06, "rating06.csv", row.names = F)
write.csv(rating09, "rating09.csv", row.names = F)
write.csv(rating12, "rating12.csv", row.names = F)
write.csv(rating15, "rating15.csv", row.names = F)
write.csv(rating18, "rating18.csv", row.names = F)
write.csv(rating21, "rating21.csv", row.names = F)
write.csv(rating24, "rating24.csv", row.names = F)
write.csv(rating27, "rating27.csv", row.names = F)
<file_sep>/stripe_mapper.py
#!/usr/bin/env python
from operator import itemgetter
import string
import sys
import csv
from itertools import combinations
from collections import defaultdict
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
userMovies = defaultdict(list)
with open('rating03.csv', 'rb') as csvfile:
csvReader = csv.reader(csvfile)
csvReader.next()
for row in csvReader:
if float(row[2]) >= 4.0 :
userMovies[row[0]].append(row[1])
for user, movieList in userMovies.items():
movieList.sort()
length = len(movieList)
for index, mv in enumerate(movieList):
if index >= length -1 :
break
sublist = '\t'.join(movieList[index + 1:])
print '%s\t%s' % (mv, sublist)
|
93e05ca3b7abea13bd5b2e3f1cf065e78cbb1e9a
|
[
"Markdown",
"Python",
"R"
] | 5 |
Python
|
vitamincc/Hadoop-Pairs-vs.-Stripes-Conditional-Probability-Lift
|
69c0de4a22e61dab0816c3810a8d5e91eca9b0bc
|
28aa480da21ecc02ad210e5c0d96d814c3531943
|
refs/heads/master
|
<file_sep># Circle Art
A tiny Python script to draw beautiful circles, with standard library `turtle`. [Demo here.](./demo.mp4)
### Usage
```
./cadraw.py [base radius] [circle list] [args...]
```
`base radius` is radius of base circle, which is the only full circle in the picture.
`circle list` is a list of triple tuples. For each tuple, the first element is either `'i'` or `'o'`. It indicates the circle is inside of base circle or outside of it. The second `n` and third `d` are two integers, which mean one component arc of current circle crosses `n/d` of perimeter of the circle it lives on.
Use `--preview` to draw circles super fastly, and use `--no-scale` to disable scaling action per circle.
----
Copyright © 2018 Correctizer.
<file_sep>#!/usr/bin/env python3
# usage: cadraw [radius] [circle list]
import sys
import turtle
from fractions import Fraction
import math
import random
arg_radius = eval(sys.argv[1])
arg_circle_list = eval(sys.argv[2])
arg_preview = False
arg_scale = True
for arg in sys.argv[3:]:
if arg == '--preview':
arg_preview = True
elif arg == '--no-scale':
arg_scale = False
else:
raise Exception(f'wrong argument: {arg}')
circle_list = [(t, Fraction(Fraction(n), Fraction(d))) for t, n, d in arg_circle_list]
print(f'radius: {arg_radius} circles: {circle_list}')
def cal_r2(r1, k):
return 2 * r1 * math.sin(0.5 * k * math.pi)
def cal_beta(k):
return 0.5 * (1 - float(k)) * math.pi
def cal_gamma(k):
return float(k) * math.pi
def draw(r1, r2, k, inner=True):
beta = cal_beta(k)
gamma = cal_gamma(k)
for _i in range((1 / (k / 2)).numerator):
turtle.pendown()
turtle.right(beta)
if inner:
turtle.circle(-r2, 2 * beta)
else:
turtle.circle(-r2, -2 * (math.pi - beta))
turtle.penup()
turtle.right(beta)
turtle.circle(-r1, gamma)
def scale(r):
size = min(turtle.window_width(), turtle.window_height())
ratio = 0.5 * 1.05 * (r * 2 / size)
width = turtle.window_width()
height = turtle.window_height()
turtle.setworldcoordinates(
-ratio * width, -ratio * height, ratio * width, ratio * height)
turtle.radians()
if arg_scale:
scale(arg_radius)
if arg_preview:
turtle.speed(0)
base_radius = arg_radius
turtle.penup()
turtle.left(math.pi)
turtle.forward(base_radius)
turtle.right(0.5 * math.pi)
turtle.pendown()
turtle.circle(-base_radius)
turtle.penup()
turtle.home()
turtle.left(0.5 * math.pi)
inner_r1 = outer_r1 = arg_radius
previous_r1 = 0
for i, (t, k) in enumerate(circle_list):
if t == 'i':
inner = True
r1 = inner_r1
elif t == 'o':
inner = False
r1 = outer_r1
else:
raise Exception(f'wrong circle type: {t}')
turtle.penup()
turtle.left(0.5 * math.pi)
turtle.forward(r1 - previous_r1)
turtle.right(0.5 * math.pi)
turtle.circle(-r1, random.random() * math.tau)
turtle.pendown()
r2 = cal_r2(r1, k)
if arg_scale:
if inner:
scale(r1)
else:
scale(r1 + r2)
draw(r1, r2, k, inner=inner)
if inner:
inner_r1 = abs(r1 - r2)
else:
outer_r1 = r1 + r2
previous_r1 = r1
turtle.penup()
turtle.home()
turtle.hideturtle()
scale(outer_r1)
turtle.done()
|
5231924bc01ec09343f4573a852e3b31633fa4df
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
whoiscc/circle-art
|
7f8d9a4ab7ff225c3c5c2a80d688d430f835c921
|
38325c8524ad8ef6bb6a68480896379d565e4241
|
refs/heads/master
|
<file_sep>"use strict";
var slideIndex = 1;
var timer = void 0;
var clickNext = function clickNext() {
plusSlides(1);
};
var stopInterval = function stopInterval() {
clearInterval(timer);
};
var slideTimer = function slideTimer() {
timer = setInterval(function () {
clickNext();
}, 10000);
};
var plusSlides = function plusSlides(n) {
showSlides(slideIndex += n);
stopInterval();
slideTimer();
};
var currentSlide = function currentSlide(n) {
showSlides(slideIndex = n);
stopInterval();
slideTimer();
};
var showSlides = function showSlides(n) {
var i = void 0;
var slides = document.getElementsByClassName("slides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = slides.length;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = 'none';
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace('active', '');
}
slides[slideIndex - 1].style.display = 'block';
dots[slideIndex - 1].className += 'active';
};
showSlides(1);
currentSlide(1);<file_sep>let slideIndex = 1;
let timer;
let clickNext = () => {
plusSlides(1);
};
let stopInterval = () => {
clearInterval(timer);
};
let slideTimer = () => {
timer = setInterval(() => {
clickNext();
}, 10000);
};
let plusSlides = (n) => {
showSlides(slideIndex += n);
stopInterval();
slideTimer();
};
let currentSlide = (n) => {
showSlides(slideIndex = n);
stopInterval();
slideTimer();
};
let showSlides = (n) => {
let i;
let slides = document.getElementsByClassName("slides");
let dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = slides.length;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = 'none';
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace('active', '');
}
slides[slideIndex - 1].style.display = 'block';
dots[slideIndex - 1].className += 'active';
};
showSlides(1);
currentSlide(1);
<file_sep>let menuFunction = ()=>{
let searchButton = document.body.querySelector('.header-search-btn')
let searchInput = document.body.querySelector('.header-search > input')
let openMenuBtn = document.getElementById('menuBtn')
let menuContainer = document.body.querySelector('.header-nav-container')
searchButton.addEventListener('click', () => {
searchInput.classList.toggle('search-field-visible')
})
openMenuBtn.addEventListener('click', () => {
openMenuBtn.classList.toggle('menu-opened-btn')
openMenuBtn.classList.toggle('menu-closed-btn')
menuContainer.classList.toggle('mobile-menu-not-active')
menuContainer.classList.toggle('mobile-menu-active')
})
}
let dataDivisionDependOnScreens = (array) => {
let screenWidth = screen.width
let dividedData
if (screenWidth > 1024) {
dividedData =_.chunk(_.filter(_.sortBy(array, (obj) => {return new Date(obj.dateAdded)}), 'price', {'category' : 'women', 'fashion': 'Casual style'}), 8)
}else if (screenWidth > 768) {
dividedData =_.chunk(_.filter(_.sortBy(array, (obj) => {return new Date(obj.dateAdded)}), 'price', {'category' : 'women', 'fashion': 'Casual style'}), 6)
}else dividedData =_.chunk(_.filter(_.sortBy(array, (obj) => {return new Date(obj.dateAdded)}), 'price', {'category' : 'women', 'fashion': 'Casual style'}), 4)
return dividedData;
}
let index = 0
let createItemHTML = (object) => {
let divContainer = document.createElement("div")
let figure = document.createElement("figure")
let imgContainer = document.createElement("div")
let link = document.createElement("a")
let img = document.createElement("img")
let text = document.createElement("p")
let figcaption = document.createElement("figcaption")
let breakLine = document.createElement("br")
let spanPrice = document.createElement("span")
let newPrice
divContainer.className = 'item mobile'
divContainer.dataset.id = object.id
imgContainer.className = 'img-container'
link.setAttribute('href', 'item.html')
img.className = 'item-photo'
img.setAttribute('src', object.thumbnail)
text.className = 'view-item'
text.innerText = 'View item'
figcaption.innerText = object.title
if (object.discountedPrice < object.price) {
spanPrice.innerText = '£ ' + object.discountedPrice
} else spanPrice.innerText = '£ ' + object.price
divContainer.appendChild(figure)
figure.appendChild(imgContainer)
imgContainer.appendChild(link)
link.appendChild(img)
link.appendChild(text)
figure.appendChild(figcaption)
figcaption.appendChild(breakLine)
figcaption.appendChild(spanPrice)
if(object.hasNew) {
newPrice = document.createElement("span")
newPrice.className = 'new-price'
newPrice.innerText = 'New'
spanPrice.appendChild(newPrice)
}
return divContainer;
}
let appendItem = (item, inBlock) => {
let block = document.body.querySelector(inBlock)
block.appendChild(item)
}
let displayItemsIn = (block, array) => {
index === array.length ? index = NaN :
array[index].forEach((item) => {
let template = createItemHTML(item)
appendItem(template, block)
})
index++
}
let initDisplayItems = () => {
displayItemsIn('.arrivals-block', dataDivisionDependOnScreens(window.catalog))
}
let insertPromoBlock = () => {
let itemToDisplay
if (screen.width > 1024) {
itemToDisplay = 4
}else if (screen.width > 768) {
itemToDisplay = 3
}else itemToDisplay = 2
let promo = document.body.querySelector('.promo-container')
let block = document.body.querySelector('.arrivals-block')
let items = Array.from(document.body.querySelectorAll('.item'))
block.insertBefore(promo, items[itemToDisplay])
}
let storageClickedItem = () => {
let items = Array.from(document.body.querySelectorAll('.item'))
items.forEach( item => {
item.addEventListener('click', (ev) => {
localStorage.setItem('id', ev.currentTarget.dataset.id)
})
})
}
let addPriceToHTML = () => {
let bagMoney = document.body.querySelector('.bag-money')
let itemCount = document.body.querySelector('#bag-item-count')
bagMoney.innerText = localStorage.getItem('money') || 0
itemCount.innerText = localStorage.getItem('count') || 0
}
let filterEvents = () => {
let categoryList = document.querySelector('.category-list')
let categoryListLi = Array.from(document.querySelectorAll('.category-list li'))
let closeIconContainer = document.querySelector('.close-icon-container')
let filter = document.querySelector('.filter')
let filterLists = Array.from(document.querySelectorAll('.filter-list'))
document.querySelector('.mobile-selected-category-container').addEventListener('click', (event) => {
if (event.target != closeIconContainer ) {
categoryList.classList.add('active')
filter.classList.add('active')
}else {
categoryList.classList.remove('active')
filter.classList.remove('active')
}
})
filterLists.forEach( (el, i) => {el.addEventListener('click', (event) => {
let siblings = Array.from(event.target.parentNode.children)
siblings.forEach((el) => {
el.classList.remove('active');
})
event.target.classList.toggle('active')
event.target.parentNode.previousSibling.previousElementSibling.classList.add('active')
event.target.parentNode.previousSibling.previousSibling.previousElementSibling.classList.add('active')
if( event.target.innerText == 'Not selected') {
event.target.parentNode.previousSibling.previousElementSibling.classList.remove('active')
event.target.parentNode.previousSibling.previousSibling.previousElementSibling.classList.remove('active')
}
event.target.parentNode.previousSibling.previousElementSibling.childNodes[1].innerText = event.target.innerText
categoryListLi[i].innerText = event.target.innerText + ','
categoryListLi[i].classList.add('active')
if (event.target.innerText == 'Not selected') {
categoryListLi[i].classList.remove('active')
}
})
})
}
let init = () => {
let resizeEnd
menuFunction()
initDisplayItems()
insertPromoBlock()
filterEvents()
window.addEventListener('resize', () => {
clearTimeout(resizeEnd)
resizeEnd = setTimeout(initDisplayItems, 500)
document.body.querySelector('.arrivals-block').innerHTML = ''
index = 0
resizeEnd()
})
window.addEventListener('onload', insertPromoBlock)
document.body.querySelector('.show-more-arrivals').addEventListener('click', initDisplayItems)
storageClickedItem()
addPriceToHTML()
}
init()<file_sep>let itemToDisplay = window.catalog.find( item => item.id == localStorage.getItem('id'))
let menuFunction = ()=>{
let searchButton = document.body.querySelector('.header-search-btn')
let searchInput = document.body.querySelector('.header-search > input')
let openMenuBtn = document.getElementById('menuBtn')
let menuContainer = document.body.querySelector('.header-nav-container')
searchButton.addEventListener('click', () => {
searchInput.classList.toggle('search-field-visible')
})
openMenuBtn.addEventListener('click', () => {
openMenuBtn.classList.toggle('menu-opened-btn')
openMenuBtn.classList.toggle('menu-closed-btn')
menuContainer.classList.toggle('mobile-menu-not-active')
menuContainer.classList.toggle('mobile-menu-active')
})
}
let cleanLocalStorage = () => {
localStorage.clear()
}
let addPriceToHTML = (price, count = 1) => {
let bagMoney = document.body.querySelector('.bag-money')
let itemCount = document.body.querySelector('#bag-item-count')
bagMoney.innerText = +bagMoney.innerText + price
itemCount.innerText = +itemCount.innerText + count
}
let append = (element, inBlock) => {
document.body.querySelector(inBlock).innerHTML = element
}
let getPrice = () => {
let price = itemToDisplay.discountedPrice < itemToDisplay.price ? itemToDisplay.discountedPrice : itemToDisplay.price
return price
}
let createTemplateFrom = (object) => {
let mainImageTemplate = _.template('<img src=<%= preview[0] %> id="mainImage" alt="">')
let thumbnailImageTemplate = _.template('<div><img src=<%= preview[1] %> alt=""></div>' +
'<div><img src=<%= preview[2] %> alt=""></div>' +
'<div><img src=<%= preview[3] %> alt=""></div>')
let itemSizeTemplate = _.template('<% _.forEach(sizes, function(size) { %>' +
'<li>' +
'<input name="size" class="size-input" id=<%= size %> type="radio" value=<%= size %> required/>' +
'<label for=<%= size %> class="item-btn size-btn"><%= size %> </label>' +
'</li>' +
'<% }) %>')
let itemColorTemplate = _.template('<% _.forEach(colors, function(color) { %>' +
'<li>' +
'<input name="color" class="size-input" id=<%= color %> type="radio" value=<%= color %> required/>' +
'<label for=<%= color %> class="item-btn size-btn"><%= color %> </label>' +
'</li>' +
'<% }) %>')
let price = getPrice()
append(mainImageTemplate(object), '.main-img')
append(thumbnailImageTemplate(object), '.thumbnail')
append(itemSizeTemplate(object), '.item-size > ul')
append(itemColorTemplate(object), '.item-color > ul')
let itemName = document.querySelector('.item-name')
let itemText = document.querySelector('.item-text')
let itemPrice = document.querySelector('.item-price')
itemName.innerText = object.title
itemText.innerText = object.description
itemPrice.innerText ='£ ' + price
}
let addItemToLocalStorage = () => {
let itemProperties = {}
let itemsArray = []
let form = document.body.querySelector('form')
form.addEventListener('submit', (ev) => {
ev.preventDefault()
let inputs = Array.from(document.body.querySelectorAll('input')).filter(el => el.checked)
let price = getPrice()
itemProperties.sizes = inputs[0].value
itemProperties.colors = inputs[1].value
itemProperties.quantity = 1
let itemStorageForBag = Object.assign({}, itemToDisplay, itemProperties)
if(localStorage.getItem('items')){
itemsArray = JSON.parse(localStorage.getItem('items'))
}
if ( itemsArray.length < 1) {
itemsArray.push(itemStorageForBag)
}else if (itemsArray.find(elem => {
if ( elem.id == itemStorageForBag.id && elem.colors == itemStorageForBag.colors && elem.sizes == itemStorageForBag.sizes) {
elem.quantity += 1
return elem
}
})){
}else itemsArray.push(itemStorageForBag)
localStorage.setItem('items', JSON.stringify(itemsArray))
addPriceToHTML(price)
})
}
let changeMainImageClickEvent = () => {
let thumbnailContainer = document.body.querySelector('.thumbnail')
let mainImage = document.body.querySelector('.main-img img')
let imgs = Array.from(document.body.querySelectorAll('.thumbnail > div'))
thumbnailContainer.addEventListener('click', (event) => {
let buffer = mainImage.getAttribute('src')
mainImage.setAttribute('src', event.target.getAttribute('src'))
event.target.setAttribute('src', buffer)
imgs.forEach(el => el.classList.remove('active'))
event.target.parentElement.classList.add('active')
})
}
localStorage.removeItem('id')
menuFunction()
cleanLocalStorage()
createTemplateFrom(itemToDisplay)
changeMainImageClickEvent()
addItemToLocalStorage()
<file_sep>'use strict';
var menuFunction = function menuFunction() {
var searchButton = document.body.querySelector('.header-search-btn');
var searchInput = document.body.querySelector('.header-search > input');
var openMenuBtn = document.getElementById('menuBtn');
var menuContainer = document.body.querySelector('.header-nav-container');
searchButton.addEventListener('click', function () {
searchInput.classList.toggle('search-field-visible');
});
openMenuBtn.addEventListener('click', function () {
openMenuBtn.classList.toggle('menu-opened-btn');
openMenuBtn.classList.toggle('menu-closed-btn');
menuContainer.classList.toggle('mobile-menu-not-active');
menuContainer.classList.toggle('mobile-menu-active');
});
};
var dataDivisionDependOnScreens = function dataDivisionDependOnScreens(array) {
var screenWidth = screen.width;
var dividedData = [];
if (screenWidth > 1024) {
dividedData = _.chunk(_.filter(array, 'price'), 8);
} else if (screenWidth > 768) {
dividedData = _.chunk(_.filter(array, 'price'), 6);
} else dividedData = _.chunk(_.filter(array, 'price'), 4);
return dividedData;
};
var index = 0;
var createItemHTML = function createItemHTML(object) {
var divContainer = document.createElement("div");
var figure = document.createElement("figure");
var imgContainer = document.createElement("div");
var link = document.createElement("a");
var img = document.createElement("img");
var text = document.createElement("p");
var figcaption = document.createElement("figcaption");
var breakLine = document.createElement("br");
var spanPrice = document.createElement("span");
var newPrice = void 0;
divContainer.className = 'item mobile';
divContainer.dataset.id = object.id;
imgContainer.className = 'img-container';
link.setAttribute('href', 'item.html');
img.className = 'item-photo';
img.setAttribute('src', object.thumbnail);
text.className = 'view-item';
text.innerText = 'View item';
figcaption.innerText = object.title;
spanPrice.innerText = '£ ' + object.price;
divContainer.appendChild(figure);
figure.appendChild(imgContainer);
imgContainer.appendChild(link);
link.appendChild(img);
link.appendChild(text);
figure.appendChild(figcaption);
figcaption.appendChild(breakLine);
figcaption.appendChild(spanPrice);
if (object.hasNew) {
newPrice = document.createElement("span");
newPrice.className = 'new-price';
newPrice.innerText = 'new';
spanPrice.appendChild(newPrice);
}
return divContainer;
};
var appendItem = function appendItem(item, inBlock) {
var block = document.body.querySelector(inBlock);
block.appendChild(item);
};
var createAndAddItemIn = function createAndAddItemIn(block, array) {
index === array.length ? index = NaN : array[index].forEach(function (item) {
var template = createItemHTML(item);
appendItem(template, block);
});
index++;
};
var initDisplayItems = function initDisplayItems() {
createAndAddItemIn('.arrivals-block', dataDivisionDependOnScreens(window.catalog));
};
var addPriceToHTML = function addPriceToHTML() {
var bagMoney = document.body.querySelector('.bag-money');
var itemCount = document.body.querySelector('#bag-item-count');
bagMoney.innerText = localStorage.getItem('money') || 0;
itemCount.innerText = localStorage.getItem('count') || 0;
};
var init = function init() {
menuFunction();
initDisplayItems();
var resizeEnd = void 0;
window.addEventListener('resize', function () {
clearTimeout(resizeEnd);
resizeEnd = setTimeout(initDisplayItems, 100);
document.body.querySelector('.arrivals-block').innerHTML = '';
index = 0;
resizeEnd();
});
document.body.querySelector('.show-more-arrivals').addEventListener('click', initDisplayItems);
addPriceToHTML();
};
init();<file_sep>window.catalog = [{
id: '014c271a-2811-47fc-b63f-ba279a4ec830',
dateAdded: '2017-05-15T16:58:40.000Z',
title: 'Monki Festival Knitted',
description: 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to usingContent here, content here',
placeholder: null,
discountedPrice: 24.75,
price: 6.75,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: ['green', 'white'],
sizes: ['UK-65', 'UK-68'],
thumbnail: 'img/items/catalog-item-1.jpg', // replace with path to image extracted from catalog layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '07cf6ce2-6eee-4e78-a441-f257fdea7ed6',
dateAdded: '2017-06-12T15:35:13.000Z',
title: 'Boyfriend T-Shirt with Bohemian print',
description: '',
placeholder: null,
discountedPrice: 90,
price: 120,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-65', 'UK-68'],
thumbnail: 'img/items/catalog-item-2.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '0fdfa061-838d-42ab-ae06-99c66115f633',
dateAdded: '2017-02-12T11:14:29.000Z',
title: 'Boyfriend T-Shirt with Paris Print',
description: '',
placeholder: null,
discountedPrice: 85.75,
price: 85.75,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-60', 'UK-66', 'UK-68', 'UK-70'],
thumbnail: 'img/items/catalog-item-3.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '4a3d3c3e-9dc5-4d99-b33d-42b22e20dc0b',
dateAdded: '2017-08-02T15:00:40.000Z',
title: 'Straight Leg Jeans',
description: '',
placeholder: null,
discountedPrice: 43,
price: 55,
hasNew: false,
category: 'women',
fashion: 'Nail the 90s',
colors: [],
sizes: ['UK-60', 'UK-66', 'UK-68', 'UK-70'],
thumbnail: 'img/items/catalog-item-4.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '5677f851-1c4a-4e9b-80e9-16d1e6265257',
dateAdded: '2017-07-07T10:00:39.000Z',
title: "Levi's Jeans",
description: '',
placeholder: 'More colours',
discountedPrice: 63,
price: null,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-60', 'UK-66', 'UK-68', 'UK-70'],
thumbnail: 'img/items/catalog-item-5.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '739d3ae0-6dca-4453-a7a4-a94b841a296d',
dateAdded: '2017-07-12T09:02:55.000Z',
title: 'With Patchwork Crochet',
description: '',
placeholder: null,
discountedPrice: 55.6,
price: 80.6,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-60', 'UK-66', 'UK-68', 'UK-70'],
thumbnail: 'img/items/catalog-item-6.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '80d32566-d81c-4ba0-9edf-0eceda3b4360',
dateAdded: '2017-01-01T13:26:14.000Z',
title: 'Dark classic fit suit',
description: 'Featuring fine Italian wool, this elegant suit has pick-stitch edging, cascade buttons at the cuffs',
placeholder: null,
discountedPrice: 180.6,
price: 180.6,
hasNew: false,
category: 'men',
fashion: 'Classical style',
colors: ['Black', 'Blue'],
sizes: ['UK-52', 'UK-54', 'UK-56'],
thumbnail: 'img/items/catalog-item-7.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '8b300772-eee3-4ff1-b091-e89f17e0e469',
dateAdded: '2017-08-10T14:59:00.000Z',
title: '<NAME>',
description: '',
placeholder: null,
discountedPrice: 76.25,
price: 76.25,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-52'],
thumbnail: 'img/items/catalog-item-8.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '8c061815-6a7d-4465-bb78-1bdc6c5adebf',
dateAdded: '2017-08-28T09:15:36.000Z',
title: 'Only Skinny Jeans',
description: '',
placeholder: null,
discountedPrice: 65.5,
price: 65.5,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-60', 'UK-66', 'UK-68', 'UK-70'],
thumbnail: 'img/items/catalog-item-9.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: '9ded7821-e510-4a16-ba9f-57c1e3442ad8',
dateAdded: '2017-07-19T15:11:04.000Z',
title: 'Turtle Neck Jumper in Rib',
description: '',
placeholder: null,
discountedPrice: 130.25,
price: 130.25,
hasNew: true,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-60', 'UK-66', 'UK-68', 'UK-70'],
thumbnail: 'img/items/catalog-item-10.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: 'bec71daa-d133-473d-bbb0-1ee0a427a17d',
dateAdded: '2017-03-09T17:51:45.000Z',
title: 'Only Busted Knee Jean',
description: '',
placeholder: null,
discountedPrice: 140.5,
price: 140.5,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-60', 'UK-66', 'UK-68', 'UK-70'],
thumbnail: 'img/items/catalog-item-11.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}, {
id: 'ccc8a5d5-7cdf-4706-95f2-abc64761400d',
dateAdded: '2017-06-09T17:32:17.000Z',
title: 'Colour Block',
description: '',
placeholder: null,
discountedPrice: 550.5,
price: 550.5,
hasNew: false,
category: 'women',
fashion: 'Casual style',
colors: [],
sizes: ['UK-60', 'UK-66', 'UK-68', 'UK-70'],
thumbnail: 'img/items/catalog-item-12.jpg', // replace with image extracted from item layout
preview: ['img/item/item_main.jpg', 'img/item/item_thumb_1.jpg', 'img/item/item_thumb_2.jpg', 'img/item/item_thumb_3.jpg'] // replace with paths to images extracted from item layout
}];<file_sep>let menuFunction = ()=>{
let searchButton = document.body.querySelector('.header-search-btn')
let searchInput = document.body.querySelector('.header-search > input')
let openMenuBtn = document.getElementById('menuBtn')
let menuContainer = document.body.querySelector('.header-nav-container')
searchButton.addEventListener('click', () => {
searchInput.classList.toggle('search-field-visible')
})
openMenuBtn.addEventListener('click', () => {
openMenuBtn.classList.toggle('menu-opened-btn')
openMenuBtn.classList.toggle('menu-closed-btn')
menuContainer.classList.toggle('mobile-menu-not-active')
menuContainer.classList.toggle('mobile-menu-active')
})
}
menuFunction()
let itemsToDisplay = {}
itemsToDisplay.items = JSON.parse(localStorage.getItem('items')).map((item, i) => {
item.id = item.id + '_' + i
return item
})
let template = (array) => {
let template = _.template(
'<% _.forEach(items, function(obj) { %>' +
'<div class="item">' +
' <figure>' +
' <div class="img-container">' +
' <a href="item.html"><img class="item-photo" src=<%= obj.thumbnail %> > </a>' +
' <p class="view-item">View item</p>' +
' </div>' +
' <figcaption data-id = <%= obj.id%>><%= obj.title %>' +
' <p class="item-price">£ <%- obj.discountedPrice < obj.price ? obj.discountedPrice : obj.price %> </p>' +
' <p class="item-color">Color: <span> <%= obj.colors %> </span></p>' +
' <p class="item-size">Size: <span><%= obj.sizes %></span></p>' +
' <p class="quantity">Quantity: <span class="qntMinus">-</span> <span> <%= obj.quantity %> </span> <span class="qntPlus">+</span></p>' +
' <button type="button" class="remove-item-btn"> Remove item</button>' +
' </figcaption>' +
' </figure>' +
'</div>' +
'<% }) %>')
return template(array)
}
let displayItems = (array) => {
let itemsHTML = template(array)
let itemsContainer = document.body.querySelector('.bag-item-container')
itemsContainer.innerHTML = itemsHTML
let bindButtonsClick = () => {
let deleteItem = Array.from(document.body.querySelectorAll('.remove-item-btn'))
let increaseQuantity = Array.from(document.body.querySelectorAll('.qntPlus'))
let decreaseQuantity = Array.from(document.body.querySelectorAll('.qntMinus'))
let clearBag = document.body.querySelector('#bag-btn-clear')
let buyBtn = document.body.querySelector('#buy-bag-btn')
increaseQuantity.forEach(elem => {
elem.addEventListener('click', (event) => {
let elementId = event.target.parentElement.parentNode.dataset.id
let objItem = itemsToDisplay.items.find(item => {
return item.id == elementId
})
objItem.quantity += 1
displayItems(itemsToDisplay)
total(itemsToDisplay)
})
})
decreaseQuantity.forEach(elem => {
elem.addEventListener('click', (event) => {
let elementId = event.target.parentElement.parentNode.dataset.id
let objItem = itemsToDisplay.items.find(item => {
return item.id == elementId
})
if (objItem.quantity > 1) {
objItem.quantity -= 1
displayItems(itemsToDisplay)
total()
total(itemsToDisplay)
}else {
objItem.quantity = 1
displayItems(itemsToDisplay)
total()
total(itemsToDisplay)
}
})
})
deleteItem.forEach(elem => {
elem.addEventListener('click', (event) => {
let elementId = event.target.parentNode.dataset.id
itemsToDisplay.items = _.filter(itemsToDisplay.items, (obj)=>{ return obj.id != elementId})
displayItems(itemsToDisplay)
total()
total(itemsToDisplay)
})
})
clearBag.addEventListener('click', () => {
itemsToDisplay.items = []
document.querySelector('#emptyBagMsg').classList.remove('d-none')
document.querySelector('.stock').classList.add('d-none')
displayItems(itemsToDisplay)
total()
total(itemsToDisplay)
})
buyBtn.addEventListener('click', () => {
itemsToDisplay.items = []
document.querySelector('#orderCompleteMsg').classList.remove('d-none')
document.querySelector('.stock').classList.add('d-none')
displayItems(itemsToDisplay)
total()
total(itemsToDisplay)
})
}
bindButtonsClick()
}
let total = (arr) => {
let price = 0
let quantity = 0
if (arr) {
arr.items.forEach(item => {
price += (item.discountedPrice < item.price ? item.discountedPrice : item.price) * +item.quantity
quantity += item.quantity
})
addPriceToHTML( price, quantity )
}else addPriceToHTML()
}
let addPriceToHTML = (price = 0, count = 0) => {
let bagMoney = document.body.querySelector('.bag-money')
let totalPrice = document.body.querySelector('.total-price')
let itemCount = document.body.querySelector('#bag-item-count')
bagMoney.innerText = price
itemCount.innerText = count
totalPrice.innerText = "£ " + +bagMoney.innerText || 0
}
displayItems(itemsToDisplay)
total(itemsToDisplay)
|
337e170e3e2d60c1dbbf16fe0873aa83b8d16ff2
|
[
"JavaScript"
] | 7 |
JavaScript
|
actimel33/actimel33.github.io
|
2f18078f7cd75503752bfea7659e80d0805e5b66
|
a0f239f40490f382560083ccca986b748f8986d0
|
refs/heads/master
|
<repo_name>paulsamchuk/odesk<file_sep>/spec/odesk_spec.rb
# encoding: utf-8
require_relative 'spec_helper'
describe Odesk do
it 'should have a client' do
Odesk.client.must_be_instance_of Odesk::Client
end
it 'should proxy method calls to client' do
client = Odesk::Client.new
client.public_methods.each do |m|
assert Odesk.respond_to?(m)
end
end
end
<file_sep>/README.md
# Odesk
[](https://travis-ci.org/bigblue/odesk) [](https://codeclimate.com/github/bigblue/odesk) [](https://coveralls.io/r/bigblue/odesk?branch=master)
Ruby gem to interact with the [ODesk REST api](http://developers.odesk.com/w/page/12363985/API%20Documentation).
## Installation
Add this line to your application's Gemfile:
gem 'odesk'
And then execute:
$ bundle
Or install it yourself as:
$ gem install odesk
## Usage
### Setup
The ODesk API uses OAuth 1.0 for authenticating requests, so you will first need to [register your application with ODesk](https://www.odesk.com/services/api/keys) to obtain a consumer key and secret. Then complete the following process to obtain an access token:
Odesk.configure do |config|
config.consumer_key = "YOUR_ODESK_KEY"
config.consumer_secret = "YOUR_ODESK_SECRET"
config.callback_url = "FULLY_QUALIFIED_URL" #e.g. http://localhost:3001/oauth/callback
end
Send your user to the `Odesk.authorize_url` and once they have agreed to allow you application access to their ODesk data they will be redirected to your callback URL with with `oauth_token` and `oauth_verifier` parameters added to the query string.
Then supply the oauth_verifier to obtain an access token:
Odesk.get_access_token("oauth_verifier")
# => {:oauth_token => "ACCESS_TOKEN", :oauth_token_secret => "SECRET"}
You will then be able to make authenticated requests to the API.
The access tokens will never expire so to skip this process in future sessions you can save these two keys and then supply then straight to configure:
Odesk.configure do |config|
config.consumer_key = YOUR_ODESK_KEY
config.consumer_secret = YOUR_ODESK_SECRET
config.oauth_token = "<PASSWORD>"
config.oauth_token_secret = "SECRET"
end
#=> Odesk ready to make requests...
## Supported Ruby Versions
This library aims to support the following Ruby implementations:
* Ruby 1.9.2
* Ruby 1.9.3
* Ruby 2.0.0
## 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
## Copyright
Copyright (c) 2013 <NAME>. See [LICENSE][] for details.
[license]: LICENSE
<file_sep>/lib/odesk/configuration.rb
# encoding: utf-8
module Odesk
class InvalidConfigurationError < StandardError
end
# Odesk gem configuration (mostly oauth tokens)
module Configuration
VALID_CONFIGURATION_KEYS = [
:consumer_key,
:consumer_secret,
:token,
:token_secret,
:verifier,
:callback_url,
:user_agent,
:endpoint,
:faraday_adapter
]
attr_accessor *VALID_CONFIGURATION_KEYS
def configure(config = nil)
load_hash_config(config) if config
yield self if block_given?
self
rescue => error
raise InvalidConfigurationError, error.message
end
alias_method :initialize, :configure
def endpoint
@endpoint || 'https://www.odesk.com'
end
def user_agent
@user_agent || "Odesk gem v#{Odesk::VERSION}"
end
def faraday_adapter
@faraday_adapter || :net_http
end
def reset_configuration
VALID_CONFIGURATION_KEYS.each { |k| send("#{k}=", nil) }
end
private
def load_hash_config(config)
config.each { |attr, value| send("#{attr}=", value) }
end
end
end
<file_sep>/lib/odesk/oauth.rb
# encoding: utf-8
module Odesk
# Methods to setup oauth request authentication
module Oauth
def authorize_url
extract_tokens(connection.post '/api/auth/v1/oauth/token/request')
querystring = URI.encode_www_form(authorize_request_params)
"#{endpoint}/services/api/auth?#{querystring}"
end
def get_access_token(verifier)
validate_access_request!
self.verifier = verifier
extract_tokens(connection.post '/api/auth/v1/oauth/token/access')
end
private
def authorize_request_params
{ oauth_callback: callback_url,
oauth_token: token }
end
def validate_access_request!
unless token && token_secret
fail OauthError, 'Oauth token and secret requrired'
end
end
def extract_tokens(response)
tokens = Hash[URI.decode_www_form(response.body)]
save_tokens(tokens)
tokens.reduce({}) { |memo, (k, v)| memo[k.to_sym] = v; memo }
end
def save_tokens(tokens)
self.token = tokens['oauth_token']
self.token_secret = tokens['oauth_token_secret']
end
end
end
<file_sep>/spec/odesk/connection_spec.rb
# encoding: utf-8
require_relative '../spec_helper'
describe Odesk::Connection do
before do
@client = Odesk::Client.new do |config|
config.consumer_key = '<KEY>'
config.consumer_secret = 'prouw9iasiuwleyl'
config.callback_url = 'http://localhost:3000/oauth/callback'
end
@connection = @client.connection
end
it 'should return a new Faraday connection' do
@connection.must_be_instance_of Faraday::Connection
end
it 'should have the host for all requests set' do
@connection.url_prefix.must_equal URI.parse(@client.endpoint)
end
it 'should have the user agent set' do
@connection.headers[:user_agent].must_equal @client.user_agent
end
it 'should use the faraday oauth middleware' do
@connection.builder[0].klass.must_equal FaradayMiddleware::OAuth
end
end
<file_sep>/spec/odesk/oauth_spec.rb
# encoding: utf-8
require_relative '../spec_helper'
def request_response
'oauth_callback_confirmed=true' +
'&token=<PASSWORD>_token' +
'&token_secret=test_token_secret'
end
def access_response
'token=access_token' +
'&token_secret=access_token_secret'
end
def build_stubs
Faraday::Adapter::Test::Stubs.new do |stub|
stub.post('/api/auth/v1/oauth/token/request') do
[200, {}, request_response]
end
stub.post('/api/auth/v1/oauth/token/access') do
[200, {}, access_response]
end
end
end
def set_odesk_configuration
Odesk::Client.new do |config|
config.consumer_key = 'test_consumer_key'
config.consumer_secret = 'test_consumer_secret'
config.callback_url = 'http://localhost:3000/oauth/callback'
config.faraday_adapter = :test, build_stubs
end
end
describe Odesk::Oauth do
before do
@client = set_odesk_configuration
end
it 'should have the oauth consumer tokens set' do
@oauth_options = @client.connection.app.instance_variable_get '@options'
@oauth_options[:consumer_key].must_equal 'test_consumer_key'
@oauth_options[:consumer_secret].must_equal 'test_consumer_secret'
end
it 'should raise an error if the consumer key is not set' do
proc do
@client.consumer_key = nil
@client.connection
end.must_raise Odesk::InvalidConfigurationError
end
it 'should raise an error if the consumer secret is not set' do
proc do
@client.consumer_secret = nil
@client.connection
end.must_raise Odesk::InvalidConfigurationError
end
describe 'when calling authorise_url' do
before do
@authorize_url = @client.authorize_url
end
it 'should set the token' do
@client.token.must_equal 'test_token'
end
it 'should set the token_secret' do
@client.token_secret.must_equal 'test_token_secret'
end
it 'should encode the correct params in the auth url' do
url = 'https://www.odesk.com/services/api/auth?' +
'oauth_callback=http%3A%2F%2Flocalhost%3A3000%2Foauth%2Fcallback' +
'&token=<PASSWORD>token'
@authorize_url.must_equal url
end
it 'should also reset the oauth options for the oauth middleware' do
@oauth_options = @client.connection.app.instance_variable_get '@options'
@oauth_options[:token].must_equal 'test_token'
@oauth_options[:token_secret].must_equal 'test_token_secret'
end
end
describe 'when getting an access token' do
it 'should raise an error if the oauth tokens are not set' do
proc do
@client.token = nil
@client.get_access_token('verify_token')
end.must_raise Odesk::OauthError
end
describe 'with correct config' do
before do
@client.token = '<PASSWORD>'
@client.token_secret = 'test_secret'
@access_tokens = @client.get_access_token('verifier')
end
it 'should set the verifier token' do
oauth_options = @client.connection.app.instance_variable_get '@options'
oauth_options[:verifier].must_equal 'verifier'
end
it 'should reset the oauth tokens with the new access token details' do
@client.token.must_equal 'access_token'
@client.token_secret.must_equal 'access_token_secret'
end
it 'should return a hash of the access tokens' do
@access_tokens[:token].must_equal @client.token
@access_tokens[:token_secret].must_equal @client.token_secret
end
end
end
end
<file_sep>/spec/odesk/configuration_spec.rb
# encoding: utf-8
require_relative '../spec_helper'
describe Odesk::Configuration do
before do
@client = Odesk::Client.new do |config|
config.consumer_key = 'test'
end
end
it 'should accept configuration block' do
@client.consumer_key.must_equal 'test'
end
it 'should also accept configuration via a hash' do
config = { consumer_key: 'consumer_key' }
@hsh_client = Odesk::Client.new(config)
@hsh_client.consumer_key.must_equal 'consumer_key'
end
it 'should not accept invalid configuration keys' do
proc do
Odesk::Client.new do |config|
config.bad_option = 'test'
end
end.must_raise Odesk::InvalidConfigurationError
end
it 'should have a default set for the endpoint' do
@client.endpoint.must_equal 'https://www.odesk.com'
end
it 'should have a default set for the user agent' do
@client.user_agent.must_equal "Odesk gem v#{Odesk::VERSION}"
end
it 'should allow defaults be overridden' do
@custom = Odesk::Client.new do |config|
config.user_agent = 'Custom User Agent'
end
@custom.user_agent.must_equal 'Custom User Agent'
end
end
<file_sep>/lib/odesk.rb
# encoding: utf-8
require 'odesk/configuration'
require 'odesk/connection'
require 'odesk/oauth'
require 'odesk/client'
require 'odesk/resources/job'
require 'odesk/version'
# global Odesk object
module Odesk
class << self
def client
@client = Odesk::Client.new unless defined?(@client)
@client
end
def respond_to_missing?(method_name, include_private = false)
client.respond_to?(method_name, include_private)
end
private
def method_missing(method_name, *args, &block)
return super unless client.respond_to?(method_name)
client.send(method_name, *args, &block)
end
end
end
<file_sep>/spec/spec_helper.rb
# encoding: utf-8
require 'coveralls'
Coveralls.wear!
require 'minitest/autorun'
require 'odesk'
<file_sep>/spec/odesk/resources/job_spec.rb
# encoding: utf-8
require_relative '../../spec_helper'
require 'json'
describe Odesk::Job do
before do
@json = File.open('spec/fixtures/job.json', 'r') { |f| JSON.load(f) }
@job = Odesk::Job.new(@json)
end
it 'should be initialized with a hash of attributes' do
@job.must_be_instance_of Odesk::Job
end
it 'should have a hash of string attributes' do
Odesk::Job::STRING_ATTRS.keys.must_equal [
:assignment_info, :company_id, :country, :description_digest,
:description, :engagement, :id, :job_category_seo, :title
]
end
Odesk::Job::STRING_ATTRS.each do |attr, key|
it "should have #{attr} set" do
@job.send(attr).must_equal @json[key]
end
end
end
<file_sep>/lib/odesk/client.rb
# encoding: utf-8
module Odesk
# Client class for making calls to the api
class Client
include Configuration
include Connection
include Oauth
end
end
<file_sep>/lib/odesk/connection.rb
# encoding: utf-8
require 'faraday'
require 'faraday_middleware'
module Odesk
class OauthError < StandardError
end
# Handles the Faraday connection to oDesk
module Connection
def connection
validate_configuration!
Faraday.new(endpoint, faraday_options) do |conn|
conn.request :oauth, oauth_options
conn.request :url_encoded
conn.adapter *faraday_adapter
end
end
private
def validate_configuration!
validate_consumer_key
validate_consumer_secret
end
def validate_consumer_key
unless consumer_key
fail InvalidConfigurationError, 'The consumer key is not set'
end
end
def validate_consumer_secret
unless consumer_secret
fail InvalidConfigurationError, 'The consumer secret is not set'
end
end
def faraday_options
{ headers: {
user_agent: user_agent
} }
end
def oauth_options
[:consumer_key, :consumer_secret, :token, :token_secret,
:verifier].reduce({}) { |opts, k| opts[k] = send(k); opts }
end
end
end
<file_sep>/lib/odesk/resources/job.rb
# encoding: utf-8
module Odesk
# Class to represent jobs return in api calls
class Job
STRING_ATTRS = {
assignment_info: 'assignment_info', #
company_id: 'company_ref', # 1094536
country: 'op_country', # United States
description_digest: 'op_desc_digest', # Market for me on Craigslist
description: 'op_description', # Market for me on Craigslist
engagement: 'op_engagement', # Full-time - 30+ hrs/week
id: 'op_recno', # 203119302
job_category_seo: 'op_job_category_seo', # Sales / Lead Generation Jobs
title: 'op_title' # Craigslist Marketer
}
attr_reader *STRING_ATTRS.keys
# amount: "amount", #10
# assignments: "assignments", #
# candidiates: "candidates", #
# active_candidates: "candidates_total_active", #0
# ciphertext: "ciphertext", #~012247edf127c1c0c5
# company_id: "company_ref", #1094536
# date_posted: "date_posted", #October 10, 2013
# engagement_related: "engagement_related", #
# engagement_weeks: "engagement_weeks", #
# hours_per_week: "hours_per_week", #40
# interviewees: "interviewees_total_active", #0
# job_category_level_one: "job_category_level_one", #Sales & Marketing
# job_category_level_two: "job_category_level_two", #Sales & Lead Generation
# job_type: "job_type", #Fixed
# offers_total: "offers_total", #0
# offers_total_open: "offers_total_open", #0
# active: "op_active", #0
# adjusted_score: "op_adjusted_score", #0
# attachment: "op_attached_doc", #
# avg_active_bid: "op_avg_bid_active", #0
# avg_active_interviewees_bid: "op_avg_bid_active_interviewees", #0
# avg_all_bid: "op_avg_bid_all", #0
# avg_interviewees_bid: "op_avg_bid_interviewees", #0
# avg_hourly_rate: "op_avg_hourly_rate_active", #0
# avg_active_interviewees_hourly_rate: "op_avg_hourly_rate_active_interviewees", #0
# avg_all_hourly_rate: "op_avg_hourly_rate_all", #0
# : "op_avg_hourly_rate_interviewees", #0
# : "op_candidate_type_pref", #0
# : "op_changed_date", #1381363200000
# : "op_city", #
# : "op_cny_description", #
# : "op_cny_show_in_profile", #
# : "op_cny_summary", #
# : "op_cny_suspended", #
# : "op_cny_upm_verified", #0
# : "op_cny_url", #
# : "op_comm_status", #Closed: Inappropriate Job Posting
# : "op_contract_date", #
# : "op_contractor_tier", #
# : "op_ctime", #1381423009000
# : "op_date_created", #October 10, 2013
# : "op_end_date", #October 10, 2013
# : "op_eng_type", #1
# : "op_est_duration", #
# : "op_high_bid_active", #0
# : "op_high_bid_active_interviewees", #0
# : "op_high_bid_all", #0
# : "op_high_bid_interviewees", #0
# : "op_high_hourly_rate_active", #0
# : "op_high_hourly_rate_active_interviewees", #0
# : "op_high_hourly_rate_all", #0
# : "op_high_hourly_rate_interviewees", #0
# : "op_hours_last30days", #0
# : "op_is_console_viewable", #1
# : "op_is_hidden", #
# : "op_is_searchable", #1
# : "op_is_validnonprivate", #1
# : "op_is_viewable", #0
# : "op_job_expiration", #
# : "op_last_buyer_activity", #January 1, 1970
# : "op_logo", #
# : "op_low_bid_active", #0
# : "op_low_bid_active_interviewees", #0
# : "op_low_bid_all", #0
# : "op_low_hourly_rate_active", #0
# : "op_low_hourly_rate_active_interviewees", #0
# : "op_low_hourly_rate_all", #0
# : "op_low_hourly_rate_interviewees", #0
# : "op_lowhigh_bid_interviewees", #0
# : "op_num_of_pending_invites", #0
# : "op_other_jobs", #
# : "op_pref_english_skill", #0
# : "op_pref_fb_score", #0
# : "op_pref_group_recno", #
# : "op_pref_has_portfolio", #0
# : "op_pref_hourly_rate_max", #
# : "op_pref_hourly_rate_min", #
# : "op_pref_hours_per_week", #
# : "op_pref_location", #
# : "op_pref_odesk_hours", #0
# : "op_pref_test", #0
# : "op_pref_test_name", #
# : "op_private_rating_active", #
# : "op_reason", #Inappropriate Job Posting
# : "op_reason_id", #116
# : "op_required_skills", #
# : "op_skill", #
# : "op_start_date", #October 10, 2013
# : "op_state", #
# : "op_time_created", #16:36:49
# : "op_time_posted", #16:36:49
# : "op_timezone", #UTC-05:00 Eastern Time (US & Canada)
# : "op_tot_asgs", #0
# : "op_tot_cand", #0
# : "op_tot_cand_client", #0
# : "op_tot_cand_prof", #0
# : "op_tot_charge", #0
# : "op_tot_feedback", #0
# : "op_tot_fp_asgs", #0
# : "op_tot_hours", #0
# : "op_tot_hr_asgs", #0
# : "op_tot_jobs_filled", #0
# : "op_tot_jobs_open", #0
# : "op_tot_jobs_posted", #0
# : "op_tot_new_cond", #0
# : "op_tot_rej", #0
# : "op_ui_profile_access", #Public
# : "search_status", #Cancelled
# : "timezone", #United States (UTC-05)
# : "tot_act_asgs", #0
# : "ui_job_profile_access", #public
# : "ui_opening_status", #Closed
# : "version" #1
# }
# end
def initialize(json)
STRING_ATTRS.each do |attr, key|
instance_variable_set("@#{attr}", json[key])
end
end
end
end
|
7dd40e3bde3791d1f86b97eae7ec52b2f31dd4dd
|
[
"Markdown",
"Ruby"
] | 13 |
Ruby
|
paulsamchuk/odesk
|
113a96f75d92e8231ba1d8f952ea3f3ec12cb353
|
7910b8275f9ab0c9b7b1172fda7dd15760357621
|
refs/heads/master
|
<repo_name>ntokozo-studio/AngularApp-ASP.NET-MVC<file_sep>/README.md
# AngularJS-WebAPI-ASP.NET-MVC-Applications
All my practice projects using AngularJS and Web API as front end on a .Net Framework
The repository currently contains three projects: <br />
1. MyAngularAppMVC <br />
2. AngularMVCAppCRUD <br />
3. MessageBoard-using-AngularJS-and-WebAPI <br />
<file_sep>/AngularMVCAppCRUD/source/AngularMVCAppCRUD/DB/FriendsContext.cs
using System.Data.Entity;
using AngularJS_MVC5_WebAPI.Models;
namespace AngularMVCAppCRUD.DB
{
public class FriendsContext :DbContext
{
public FriendsContext() : base("name=DefaultConnection")
{
base.Configuration.ProxyCreationEnabled = false;
}
public DbSet<Friend> Friends { get; set; }
}
}<file_sep>/MyAngularAppMVC/source/MyAngularAppMVC/Scripts/MyAngularAppMVC.js
var MyAngularAppMVC = angular.module('MyAngularAppMVC', ['ui.router', 'ui.bootstrap']);
MyAngularAppMVC.controller('LandingPageController', LandingPageController);
MyAngularAppMVC.controller('LoginController', LoginController);
MyAngularAppMVC.controller('RegisterController', RegisterController);
MyAngularAppMVC.factory('AuthHttpResponseInterceptor', AuthHttpResponseInterceptor);
MyAngularAppMVC.factory('LoginFactory', LoginFactory);
MyAngularAppMVC.factory('RegistrationFactory', RegistrationFactory);
var configFunction = function ($stateProvider, $httpProvider, $locationProvider) {
$locationProvider.hashPrefix('!').html5Mode(true);
$stateProvider.state('stateOne',
{
url: '/stateOne?donuts',
views:
{
"containerOne": { templateUrl: '/routesDemo/one' },
"containerTwo": { templateUrl: function (params) { return '/routesDemo/two?donuts=' + params.donuts; }},
"nestedView@stateOne": { templateUrl: '/routesDemo/four' }
}
})
.state('stateTwo',
{
url: '/stateTwo',
views:
{
"containerOne": { templateUrl: '/routesDemo/one' },
"containerTwo": { templateUrl: '/routesDemo/three' }
}
})
.state('stateThree',
{
url: '/stateThree?donuts',
views:
{
"containerOne": { templateUrl: function (params) { return '/routesDemo/two?donuts=' + params.donuts; } },
"containerTwo": { templateUrl: '/routesDemo/three' }
}
})
.state('login',
{
url: '/loginRegister?returnUrl',
views:
{
"containerOne": { templateUrl: '/Account/Login', controller: LoginController }
}
})
.state('register',
{
url: '/loginRegister?returnUrl',
views:
{
"containerTwo": { templateUrl: '/Account/Register', controller: RegisterController}
}
});
$httpProvider.interceptors.push('AuthHttpResponseInterceptor');
}
configFunction.$inject = ['$stateProvider', '$httpProvider', '$locationProvider'];
MyAngularAppMVC.config(configFunction);<file_sep>/AngularMVCAppCRUD/source/AngularMVCAppCRUD/Scripts/Controllers/friendController.js
function friendController($scope, $http)
{
$scope.loading = true;
$scope.addMode = false;
//Used to display the data
$http.get('/api/Friend/').success(function (data){
$scope.friends = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
$scope.toggleEdit = function ()
{
this.friend.editMode = !this.friend.editMode;
};
$scope.toggleAdd = function ()
{
$scope.addMode = !$scope.addMode;
};
//Used to save a record after edit
$scope.save = function ()
{
alert("Edit");
$scope.loading = true;
var maFriendo = this.friend;
alert(window.emp);
$http.put('/api/Friend/', maFriendo).success(function (data)
{
alert("Saved Successfully!!");
window.emp.editMode = false;
$scope.loading = false;
})
.error(function (data)
{
$scope.error = "An Error has occured while Saving Friend! " + data;
$scope.loading = false;
});
};
//Used to add a new record
$scope.add = function ()
{
$scope.loading = true;
$http.post('/api/Friend/', this.newfriend).success(function (data)
{
alert("Added Successfully!!");
$scope.addMode = false;
$scope.friends.push(data);
$scope.loading = false;
})
.error(function (data)
{
$scope.error = "An Error has occured while Adding Friend! " + data;
$scope.loading = false;
});
};
//Used to edit a record
$scope.deletefriend = function ()
{
$scope.loading = true;
var friendid = this.friend.FriendId;
$http.delete('/api/Friend/' + friendid).success(function (data)
{
alert("Deleted Successfully!!");
$.each($scope.friends, function (i)
{
if ($scope.friends[i].FriendId === friendid)
{
$scope.friends.splice(i, 1);
return false;
}
});
$scope.loading = false;
})
.error(function (data)
{
$scope.error = "An Error has occured while Saving Friend! " + data;
$scope.loading = false;
});
};
}
|
d320a6c47fcfdb0ebc765a009cbf7333387f7905
|
[
"Markdown",
"C#",
"JavaScript"
] | 4 |
Markdown
|
ntokozo-studio/AngularApp-ASP.NET-MVC
|
546c5b3065be9d3da87b5b82d39268ec17ed4a3f
|
87b39b91fa0f6c3fddf0c23fc61e7d2e8b443d5a
|
refs/heads/master
|
<repo_name>third-meow/simple-cellular-automaton<file_sep>/README.md
## simple cellular automaton
just a simple test cellular automaton. doesnt do much
<file_sep>/src/main.rs
use std::{thread, time};
const ENV_HEIGHT: usize = 30;
const ENV_WIDTH: usize = 30;
fn print_2d_vec(v: &Vec<Vec<u32>>) {
for i in v.iter() {
for j in i.iter() {
if *j > 0 {
print!("{}[41m{}{}[40m ",27 as char, j, 27 as char);
} else {
print!("{} ", j);
}
}
println!("");
}
}
fn clear_tui() {
print!("{}[2J", 27 as char);
}
fn get_surrounding_free_cells(x: usize, y: usize) -> Vec<(usize, usize)> {
let mut v: Vec<(usize, usize)> = Vec::new();
if y >= 1 {
v.push((x, y-1));
if x >= 1 {
v.push((x-1, y-1));
}
if x < (ENV_HEIGHT - 1) {
v.push((x+1, y-1));
}
}
if y < (ENV_HEIGHT - 1) {
v.push((x, y+1));
if x >= 1 {
v.push((x-1, y+1));
}
if x < (ENV_HEIGHT - 1) {
v.push((x+1, y+1));
}
}
if x < (ENV_HEIGHT - 1) {
v.push((x+1, y));
}
if x >= 1 {
v.push((x-1, y));
}
v
}
fn kill_surrounding_cells(env: &mut Vec<Vec<u32>>, x: usize, y: usize){
if y >= 1 {
env[x][y-1] = 0;
if x >= 1 {
env[x-1][y-1] = 0;
}
if x < (ENV_HEIGHT - 1) {
env[x+1][y-1] = 0;
}
}
if y < (ENV_HEIGHT - 1) {
env[x][y+1] = 0;
if x >= 1 {
env[x-1][y+1] = 0;
}
if x < (ENV_HEIGHT - 1) {
env[x+1][y+1] = 0;
}
}
if x < (ENV_HEIGHT - 1) {
env[x+1][y] = 0;
}
if x >= 1 {
env[x-1][y] = 0;
}
}
fn take_step(env: &mut Vec<Vec<u32>>){
for i in 0..env.len() {
for j in 0..env[i].len() {
if env[i][j] > 1 {
env[i][j] -= 1;
} else if env[i][j] == 1 as u32 {
let free_cells = get_surrounding_free_cells(i, j);
if free_cells.len() < 2 {
kill_surrounding_cells(env, i, j);
} else {
for (x, y) in free_cells.iter() {
env[*x][*y] = 4;
}
}
env[i][j] = 0;
}
}
}
}
fn main() {
let mut env: Vec<Vec<u32>> = Vec::new();
for i in 0..ENV_HEIGHT {
env.push(Vec::new());
for _ in 0..ENV_WIDTH {
env[i].push(0);
}
}
env[0][0] = 4;
loop {
clear_tui();
print_2d_vec(&env);
thread::sleep(time::Duration::from_millis(100));
take_step(&mut env);
}
}
|
1f34bc3de270deb93075f436cd82f5b44dc86597
|
[
"Markdown",
"Rust"
] | 2 |
Markdown
|
third-meow/simple-cellular-automaton
|
7bfef77c8ccc0bd56b62087291bf8eb5081588d9
|
8c1fac7f2f9308dddbea3c8927fb4f269433d435
|
refs/heads/master
|
<repo_name>vijithvenganoor/queryhelper<file_sep>/Querry Helper/querry helper/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Querry_Helper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public MySqlConnection connection()
{
MySqlConnection conn = new MySqlConnection();
try
{
string cons = "server="+txtServer.Text+";User Id="+txtID.Text+";password="+txtPwd.Text+";Persist Security Info=True;database="+txtScema.Text+"";
String connectionString = cons;
conn.ConnectionString = connectionString;
return conn;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
public DataTable getTableQry(string Querry)
{
DataTable dt = new DataTable();
MySqlConnection con = connection();
try
{
MySqlCommand cmd = new MySqlCommand(Querry, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
return dt;
}
public bool checkConnection()
{
bool check = true;
MySqlConnection con = connection();
try
{
con.Open();
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 4060: // Invalid Database
System.Windows.Forms.MessageBox.Show("Invalid Database");
break;
case 18456: // Login Failed
System.Windows.Forms.MessageBox.Show("Login Failed ");
break;
default:
//....
break;
}
}
return check;
}
private void btnGO_Click(object sender, EventArgs e)
{
try
{
if (txtServer.Text == "" && txtID.Text == "" && txtPwd.Text == "")
MessageBox.Show("Enter a server, ID and password");
else
{
if (txtScema.Text == "")
MessageBox.Show("Enter a schema name");
else
if (txtTable.Text == "")
MessageBox.Show("Enter the Table Name");
else
go();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void go()
{
string qry = @"SELECT TABLE_NAME
, COLUMN_NAME
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, CHARACTER_OCTET_LENGTH
, NUMERIC_PRECISION
, NUMERIC_SCALE AS SCALE
, COLUMN_DEFAULT
, IS_NULLABLE
,TABLE_SCHEMA
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + txtTable.Text.Trim().ToString() + "' ";
if (txtScema.Text.Trim().ToString() != "")
qry += " and TABLE_SCHEMA='" + txtScema.Text + "'";
DataTable dt = getTableQry(qry);
if (dt.Rows.Count > 0)
{
storedPros(dt);
dataModel(dt);
parameter(dt);
}
else
MessageBox.Show("No Data Available");
}
private void parameter(System.Data.DataTable dt)
{
string pm = "";
char ch = '"';
pm += @"string qry = @"+ch.ToString()+"addEditSystemSetting"+ch.ToString()+@";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = qry;
cmd.CommandType = System.Data.CommandType.StoredProcedure;";
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["DATA_TYPE"].ToString() == "int")
pm += "cmd.Parameters.Add(" + ch.ToString() + "@p_" + dt.Rows[i]["COLUMN_NAME"].ToString() + "" + ch.ToString() + ", MySqlDbType.Int32).Value = obj." + dt.Rows[i]["COLUMN_NAME"].ToString() + "; \n";
else if (dt.Rows[i]["DATA_TYPE"].ToString() == "varchar")
pm += "cmd.Parameters.Add(" + ch.ToString() + "@p_" + dt.Rows[i]["COLUMN_NAME"].ToString() + "" + ch.ToString() + ", MySqlDbType.VarChar, " + dt.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString() + ").Value = obj." + dt.Rows[i]["COLUMN_NAME"].ToString() + "; \n";
else if (dt.Rows[i]["DATA_TYPE"].ToString() == "timestamp" || dt.Rows[i]["DATA_TYPE"].ToString() == "datetime")
pm += "cmd.Parameters.Add(" + ch.ToString() + "@p_" + dt.Rows[i]["COLUMN_NAME"].ToString() + "" + ch.ToString() + ", MySqlDbType.DateTime).Value = obj." + dt.Rows[i]["COLUMN_NAME"].ToString() + "; \n";
else if (dt.Rows[i]["DATA_TYPE"].ToString() == "tinyint")
pm += "cmd.Parameters.Add(" + ch.ToString() + "@p_" + dt.Rows[i]["COLUMN_NAME"].ToString() + "" + ch.ToString() + ", MySqlDbType.Int16).Value = obj." + dt.Rows[i]["COLUMN_NAME"].ToString() + "; \n";
else
pm += "//contact Vijith \n";
}
pm += "return excQry(cmd);";
txtParameter.Text = pm;
}
private void dataModel(System.Data.DataTable dt)
{
string dm = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
dm += "private ";
if (dt.Rows[i]["DATA_TYPE"].ToString() == "int")
dm += "int _" + dt.Rows[i]["COLUMN_NAME"].ToString()+";\n";
else if(dt.Rows[i]["DATA_TYPE"].ToString() == "varchar")
dm += "string _" + dt.Rows[i]["COLUMN_NAME"].ToString() + ";\n";
else if (dt.Rows[i]["DATA_TYPE"].ToString() == "timestamp" || dt.Rows[i]["DATA_TYPE"].ToString() == "datetime")
dm += "DateTime _" + dt.Rows[i]["COLUMN_NAME"].ToString() + ";\n";
else if (dt.Rows[i]["DATA_TYPE"].ToString() == "tinyint")
dm += "bool _" + dt.Rows[i]["COLUMN_NAME"].ToString() + ";\n";
else
dm += "// contact Vijith \n";
}
dm += "\n";
for (int i = 0; i < dt.Rows.Count; i++)
{
dm += "\n public ";
if (dt.Rows[i]["DATA_TYPE"].ToString() == "int")
dm += "int " + dt.Rows[i]["COLUMN_NAME"].ToString() + "";
else if (dt.Rows[i]["DATA_TYPE"].ToString() == "varchar")
dm += "string " + dt.Rows[i]["COLUMN_NAME"].ToString() + "";
else if (dt.Rows[i]["DATA_TYPE"].ToString() == "timestamp" || dt.Rows[i]["DATA_TYPE"].ToString() == "datetime")
dm += "DateTime " + dt.Rows[i]["COLUMN_NAME"].ToString() + "";
else if (dt.Rows[i]["DATA_TYPE"].ToString() == "tinyint")
dm += "bool " + dt.Rows[i]["COLUMN_NAME"].ToString() + "";
else
dm += "// contact Vijith \n";
dm += @"
{
get { return _"+dt.Rows[i]["COLUMN_NAME"].ToString()+@"; }
set { _"+dt.Rows[i]["COLUMN_NAME"].ToString()+@" = value; }
} ";
}
txtModel.Text = dm;
}
private void storedPros(DataTable dt)
{
string sp = "CREATE DEFINER=`root`@`%` PROCEDURE `procedure Name`(";
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["DATA_TYPE"].ToString() == "varchar")
sp += "IN p_" + dt.Rows[i]["COLUMN_NAME"].ToString() + " " + dt.Rows[i]["DATA_TYPE"].ToString() + "(" + dt.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString() + ")";
else
sp += "IN p_" + dt.Rows[i]["COLUMN_NAME"].ToString() + " " + dt.Rows[i]["DATA_TYPE"].ToString() + "";
if (dt.Rows.Count != (i + 1))
sp += ",\n";
}
sp += @")
BEGIN
if p_" + dt.Rows[0]["COLUMN_NAME"].ToString() + "='0' THEN ";
sp += "Insert into " + txtTable.Text + " (\n";
for (int i = 1; i < dt.Rows.Count; i++)
{
sp += dt.Rows[i]["COLUMN_NAME"].ToString();
if (dt.Rows.Count != (i + 1))
sp += ",";
}
sp += ") values ( \n";
for (int i = 1; i < dt.Rows.Count; i++)
{
sp += "p_" + dt.Rows[i]["COLUMN_NAME"].ToString();
if (dt.Rows.Count != (i + 1))
sp += ",";
}
sp += @");
else
update " + txtTable.Text.ToString() + " set ";
for (int i = 1; i < dt.Rows.Count; i++)
{
sp += dt.Rows[i]["COLUMN_NAME"].ToString() + "=" + "p_" + dt.Rows[i]["COLUMN_NAME"].ToString();
if (dt.Rows.Count != (i + 1))
sp += ",";
}
sp += "\n where " + dt.Rows[0]["COLUMN_NAME"].ToString() + "=" + "p_" + dt.Rows[0]["COLUMN_NAME"].ToString() + ";\n";
sp += @"end if;
END";
txtSP.Text = sp;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtTable.Text = "";
txtSP.Text = "";
txtModel.Text = "";
txtParameter.Text = "";
}
private void txtScema_Leave(object sender, EventArgs e)
{
//System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(autoComplete));
//try
//{
// t.Start();
//}
//catch (Exception ex)
//{
//}
}
private void autoComplete()
{
string qry = @"SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='" + txtScema.Text + "'";
DataTable dt = getTableQry(qry);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
txtTable.AutoCompleteCustomSource.Add(dt.Rows[i][0].ToString());
}
}
}
}
<file_sep>/README.md
# queryhelper
A module in ADO .Net 4.0 intended to help with database querying
|
843b06b92249fdc35dd971c9c9862a6496d5dc1b
|
[
"Markdown",
"C#"
] | 2 |
C#
|
vijithvenganoor/queryhelper
|
92c816502126b83898fa850a08d4472b9b19a989
|
139066fc11ba446891ebfba685cc124163cf6f7f
|
refs/heads/master
|
<file_sep>#---
#title: "Wine Quality"
#author: "<NAME>"
#date: "March 21, 2018"
#---
# Red wine exploration
#================================
# Loading the required packages
library(ggplot2)
library(dplyr)
library(scales)
library(gridExtra)
library(GGally)
library(memisc)
library(corrplot)
# Loading the data
setwd("C:/Users/dell/Desktop/Sapient Online assignment")
getwd()
RedWine = read.csv("winequality-red.csv",sep = ";", header = T)
# Red wine data- 1599 observations with 11 variables + quality(12th) as target variable.
names(RedWine)
summary(RedWine)
str(RedWine)
# Quality distribution
# Wine quality is a discrete variable. Its value ranging from 3 to 8. Median value is at 6.
ggplot(RedWine, aes(quality)) + geom_histogram(colour = "black", fill = "#993366",
binwidth = 0.2) +
xlab("Wine Quality") + ylab("count") + ggtitle("Distribution of (Red) Wine Quality")
# Distribution of other chemical properties using histogram
p1 = ggplot(RedWine, aes(x=fixed.acidity)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.5)
p2 = ggplot(RedWine, aes(x=volatile.acidity)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.05)
p3 = ggplot(RedWine, aes(x=citric.acid)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.05)
p4 = ggplot(RedWine, aes(x=residual.sugar)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.4)
p5 = ggplot(RedWine, aes(x=chlorides)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.025)
p6 = ggplot(RedWine, aes(x=free.sulfur.dioxide)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 4)
p7 = ggplot(RedWine, aes(x=total.sulfur.dioxide)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 20)
p8 = ggplot(RedWine, aes(x=density)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.001)
p9 = ggplot(RedWine, aes(x=pH)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.05)
p10 = ggplot(RedWine, aes(x=sulphates)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.1)
p11 = ggplot(RedWine, aes(x=alcohol)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.25)
grid.arrange(p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11, ncol = 3)
# Observations:
# 1. Normal: volatile.acidity, density, pH
# 2. Positive Skewed: fixed.acidity, citric.acid, free.sulfur.dioxide, total.sulfur.dioxide,sulphates,alcohol
# 3. Long Tail: choloride, residual.sugar
# Rescale variable - Taking "log" of the skewed data
# Original data
p1 = ggplot(RedWine, aes(x=sulphates)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.1)
# Original data
RedWine$log_sulphate = log(RedWine$sulphates)
p2 = ggplot(RedWine, aes(x=log_sulphate)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.1) +
xlab("Logarithm of Sulphates")
grid.arrange(p1,p2, ncol =1) # In comparison, log scale is more normally distributed.
# correlation between the wine quality and the other chemical properties
CorMatrix = cor(RedWine)
corrplot(CorMatrix, type = "upper", method = "number") # Alcohol is having highest correlation with the wine quality
# Scatter plot of quality Vs Alcohol
ggplot(aes(x=quality,y=alcohol),data=RedWine)+
geom_point() + ggtitle("Red Wine")
# modification in scatter plot with median line
ggplot(RedWine, aes(x = quality, y = alcohol)) +
geom_point(color = '#993366', alpha = 0.25) +
geom_line(stat = 'summary', fun.y = quantile, fun.args = list(probs = .5), color = '#FF6660') +
xlab("Wine quality") + ylab("Alcohol") +
ggtitle("Red Wine Quality and Alcohol") # In the plot wine quality is increasing with the increase in the alcohol contain of wine.
# Transforming Wine Quality into Categorical data
RedWine$grade_number = cut(RedWine$quality, c(2.5,3.5,4.5,5.5,6.5,7.5,8.5),
labels = c('3','4','5','6','7','8'))
str(RedWine)
# Plotting boxplot
ggplot(RedWine, aes(x = grade_number, y = alcohol, fill = grade_number)) +
geom_boxplot() +
xlab("Wine Grade") + ylab("Alcohol") +
ggtitle("Alcohol Vs (Red) Wine Quality")
# Similar analysis for other 3 chemical components (volatile acid, citric acid $ Sulphates) having higher value of correlation coefficient with wine quality.
# Boxplot of Volatile acid Vs Wine Quality
ggplot(RedWine, aes(x=grade_number, y = volatile.acidity, fill= grade_number)) +
geom_boxplot() +
xlab("Wine grade") + ylab("Volatile acidity") +
ggtitle("Volatile acid Vs (Red) Wine Quality")
# Boxplot of citric acid Vs Wine Quality
ggplot(RedWine, aes(x = grade_number, y = citric.acid, fill = grade_number)) +
geom_boxplot() +
xlab("Wine Grade") + ylab("Citric acid") +
ggtitle("Citric acid Vs (Red) Wine Quality")
# Boxplot of Sulphates Vs Wine Quality
ggplot(RedWine, aes(x=grade_number, y = sulphates, fill = grade_number)) +
geom_boxplot() +
xlab("Wine Quality") + ylab("Sulphates") +
ggtitle(" Sulphates Vs (Red) Wine Quality")
# Analysis using density plot
ggplot(RedWine, aes(x=alcohol, fill = grade_number)) +
geom_density(aes(y=..density..), alpha = 0.5) +
xlab("Wine grade") + ylab("Alcohol") +
ggtitle("Alcohol distribution of different wine grade")
# The density plots are unclear so we can do labeling of wine quality....
# 1. Grade 3 & 4 = Low grade
# 2. Grade 5 & 6 = Medium grade
# 3. Grade 7 & 8 = High grade
RedWine$grade = cut(RedWine$quality, c(2.5,4.5,6.5,8.5),
labels = c("Low", "Medium", "High"))
str(RedWine)
# Wine grade Vs Alcohol
ggplot(RedWine, aes(x=alcohol, fill = grade)) +
geom_density(aes(y=..density..), alpha = 0.5, position = "identity") +
xlab("Wine grade") + ylab("Alcohol") +
ggtitle("Alcohol distribution of different wine grade(Red)")
# Wine grade Vs Volatile acidity
ggplot(RedWine, aes(x=volatile.acidity, fill = grade)) +
geom_density(aes(y=..density..), alpha = 0.5, position = "identity") +
xlab("Wine Grade") + ylab("Volatile acidity") +
ggtitle("Distribution of Volatile Acidity with Wine grade(Red)")
# Wine grade Vs Citric acid
ggplot(RedWine, aes(x=citric.acid, fill = grade)) +
geom_density(aes(y=..density..), alpha = 0.5, position = "identity") +
xlab("Wine Grade") + ylab("citric acid") +
ggtitle("Distribution of citric Acid with Wine grade(Red)")
# Wine grade Vs Logarithmic sulphate
ggplot(RedWine, aes(x=log_sulphate, fill = grade)) +
geom_density(aes(y=..density..), alpha = 0.5, position = "identity") +
xlab("Wine Grade") + ylab("Sulphates") +
ggtitle("Distribution of Sulphates with Wine grade (Red)")
# Main chemical Property Vs Wine Quality - using multi dimensional approach
# Plot using jitter
ggplot(RedWine, aes(x=quality, y=alcohol, color = volatile.acidity)) +
geom_jitter(alpha=0.5, size=3) +
xlab("Wine Quality") + ylab("Alcohol") +
scale_color_gradient2(low="red", high = "blue", mid = "#9933CC", midpoint = 0.8)
# We can see that higher quality wine have higher percentage of alcohol with lower amount of volatile acidity.
# log sulphates Vs Wine Quality
ggplot(RedWine, aes(x=alcohol, y=volatile.acidity)) +
geom_point(aes(color = log_sulphate), alpha = 0.5, size = 3) +
xlab("alcohol") + ylab("Log of Sulphates") +
scale_color_gradient2(low="red", high="blue", mid="#9933CC", midpoint = -0.25) +
facet_grid(grade~.)
# We can see higher quality wine have higher alcohol, lower volatile acidity and higher sulphates.
# Another way to look into the main Chemical Property Vs Wine Quality
ggplot(RedWine, aes(x=volatile.acidity, y=alcohol)) +
xlab("volatile acidity") + ylab("alcohol") +
geom_point(aes(color=grade), size=2)
ggplot(RedWine, aes(x=log_sulphate, y=citric.acid)) +
geom_point(aes(color = grade), size=2) +
xlab("log Sulphate") + ylab("citric acid")
# Higher quality wine have higher citric acid and higher sulphates.
# Linear Multi-variable Model
# Modeling is done to identify the mathematical relationship between chemical properties of wine and the wine quality. It is done in incremental form.
m1 = lm(quality~volatile.acidity, data=RedWine)
m2 = update(m1,~. + alcohol)
m3 = update(m2,~. + sulphates)
m4 = update(m3,~. + citric.acid)
m5 = update(m4,~. + chlorides)
m6 = update(m5,~. + total.sulfur.dioxide)
m7 = update(m6,~. + density)
mtable(m1,m2,m3,m4,m5,m6,m7)
# The model with 6 features (m6) has the lowest AIC (akaike information criterion) number. As the number of feature increase AIC become higher.The parameter of the predictor also changed.
# The model can be described as
# wine_quality = 2.985 - 1.104*volatile.acidity + 0.276*alcohol + 0.908*sulphates + 0.065*citric.acid - 1.763*chlorides - 0.002*total.sulfur.dioxide
# -----------------------<file_sep># Wine_Quality_Dataset_UCI
Insights from wine data on how to maximize the appeal of wines
[Wine_quality_data](https://archive.ics.uci.edu/ml/datasets/wine+quality)
<file_sep>#---
#title: "Wine Quality"
#author: "<NAME>"
#date: "March 21, 2018"
#---
# White wine exploration
#================================
# Loading the required packages
library(ggplot2)
library(dplyr)
library(scales)
library(gridExtra)
library(GGally)
library(memisc)
library(corrplot)
# Loading the data
setwd("C:/Users/dell/Desktop/Sapient Online assignment")
getwd()
WhiteWine = read.csv("winequality-white.csv",sep = ";", header = T)
# White wine data- 4898 observations with 11 variables + quality(12th) as target variable.
names(WhiteWine)
summary(WhiteWine)
str(WhiteWine)
# Quality distribution
# Wine quality is a discrete variable. Its value ranging from 3 to 9. Median value is at 6.
ggplot(WhiteWine, aes(quality)) + geom_histogram(colour = "black", fill = "#993366",
binwidth = 0.2) +
xlab("Wine Quality") + ylab("count") + ggtitle("Distribution of (White) Wine Quality")
# Distribution of other chemical properties using histogram
p1 = ggplot(WhiteWine, aes(x=fixed.acidity)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.5)
p2 = ggplot(WhiteWine, aes(x=volatile.acidity)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.05)
p3 = ggplot(WhiteWine, aes(x=citric.acid)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.05)
p4 = ggplot(WhiteWine, aes(x=residual.sugar)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.4)
p5 = ggplot(WhiteWine, aes(x=chlorides)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.025)
p6 = ggplot(WhiteWine, aes(x=free.sulfur.dioxide)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 4)
p7 = ggplot(WhiteWine, aes(x=total.sulfur.dioxide)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 20)
p8 = ggplot(WhiteWine, aes(x=density)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.001)
p9 = ggplot(WhiteWine, aes(x=pH)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.05)
p10 = ggplot(WhiteWine, aes(x=sulphates)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.1)
p11 = ggplot(WhiteWine, aes(x=alcohol)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.25)
grid.arrange(p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11, ncol = 3)
# Rescale variable - Taking "log" of the skewed data
# Original data
p1 = ggplot(WhiteWine, aes(x=chlorides)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.08)
# Original data
WhiteWine$log_chlorides= log(WhiteWine$chlorides)
p2 = ggplot(WhiteWine, aes(x=log_chlorides)) +
geom_histogram(colour = "black", fill = "#993366", binwidth = 0.08) +
xlab("Logarithm of chlorides")
grid.arrange(p1,p2, ncol =1) # In comparison, log scale is more normally distributed.
# correlation between the wine quality and the other chemical properties
CorMatrix = cor(WhiteWine)
corrplot(CorMatrix, type = "upper", method = "number") # Alcohol is having highest correlation with the wine quality
# Scatter plot of quality Vs Alcohol
ggplot(aes(x=quality,y=alcohol),data=WhiteWine)+
geom_point() + ggtitle("Red Wine")
# modification in scatter plot with median line
ggplot(WhiteWine, aes(x = quality, y = alcohol)) +
geom_point(color = '#993366', alpha = 0.25) +
geom_line(stat = 'summary', fun.y = quantile, fun.args = list(probs = .5), color = '#FF6660') +
xlab("Wine quality") + ylab("Alcohol") +
ggtitle("Red Wine Quality and Alcohol") # In the plot wine quality is increasing with the increase in the alcohol contain of wine.
# Transforming Wine Quality into Categorical data
WhiteWine$grade_number = cut(WhiteWine$quality, c(2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5),
labels = c('3','4','5','6','7','8','9'))
str(WhiteWine)
# Plotting boxplot
ggplot(WhiteWine, aes(x = grade_number, y = alcohol, fill = grade_number)) +
geom_boxplot() +
xlab("Wine Grade") + ylab("Alcohol") +
ggtitle("Alcohol Vs (White) Wine Quality")
# Similar analysis for other 3 chemical components (volatile acid, citric acid $ Sulphates) having higher value of correlation coefficient with wine quality.
# Boxplot of Volatile acid Vs Wine Quality
ggplot(WhiteWine, aes(x=grade_number, y = volatile.acidity, fill= grade_number)) +
geom_boxplot() +
xlab("Wine grade") + ylab("Volatile acidity") +
ggtitle("Volatile acid Vs (White) Wine Quality")
# Boxplot of chlorides Vs Wine Quality
ggplot(WhiteWine, aes(x = grade_number, y = chlorides, fill = grade_number)) +
geom_boxplot() +
xlab("Wine Grade") + ylab("chlorides") +
ggtitle("chlorides Vs (White) Wine Quality")
# Boxplot of density Vs Wine Quality
ggplot(WhiteWine, aes(x=grade_number, y = density, fill = grade_number)) +
geom_boxplot() +
xlab("Wine Quality") + ylab("density") +
ggtitle(" density Vs (White) Wine Quality")
# Analysis using density plot
ggplot(WhiteWine, aes(x=alcohol, fill = grade_number)) +
geom_density(aes(y=..density..), alpha = 0.5) +
xlab("Wine grade") + ylab("Alcohol") +
ggtitle("Alcohol distribution of different wine grade")
# The density plots are unclear so we can do labeling of wine quality....
# 1. Grade 3 & 4 = Low grade
# 2. Grade 5 & 6 = Medium grade
# 3. Grade 7, 8 & 9 = High grade
WhiteWine$grade = cut(WhiteWine$quality, c(2.5,4.5,6.5,9.5),
labels = c("Low", "Medium", "High"))
str(WhiteWine)
# Wine grade Vs Alcohol
ggplot(WhiteWine, aes(x=alcohol, fill = grade)) +
geom_density(aes(y=..density..), alpha = 0.5, position = "identity") +
xlab("Wine grade") + ylab("Alcohol") +
ggtitle("Alcohol distribution of different wine grade(White)")
# Wine grade Vs Volatile acidity
ggplot(WhiteWine, aes(x=volatile.acidity, fill = grade)) +
geom_density(aes(y=..density..), alpha = 0.5, position = "identity") +
xlab("Wine Grade") + ylab("Volatile acidity") +
ggtitle("Distribution of Volatile Acidity with Wine grade(White)")
# Wine grade Vs chlorides
ggplot(WhiteWine, aes(x=log_chlorides, fill = grade)) +
geom_density(aes(y=..density..), alpha = 0.5, position = "identity") +
xlab("Wine Grade") + ylab("Log of chlorides") +
ggtitle("Distribution of chlorides with Wine grade(White)")
# Wine grade Vs density
ggplot(WhiteWine, aes(x=density, fill = grade)) +
geom_density(aes(y=..density..), alpha = 0.5, position = "identity") +
xlab("Wine Grade") + ylab("density") +
ggtitle("Distribution of density with Wine grade (White)")
# Main chemical Property Vs Wine Quality - using multi dimensional approach
# Plot using jitter
ggplot(WhiteWine, aes(x=quality, y=alcohol, color = volatile.acidity)) +
geom_jitter(alpha=0.5, size=3) +
xlab("Wine Quality") + ylab("Alcohol") +
scale_color_gradient2(low="red", high = "blue", mid = "#9933CC", midpoint = 0.4)
# We can see that higher quality wine have higher percentage of alcohol with lower amount of volatile acidity.
# log chlorides Vs Wine Quality
ggplot(WhiteWine, aes(x=alcohol, y=volatile.acidity)) +
geom_point(aes(color = log_chlorides), alpha = 0.5, size = 3) +
xlab("alcohol") + ylab("Log of chlorides") +
scale_color_gradient2(low="red", high="blue", mid="#9933CC", midpoint = -0.25) +
facet_grid(grade~.)
# We can see higher quality wine have higher alcohol, lower volatile acidity and lower chlorides.
# Another way to look into the main Chemical Property Vs Wine Quality
ggplot(WhiteWine, aes(x=volatile.acidity, y=alcohol)) +
xlab("volatile acidity") + ylab("alcohol") +
geom_point(aes(color=grade), size=2)
ggplot(WhiteWine, aes(x=log_chlorides, y=density)) +
geom_point(aes(color = grade), size=2) +
xlab("log chlorides") + ylab("density")
# Higher quality wine have higher citric acid and higher sulphates.
# Linear Multi-variable Model
# Modeling is done to identify the mathematical relationship between chemical properties of wine and the wine quality. It is done in incremental form.
m1 = lm(quality~volatile.acidity, data=WhiteWine)
m2 = update(m1,~. + alcohol)
m3 = update(m2,~. + sulphates)
m4 = update(m3,~. + citric.acid)
m5 = update(m4,~. + chlorides)
m6 = update(m5,~. + total.sulfur.dioxide)
m7 = update(m6,~. + density)
m8 = update(m7,~. + residual.sugar)
mtable(m1,m2,m3,m4,m5,m6,m7,m8)
# The model with 8 features (m8) has the lowest AIC (akaike information criterion) number. As the number of feature increase AIC become higher.The parameter of the predictor also changed.
# The model can be described as
# wine_quality = 2.985 - 1.104*volatile.acidity + 0.276*alcohol + 0.908*sulphates + 0.065*citric.acid - 1.763*chlorides - 0.002*total.sulfur.dioxide
# -----------------------
|
b35bbf41f36718a8a2098f210f45939a90b6f590
|
[
"Markdown",
"R"
] | 3 |
R
|
abhishekporwal1991/Wine_Quality_Dataset_UCI
|
f4308fa9dff784160dd735617bcdba192b9e63d4
|
e321379484d37496132be20b2e1a7568294fe0f9
|
refs/heads/master
|
<repo_name>karthik25/ajaxified-paging<file_sep>/AjaxifiedPaging/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AjaxifiedPaging.Infrastructure.AjaxPaging;
using AjaxifiedPaging.Infrastructure.AjaxPaging.Entities;
using AjaxifiedPaging.Models;
using Newtonsoft.Json;
namespace AjaxifiedPaging.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetPagedData(string pageContentRequest)
{
var request = JsonConvert.DeserializeObject<PageContent>(pageContentRequest);
var entries = GetEntries();
var pageContent = entries.AsPagedContent(request);
return Json(pageContent, JsonRequestBehavior.AllowGet);
}
private static List<Camp> GetEntries()
{
var camps = Enumerable.Range(1, 65).Select(r => new Camp
{
CampId = r,
CampName = "Camp " + r,
StartDate = DateTime.Now.AddMonths(-(r + 2)),
EndDate = DateTime.Now.AddMonths(r)
});
return camps.ToList();
}
}
}
<file_sep>/AjaxifiedPaging/Infrastructure/AjaxPaging/Entities/PageContent.cs
namespace AjaxifiedPaging.Infrastructure.AjaxPaging.Entities
{
public class PageContent
{
public string Container { get; set; }
public string GetUrl { get; set; }
public Paging Paging { get; set; }
public Search Search { get; set; }
public object[] Entries { get; set; }
}
}<file_sep>/AjaxifiedPaging/Infrastructure/AjaxPaging/PagingHelpers.cs
using System.Linq;
using System.Collections.Generic;
using AjaxifiedPaging.Infrastructure.AjaxPaging.Entities;
namespace AjaxifiedPaging.Infrastructure.AjaxPaging
{
public static class PagingHelpers
{
public static PageContent AsPagedContent<T>(this List<T> entries, PageContent current)
where T : class
{
var paging = current.Paging == null ?
new Paging
{
CurrentPage = 1,
ItemsPerPage = 10,
TotalItems = entries.Count
}
: new Paging
{
CurrentPage = current.Paging.CurrentPage,
ItemsPerPage = 10,
TotalItems = entries.Count
};
var pageContent = new PageContent
{
Container = current.Container,
GetUrl = current.GetUrl,
Paging = paging,
Entries = entries.Skip((paging.CurrentPage - 1) * paging.ItemsPerPage)
.Take(paging.ItemsPerPage)
.Select(c => (object)c)
.ToArray()
};
return pageContent;
}
}
}
<file_sep>/AjaxifiedPaging/Models/Camp.cs
using System;
namespace AjaxifiedPaging.Models
{
public class Camp
{
public int CampId { get; set; }
public string CampName { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
}<file_sep>/AjaxifiedPaging/Infrastructure/AjaxPaging/Entities/Search.cs
namespace AjaxifiedPaging.Infrastructure.AjaxPaging.Entities
{
public class Search
{
public string Name { get; set; }
}
}<file_sep>/AjaxifiedPaging/Scripts/paging-core.js
function renderTableData(options) {
var template = $('#template').html();
Mustache.parse(template);
Mustache.Formatters = {
date: function (str) {
var dt = new Date(parseInt(str.substr(6, str.length - 8), 10));
return (dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear());
}
};
var rendered = Mustache.render(template, {
Entries: options.Entries
});
$('#' + options.Container).html(rendered);
}
function renderPagerData(options, currentPageNo) {
var pagerTemplate = $('#pagerTemplate').html();
Mustache.parse(pagerTemplate);
var rendered = Mustache.render(pagerTemplate, {
FirstPage: 1,
LastPage: options.Paging.TotalPages,
Pages: createDataForPager(options, currentPageNo)
});
$('#pager').html(rendered);
}
function createDataForPager(options, currentPageNo) {
var paging = options.Paging;
var pages = [];
for (var i = 1; i <= paging.TotalPages; i++) {
pages.push({
PageNumber: i,
PageItemClass: (currentPageNo && i === parseInt(currentPageNo)) ? "active" : ""
});
}
return pages;
}
function pagerCallback(data, pageNo) {
paging_options = data;
renderTableData(data);
renderPagerData(data, pageNo);
setupPager();
if (pageNo !== "1") {
window.location.hash = "!/" + pageNo;
}
}
function getPagingData(pagingOptions, callback, pageNo) {
$.ajax({
type: 'post',
url: pagingOptions.GetUrl,
data: { 'pageContentRequest': JSON.stringify(pagingOptions) },
dataType: 'json',
success: function (data) {
callback(data, pageNo);
}
});
}
function setupPager() {
$('.page-entry').on('click', function (e) {
e.preventDefault();
var pageNo = $(this).data('page-no');
paging_options.Paging.CurrentPage = pageNo;
paging_options.Entries = [],
getPagingData(paging_options, pagerCallback, pageNo);
});
}
$(function () {
if ($('script[type="x-tmpl-mustache"]') && typeof (paging_options) === "object") {
var pageNo = "1";
if (window.location.hash) {
pageNo = window.location.hash.match(/\d+/g)[0];
paging_options.Paging.CurrentPage = parseInt(pageNo);
}
getPagingData(paging_options, pagerCallback, pageNo);
}
});
$(window).on('hashchange', function () {
if ($('script[type="x-tmpl-mustache"]') && typeof(paging_options) === "object") {
var pageNo = location.hash.slice(1).match(/\d+/g)[0];
paging_options.Paging.CurrentPage = parseInt(pageNo);
getPagingData(paging_options, pagerCallback, pageNo);
}
});
|
aefffd5fa88bc284f08e41bac10a46731a6235f3
|
[
"JavaScript",
"C#"
] | 6 |
C#
|
karthik25/ajaxified-paging
|
3ddcd2bf054980f1364388005de5f11094fcc6df
|
2a29e56c1e6bbc229ace8c6f75146345a24b427f
|
refs/heads/master
|
<repo_name>jokoyoski/OnlineExam<file_sep>/OnlineExamApp.API/Dto/QuestionsForDisplayDto.cs
using System.Collections.Generic;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class QuestionsForDisplayDto : IQuestionsForDisplayDto
{
public int Trials { get; set; }
public IEnumerable<IQuestionForDisplay> QuestionsCollections { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/ISystemSettingRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface ISystemSettingRepository
{
Task<IList<Setting>> GetSettings();
Task<ISetting> GetSetting(int settingId);
Task<ISetting> AddSetting(ISetting settings);
Task<ISetting> UpdateSetting(ISetting settings);
Task<ISetting> RemoveSetting(ISetting settings);
}
}<file_sep>/OnlineExamApp.API/Interfaces/IUploadQuestionDto.cs
using Microsoft.AspNetCore.Http;
namespace OnlineExamApp.API.Interfaces
{
public interface IUploadQuestionDto
{
IFormFile File { get; set; }
int CategoryId { get; set; }
}
}<file_sep>/OnlineExamApp.API/Dto/Seed.cs
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using OnlineExamApp.API.Repository;
namespace OnlineExamApp.API.Dto
{
public class Seed
{
private readonly DataContext dataContext;
public Seed(IQuestionRepository questionRepository, DataContext dataContext)
{
this.dataContext = dataContext;
}
/* */ public void SeedQuestions()
{
if (dataContext.Questions.Find(1) == null)
{
var questionJSONs = System.IO.File.ReadAllText("Dto/QuestionsJSON.json");
var questionJSONCollection = JsonConvert.DeserializeObject<List<Question>>(questionJSONs);
foreach (var question in questionJSONCollection)
{
question.DateCreated = DateTime.UtcNow;
dataContext.Questions.Add(question);
dataContext.SaveChanges();
var optionsJSONs = System.IO.File.ReadAllText("Dto/OptionsJSON.json");
var optionsJSONCollection = JsonConvert.DeserializeObject<List<Option>>(questionJSONs);
foreach (var option in optionsJSONCollection)
{
option.DateCreated = DateTime.UtcNow;
option.QuestionId = question.QuestionId;
dataContext.Options.Add(option);
dataContext.SaveChanges();
}
}
}
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/ICategoryScore.cs
namespace OnlineExamApp.API.Interfaces
{
public interface ICategoryScore
{
string CategoryName { get; set; }
decimal PercentageAverageScore { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IAnweredQuestionDto.cs
using System.Collections.Generic;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IAnweredQuestionDto
{
int QuestionId { get; set; }
int OptionId { get; set; }
int CategoryId { get; set; }
}
}<file_sep>/OnlineExamApp.API/Factory/PurchaseDetailsEmail.cs
using System.Threading.Tasks;
using OnlineExamApp.API.Dto;
namespace OnlineExamApp.API.Factory
{
public class PurchaseDetailsEmail : IEmailTemplate
{
public int _coin { get; set; }
//TODO;
public async Task<EmailTemplateResponse> Template()
{
var template = new EmailTemplateResponse();
template.Subject = "TISA Coin";
template.PlainTextContent = $"You just purchased {_coin} TISA coin";
template.HtmlContent = $"<p>You just purchased {_coin} TISA coin<p>";
return template;
}
}
}<file_sep>/OnlineExamApp-SPA/src/app/layoutguard.guard.spec.ts
import { TestBed, async, inject } from '@angular/core/testing';
import { LayoutguardGuard } from './layoutguard.guard';
describe('LayoutguardGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [LayoutguardGuard]
});
});
it('should ...', inject([LayoutguardGuard], (guard: LayoutguardGuard) => {
expect(guard).toBeTruthy();
}));
});
<file_sep>/OnlineExamApp.API/Interfaces/IQuestionsForDisplayDto.cs
using System.Collections.Generic;
namespace OnlineExamApp.API.Interfaces
{
public interface IQuestionsForDisplayDto
{
int Trials { get; set; }
IEnumerable<IQuestionForDisplay> QuestionsCollections { get; set; }
}
}<file_sep>/OnlineExamApp.API/Service/AccountService.cs
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Linq;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using Microsoft.AspNetCore.Mvc;
using OnlineExamApp.API.Dto;
using static OnlineExamApp.API.Service.EmailService;
using Mono.Web;
namespace OnlineExamApp.API.Service
{
public class AccountService : IAccountService
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IConfiguration _config;
private readonly IMapper _mapper;
private readonly IEmailService _emailService;
public AccountService(UserManager<User> userManager, SignInManager<User> signInManager,
IConfiguration config, IMapper mapper, IEmailService emailService)
{
_mapper = mapper;
_config = config;
_signInManager = signInManager;
_userManager = userManager;
_emailService = emailService;
}
public async Task<string> SignIn(UserForLoginDto userForLogInDto)
{
if (userForLogInDto == null) throw new ArgumentNullException(nameof(userForLogInDto));
var user = await _userManager.FindByNameAsync(userForLogInDto.Username);
if (user == null) return "User not found";
var result = await _signInManager
.CheckPasswordSignInAsync(user, userForLogInDto.Password, false);
if (result.Succeeded)
{
var appUser = _userManager.Users
.FirstOrDefault(u => u.NormalizedUserName == userForLogInDto.Username.ToUpper());
return GenerateJwtToken(appUser).Result;
}
return string.Empty;
}
public async Task<string> SignUp(UserForRegisterDto userForRegisterDto)
{
string errorInfo = string.Empty;
var userToCreate = _mapper.Map<User>(userForRegisterDto);
userToCreate.Trials = 3;
var result = await _userManager.CreateAsync(userToCreate, userForRegisterDto.Password);
if (result.Succeeded)
{
var userroles = this._userManager.AddToRolesAsync(userToCreate, new[] { "USER" });
var token = await this._userManager.GenerateEmailConfirmationTokenAsync(userToCreate);
_emailService._toEmail = userToCreate.Email;
_emailService._toName = userToCreate.LastName + " " + userToCreate.FirstName;
_emailService._token = token;
_emailService._email = userForRegisterDto.Email;
_ = await _emailService.Execute(EmailType.AccountVerification);
return "";
}
foreach (var error in result.Errors)
{
errorInfo = error.Description;
}
return errorInfo;
}
public async Task<string> ProcessConfirmEmail(string email, string token)
{
string result = string.Empty;
if(string.IsNullOrEmpty(email)) throw new ArgumentNullException(nameof(email));
if(string.IsNullOrEmpty(token)) throw new ArgumentNullException(nameof(token));
var user = await this._userManager.FindByEmailAsync(email);
if(user == null)
{
result = "User not found";
}
var output = await this._userManager.ConfirmEmailAsync(user, token);
if(!output.Succeeded)
{
result = output.Errors.FirstOrDefault().ToString();
}
return result;
}
public async Task<string> ProcessChangePassword(string email)
{
string result = string.Empty;
if (email == null) throw new ArgumentNullException(nameof(email));
var user = await this._userManager.FindByEmailAsync(email);
if(user == null)
{
result = "User not found";
return result;
}
_emailService._toEmail = user.Email;
_emailService._toName = user.LastName + " " + user.FirstName;
var token = await this._userManager.GeneratePasswordResetTokenAsync(user);
_emailService._token = token;
await _emailService.Execute(EmailType.ChangePassword);
return result;
}
public async Task<string> ProcessConfirmChangePassword(IChangePasswordDto changePassword)
{
string result = string.Empty;
if(changePassword == null) throw new ArgumentNullException(nameof(changePassword));
if(string.IsNullOrEmpty(changePassword.Email)) throw new ArgumentNullException(nameof(changePassword.Email));
if(string.IsNullOrEmpty(changePassword.Token)) throw new ArgumentNullException(nameof(changePassword.Token));
if(string.IsNullOrEmpty(changePassword.NewPassword)) throw new ArgumentNullException(nameof(changePassword.NewPassword));
var user = await this._userManager.FindByEmailAsync(changePassword.Email);
if(user == null)
{
result = "User not found";
}
try
{
var identity = await this._userManager.ResetPasswordAsync(user, changePassword.Token, changePassword.NewPassword);
if (!identity.Succeeded)
{
result = "Unable to reset password";
}
}
catch(Exception e)
{
result = $"{e.Message}";
}
return result;
}
private async Task<string> GenerateJwtToken(User user)
{
var claims = new List<Claim>
{
new Claim (ClaimTypes.NameIdentifier, user.Id.ToString ()),
new Claim (ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName,user.FirstName),
new Claim(ClaimTypes.PrimarySid,user.Trials.ToString())
};
var roles = await _userManager.GetRolesAsync(user);
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var key = new SymmetricSecurityKey(Encoding.UTF8
.GetBytes(_config.GetSection("AppSettings:Token").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
public async Task<string> GetTrials(int userId, int numberOfTrials)
{
string result = string.Empty;
bool isExist = true;
var userInfo = await this._userManager.FindByIdAsync(userId.ToString());
isExist = (userInfo == null) ? false : true;
if (!isExist)
{
return "User Does not Exist";
}
userInfo.Trials += numberOfTrials;
var output = await this._userManager.UpdateAsync(userInfo);
if (!output.Succeeded)
{
result = output.Errors.ToString();
}
_emailService._toEmail = userInfo.Email;
_emailService._toName = userInfo.LastName + " " + userInfo.FirstName;
_emailService._coin = numberOfTrials;
await _emailService.Execute(EmailType.Purchase);
return result;
}
}
}<file_sep>/OnlineExamApp.API/Repository/ScoreRepository.cs
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Dto;
namespace OnlineExamApp.API.Repository
{
public class ScoreRepository : IScoreRepository
{
private readonly DataContext _dataContext;
private readonly ILogger<ScoreRepository> _logger;
public ScoreRepository(DataContext dataContext, ILogger<ScoreRepository> logger)
{
this._dataContext = dataContext;
this._logger = logger;
}
public async Task<IScore> GetScoresByUserIdAndCategoryId(int userId, int categoryId)
{
var score = new Score();
try
{
score = await this._dataContext.Scores
.Where(p => p.UserId == userId && p.CategoryId == categoryId)
.FirstOrDefaultAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return score;
}
public async Task<IEnumerable<IScoreDto>> GetScoresCollectionByCategoryId(int categoryId)
{
var scores = new List<ScoreDto>();
try
{
scores = await (
from d in _dataContext.Scores
select new Dto.ScoreDto{
ScoreId = d.ScoreId,
Value = d.Value,
UserId = d.UserId,
CategoryId = d.CategoryId,
DateCreated = d.DateCreated,
DateModified = d.DateModified
}
)
.Where(p => p.CategoryId.Equals(categoryId))
.OrderByDescending(p => p.Value).ToListAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return scores;
}
public async Task<string> SaveScoreHistory(IScore score)
{
if (score == null) throw new ArgumentNullException(nameof(score));
string result = string.Empty;
var newRecored = new Score
{
Value = score.Value,
UserId = score.UserId,
CategoryId = score.CategoryId,
DateCreated = DateTime.UtcNow
};
try
{
await this._dataContext.Scores.AddAsync(newRecored);
await this._dataContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
public async Task<string> UpdateScoreHistory(IScore score)
{
if (score == null) throw new ArgumentNullException(nameof(score));
string result = string.Empty;
try
{
var model = await this._dataContext.Scores.Where(p => p.ScoreId.Equals(score.ScoreId))
.SingleOrDefaultAsync();
model.Value = score.Value;
model.DateModified = DateTime.UtcNow;
await this._dataContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/ITransactionRepository.cs
namespace OnlineExamApp.API.Interfaces
{
public interface ITransactionRepository
{
}
}<file_sep>/OnlineExamApp.API/Service/EmailService.cs
using System;
using System.Threading.Tasks;
using Mono.Web;
using OnlineExamApp.API.Factory;
using OnlineExamApp.API.Interfaces;
using SendGrid;
using SendGrid.Helpers.Mail;
namespace OnlineExamApp.API.Service
{
public class EmailService : IEmailService
{
IEmailTemplate _template;
private readonly IAppSettingsService _appSettings;
private string FromEmail;
private string FromName;
public string _environment { get; set; }
public string _toEmail { get; set; }
public string _toName { get; set; }
public string _token { get; set; }
public string _email { get; set; }
public int _coin { get; set; }
public int _score { get; set; }
public EmailService(IEmailTemplate template, IAppSettingsService appSettings)
{
_template = template;
_appSettings = appSettings;
}
public async Task<Response> Execute(Enum emailType)
{
FromEmail = await _appSettings.AdminEmail;
FromName = await _appSettings.AdminName;
var apiKey = await _appSettings.SendGridAPIKey;
var client = new SendGridClient(apiKey);
var from = new EmailAddress(FromEmail, FromName);
var to = new EmailAddress(_toEmail, _toName);
_token = HttpUtility.UrlEncode(_token);
switch(emailType)
{
case EmailType.AccountVerification:
var accountVerification = new AccountVerificationEmail(_appSettings);
accountVerification._email = _email;
accountVerification._token = _token;
_template = accountVerification;
break;
case EmailType.ScoreDetail:
var scoreDetails = new ScoreDetailsEmail();
scoreDetails._score = _score;
_template = scoreDetails;
break;
case EmailType.Purchase:
var purchaseDetails= new PurchaseDetailsEmail();
purchaseDetails._coin = _coin;
_template = purchaseDetails;
break;
case EmailType.ChangePassword:
var changePasswordEmail = new ChangePasswordEmail(_appSettings);
changePasswordEmail._email = _email;
changePasswordEmail._token = _token;
_template = changePasswordEmail;
break;
default:
break;
}
var item = await _template.Template();
var msg = MailHelper.CreateSingleEmail(from, to, item.Subject, item.PlainTextContent, item.HtmlContent);
var response = await client.SendEmailAsync(msg);
return response;
}
public enum EmailType
{
AccountVerification,
ChangePassword,
ScoreDetail,
Purchase
}
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/services/questionfromServer.ts
export const questionFromDb: any = [
{
questionId: 4,
questions: 'what is your name?',
options: [
{
optionId: 4,
optionName: 'Lamba',
optionLabel: 'male',
checked : false
},
{
optionId: 5,
optionName: 'Lamba1',
optionLabel: 'female',
checked : false
}, {
optionId: 7,
optionName: 'Lamba20',
optionLabel: 'femalo',
checked : false
}],
},
{
questionId: 7,
questions: 'what is your nick?',
options: [
{
optionId: 9,
optionName: 'joko',
optionLabel: 'male',
checked : false
},
{
optionId: 7,
optionName: 'makanga',
optionLabel: 'female',
checked : false
}
],
},
{
questionId: 7,
questions: 'where do you stay?',
options: [
{
optionId: 8,
optionName: 'Ajah-Akins',
optionLabel: 'male',
checked : false
},
{
optionId: 2,
optionName: '<NAME>',
optionLabel: 'female',
checked : false
}
],
},
{
questionId: 73,
questions: 'what is your best food?',
options: [
{
optionId: 9,
optionName: 'rice',
optionLabel: 'male',
checked : false
},
{
optionId: 7,
optionName: 'amala',
optionLabel: 'female',
checked : false
},
{
optionId: 72,
optionName: 'dodo',
optionLabel: 'female',
checked : false
}
],
}, {
questionId: 7,
questions: 'what is your best dance?',
options: [
{
optionId: 9,
optionName: 'zanku',
optionLabel: 'male',
checked : false
},
{
optionId: 47,
optionName: 'gralala',
optionLabel: 'female',
checked : false
}
],
},
{
questionId: 7,
questions: 'what is your best series?',
options: [
{
optionId: 9,
optionName: 'HTGAWM',
optionLabel: 'male',
checked : false
},
{
optionId: 7,
optionName: 'arrow',
optionLabel: 'female',
checked : false
}
],
}
];
<file_sep>/OnlineExamApp.API/Interfaces/IPaymentService.cs
namespace OnlineExamApp.API.Interfaces
{
public interface IPaymentService
{
}
}<file_sep>/OnlineExamApp.API/Interfaces/IQuestionService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IQuestionService
{
Task<IEnumerable<ICategoryForDisplayDto>> GetCategories();
Task<IQuestionsForDisplayDto> GetQuestionListForDislay(int userId, int categoryId);
Task<IProcessAnswerReturnDto> ProcessAnweredQuestions(int userId, List<AnweredQuestionDto> anweredQuestion);
Task<string> SaveQuestion(IUploadQuestionDto formFile);
Task<List<QuestionOptionDto>> GetQuestion(int categoryId);
Task<string> AddQuestion(IQuestion question);
Task<string> EditQuestion(IQuestion question);
Task<string> DeleteQuestion(IQuestion question);
Task<string> AddOption(IOption option);
Task<string> EditOption(IOption option);
Task<string> DeleteOption(IOption option);
}
}<file_sep>/OnlineExamApp.API/Interfaces/ISetting.cs
namespace OnlineExamApp.API.Interfaces
{
public interface ISetting
{
int Id { get; set; }
string Key { get; set; }
string Value { get; set;}
}
}<file_sep>/OnlineExamApp.API/Service/UserService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Service
{
public class UserService : IUserService
{
private readonly IUserScoreRepository _userScoreRepository;
private readonly ICategoryRepository _categoryRepository;
private readonly IUserRepository _userRepository;
private readonly IAppSettingsService _appSettingsService;
public UserService(IUserScoreRepository userScoreRepository, ICategoryRepository categoryRepository,
IUserRepository userRepository, IAppSettingsService appSettingsService)
{
this._categoryRepository = categoryRepository;
this._userRepository = userRepository;
this._appSettingsService = appSettingsService;
this._userScoreRepository = userScoreRepository;
}
public async Task<IPerformanceDisplayDto> GetUserPerformanceByCatetgory(int userId, int categoryId)
{
if (userId <= 0) throw new ArgumentNullException(nameof(userId));
if (categoryId <= 0) throw new ArgumentNullException(nameof(categoryId));
decimal averageScoreUser = 0;
decimal averageScoreOverall = 0;
//get all the user score for a specific category
IEnumerable<IUserScore> usersScoreCollectionByUserIdAndCategoryId = await this._userScoreRepository.GetUserScoresByUserIdAndCategoryId(userId, categoryId);
if (usersScoreCollectionByUserIdAndCategoryId != null && usersScoreCollectionByUserIdAndCategoryId.Count() > 0)
{
//getting just the score value from the above list
decimal[] scoreUser = usersScoreCollectionByUserIdAndCategoryId.ToList().Select(p => p.Score).ToArray();
//get the average user score from extension method
averageScoreUser = scoreUser.Average();
}
//get all the scores for a category
IEnumerable<IUserScore> usersScoreCollectionByCategoryId = await this._userScoreRepository.GetUserScoresByCategoryId(categoryId);
if (usersScoreCollectionByCategoryId != null && usersScoreCollectionByCategoryId.Count() > 0)
{
//getting just the score value from the above list
decimal[] scoreOverall = usersScoreCollectionByCategoryId.ToList().Select(p => p.Score).ToArray();
//get the average user score from extension method
averageScoreOverall = scoreOverall.Average();
}
IPerformanceDisplayDto performanceDisplayDto = new PerformanceDisplayDto();
performanceDisplayDto.UserAverageScore = new Chat();
performanceDisplayDto.OverallAverageScore = new Chat();
//Passing user value
performanceDisplayDto.UserAverageScore.Label = "User Performance";
performanceDisplayDto.UserAverageScore.Data = new decimal[1];
performanceDisplayDto.UserAverageScore.Data[0] = Math.Round(averageScoreUser, 1);
//Passing user value
performanceDisplayDto.OverallAverageScore.Label = "Overall Performance";
performanceDisplayDto.OverallAverageScore.Data = new decimal[1];
performanceDisplayDto.OverallAverageScore.Data[0] = Math.Round(averageScoreOverall, 1);
return performanceDisplayDto;
}
#region User Management
public async Task<IUser> GetUserById(int id)
{
if(id <= 0) throw new ArgumentNullException(nameof(id));
var user = await _userRepository.GetUserById(id);
return user;
}
public async Task<string> Activate(IUser user)
{
string result = string.Empty;
if(user == null) return "User is null";
var response = await _userRepository.Activate(user);
if(!string.IsNullOrEmpty(response)) return $"Request not successful: {response}";
return result;
}
public async Task<string> RemoveUser(IUser user)
{
string result = string.Empty;
if(user == null) return "User is null";
var response = await _userRepository.RemoveUser(user);
if(!string.IsNullOrEmpty(response)) return $"Request not successful: {response}";
return result;
}
public async Task<string> Deactivate(IUser user)
{
string result = string.Empty;
if(user == null) return "User is null";
//int.TryParse(await _appSettingsService.DeactivateDay, out int days);
var response = await _userRepository.DeactivateUser(user);
if(!string.IsNullOrEmpty(response)) return $"Request not successful: {response}";
return result;
}
public async Task<string> AddUser(IUser user)
{
string result = string.Empty;
if(user == null) return "User is null";
var response = await _userRepository.AddUser(user);
if(!string.IsNullOrEmpty(response)) return $"Request not successfull: {response}";
return result;
}
public async Task<IList<User>> Users()
{
var result = await _userRepository.Users();
return result;
}
public async Task<string> EditUser(IUser user)
{
string result = string.Empty;
if(user == null) return "User is null";
var response = await _userRepository.EditUser(user);
if(!string.IsNullOrEmpty(response)) return $"Request not successfull: {response}";
return result;
}
#endregion
public async Task<string> AddUserToRole(User user, string role)
{
string result = string.Empty;
if(user == null) return "User is null";
if(string.IsNullOrEmpty(role)) return "Role is null";
var response = await _userRepository.AddUserToRole(user, role);
if(response == null) return $"Request not successfull";
return result;
}
public async Task<string> RemoveUserFromRole(User user, string role)
{
string result = string.Empty;
if(user == null) return "User is null";
if(string.IsNullOrEmpty(role)) return "Role is null";
var response = await _userRepository.RemoveUserFromRole(user, role);
if(response == null) return $"Request not successfull";
return result;
}
public async Task<IList<string>> UserToRole(User user)
{
var result = await _userRepository.UserToRole(user);
return result;
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/ICoreRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Interfaces
{
public interface ICoreRepository<T, in TIdT>
{
Task<List<T>> GetAll();
Task<List<T>> GetAll(TIdT id);
Task<List<T>> GetAll(int page, int limit);
Task<T> Get(TIdT id);
Task<T> Add(T t);
Task<T> Update(T t);
Task<T> Remove(T t);
}
}<file_sep>/OnlineExamApp.API/Interfaces/IChangePasswordDto.cs
namespace OnlineExamApp.API.Interfaces
{
public interface IChangePasswordDto
{
string Email { get; set; }
string Token { get; set; }
string NewPassword { get; set; }
}
}<file_sep>/OnlineExamApp.API/Dto/OptionsForDisplay.cs
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class OptionsForDisplay : IOptionsForDisplay
{
public int OptionId { get; set; }
public string OptionName { get; set; }
public string OptionLabel { get; set; }
public bool IsAvailable { get; set; }
public bool Checked { get; set; }
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/services/questionEnvironment.ts
export const questionEnviroment = [
{
Question : 'What is the capital of lagos ?',
Options: [
{
isAvailable : 1,
checked: '0',
A: 'Oshodi',
},
{
isAvailable : 1,
checked: '0',
B: 'Epe',
},
{
isAvailable : 1,
checked: '0',
C: 'Lekki',
},
{
isAvailable : 1,
checked: '0',
D: 'Lambasa',
},
{
isAvailable : 1,
checked: '0',
E: 'Ajah',
},
],
QID: 3,
Selected_Answer: '',
Question_Number: 0
},
{
Question : 'What is the capital of Ogun ?',
Options: [
{
isAvailable : 0,
checked: '0',
A: 'Abeokuta',
},
{
isAvailable : 1,
checked: '0',
B: 'Sagamu',
},
{
isAvailable : 1,
checked: '0',
C: 'Ijebu',
},
{
isAvailable : 1,
checked: '0',
D: 'Yewa',
},
{
isAvailable : 1,
checked: '0',
E: 'Remo',
}
],
QID: '2',
Selected_Answer: '0',
Question_Number: 0
},
{
Question : 'What is the capital of Oyo?',
Options: [
{
isAvailable : 0,
checked: '0',
A: 'Challenge',
},
{
isAvailable : 1,
isChecked: 0,
B: 'Apata',
},
{
isAvailable : 1,
checked: '0',
C: 'Cocoa House',
},
{
isAvailable : 1,
checked: '0',
D: 'Dugbe',
},
{
isAvailable : 1,
checked: '0',
E: 'Ibadan',
}
]
,
QID: 1,
Selected_Answer: '0',
Question_Number: '0'
},
];
<file_sep>/OnlineExamApp.API/Interfaces/IChat.cs
namespace OnlineExamApp.API.Interfaces
{
public interface IChat
{
string Label { get; set; }
decimal[] Data { get; set; }
}
}<file_sep>/OnlineExamApp.API/Repository/CategoryRepository.cs
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Repository
{
public class CategoryRepository : ICategoryRepository
{
private readonly DataContext _dbContext;
private readonly ILogger<CategoryRepository> _logger;
public CategoryRepository(DataContext dbContext, ILogger<CategoryRepository> logger)
{
this._dbContext = dbContext;
this._logger = logger;
}
public async Task<ICategory> GetCateogoryByCategoryId(int categoryId)
{
var result = new Category();
try
{
result = await this._dbContext.Categories.Where(p=>p.CategoryId.Equals(categoryId))
.SingleOrDefaultAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
public async Task<ICategory> GetCateogoryByName(string categoryName)
{
var result = new Category();
try
{
result = await this._dbContext.Categories.Where(p=>p.CategoryName.Equals(categoryName))
.SingleOrDefaultAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
public async Task<IEnumerable<ICategory>> GetCateogory()
{
var result = new List<Category>();
try
{
result = await this._dbContext.Categories
.OrderByDescending(p => p.CategoryId).ToListAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
public async Task<string> SaveCategory(ICategory category)
{
if(category == null) throw new ArgumentNullException(nameof(category));
string result = string.Empty;
var newCategory = new Category
{
CategoryName = category.CategoryName,
CategoryDescription = category.CategoryDescription,
DateCreated = DateTime.UtcNow,
Duration = category.Duration,
NumberofQueston = category.NumberofQueston,
PhotoId = category.PhotoId
};
try
{
await this._dbContext.Categories.AddAsync(newCategory);
await this._dbContext.SaveChangesAsync();
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
public async Task<string> EditCategory(ICategory category)
{
if(category == null) throw new ArgumentNullException(nameof(category));
string result = string.Empty;
try
{
var model = await this._dbContext.Categories.SingleOrDefaultAsync(p=>p.CategoryId.Equals(category.CategoryId));
model.CategoryName = category.CategoryName;
model.CategoryDescription = category.CategoryDescription;
model.Duration = category.Duration;
model.NumberofQueston = category.NumberofQueston;
model.PhotoId = category.PhotoId;
model.DateModified = DateTime.UtcNow;
await this._dbContext.SaveChangesAsync();
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
public async Task<string> DeleteCategory(int categoryId)
{
if(categoryId <= 0) throw new ArgumentNullException(nameof(categoryId));
string result = string.Empty;
try
{
var model = await this._dbContext.Categories.SingleOrDefaultAsync(p=>p.CategoryId.Equals(categoryId));
this._dbContext.Categories.Remove(model);
await this._dbContext.SaveChangesAsync();
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
}
}<file_sep>/OnlineExamApp.API/Repository/CoreRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Repository
{
public class CoreRepository<T, TIdT> : ICoreRepository<T, TIdT> where T : class
{
private readonly DataContext _dataContext;
private readonly Type _type;
private readonly ILogger<CoreRepository<T, TIdT>> _logger;
public CoreRepository(DataContext dataContext, ILogger<CoreRepository<T, TIdT>> logger)
{
this._dataContext = dataContext;
this._logger = logger;
this._type = typeof(T);
}
public virtual async Task<List<T>> GetAll()
{
_logger.LogDebug($"Get {_type.Name} from db");
List<T> result = default(List<T>);
try
{
result = _dataContext.Set<T>().AsEnumerable().ToList();
_logger.LogDebug($"Get {_type.FullName} was successful");
}
catch (Exception e)
{
_logger.LogError($"{e.Message}");
}
return (List<T>)result;
}
public virtual async Task<List<T>> GetAll(TIdT id)
{
_logger.LogDebug($"Get {_type.Name} from db");
List<T> result = default(List<T>);
try
{
result = _dataContext.Set<T>().Where(p=>p.Equals(id)).AsEnumerable().ToList();
_logger.LogDebug($"Get {_type.FullName} was successful");
}
catch (Exception e)
{
_logger.LogError($"{e.Message}");
}
return (List<T>)result;
}
public virtual async Task<List<T>> GetAll(int page, int limit)
{
if (page == 0)
page = 1;
if (limit == 0)
limit = int.MaxValue;
var skip = (page - 1) * limit;
List<T> result = default(List<T>);
try
{
result = _dataContext.Set<T>().AsEnumerable().Skip(skip).Take(limit).ToList();
_logger.LogDebug($"Get Pageed {_type.Name} was successful");
}
catch(Exception e)
{
_logger.LogError($"{e.Message}");
}
return (List<T>)result;
}
public virtual async Task<T> Get(TIdT id)
{
_logger.LogDebug($"Get {_type.Name} from db with id {id}");
T result = default(T);
try
{
result = await _dataContext.FindAsync<T>(id);
_logger.LogDebug($"Get {_type.Name} from db with id {id} was successful");
}
catch (Exception e)
{
_logger.LogError($"{e.Message}");
}
return (T)result;
}
public virtual async Task<T> Add(T t)
{
_logger.LogDebug($"Get {_type.Name} from db with id {t}");
T result = default(T);
try
{
var response = await _dataContext.AddAsync<T>(t);
await _dataContext.SaveChangesAsync();
_logger.LogDebug($"Get {t} was successful");
result = response.Entity;
}
catch (Exception e)
{
_logger.LogError($"{e.Message}");
}
return (T)result;
}
public virtual async Task<T> Update(T t)
{
_logger.LogDebug($"Get {_type.Name} from db");
T result = default(T);
try
{
var response = _dataContext.Update<T>(t);
await _dataContext.SaveChangesAsync();
_logger.LogDebug($"Updating {t} from db was successful");
result = response.Entity;
}
catch (Exception e)
{
_logger.LogError($"{e.Message}");
}
return (T)result;
}
public virtual async Task<T> Remove(T t)
{
_logger.LogDebug($"Get {_type.Name} from db");
T result = default(T);
try
{
result = _dataContext.Remove<T>(t).Entity;
await _dataContext.SaveChangesAsync();
_logger.LogDebug($"Get {t} from db was successful");
}
catch (Exception e)
{
_logger.LogError($"{e.Message}");
}
return (T)result;
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/IPerformanceDisplayDto.cs
namespace OnlineExamApp.API.Interfaces
{
public interface IPerformanceDisplayDto
{
IChat UserAverageScore { get; set; }
IChat OverallAverageScore { get; set; }
}
}<file_sep>/OnlineExamApp.API/Service/CategoryService.cs
using System;
using System.Threading.Tasks;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Service
{
public class CategoryService : ICategoryService
{
private readonly ICategoryRepository _categoryRepository;
public CategoryService(ICategoryRepository categoryRepository)
{
this._categoryRepository = categoryRepository;
}
public async Task<string> ProcessSaveCategory(ICategory category)
{
if(category == null) throw new ArgumentNullException(nameof(category));
bool isDataOkay = (this._categoryRepository.GetCateogoryByName(category.CategoryName) == null) ? true : false;
if(!isDataOkay)
{
return "Category is already exist";
}
return await this._categoryRepository.SaveCategory(category);
}
public async Task<string> ProcessEditCategory(ICategory category)
{
if(category == null) throw new ArgumentNullException(nameof(category));
return await this._categoryRepository.EditCategory(category);
}
public async Task<string> ProcessDeleteCategory(int categoryId)
{
if(categoryId <= 0) throw new ArgumentNullException(nameof(categoryId));
return await this._categoryRepository.DeleteCategory(categoryId);
}
}
}<file_sep>/OnlineExamApp.API/Controllers/AccountController.cs
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using OnlineExamApp.API.Dto;
using System;
using OnlineExamApp.API.Interfaces;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
namespace OnlineExamApp.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
private readonly IAccountService _accountService;
public AccountController(IAccountService accountService)
{
this._accountService = accountService;
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody]UserForRegisterDto userForRegisterDto)
{
userForRegisterDto.Username = userForRegisterDto.Email;
if (userForRegisterDto == null) throw new ArgumentNullException(nameof(userForRegisterDto));
var model = await this._accountService.SignUp(userForRegisterDto);
if (string.IsNullOrEmpty(model))
{
return Ok(new
{
success = "User Has been Registered Successfully, verify your email.",
});
}
return BadRequest(model);
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]UserForLoginDto userForLogInDto)
{
if (userForLogInDto == null) throw new ArgumentNullException(nameof(userForLogInDto));
var model = await this._accountService.SignIn(userForLogInDto);
if (model.Equals("User not found")) return BadRequest("User not found");
if (!string.IsNullOrEmpty(model))
{
return Ok(new
{
token = model
});
}
return Unauthorized("You are not authorized");
}
[HttpGet("confirmemail")]
public async Task<IActionResult> ConfirmEmail(string email, string token)
{
if (string.IsNullOrEmpty(email)) throw new ArgumentNullException(nameof(email));
var model = await this._accountService.ProcessConfirmEmail(email, token);
if(!string.IsNullOrEmpty(model)){
return BadRequest(model);
}
return Ok("Successfully confirmed email.");
}
[HttpPost("changepassword")]
public async Task<IActionResult> ChangePassword([FromBody]string email)
{
if (email == null) throw new ArgumentNullException(nameof(email));
var model = await this._accountService.ProcessChangePassword(email);
if (!string.IsNullOrEmpty(model))
{
return Ok("Check your email, a link is sent to change your password");
}
return BadRequest(model);
}
[HttpPost("confirmchange")]
public async Task<IActionResult> ConfirmChange([FromBody]ChangePasswordDto changePassword)
{
if (changePassword == null) throw new ArgumentNullException(nameof(changePassword));
var model = await this._accountService.ProcessConfirmChangePassword(changePassword);
if(!string.IsNullOrEmpty(model))
{
return BadRequest(model);
}
return Ok("Successfully confirmed email.");
}
[Authorize]
[HttpPost("buy")]
public async Task<IActionResult> BuyTrial(int userId, int numberOfTrials)
{
if (userId <= 0) throw new ArgumentNullException(nameof(userId));
if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();
if (numberOfTrials <= 0) throw new ArgumentNullException(nameof(numberOfTrials));
var model = await this._accountService.GetTrials(userId, numberOfTrials);
if (!string.IsNullOrEmpty(model))
{
return NotFound(model);
}
return Ok(model + "You have successful buy " + numberOfTrials);
}
}
}
<file_sep>/OnlineExamApp.API/Dto/AnweredQuestionDto.cs
using System.Collections.Generic;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Dto
{
public class AnweredQuestionDto : IAnweredQuestionDto
{
public int QuestionId { get; set; }
public int OptionId { get; set; }
public int CategoryId { get; set; }
}
}<file_sep>/OnlineExamApp.API/Repository/DigitalFileRepository.cs
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Repository
{
public class DigitalFileRepository : IDigitalFileRepository
{
private readonly DataContext _dataContext;
private readonly ILogger<DigitalFileRepository> _logger;
public DigitalFileRepository(DataContext dataContext, ILogger<DigitalFileRepository> logger)
{
this._dataContext = dataContext;
this._logger = logger;
}
public async Task<IPhoto> GetPhotoById(int photoId)
{
var photo = new Photo();
try
{
photo = await this._dataContext.Photos.Where(d=>d.Id.Equals(photoId)).SingleOrDefaultAsync();
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return photo;
}
}
}<file_sep>/OnlineExamApp.API/Controllers/RoleController.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class RoleController : ControllerBase
{
private readonly IRoleService _roleService;
public RoleController(IRoleService roleService)
{
this._roleService = roleService;
}
#region Roles Management CRUD
[HttpGet]
public async Task<IActionResult> Roles()
{
var roles = await _roleService.Roles();
return Ok(roles);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetRole(int id)
{
if(id <= 0) return BadRequest($"{id} is less than or equal 0");
var role = await _roleService.GetRole(id);
return Ok(role);
}
[HttpPost("add")]
public async Task<IActionResult> AddRole([FromBody]Role role)
{
if(role == null) return BadRequest();
var stg = await _roleService.AddRole(role);
if(!string.IsNullOrEmpty(stg)) return NotFound(stg);
return Created("role/add", role);
}
[HttpPost("edit")]
public async Task<IActionResult> EditRole([FromBody]Role role)
{
if(role == null) return BadRequest();
var stg = await _roleService.EditRole(role);
if(!string.IsNullOrEmpty(stg)) return NotFound(stg);
return Ok($"Successfully edited {role.Name}");
}
[HttpPost("delete")]
public async Task<IActionResult> DeleteRoelce([FromBody]Role role)
{
if(role == null) return BadRequest();
var stg = await _roleService.RemoveRole(role);
if(!string.IsNullOrEmpty(stg)) return NotFound(stg);
return Ok($"Successfully deleted {role.Name}");
}
#endregion
}
}<file_sep>/OnlineExamApp.API/Dto/UploadQuestionDto.cs
using Microsoft.AspNetCore.Http;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class UploadQuestionDto : IUploadQuestionDto
{
public IFormFile File { get; set; }
public int CategoryId { get; set; }
}
}<file_sep>/OnlineExamApp.API/Dto/CategoryScore.cs
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class CategoryScore : ICategoryScore
{
public string CategoryName { get; set; }
public decimal PercentageAverageScore { get; set; }
}
}<file_sep>/OnlineExamApp.API/Dto/ProcessAnswerReturnDto.cs
using System.Collections.Generic;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class ProcessAnswerReturnDto : IProcessAnswerReturnDto
{
public decimal Score { get; set; }
public decimal HighestScore { get; set; }
public IList<IScoreDto> ScoreBoardCollection { get; set; }
public int Position { get; set; }
public int NoOfParticipant { get; set; }
public int Trials { get; set; }
public string ReturnMessage { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IOptionsForDisplay.cs
namespace OnlineExamApp.API.Interfaces
{
public interface IOptionsForDisplay
{
int OptionId { get; set; }
string OptionName { get; set; }
string OptionLabel { get; set; }
bool IsAvailable { get; set; }
bool Checked { get; set; }
}
}<file_sep>/OnlineExamApp.API/Helpers/AutoMapperProfiles.cs
using System.Collections.Generic;
using AutoMapper;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Helpers
{
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles(){
CreateMap<IQuestion, IQuestionForDisplay>();
CreateMap<ICategory, ICategoryForDisplayDto>();
CreateMap<IOption, IOptionsForDisplay>();
CreateMap<UserForRegisterDto, User>();
CreateMap<UserScore, IUserScore>();
CreateMap<IEnumerable<IQuestion>, IEnumerable<IQuestionForDisplay>>();
CreateMap<IEnumerable<IOption>, IEnumerable<IOptionsForDisplay>>();
CreateMap<IEnumerable<ICategory>, IEnumerable<ICategoryForDisplayDto>>();
}
}
}<file_sep>/OnlineExamApp-SPA/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { routerTransition } from '../router.animations';
import { AuthService } from '../services/Auth.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { AlertifyService } from '../services/AlertifyService';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
animations: [routerTransition()]
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
model: any = {};
loading = false;
constructor(public authService: AuthService,
private alertifyService: AlertifyService, private router: Router) { }
ngOnInit() {
this.loginForm = new FormGroup({ // we created a new instance here
username: new FormControl('', Validators.required),
password: new FormControl('', Validators.required),
});
}
login() {
if (this.loginForm.valid) {
this.model = Object.assign({}, this.loginForm.value);
}
this.loading = true;
this.authService.login(this.model).subscribe(next => {
this.alertifyService.success('logged in successfully');
this.loading = false;
}, error => {
this.alertifyService.error(error);
this.loading = false;
}, () => {
this.router.navigate(['/dashboard']);
});
}
onLoggedin() {
localStorage.setItem('isLoggedin', 'true');
}
}
<file_sep>/OnlineExamApp.API/Dto/EmailTemplateResponse.cs
namespace OnlineExamApp.API.Dto
{
public class EmailTemplateResponse
{
public string Subject { get; set; }
public string PlainTextContent { get; set; }
public string HtmlContent { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IAccountService.cs
using System.Threading.Tasks;
using OnlineExamApp.API.Dto;
namespace OnlineExamApp.API.Interfaces
{
public interface IAccountService
{
Task<string> SignUp(UserForRegisterDto userForRegisterDto);
Task<string> SignIn(UserForLoginDto userForLogInDto);
Task<string> ProcessConfirmEmail(string email, string code);
Task<string> ProcessChangePassword(string email);
Task<string> ProcessConfirmChangePassword(IChangePasswordDto changePassword);
Task<string> GetTrials(int userId, int numberOfTrials);
}
}<file_sep>/OnlineExamApp.API/Interfaces/IScore.cs
using System;
namespace OnlineExamApp.API.Interfaces
{
public interface IScore
{
int ScoreId { get; set; }
decimal Value { get; set; }
int UserId { get; set; }
int CategoryId { get; set; }
DateTime DateCreated { get; set; }
DateTime? DateModified { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IUserRoleService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IUserRoleService
{
}
}<file_sep>/OnlineExamApp.API/Interfaces/IRoleRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IRoleRepository
{
Task<IList<Role>> Roles();
Task<Role> GetRole(int id);
Task<Role> AddRole(Role role);
Task<Role> EditRole(Role role);
Task<Role> RemoveRole(Role role);
}
}<file_sep>/OnlineExamApp.API/Interfaces/IQuestionRepository.cs
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Interfaces
{
public interface IQuestionRepository
{
Task<IEnumerable<IQuestion>> GetQuestionsByCaregoryId(int categoryId);
Task<IQuestion> SaveQuestion(IQuestion question);
Task<IQuestion> UpdateQuestion(IQuestion question);
Task<IQuestion> RemoveQuestion(IQuestion question);
Task<IQuestion> AddQuestion(IQuestion question);
}
}
<file_sep>/OnlineExamApp.API/Service/QuestionService.cs
using AutoMapper;
using Newtonsoft.Json;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Text.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
using Microsoft.AspNetCore.Identity;
using static OnlineExamApp.API.Service.EmailService;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
namespace OnlineExamApp.API.Service
{
public class QuestionService : IQuestionService
{
private readonly IQuestionRepository _questionRepository;
private readonly IOptionRepository _optionRepository;
private readonly IMapper _mapper;
private readonly IUserScoreRepository _userScoreRepository;
private readonly ICategoryRepository _categoryRepository;
private readonly IDigitalFileRepository _digitalFileRepository;
private readonly IScoreRepository _scoreRepository;
private readonly IEmailService _emailService;
private readonly ICacheService _cacheService;
private readonly IAppSettingsService _appSettings;
private readonly UserManager<User> _userManager;
public QuestionService(IQuestionRepository questionRepository, UserManager<User> userManager,
IOptionRepository optionRepository, IMapper mapper, IUserScoreRepository userScoreRepository,
ICategoryRepository categoryRepository, IDigitalFileRepository digitalFileRepository,
IScoreRepository scoreRepository, IEmailService emailService, ICacheService cacheService, IAppSettingsService appSettings)
{
this._digitalFileRepository = digitalFileRepository;
this._scoreRepository = scoreRepository;
this._emailService = emailService;
this._cacheService = cacheService;
this._appSettings = appSettings;
this._categoryRepository = categoryRepository;
this._userScoreRepository = userScoreRepository;
this._mapper = mapper;
this._optionRepository = optionRepository;
this._questionRepository = questionRepository;
this._userManager = userManager;
}
public async Task<string> AddOption(IOption option)
{
if (option == null) return $"{option} is null";
var qtn = await _optionRepository.AddOption(option);
if (qtn == null) return $"Option not added Successfull";
return string.Empty;
}
public async Task<string> AddQuestion(IQuestion question)
{
if (question == null) return $"{question} is null";
var qtn = await _questionRepository.AddQuestion(question);
if (qtn == null) return $"Question not added successfully";
return string.Empty;
}
public async Task<string> DeleteOption(IOption option)
{
if (option == null) return $"{option} is null";
var qtn = await _optionRepository.DeleteOption(option);
if (qtn == null) return $"Option not deleted successfully";
return string.Empty;
}
public async Task<string> DeleteQuestion(IQuestion question)
{
if (question == null) return $"{question} is null";
var qtn = await _questionRepository.RemoveQuestion(question);
if (qtn == null) return $"Question not deleted successfully";
return string.Empty;
}
public async Task<string> EditOption(IOption option)
{
if (option == null) return $"{option} is null";
var qtn = await _optionRepository.UpdateOption(option);
if (qtn == null) return $"Option not edited successfully";
return string.Empty;
}
public async Task<string> EditQuestion(IQuestion question)
{
if (question == null) return $"{question} is null";
var qtn = await _questionRepository.UpdateQuestion(question);
if (qtn == null) return $"Question not edited successfully";
return string.Empty;
}
public async Task<IEnumerable<ICategoryForDisplayDto>> GetCategories()
{
var categoryCollection = _cacheService.Get<IEnumerable<ICategory>>("::category::");
if (categoryCollection == null)
{
categoryCollection = await this._categoryRepository.GetCateogory();
_cacheService.Add<IEnumerable<ICategory>>("::category::", categoryCollection);
}
var categoryForDisplayDto = _mapper.Map<IEnumerable<ICategoryForDisplayDto>>(categoryCollection).ToList();
foreach (var d in categoryForDisplayDto)
{
var model = await this._digitalFileRepository.GetPhotoById(d.PhotoId);
if (model != null) d.PhotoUrl = model.Url;
}
return categoryForDisplayDto;
}
public async Task<List<QuestionOptionDto>> GetQuestion(int categoryId)
{
if (categoryId <= 0) throw new ArgumentNullException(nameof(categoryId));
var questions = await _questionRepository.GetQuestionsByCaregoryId(categoryId);
if (questions == null) throw new NullReferenceException(nameof(questions));
var questionOptions = new List<QuestionOptionDto>();
foreach (var qtn in questions)
{
var questionOption = new QuestionOptionDto();
questionOption.Question = qtn;
questionOption.Options = new List<IOption>();
var options = await _optionRepository.GetOptionsByQuestionId(qtn.QuestionId);
if (options == null) throw new NullReferenceException(nameof(options));
foreach (var item in options)
{
questionOption.Options.Add(item);
}
questionOptions.Add(questionOption);
}
return questionOptions;
}
public async Task<IQuestionsForDisplayDto> GetQuestionListForDislay(int userId, int categoryId)
{
if (userId <= 0) throw new ArgumentNullException(nameof(userId));
if (categoryId <= 0) throw new ArgumentNullException(nameof(categoryId));
var userInfo = await this._userManager.FindByIdAsync(userId.ToString());
var questionList = await this._questionRepository.GetQuestionsByCaregoryId(categoryId);
var category = await this._categoryRepository.GetCateogoryByCategoryId(categoryId);
var questionCollection = _mapper.Map<IEnumerable<IQuestionForDisplay>>(questionList).ToList();
Random rand = new Random();
int n = 0;
if (userInfo.Trials > 0) n = questionCollection.Count;
while (n > 1)
{
n--;
int k = rand.Next(n + 1);
var value = questionCollection[k];
questionCollection[k] = questionCollection[n];
questionCollection[n] = value;
}
var displayModel = new QuestionsForDisplayDto();
var randomSpecificList = new List<IQuestionForDisplay>();
if (category != null && category.NumberofQueston > 0 && category.NumberofQueston <= questionCollection.Count)
{
randomSpecificList = questionCollection.GetRange(0, category.NumberofQueston);
if (userInfo != null && userInfo.Trials > 0)
{
displayModel.Trials = userInfo.Trials;
}
}
else
{
randomSpecificList = questionCollection.GetRange(0, questionCollection.Count);
if (userInfo != null && userInfo.Trials > 0)
{
var successful = await this._userManager.UpdateAsync(userInfo);
if (successful.Succeeded)
{
displayModel.Trials = userInfo.Trials;
}
}
}
foreach (var options in randomSpecificList)
{
var optionCollection = await this._optionRepository.GetOptionsByQuestionId(options.QuestionId);
options.Options = _mapper.Map<IEnumerable<IOptionsForDisplay>>(optionCollection);
}
displayModel.QuestionsCollections = randomSpecificList;
return displayModel;
}
public async Task<IProcessAnswerReturnDto> ProcessAnweredQuestions(int userId, List<AnweredQuestionDto> anweredQuestion)
{
if (anweredQuestion == null) throw new ArgumentNullException(nameof(anweredQuestion));
decimal score = 0;
int categoryId = 0;
IProcessAnswerReturnDto result = new ProcessAnswerReturnDto();
foreach (var answers in anweredQuestion)
{
var correctOptionCollection = await this._optionRepository.GetCorrectOptionByQuestionId(answers.QuestionId);
foreach (var correctAnswer in correctOptionCollection)
{
if (answers.OptionId == correctAnswer.OptionId) score++;
}
categoryId = answers.CategoryId;
}
result.Score = score;
IUserScore userScore = new UserScore
{
Score = score,
UserId = userId,
CategoryId = categoryId,
DateCreated = DateTime.UtcNow,
DateTaken = DateTime.UtcNow
};
var output = await this._userScoreRepository.SaveUserScore(userScore);
if (!string.IsNullOrEmpty(output))
{
result.ReturnMessage = output;
}
var userScoreHistory = await this._scoreRepository.GetScoresByUserIdAndCategoryId(userId, categoryId);
IScore presentScore = new Score
{
Value = score,
CategoryId = categoryId,
UserId = userId
};
if (userScoreHistory == null)
{
result.ReturnMessage = await this._scoreRepository.SaveScoreHistory(presentScore);
if (!string.IsNullOrEmpty(result.ReturnMessage)) return result;
}
else if (userScoreHistory != null && userScoreHistory.Value < score)
{
presentScore.ScoreId = userScoreHistory.ScoreId;
result.ReturnMessage = await this._scoreRepository.UpdateScoreHistory(presentScore);
if (!string.IsNullOrEmpty(result.ReturnMessage)) return result;
}
var highScoresCollections = await this._scoreRepository.GetScoresCollectionByCategoryId(categoryId);
if (highScoresCollections != null)
{
var scorePosition = highScoresCollections.Where(p => p.UserId.Equals(userId)).SingleOrDefault();
var count = 0;
foreach (var item in highScoresCollections)
{
var user = await this._userManager.FindByIdAsync(item.UserId.ToString());
item.Username = user.UserName;
var category = await this._categoryRepository.GetCateogoryByCategoryId(item.CategoryId);
item.CategoryName = category.CategoryName;
count++;
if (item.UserId == userId)
{
break;
}
}
//Find how to pass position
result.Position = count;
//Total Number of Participant
result.NoOfParticipant = highScoresCollections.Count();
//Whats my hghestScore
result.HighestScore = scorePosition.Value;
//Select First Five
result.ScoreBoardCollection = highScoresCollections.Take(5).ToList();
}
var userInfo = await this._userManager.FindByIdAsync(userId.ToString());
--userInfo.Trials;
var successful = await this._userManager.UpdateAsync(userInfo);
result.Trials = userInfo.Trials;
_emailService._toEmail = userInfo.Email;
_emailService._toName = userInfo.LastName + " " + userInfo.FirstName;
_ = await _emailService.Execute(EmailType.ScoreDetail);
return result;
}
public async Task<string> SaveQuestion(IUploadQuestionDto file)
{
string result = string.Empty;
int categoryId = file.CategoryId;
if (file.File == null) return "No Uploaded file";
Stream pdf = file.File.OpenReadStream();
if (pdf == null) return "Invalid file";
try
{
var questionResponse = new QuestionRipperResponse();
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(await _appSettings.QuestionRipperUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("TerminalId", await _appSettings.TerminalId);
var filepath = file.File;
string filename = file.File.FileName;
MultipartFormDataContent content = new MultipartFormDataContent();
ByteArrayContent fileContent = new ByteArrayContent(pdf.StreamToByteArray());
//fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
content.Headers.Add("TerminalId", await _appSettings.TerminalId);
//content.Add(fileContent,"File");
content.Add(fileContent, "file", file.File.FileName);
//content.Add(fileContent);
HttpResponseMessage response = await client.PostAsync("/api/product/pdf", content);
var resp = await response.Content.ReadAsStringAsync();
questionResponse = JsonConvert.DeserializeObject<QuestionRipperResponse>(resp);
}
if (questionResponse == null || !questionResponse.ResponseCode.Equals("00")) return "Request Failed";
result = await SaveQuestionHelper(questionResponse.Questions, categoryId);
return result;
}
catch (Exception e)
{
return $"{e.Message}";
}
}
private async Task<string> SaveQuestionHelper(List<QuestionObject> questions, int categoryId)
{
string result = string.Empty;
if (questions == null || !questions.Any()) return "No question exist";
foreach (var question in questions)
{
if (question.isQuestionValid)
{
IQuestion questionModel = new Question
{
Questions = question.Question,
CategoryId = categoryId,
DateCreated = DateTime.UtcNow
};
var response = await this._questionRepository.SaveQuestion(questionModel);
if (response != null && response.QuestionId > 0)
{
foreach (var option in question.Options)
{
IOption questionOption = new Option
{
QuestionId = response.QuestionId,
OptionName = option.Option,
DateCreated = DateTime.UtcNow
};
_ = await this._optionRepository.SaveQuestionOption(questionOption);
}
}
}
}
return result;
}
}
public static class ExtensionMethodHelper
{
public static byte[] StreamToByteArray(this Stream inputStream)
{
byte[] bytes = new byte[16384];
using (MemoryStream memoryStream = new MemoryStream())
{
int count;
while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
{
memoryStream.Write(bytes, 0, count);
}
return memoryStream.ToArray();
}
}
}
}<file_sep>/OnlineExamApp.API/Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Serialization;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Factory;
using OnlineExamApp.API.Helpers;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using OnlineExamApp.API.Repository;
using OnlineExamApp.API.Service;
namespace OnlineExamApp.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
.EnableSensitiveDataLogging(), ServiceLifetime.Scoped);
IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
{
opt.Password.RequireDigit = false;
opt.Password.RequiredLength = 4;
opt.Password.RequireNonAlphanumeric = false;
opt.Password.RequireUppercase = false;
});
builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
builder.AddEntityFrameworkStores<DataContext>().AddDefaultTokenProviders();
builder.AddRoleValidator<RoleValidator<Role>>();
builder.AddRoleManager<RoleManager<Role>>();
builder.AddSignInManager<SignInManager<User>>();
services.AddAutoMapper(typeof(DataContext));
services.AddTransient<Seed>();
services.Configure<CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));
services.AddCors();
//Register Factory
services.AddScoped<IEmailTemplate, AccountVerificationEmail>();
services.AddScoped<IEmailTemplate, ChangePasswordEmail>();
services.AddScoped<IEmailTemplate, PurchaseDetailsEmail>();
services.AddScoped<IEmailTemplate, ScoreDetailsEmail>();
//Registered repository
services.AddScoped<ISystemSettingRepository, SystemSettingRepository>();
services.AddScoped<ICategoryRepository, CategoryRepository>();
services.AddScoped<IDigitalFileRepository, DigitalFileRepository>();
services.AddScoped<IOptionRepository, OptionRepository>();
services.AddScoped<IQuestionRepository, QuestionRepository>();
services.AddScoped<IScoreRepository, ScoreRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IUserScoreRepository, UserScoreRepository>();
services.AddScoped(typeof(ICoreRepository<,>), typeof(CoreRepository<,>));
services.AddScoped<ITransactionRepository, TransactionRepository>();
services.AddScoped<IRoleRepository, RoleRepository>();
services.AddScoped<IUserRoleRepository, UserRoleRepository>();
//Registered service1
services.AddScoped<IAppSettingsService, AppSettingsService>();
services.AddScoped<IAccountService, AccountService>();
services.AddScoped<IEmailService, EmailService>();
services.AddScoped<IPaymentService, PaymentService>();
services.AddScoped<ICategoryService, CategoryService>();
services.AddScoped<IQuestionService, QuestionService>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IRoleService, RoleService>();
services.AddScoped<ICacheService, CacheService>();
services.AddMvc().AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("UserPolicy", policy => policy.RequireRole("USER"));
options.AddPolicy("AdminPolicy", policy => policy.RequireRole("ADMIN", "USER"));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Seed seeder)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); //cors
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseAuthentication(); //for authentication middleware
app.UseAuthorization();
//seeder.SeedQuestions();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
//endpoints.MapFallbackToController("Index","Fallback");
});
}
}
}
<file_sep>/OnlineExamApp.API/Interfaces/IEmailService.cs
using System;
using System.Threading.Tasks;
using SendGrid;
namespace OnlineExamApp.API.Interfaces
{
public interface IEmailService
{
string _token { get; set; }
string _email { get; set; }
string _environment { get; set; }
string _toEmail { get; set; }
string _toName { get; set; }
int _coin { get; set; }
Task<Response> Execute(Enum emailType);
}
}<file_sep>/OnlineExamApp.API/Model/UserScore.cs
using System;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class UserScore : IUserScore
{
public int UserScoreId { get; set; }
public int UserId { get; set; }
public decimal Score { get; set; }
public int CategoryId { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateTaken { get; set; }
}
}<file_sep>/OnlineExamApp.API/Repository/DataContext.cs
using System.Configuration;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Repository
{
public class DataContext : IdentityDbContext<User, Role, int,
IdentityUserClaim<int>, UserRole, IdentityUserLogin<int>,
IdentityRoleClaim<int>, IdentityUserToken<int>>
{
public DataContext (DbContextOptions<DataContext> option) : base (option)
{}
public DbSet<Question> Questions { get; set; }
public DbSet<Option> Options { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<UserScore> UserScores { get; set; }
public DbSet<Photo> Photos { get; set; }
public DbSet<Score> Scores { get; set; }
public DbSet<Setting> Settings { get; set; }
protected override void OnModelCreating (ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<UserRole>(userRole =>
{
userRole.HasKey(ur => new {ur.UserId, ur.RoleId});
userRole.HasOne(ur => ur.Role)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
userRole.HasOne(ur => ur.User)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
});
}
}
}<file_sep>/OnlineExamApp.API/Factory/EmailTemplate.cs
using System;
using System.Threading.Tasks;
using OnlineExamApp.API.Dto;
namespace OnlineExamApp.API.Factory
{
public interface IEmailTemplate
{
Task<EmailTemplateResponse> Template ();
}
}<file_sep>/OnlineExamApp.API/Dto/UserForLoginDto.cs
using System.ComponentModel.DataAnnotations;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class UserForLoginDto : IUserForLoginDto
{
[Required(ErrorMessage="Please Enter Username")]
public string Username { get; set; }
[Required(ErrorMessage="Please Enter Password")]
public string Password { get; set; }
}
}<file_sep>/OnlineExamApp.API/Model/Option.cs
using System;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class Option : IOption
{
public int OptionId { get; set; }
public string OptionName { get; set; }
public bool IsCorrect { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public int QuestionId { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IRoleService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IRoleService
{
Task<IList<Role>> Roles();
Task<Role> GetRole(int id);
Task<string> AddRole(Role role);
Task<string> EditRole(Role role);
Task<string> RemoveRole(Role role);
}
}<file_sep>/OnlineExamApp.API/Interfaces/IUserScoreForDisplayDto.cs
using System.Collections.Generic;
namespace OnlineExamApp.API.Interfaces
{
public interface IUserScoreForDisplayDto
{
int UserId { get; set; }
IList<ICategoryScore> CategoryScoreCollection { get; set; }
}
}<file_sep>/OnlineExamApp-SPA/src/app/signup/signup.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { routerTransition } from '../router.animations';
import { AuthService } from '../services/Auth.service';
import { AlertifyService } from '../services/AlertifyService';
import { Router } from '@angular/router';
import { LoaderService } from '../layout/services/loader.service';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.scss'],
animations: [routerTransition()]
})
export class SignupComponent implements OnInit {
registerForm: FormGroup;
loader = false;
loading = false;
constructor(private authService: AuthService, private alertifyService:
AlertifyService, private router: Router) {
this.loader = true;
}
model: any = {};
ngOnInit() {
this.registerForm = new FormGroup({ // we created a new instance here
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
email: new FormControl('', Validators.required),
password: new FormControl('', [Validators.required, Validators.minLength(4), Validators.maxLength(8)]),
confirmPassword: new FormControl('', Validators.required),
dateOfBirth: new FormControl('', Validators.required)
}, this.passwordMatchValidator);
}
passwordMatchValidator(g: FormGroup) { // if password are equal
return g.get('password').value === g.get('confirmPassword').value ? null : {mismatch: true};
}
register() {
if (this.registerForm.valid) {
this.model = Object.assign({}, this.registerForm.value);
}
this.loading = true;
this.authService.register(this.model).subscribe((response: any) => {
this.alertifyService.success(response.success);
this.loading = false;
}, (error) => {
this.alertifyService.error(error);
this.loading = false;
}, () => {
this.model.userName = this.model.email;
this.authService.login(this.model).subscribe((response: any) => {
this.router.navigate(['']); // redirect users to the dashboard page when they login
});
} );
}
}
<file_sep>/OnlineExamApp.API/Factory/ChangePasswordEmail.cs
using System.Threading.Tasks;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Factory
{
public class ChangePasswordEmail : IEmailTemplate
{
public string _email { get; set; }
public string _token { get; set; }
public IAppSettingsService _appSettingsService { get; }
public ChangePasswordEmail(IAppSettingsService appSettingsService)
{
this._appSettingsService = appSettingsService;
}
public async Task<EmailTemplateResponse> Template()
{
var template = new EmailTemplateResponse();
var confirmationURL = $"{await _appSettingsService.BaseUrl}/api/account/confirmchange?email={_email}&token={_token}";
template.Subject = "Change Password";
template.PlainTextContent = "Click on the link below to change your password";
template.HtmlContent = $"<p>Click on the link below to change your password.<p><a href=\"{confirmationURL}\">Click to change password.</a></p>";
return template;
}
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/services/question.service.ts
import { Injectable } from '@angular/core';
import { questionEnviroment } from './questionEnvironment';
import {questionFromDb} from './questionfromServer';
import { CookieService } from 'ngx-cookie-service';
import { HttpClient } from '@angular/common/http';
import {map} from 'rxjs/operators';
import { Category } from '../QuestionModel';
@Injectable({
providedIn: 'root'
})
export class QuestionService {
questions = questionEnviroment;
private cookieValue = [];
questionList: any;
newquestion: any;
questionNumber: number;
question: any = [];
seconds: number;
timer: any;
result: any;
categories: Category[];
componentQuestion: any = {};
prodUrl='http://bomanaziba-001-site1.dtempurl.com/';
value: string;
constructor(private cookie: CookieService, private httpClient: HttpClient) { }
displayTimeElapsed() {
return Math.floor(this.seconds / 3600) + ':' + Math.floor((this.seconds % 3600) / 60) + ':' + Math.floor(this.seconds % 60);
}
getQuestions() {
let j = 1;
for (let i = 0; i <= this.questions.length - 1; i++) {
this.questions[i].Question_Number = j;
j++;
}
this.cookie.set('questions', JSON.stringify(this.questions));
this.question.QuestionList = this.questions;
this.question.Current = this.questions[0];
return this.question;
}
GetQuestion(categoryId: number) {
const tokenId = localStorage.getItem('userId');
return this.httpClient.get(this.prodUrl + tokenId + '/' + categoryId);
}
getCategories() {
return this.httpClient.get(this.prodUrl);
}
Submit(question: any) {
const tokenId = localStorage.getItem('userId');
const url = this.prodUrl + tokenId + '/submitTest';
return this.httpClient.post(this.prodUrl + tokenId + '/submitTest', question).pipe(
map((response: any) => {
this.result = response;
localStorage.setItem('result', this.result.score);
}));
}
}
<file_sep>/OnlineExamApp.API/Repository/TransactionRepository.cs
using System.Transactions;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Repository
{
public class TransactionRepository : ITransactionRepository
{
private readonly DataContext _dbContext;
public TransactionRepository(DataContext dbContext)
{
this._dbContext = dbContext;
}
}
}<file_sep>/OnlineExamApp.API/Dto/Chat.cs
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class Chat : IChat
{
public string Label { get; set; }
public decimal[] Data { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/ICacheService.cs
namespace OnlineExamApp.API.Interfaces
{
public interface ICacheService
{
T Get<T>(string key) where T : class;
void Add<T>(string key, T data, double? expiration = null) where T : class;
void Remove(string cacheKey);
void RemoveAllFromCache();
}
}<file_sep>/OnlineExamApp.API/Controllers/AdminController.cs
using System;
using System.IO;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Controllers
{
//[Authorize(Policy="AdminPolicy")]
[ApiController]
[Route("api/[controller]")]
public class AdminController : ControllerBase
{
private readonly IQuestionService _questionService;
private readonly ICacheService _cacheService;
private readonly IAppSettingsService _appSettingsService;
private readonly ICategoryService _categoryService;
private readonly IPaymentService _paymentService;
public AdminController(IQuestionService questionService, ICacheService cacheService,
IAppSettingsService appSettingsService, ICategoryService categoryService,
IPaymentService paymentService)
{
this._questionService = questionService;
this._cacheService = cacheService;
this._appSettingsService = appSettingsService;
this._categoryService = categoryService;
this._paymentService = paymentService;
}
[HttpPost("import")]
public async Task<IActionResult> Import([FromForm]UploadQuestionDto formFile)
{
if (formFile == null || formFile.File.Length <= 0)
{
return BadRequest("You uploaded an empty file");
}
if (!Path.GetExtension(formFile.File.FileName).Equals(".pdf", StringComparison.OrdinalIgnoreCase))
{
return BadRequest("invalid file format");
}
var result = await this._questionService.SaveQuestion(formFile);
return Ok(result);
}
[HttpPost("resync")]
public async Task<IActionResult> Resync()
{
_cacheService.RemoveAllFromCache();
return Ok("Resynce Successful");
}
#region System Setting CRUD
[HttpGet("settings")]
public async Task<IActionResult> GetSettings()
{
var roles = await _appSettingsService.GetSettings();
return Ok(roles);
}
[HttpGet("setting/{id}")]
public async Task<IActionResult> GetSetting(int id)
{
if(id <= 0) return BadRequest($"{id} is less than or equal 0");
var role = await _appSettingsService.GetSetting(id);
return Ok(role);
}
[HttpPost("setting/add")]
public async Task<IActionResult> AddSettings([FromBody]Setting setting)
{
if(setting == null) return BadRequest("Setting is null");
var stn = await _appSettingsService.AddSetting(setting);
if(!string.IsNullOrEmpty(stn)) return NotFound(stn);
return Created("settings/add", setting);
}
[HttpPost("setting/edit")]
public async Task<IActionResult> EditSettings([FromBody]Setting setting)
{
if(setting == null) return BadRequest("Setting is null");
var stn = await _appSettingsService.EditSetting(setting);
if(!string.IsNullOrEmpty(stn)) return NotFound(stn);
return Ok($"Successfully edited {setting.Key}");
}
[HttpPost("setting/delete")]
public async Task<IActionResult> DeleteSettings([FromBody]Setting setting)
{
if(setting == null) return BadRequest("Setting is null");
var stn = await _appSettingsService.RemoveSetting(setting);
if(!string.IsNullOrEmpty(stn)) return NotFound(stn);
return Ok($"Successfully deleted {setting.Key}");
}
#endregion
#region Question CRUD
[HttpGet("question/{categoryId}")]
public async Task<IActionResult> GetQuestion(int categoryId)
{
if(categoryId <= 0) return BadRequest($"{categoryId} is less than or equal 0");
var questions = await _questionService.GetQuestion(categoryId);
return Ok(questions);
}
[HttpPost("question/add")]
public async Task<IActionResult> AddQuestion(Question question)
{
if(question == null) return BadRequest($"{question} is null");
var qtn = await _questionService.AddQuestion(question);
if(!string.IsNullOrEmpty(qtn)) return NotFound(qtn);
return Created("question/add", qtn);
}
[HttpPost("question/edit")]
public async Task<IActionResult> EditQuestion(Question question)
{
if(question == null) return BadRequest($"{question} is null");
var qtn = await _questionService.EditQuestion(question);
if(!string.IsNullOrEmpty(qtn)) return NotFound(qtn);
return Ok("Successfully edited question");
}
[HttpPost("question/delete")]
public async Task<IActionResult> DeleteQuestion(Question question)
{
if(question == null) return BadRequest($"{question} is null");
var qtn = await _questionService.DeleteQuestion(question);
if(!string.IsNullOrEmpty(qtn)) return NotFound(qtn);
return Ok("Successfully deleted question");
}
#endregion
#region Question Option CRUD
[HttpPost("option/add")]
public async Task<IActionResult> AddOption(Option option)
{
if(option == null) return BadRequest($"{option} is null");
var opn = await _questionService.AddOption(option);
if(!string.IsNullOrEmpty(opn)) return NotFound(opn);
return Created("option/add", opn);
}
[HttpPost("option/edit")]
public async Task<IActionResult> EditOption(Option option)
{
if(option == null) return BadRequest($"{option} is null");
var opn = await _questionService.EditOption(option);
if(!string.IsNullOrEmpty(opn)) return NotFound(opn);
return Ok("Successfully Edited");
}
[HttpPost("option/delete")]
public async Task<IActionResult> DeleteOption(Option option)
{
if(option == null) return BadRequest($"{option} is null");
var opn = await _questionService.DeleteOption(option);
if(!string.IsNullOrEmpty(opn)) return NotFound(opn);
return Ok("Successfully Deleted");
}
#endregion
#region Transactions
#endregion
}
}<file_sep>/OnlineExamApp.API/Interfaces/IScoreRepository.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Interfaces
{
public interface IScoreRepository
{
Task<IEnumerable<IScoreDto>> GetScoresCollectionByCategoryId(int categoryId);
Task<IScore> GetScoresByUserIdAndCategoryId(int userId, int categoryId);
Task<string> SaveScoreHistory(IScore score);
Task<string> UpdateScoreHistory(IScore score);
}
}<file_sep>/OnlineExamApp.API/Repository/UserScoreRepository.cs
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using Microsoft.Extensions.Logging;
namespace OnlineExamApp.API.Repository
{
public class UserScoreRepository : IUserScoreRepository
{
private readonly DataContext _dataContext;
private readonly ILogger<UserScore> _logger;
public UserScoreRepository(DataContext dataContext, ILogger<UserScore> logger)
{
this._dataContext = dataContext;
this._logger = logger;
}
public async Task<IEnumerable<IUserScore>> GetUserScoresByUserId(int userId)
{
var userScore = new List<UserScore>();
try{
userScore = await this._dataContext.UserScores
.Where(p=>p.UserId.Equals(userId))
.OrderByDescending(p => p.CategoryId).ToListAsync();
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return userScore;
}
public async Task<IEnumerable<IUserScore>> GetUserScoresByUserIdAndCategoryId(int userId, int categoryId)
{
var userScore = new List<UserScore>();
try{
userScore = await this._dataContext.UserScores
.Where(p=>p.UserId.Equals(userId) && p.CategoryId.Equals(categoryId))
.OrderByDescending(p => p.CategoryId).ToListAsync();
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return userScore;
}
public async Task<IEnumerable<IUserScore>> GetUserScoresByCategoryId(int categoryId)
{
if(categoryId <= 0) throw new ArgumentNullException(nameof(categoryId));
var userscores = new List<UserScore>();
try{
userscores = await this._dataContext.UserScores
.Where(p=>p.CategoryId.Equals(categoryId))
.OrderByDescending(p => p.CategoryId).ToListAsync();
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return userscores;
}
public async Task<string> SaveUserScore(IUserScore userScore)
{
if (userScore == null) throw new ArgumentNullException(nameof(userScore));
string result = string.Empty;
var newUserScore = new UserScore{
UserId = userScore.UserId,
Score = userScore.Score,
CategoryId = userScore.CategoryId,
DateCreated = DateTime.UtcNow,
DateTaken = DateTime.Now,
};
try
{
await this._dataContext.UserScores.AddAsync(newUserScore);
await this._dataContext.SaveChangesAsync();
}
catch (Exception e)
{
_logger.LogError(e.Message);
result = $"{e.Message}";
}
return result;
}
}
}<file_sep>/OnlineExamApp.API/Dto/answeredQuestionString.cs
using System.IO;
namespace OnlineExamApp.API.Dto
{
public static class answeredQuestionString
{
public static string anweredQuestion = File.ReadAllText("Dto/answeredQuestion.json");
}
}<file_sep>/OnlineExamApp.API/Repository/OptionRepository.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Repository
{
public class OptionRepository : IOptionRepository
{
private readonly DataContext _dbContext;
private readonly ILogger<OptionRepository> _logger;
public OptionRepository(DataContext dbContext, ILogger<OptionRepository> logger)
{
this._dbContext = dbContext;
this._logger = logger;
}
public async Task<IEnumerable<IOption>> GetOptionsByQuestionId(int questionId)
{
var options = new List<Option>();
try
{
options = await this._dbContext.Options.Where(p=>p.QuestionId.Equals(questionId)).ToListAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return options;
}
public async Task<IEnumerable<IOption>> GetCorrectOptionByQuestionId(int questionId)
{
var result = new List<Option>();
try
{
result = await (from d in _dbContext.Options
where d.QuestionId.Equals(questionId) && d.IsCorrect.Equals(true)
select new Model.Option{
QuestionId = d.QuestionId,
OptionId = d.OptionId,
OptionName = d.OptionName,
DateCreated = d.DateCreated,
//DateModified = d.DateModified,
IsCorrect = d.IsCorrect
}).OrderByDescending(p=>p.QuestionId).ToListAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
public async Task<IOption> SaveQuestionOption(IOption option)
{
if(option == null) throw new ArgumentNullException(nameof(option));
try
{
await this._dbContext.Options.AddAsync(option as Option);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return option;
}
public async Task<IOption> AddOption(IOption option)
{
if(option == null) throw new ArgumentNullException(nameof(option));
try
{
await _dbContext.Options.AddAsync(option as Option);
await _dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return option;
}
public async Task<IOption> UpdateOption(IOption option)
{
if(option == null) throw new ArgumentNullException(nameof(option));
try
{
_dbContext.Options.Update(option as Option);
await _dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return option;
}
public async Task<IOption> DeleteOption(IOption option)
{
if(option == null) throw new ArgumentNullException(nameof(option));
try
{
_dbContext.Options.Remove(option as Option);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return option;
}
}
}<file_sep>/OnlineExamApp-SPA/src/app/services/Auth.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {map} from 'rxjs/operators';
import {BehaviorSubject} from 'rxjs';
import {JwtHelperService} from '@auth0/angular-jwt';
import { Progress, BarChart } from '../layout/QuestionModel';
@Injectable({
providedIn: 'root'
})
export class AuthService {
decodedToken: any;
decodedTokenName: any;
userPic: any;
barChartData: any[];
barData: BarChart;
pic: any = '../../assets/web/images/user.png';
result: any;
trials = new BehaviorSubject<string>('0');
currentTrials = this.trials.asObservable();
jwtHelper = new JwtHelperService();
Gender: any;
value: BarChart[];
// URL = 'http://localhost:5000/api/';
// prodUrl = 'http://adeola-001-site1.atempurl.com/api/';
prodUrl = 'http://bomanaziba-001-site1.dtempurl.com/';
httpClient: any;
constructor(private http: HttpClient, ) { }
canUpdateTrials(trials: string) {
this.trials.next(trials); // the behaviour subject has a next attr which signifies the next value
}
login(model: any) {
return this.http.post(this.prodUrl + 'account/login', model)
.pipe(
map((response: any) => { // maping of the values
this.result = response;
if (this.result) {
localStorage.setItem('token', this.result.token);
this.decodedToken = this.jwtHelper.decodeToken(this.result.token); // decoding token
localStorage.setItem('userId', this.decodedToken.nameid);
localStorage.setItem('userName', this.decodedToken.unique_name);
localStorage.setItem('givenName', this.decodedToken.given_name);
localStorage.setItem('trials', this.decodedToken.primarysid);
this.canUpdateTrials( localStorage.getItem('trials'));
this.decodedTokenName = this.decodedToken.unique_name;
}
})
);
}
register(model: any) {
return this.http.post(this.prodUrl + 'account/register', model);
}
getProgress() {
const tokenId = localStorage.getItem('userId');
return this.http.get(this.prodUrl + 'user/' + tokenId);
}
loggedIn() {
const token = localStorage.getItem('token');
const tokens = this.jwtHelper.isTokenExpired(token);
if (tokens === false) {
return true;
}
return false;
}
Submit(question: any) {
const tokenId = localStorage.getItem('userId');
return this.http.post(this.prodUrl + 'question/' + tokenId + '/submitTest', question).pipe(
map((response: any) => {
this.result = response;
localStorage.setItem('result', this.result);
}));
}
GetProgress(categoryId: any) {
const tokenId = localStorage.getItem('userId');
return this.http.get(this.prodUrl + 'user/' + tokenId + '/' + categoryId.category);
}
roleMatch(allowedRoles): boolean {
let isMatch = false;
const userRoles = this.decodedToken.role as Array<string>;
allowedRoles.forEach(element => {
if (userRoles.includes(element)) {
isMatch = true;
}
});
return isMatch;
}
}
<file_sep>/OnlineExamApp.API/Model/Photo.cs
using System;
using System.Collections.Generic;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class Photo : IPhoto
{
public int Id { get; set; }
public string Url { get; set; }
public DateTime DateAdded { get; set; }
public string Description { get; set; }
}
}<file_sep>/OnlineExamApp.API/Model/Question.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class Question : IQuestion
{
public int QuestionId { get; set; }
public string Questions { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public int CategoryId { get; set; }
}
}<file_sep>/OnlineExamApp.API/Dto/UserScoreForDisplayDto.cs
using System.Collections.Generic;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class UserScoreForDisplayDto : IUserScoreForDisplayDto
{
public int UserId { get; set; }
public IList<ICategoryScore> CategoryScoreCollection { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IUser.cs
using System;
using System.Collections.Generic;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IUser
{
DateTime DateOfBirth { get; set; }
DateTime Created { get; set; }
int Trials { get; set; }
string Password { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
ICollection<UserRole> UserRoles { get; set; }
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/charts/charts.component.ts
import { Component, OnInit } from '@angular/core';
import { routerTransition } from '../../router.animations';
import { AuthService } from 'src/app/services/Auth.service';
import { Progress , BarChart} from '../QuestionModel';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-charts',
templateUrl: './charts.component.html',
styleUrls: ['./charts.component.scss'],
animations: [routerTransition()]
})
export class ChartsComponent implements OnInit {
constructor(private authService: AuthService, private route: ActivatedRoute) {
}
loader = true;
progress: Progress;
response: any;
char: any = [];
categoryList: [] = [];
progressParams: any = {};
isShowChart: any = false;
// bar chart
public barChartOptions: any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartType: string;
public barChartLegend: boolean;
barChartData: any[] = [
];
public randomize(): void {
const data = [
Math.round(Math.random() * 100),
59,
80,
Math.random() * 100,
56,
Math.random() * 100,
40
];
const clone = JSON.parse(JSON.stringify(this.barChartData));
clone[0].data = data;
this.barChartData = clone;
/**
* (My guess), for Angular to recognize the change in the dataset
* it has to change the dataset variable directly,
* so one way around it, is to clone the data, change it and then
* assign it;
*/
}
submitCategory() {
this.barChartData = [];
this.char = [];
this.authService.GetProgress(this.progressParams).subscribe((data: any) => {
console.log(data);
this.barChartData = data;
this.char.push(data.userAverageScore);
this.char.push(data.overallAverageScore);
this.barChartData = this.char;
this.isShowChart = true;
});
}
// events
public chartClicked(e: any): void {
}
public chartHovered(e: any): void {
}
ngOnInit() {
this.isShowChart = false;
this.barChartType = 'bar';
this.barChartLegend = true;
this.route.data.subscribe((data: any) => {
this.loader = true;
setTimeout(() => {
this.categoryList = JSON.parse(localStorage.getItem('categories'));
this.loader = false;
}, 3000);
});
}
}
<file_sep>/OnlineExamApp-SPA/src/app/_directives/role.directive.ts
import { Directive, Input, ViewContainerRef, TemplateRef } from '@angular/core';
import { AuthService } from '../services/Auth.service';
@Directive({
selector: '[appRole]'
})
export class RoleDirective {
@Input() appRole: string[];
isVisible = false;
constructor(private viewContaierRef: ViewContainerRef, private templateRef: TemplateRef<any>, private authService: AuthService) { }
ngInit() {
const userRoles = this.authService.decodedToken.role as Array<string>;
if (!userRoles) {
this.viewContaierRef.clear();
}
if (this.authService.roleMatch(this.appRole)) {
if (!this.isVisible) {
this.isVisible = true;
this.viewContaierRef.createEmbeddedView(this.templateRef);
} else {
this.isVisible = false;
this.viewContaierRef.clear();
}
}
}
}
<file_sep>/OnlineExamApp.API/Interfaces/IUserScore.cs
using System;
namespace OnlineExamApp.API.Interfaces
{
public interface IUserScore
{
int UserScoreId { get; set; }
int UserId { get; set; }
decimal Score { get; set; }
int CategoryId { get; set; }
DateTime DateCreated { get; set; }
DateTime DateTaken { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IProcessAnswerReturnDto.cs
using System.Collections.Generic;
using OnlineExamApp.API.Dto;
namespace OnlineExamApp.API.Interfaces
{
public interface IProcessAnswerReturnDto
{
decimal Score { get; set; }
decimal HighestScore { get; set; }
IList<IScoreDto> ScoreBoardCollection { get; set; }
int Trials { get; set; }
int Position { get; set; }
int NoOfParticipant { get; set; }
string ReturnMessage { get; set; }
}
}<file_sep>/OnlineExamApp.API/Model/QuestionExtract.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace OnlineExamApp.API.Model
{
#region
public class QuestionObject
{
public string Question { get; set; }
public int No { get; set; }
public List<OptionObject> Options { get; set; }
public Guid PictureId { get; set; }
public bool isQuestionValid
{
get
{
if(!string.IsNullOrEmpty(Question) && Options != null && Options.Any() && Options.Count() == 4)
{
return true;
}
return false;
}
}
}
public class OptionObject
{
public char Num { get; set; }
public string Option { get; set; }
public bool isCorrect { get; set; }
}
#endregion
}<file_sep>/OnlineExamApp.API/Model/Settings.cs
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class Setting : ISetting
{
public int Id { get; set; }
public string Key { get; set; }
public string Value { get; set;}
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/services/loader.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class LoaderService {
public status: BehaviorSubject<number> = new BehaviorSubject<number>(0);
cast = this.status.asObservable();
display(value: number) {
this.status.next(value);
}
}
<file_sep>/OnlineExamApp.API/Dto/QuestionRipperResponse.cs
using System.Collections.Generic;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Dto
{
public class QuestionRipperResponse
{
public List<QuestionObject> Questions { get; set; }
public string ResponseCode { get; set; }
public string ResponseDescription { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IQuestionForDisplay.cs
using System.Collections.Generic;
namespace OnlineExamApp.API.Interfaces
{
public interface IQuestionForDisplay
{
int QuestionId { get; set;}
string Questions { get; set; }
int CategoryId { get; set; }
IEnumerable<IOptionsForDisplay> Options { get; set; }
}
}<file_sep>/OnlineExamApp.API/Repository/UserRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Repository
{
public class UserRepository : IUserRepository
{
private readonly ILogger<UserRepository> _logger;
private readonly UserManager<User> _userManager;
public UserRepository(ILogger<UserRepository> logger, UserManager<User> userManager)
{
_logger = logger;
_userManager = userManager;
}
public async Task<IUser> GetUserById(int userId)
{
_logger.LogDebug($"Getting {typeof(User).FullName} with id {userId}");
if (userId <= 0) throw new ArgumentNullException(nameof(userId));
var user = new User();
try
{
user = await _userManager.FindByIdAsync(userId.ToString());
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return user;
}
public async Task<string> Activate(IUser user)
{
string result = string.Empty;
try
{
var response = await _userManager.SetLockoutEnabledAsync(user as User, false);
if (!response.Succeeded)
{
return $"Unable to unlock {user.FirstName}, Error: {response.Errors.FirstOrDefault().Description}";
}
}
catch (Exception e)
{
_logger.LogError(e.Message);
result = e.Message;
}
return result;
}
public async Task<string> RemoveUser(IUser user)
{
_logger.LogDebug($"Deleting {user.FirstName}");
if (user == null) return "User is null";
string result = string.Empty;
try
{
var response = await _userManager.DeleteAsync(user as User);
if (!response.Succeeded) return $"Unable to remove {user.FirstName}";
}
catch (Exception e)
{
_logger.LogError(e.Message);
result = e.Message;
}
return result;
}
public async Task<string> DeactivateUser(IUser user, int days = 30)
{
string result = string.Empty;
var userModel = (User)user;
try
{
await _userManager.SetLockoutEnabledAsync(userModel, true);
await _userManager.SetLockoutEndDateAsync(user as User, DateTime.Today.AddDays(days));
}
catch (Exception e)
{
_logger.LogError(e.Message);
result = e.Message;
}
return result;
}
public async Task<string> AddUser(IUser user)
{
_logger.LogDebug($"Adding {user.FirstName}");
if (user == null) return "User is null";
string result = string.Empty;
try
{
var response = await _userManager.CreateAsync(user as User);
if (!response.Succeeded) return $"Unable to add {user.FirstName}";
_logger.LogDebug($"Adding {user.FirstName} was successful");
}
catch (Exception e)
{
_logger.LogError(e.Message);
result = e.Message;
}
return result;
}
public async Task<string> EditUser(IUser user)
{
_logger.LogDebug($"Editing {user.FirstName}");
if (user == null) return "User is null";
string result = string.Empty;
try
{
var response = await _userManager.UpdateAsync(user as User);
if (!response.Succeeded) return $"Unable to remove {user.FirstName}";
_logger.LogDebug($"Editing {user.FirstName} was successful");
}
catch (Exception e)
{
_logger.LogError(e.Message);
result = e.Message;
}
return result;
}
public async Task<IList<User>> Users()
{
_logger.LogDebug($"Gatting all {typeof(User).FullName} out");
var users = new List<User>();
try
{
users = this._userManager.Users.ToList();
_logger.LogDebug($"Getting all {typeof(User).FullName} was successful");
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return users;
}
public async Task<string> AddUserToRole(User user, string role)
{
string result = string.Empty;
var response = await _userManager.AddToRoleAsync(user, role);
if(!response.Succeeded) return $"Adding {user.UserName} to {role} was not successful: Error {response.Errors.SingleOrDefault().ToString()}";
return result;
}
public async Task<string> RemoveUserFromRole(User user, string role)
{
string result = string.Empty;;
var response = await _userManager.RemoveFromRoleAsync(user, role);
if(!response.Succeeded) return $"Removing {user.UserName} to {role} was not successful: Error {response.Errors.SingleOrDefault().ToString()}";
return result;
}
public async Task<IList<string>> UserToRole(User user)
{
var response = await _userManager.GetRolesAsync(user);
return response;
}
}
}<file_sep>/OnlineExamApp-SPA/src/app/app.module.ts
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LanguageTranslationModule } from './shared/modules/language-translation/language-translation.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthGuard } from './shared';
import { CookieService } from 'ngx-cookie-service';
import { AlertifyService } from './services/AlertifyService';
import { ErrorInterceptorProvider } from './services/error.Interceptor';
import { RoleDirective } from './_directives/role.directive';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { SignupComponent } from './signup/signup.component';
import { NavComponent } from './nav/nav.component';
@NgModule({
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
LanguageTranslationModule,
AppRoutingModule,
ReactiveFormsModule,
FormsModule
],
declarations: [
AppComponent,
LoginComponent,
SignupComponent,
HomeComponent,
NavComponent
],
providers: [
AuthGuard,
CookieService,
AlertifyService,
ErrorInterceptorProvider,
RoleDirective
],
bootstrap: [
AppComponent
]
})
export class AppModule {}
<file_sep>/OnlineExamApp.API/Interfaces/ICategoryService.cs
namespace OnlineExamApp.API.Interfaces
{
public interface ICategoryService
{
}
}<file_sep>/OnlineExamApp.API/Controllers/UserController.cs
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
this._userService = userService;
}
[HttpGet("{userId}/{categoryId}")]
public async Task<IActionResult> GetUserScore(int userId, int categoryId)
{
// if (userId != int.Parse (User.FindFirst(ClaimTypes.NameIdentifier).Value))
// return Unauthorized ();
if(categoryId <= 0) throw new ArgumentNullException(nameof(categoryId));
var model = await this._userService.GetUserPerformanceByCatetgory(userId, categoryId);
if(model != null)
{
return Ok(model);
}
return NoContent();
}
#region User CRUD
[HttpGet]
public async Task<IActionResult> List()
{
var settings = await _userService.Users();
return Ok(settings);
}
[HttpGet("{userId}")]
public async Task<IActionResult> Get(int userId)
{
if(userId <= 0) return BadRequest($"{userId} is less than one");
var model = await this._userService.GetUserById(userId);
if(model == null)
{
return NotFound($"No User found with {userId}");
}
return Ok(model);
}
[HttpPost("add")]
public async Task<IActionResult> AddUser([FromBody]User user)
{
if(user == null) return BadRequest($"User is null");
var userResponse = await _userService.AddUser(user);
if(!string.IsNullOrEmpty(userResponse)) return NotFound(userResponse);
return Created("user/add" ,user);
}
[HttpPost("edit")]
public async Task<IActionResult> EditSettings([FromBody]User user)
{
if(user == null) return BadRequest($"User is null");
var userResponse = await _userService.EditUser(user);
if(!string.IsNullOrEmpty(userResponse)) return NotFound(userResponse);
return Ok($"Successfully edited {user.LastName}");
}
[HttpPost("deactivate")]
public async Task<IActionResult> Deactivate([FromBody]User user)
{
if(user == null) return BadRequest($"User is null");
var userResponse = await _userService.Deactivate(user);
if(!string.IsNullOrEmpty(userResponse)) return NotFound(userResponse);
return Ok($"Successfully deactivated {user.LastName}");
}
[HttpPost("activate")]
public async Task<IActionResult> Activate([FromBody]User user)
{
if(user == null) return BadRequest($"User is null");
var userResponse = await _userService.Activate(user);
if(!string.IsNullOrEmpty(userResponse)) return NotFound(userResponse);
return Ok($"Successfully activated {user.LastName}");
}
[HttpPost("delete")]
public async Task<IActionResult> DeleteUser([FromBody]User user)
{
if(user == null) return BadRequest($"User is null");
var userResponse = await _userService.RemoveUser(user);
if(!string.IsNullOrEmpty(userResponse)) return NotFound(userResponse);
return Ok($"Successfully deleted {user.LastName}");
}
#endregion
#region User Roles
[HttpGet("roles")]
public async Task<IActionResult> UserRoles([FromBody]User user)
{
if(user == null) return BadRequest("User is null");
var stg = await _userService.UserToRole(user);
return Ok(stg);
}
[HttpPost("role/add")]
public async Task<IActionResult> AddToRole([FromBody]UserRoleDto userRole)
{
if(userRole == null) return BadRequest("Request is null");
if(userRole.User == null) return BadRequest("User is null");
if(string.IsNullOrEmpty(userRole.Role)) return BadRequest("Role is null");
var stg = await _userService.AddUserToRole(userRole.User, userRole.Role);
if(!string.IsNullOrEmpty(stg)) return NotFound(stg);
return Ok($"Successfully add {userRole.User.FirstName} from {userRole.Role}");
}
[HttpPost("role/remove")]
public async Task<IActionResult> RemoveFromRole([FromBody]UserRoleDto userRole)
{
if(userRole == null) return BadRequest("Request is null");
if(userRole.User == null) return BadRequest("User is null");
if(string.IsNullOrEmpty(userRole.Role)) return BadRequest("Role is null");
var stg = await _userService.RemoveUserFromRole(userRole.User, userRole.Role);
if(!string.IsNullOrEmpty(stg)) return NotFound(stg);
return Ok($"Successfully removes {userRole.User.FirstName} from {userRole.Role}");
}
#endregion
}
}<file_sep>/OnlineExamApp.API/Model/User.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class User : IdentityUser<int>, IUser
{
public DateTime DateOfBirth { get; set; }
public DateTime Created { get; set; }
public string Password { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public int Trials { get; set; }
public ICollection<UserRole> UserRoles { get; set; }
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/result/result.component.html
<ng-container [ngSwitch]="true">
<div *ngSwitchCase="loader === true" class="col-12" style="text-align: center;">
<img src="../../assets/img-loader.gif">
</div>
<div *ngSwitchCase="loader === false">
<div *ngSwitchCase="loader === false" class="card text-white bg-success mb-3">
<div class="card-header">
Score
<img src="./../../../assets/images/check.png" width="30" />
</div>
<div class="card-body">
<h5 class="card-title">Success card title</h5>
<p class="card-text">
You had {{result}} marks, you can do better
</p>
</div>
</div>
<div class="jumbotron jumbotron-fluid alert-success">
<div class="container text-center">
<h1 class="display-4">Hi, {{name}}</h1>
<h5 class="display-4"><strong>We are working greatly to fix this page</strong></h5>
<p class="lead">
This page will display your score
</p>
</div>
</div>
</div>
</ng-container>
<file_sep>/OnlineExamApp.API/Dto/UserForRegisterDto.cs
using System;
using System.ComponentModel.DataAnnotations;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class UserForRegisterDto
{
public UserForRegisterDto()
{
DateCreated = DateTime.UtcNow;
}
[Required(ErrorMessage="Username is required")]
public string Username { get; set; }
[Required(ErrorMessage="Email is required")]
public string Email { get; set; }
[Required(ErrorMessage="Last Name is required")]
public string LastName { get; set; }
[Required(ErrorMessage="First Name is required")]
public string FirstName { get; set; }
[Required(ErrorMessage="Password is required")]
public string Password { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateCreated { get; set;}
}
}<file_sep>/OnlineExamApp.API/Interfaces/IOption.cs
using System;
namespace OnlineExamApp.API.Interfaces
{
public interface IOption
{
int OptionId { get; set; }
string OptionName { get; set; }
bool IsCorrect { get; set; }
int QuestionId { get; set; }
DateTime DateCreated { get; set; }
DateTime? DateModified { get; set; }
}
}<file_sep>/OnlineExamApp.API/Model/Category.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class Category : ICategory
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string CategoryDescription { get; set; }
public int Duration { get; set; }
public int NumberofQueston { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
[JsonIgnore]
public int PhotoId { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IUserForRegisterDto.cs
using System;
namespace OnlineExamApp.API.Interfaces
{
public interface IUserForRegisterDto
{
string Username { get; set; }
string Email { get; set; }
string LastName { get; set; }
string FirstName { get; set; }
string Password { get; set; }
DateTime DateOfBirth { get; set; }
}
}<file_sep>/OnlineExamApp.API/Repository/SystemSettingsRepository..cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Repository
{
public class SystemSettingRepository : ISystemSettingRepository
{
private readonly DataContext _dbContext;
private readonly ILogger<SystemSettingRepository> _logger;
public SystemSettingRepository(DataContext dbContext, ILogger<SystemSettingRepository> logger)
{
this._dbContext = dbContext;
this._logger = logger;
}
public async Task<IList<Setting>> GetSettings()
{
var settings = new List<Setting>();
try
{
settings = this._dbContext.Settings.ToList();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return settings;
}
public async Task<ISetting> GetSetting(int settingId)
{
if(settingId <= 0) throw new ArgumentNullException(nameof(settingId));
var setting = new Setting();
try
{
setting = await this._dbContext.Settings.FindAsync(settingId);
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return setting;
}
public async Task<ISetting> AddSetting(ISetting setting)
{
if(setting == null) throw new ArgumentNullException(nameof(setting));
try
{
await this._dbContext.Settings.AddAsync(setting as Setting);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return setting;
}
public async Task<ISetting> UpdateSetting(ISetting setting)
{
if(setting == null) throw new ArgumentNullException(nameof(setting));
try
{
this._dbContext.Settings.Update(setting as Setting);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return setting;
}
public async Task<ISetting> RemoveSetting(ISetting setting)
{
if(setting == null) throw new ArgumentNullException(nameof(setting));
try
{
this._dbContext.Settings.Remove(setting as Setting);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return setting;
}
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/question/question.component.ts
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { QuestionService } from '../services/question.service';
import { questionFromDb } from '../services/questionfromServer';
import { Question, Options, Answer } from '../QuestionModel';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from 'src/app/services/Auth.service';
@Component({
selector: 'app-question',
templateUrl: './question.component.html',
styleUrls: ['./question.component.scss']
})
export class QuestionComponent implements OnInit {
questionList = [];
isLoad = true;
categoryId: number;
updateRadioSel: Options;
questionArray: Question[];
radioSelectedString: string;
questionNumber: number;
materialExampleRadios: any = {};
radioSelected: any = {};
answerInfo: any = {};
answerArray: any = [];
currentQuestion: Question;
allQuestion: any = {};
questionFromService: any = {};
question: any = {};
radioSel: any;
gender: any = {};
questionId: number;
// options: any = [];
optionId: number;
answered: any = {};
showLoader = true;
constructor(private cookie: CookieService,
private route: ActivatedRoute, private router: Router , private questionService: QuestionService, private authService: AuthService) {
}
radioModel: any;
ngOnInit() {
setTimeout(() => {
this.showLoader = false;
}, 4000);
this.route.data.subscribe((data: any) => {
this.authService.canUpdateTrials(data.question.trials);
localStorage.setItem('trials', data.question.trials);
this.getQuestion(data.question.questionsCollections);
});
this.questionService.seconds = 1000;
this.setTimer();
this.radioSelected = 'Lamba1';
}
setTimer() {
this.questionService.timer = setInterval(() => {
this.questionService.seconds--;
if (this.questionService.seconds === 0) {
this.submitQuestion();
}
}, 1000); // the function will be called after a second
}
selectedOption(value: any, QId: number) {
console.log(value, QId);
const question = this.allQuestion.find(x => x.questionId === QId);
question.selectedAnswer = value;
try {
const values = question.options.find(x => x.checked === true);
values.checked = false;
const newValues = question.options.find(x => x.optionId === value);
newValues.checked = true;
values.selectedAnswer = newValues.optionId;
} catch (e) {
const newValues = question.options.find(x => x.optionId === value);
newValues.checked = true;
this.radioSelected = newValues.optionName;
}
}
getSelecteditem(QId: any, optionId: number) {
try {
this.currentQuestion = this.allQuestion.find(x => x.questionNumber === QId);
this.radioSel = this.currentQuestion.options.find(Item => Item.checked === true);
this.radioSel.checked = false;
this.updateRadioSel = this.currentQuestion.options.find(x => x.optionId === optionId);
this.updateRadioSel.checked = true;
this.radioSelected = this.updateRadioSel.optionName;
} catch {
this.currentQuestion = this.allQuestion.find(x => x.questionNumber === QId);
this.updateRadioSel = this.currentQuestion.options.find(x => x.optionId === optionId);
this.updateRadioSel.checked = true;
this.radioSelected = this.updateRadioSel.optionName;
}
this.currentQuestion.selectedAnswer = optionId;
}
goTo(QId: any) {
try {
this.currentQuestion = this.allQuestion.find(x => x.questionNumber === QId);
this.updateRadioSel = this.currentQuestion.options.find(x => x.checked === true);
this.radioSelected = this.updateRadioSel.optionName;
} catch (e) {
}
}
getQuestion(question: Question[]) {
this.questionArray = question;
this.questionNumber = 1;
for (let i = 0; i < this.questionArray.length; i++) {
this.questionArray[i].questionNumber = this.questionNumber;
this.questionArray[i].selectedAnswer = 0;
this.questionNumber++;
}
this.currentQuestion = this.questionArray[0];
this.allQuestion = this.questionArray;
}
submitQuestion() {
for (let i = 0; i < this.allQuestion.length; i++) {
const joko = this.allQuestion[i].questionId;
this.questionId = this.allQuestion[i].questionId;
this.optionId = this.allQuestion[i].selectedAnswer;
this.categoryId = this.allQuestion[i].categoryId;
this.answered.questionId = this.questionId;
this.answered.optionId = this.optionId;
this.answered.categoryId = this.categoryId;
this.answerArray.push(this.answered);
this.answered = {};
}
console.log(this.answerArray);
this.questionService.Submit(this.answerArray).subscribe((data: any) => {
}, error => {
}, () => {
this.router.navigate(['/result']);
});
}
}
<file_sep>/OnlineExamApp.API/Controllers/FallBackController.cs
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using OnlineExamApp.API.Dto;
using System;
using OnlineExamApp.API.Interfaces;
using System.Security.Claims;
using System.IO;
namespace OnlineExamApp.API.Controllers
{
public class FallBackController : Controller
{
public IActionResult Index()
{
return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "index.html"), "text/HTML");
}
}
}<file_sep>/OnlineExamApp.API/Dto/PerformanceDisplayDto.cs
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class PerformanceDisplayDto : IPerformanceDisplayDto
{
public IChat UserAverageScore { get; set; }
public IChat OverallAverageScore { get; set; }
}
}<file_sep>/OnlineExamApp.API/Repository/UserRoleRepository.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Repository
{
public class UserRoleRepository : IUserRoleRepository
{
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/question/question.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { QuestionComponent } from './question.component';
import { QuestionRoutingModule } from './question-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { QuestionService } from '../services/question.service';
import { JwtModule } from '@auth0/angular-jwt';
import { QuestionResolver } from 'src/app/resolver/question-resolver';
export function TokenGetter() {
return localStorage.getItem('token'); // this is the token
}
@NgModule({
imports: [
CommonModule,
QuestionRoutingModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: TokenGetter
,
whitelistedDomains: ['adeola-001-site1.atempurl.com'], // we just got the token from (Token Getter function above) and we send request ,
// it is automatically sending token
blacklistedRoutes: ['adeola-001-site1.atempurl.com/api/account'] // we dont want
// to send token to this address
}
})
],
declarations: [QuestionComponent],
providers: [QuestionService, QuestionResolver]
})
export class QuestionModule { }
<file_sep>/OnlineExamApp.API/Model/Score.cs
using System;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class Score : IScore
{
public int ScoreId { get; set; }
public decimal Value { get; set; }
public int UserId { get; set; }
public int CategoryId { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IPhoto.cs
using System;
using System.Collections.Generic;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IPhoto
{
int Id { get; set; }
string Url { get; set; }
DateTime DateAdded { get; set; }
string Description { get; set; }
}
}<file_sep>/OnlineExamApp-SPA/src/app/resolver/progress-list.resolver.ts
import { Injectable } from '@angular/core';
import { Category, Question, Progress } from '../../app/layout/QuestionModel';
import { Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
import { QuestionService } from '../../app/layout/services/question.service';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthService } from '../services/Auth.service';
@Injectable()
export class ProgressResolver implements Resolve<Progress> {
constructor(private questionService: QuestionService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot): Observable<Progress> {
return this.questionService.getCategories().pipe(
catchError(error => {
this.router.navigate(['/dashboard']);
return of(null);
}
)
);
}
}
<file_sep>/OnlineExamApp-SPA/src/app/layout/QuestionModel.ts
import { DecimalPipe } from '@angular/common';
export interface Question {
questionId: number;
question: string;
options: Options[];
questionNumber: number;
selectedAnswer: number;
categoryId: number;
}
export interface Options {
optionId: number;
optionName: string;
optionNumber: string;
optionlabel: string;
isAvaialable: boolean;
checked: boolean;
}
export interface Category {
categoryId: number;
categoryName: string;
duration: number;
}
export interface Answer {
questionId: number;
optionId: number;
}
export interface Result {
result: number;
}
export interface CategoryScoreCollection {
categoryName: string;
percentageAverageScore: number;
}
export interface Progress {
categoryName: any;
percentageAverageScore: number;
}
export class BarChart {
label: string;
data: number[];
}
<file_sep>/OnlineExamApp.API/Interfaces/IDigitalFileRepository.cs
using System.Threading.Tasks;
namespace OnlineExamApp.API.Interfaces
{
public interface IDigitalFileRepository
{
Task<IPhoto> GetPhotoById(int photoId);
}
}<file_sep>/OnlineExamApp.API/Dto/CategoryForDisplayDto.cs
using System;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class CategoryForDisplayDto : ICategoryForDisplayDto
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string CategoryDescription { get; set; }
public int Duration { get; set; }
public int NumberofQueston { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public int PhotoId { get; set; }
public string PhotoUrl { get; set; }
}
}<file_sep>/OnlineExamApp.API/Dto/QuestionForDisplay.cs
using System.Collections.Generic;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class QuestionForDisplay : IQuestionForDisplay
{
public int QuestionId { get; set;}
public string Questions { get; set; }
public int CategoryId { get; set; }
public IEnumerable<IOptionsForDisplay> Options { get; set; }
}
}<file_sep>/OnlineExamApp.API/Service/UserRoleService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Service
{
public class UserRoleService : IUserRoleService
{
}
}<file_sep>/OnlineExamApp.API/Dto/UserRoleDto.cs
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Dto
{
public class UserRoleDto
{
public User User { get; set; }
public string Role { get; set; }
}
}<file_sep>/OnlineExamApp.API/Dto/ChangePasswordDto.cs
using System.ComponentModel.DataAnnotations;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class ChangePasswordDto : IChangePasswordDto
{
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Token is required")]
public string Token { get; set; }
[Required(ErrorMessage = "Password is required")]
public string NewPassword { get; set; }
}
}<file_sep>/OnlineExamApp.API/Interfaces/IAppSettingsService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IAppSettingsService
{
Task<string> BaseUrl { get; }
Task<string> SendGridAPIKey { get; }
Task<string> AdminEmail { get; }
Task<string> AdminName { get; }
Task<string> DeactivateDay { get; }
Task<string> QuestionRipperUrl { get; }
Task<string> TerminalId { get; }
Task<IList<Setting>> GetSettings();
Task<ISetting> GetSetting(int settingId);
Task<string> AddSetting(ISetting setting);
Task<string> EditSetting(ISetting setting);
Task<string> RemoveSetting(ISetting setting);
}
}<file_sep>/OnlineExamApp.API/Controllers/QuestionController.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OnlineExamApp.API.Interfaces;
using System.Security.Claims;
using Newtonsoft.Json;
using OnlineExamApp.API.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.IO;
namespace OnlineExamApp.API.Controllers
{
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class QuestionController : ControllerBase
{
private readonly IQuestionService questionService;
public QuestionController(IQuestionService questionService)
{
this.questionService = questionService;
}
[HttpGet()]
public async Task<IActionResult> GetCategories()
{
var model = await this.questionService.GetCategories();
return Ok(model);
}
[HttpGet("{userId}/{categoryId}")]
public async Task<IActionResult> GetQuestions(int userId, int categoryId)
{
if(userId <= 0) throw new ArgumentNullException(nameof(userId));
if (userId != int.Parse (User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized ();
if(categoryId <= 0) throw new ArgumentNullException(nameof(categoryId));
var model = await this.questionService.GetQuestionListForDislay(userId, categoryId);
return Ok(model);
}
[HttpPost("{userId}/submitTest")]
public async Task<IActionResult> SubmitTest(int userId, List<AnweredQuestionDto> anweredQuestion )
{
if(userId <= 0) throw new ArgumentNullException(nameof(userId));
if (userId != int.Parse (User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized ();
var model = await this.questionService.ProcessAnweredQuestions(userId, anweredQuestion);
return Ok(model);
}
}
}<file_sep>/OnlineExamApp.API/Model/Transaction.cs
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Model
{
public class Transaction : ITransaction
{
}
}<file_sep>/OnlineExamApp.API/Repository/QuestionRepository.cs
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Repository
{
public class QuestionRepository : IQuestionRepository
{
private readonly DataContext _dbContext;
private readonly ILogger<QuestionRepository> _logger;
public QuestionRepository(DataContext dbContext, ILogger<QuestionRepository> logger)
{
this._dbContext = dbContext;
this._logger = logger;
}
public async Task<IQuestion> AddQuestion(IQuestion question)
{
if (question == null) throw new ArgumentNullException(nameof(question));
try
{
await this._dbContext.Questions.AddAsync(question as Question);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return question;
}
public async Task<IEnumerable<IQuestion>> GetQuestionsByCaregoryId(int categoryId)
{
var result = new List<Question>();
try
{
result = await this._dbContext.Questions.Where(p=>p.CategoryId.Equals(categoryId)).ToListAsync();
return result;
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return result;
}
public async Task<IQuestion> RemoveQuestion(IQuestion question)
{
if (question == null) throw new ArgumentNullException(nameof(question));
try
{
this._dbContext.Questions.Remove(question as Question);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return question;
}
public async Task<IQuestion> SaveQuestion(IQuestion question)
{
if (question == null) throw new ArgumentNullException(nameof(question));
try
{
await this._dbContext.Questions.AddAsync(question as Question);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return question;
}
public async Task<IQuestion> UpdateQuestion(IQuestion question)
{
if (question == null) throw new ArgumentNullException(nameof(question));
try
{
this._dbContext.Questions.Update(question as Question);
await this._dbContext.SaveChangesAsync();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return question;
}
}
}
<file_sep>/OnlineExamApp.API/Dto/QuestionOptionDto.cs
using System.Collections.Generic;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class QuestionOptionDto
{
public IQuestion Question { get; set; }
public IList<IOption> Options { get; set; }
}
}<file_sep>/OnlineExamApp.API/Service/RoleService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Service
{
public class RoleService : IRoleService
{
private readonly IRoleRepository _roleRepository;
public RoleService(IRoleRepository roleRepository)
{
this._roleRepository = roleRepository;
}
public async Task<IList<Role>> Roles()
{
var result = await _roleRepository.Roles();
return result;
}
public async Task<Role> GetRole(int id)
{
if(id <= 0) throw new ArgumentNullException(nameof(id));
var role = await _roleRepository.GetRole(id);
return role;
}
public async Task<string> AddRole(Role role)
{
string result = string.Empty;
if(role == null) return "Role is null";
var response = await _roleRepository.AddRole(role);
if(response == null) return $"Request not successfull";
return result;
}
public async Task<string> EditRole(Role role)
{
string result = string.Empty;
if(role == null) return "Role is null";
var response = await _roleRepository.EditRole(role);
if(response == null) return $"Request not successfull";
return result;
}
public async Task<string> RemoveRole(Role role)
{
string result = string.Empty;
if(role == null) return "Role is null";
var response = await _roleRepository.RemoveRole(role);
if(response == null) return $"Request not successfull";
return result;
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/ITransaction.cs
namespace OnlineExamApp.API.Interfaces
{
public interface ITransaction
{
}
}<file_sep>/OnlineExamApp.API/Interfaces/ICategoryForDisplayDto.cs
using System;
namespace OnlineExamApp.API.Interfaces
{
public interface ICategoryForDisplayDto
{
int CategoryId { get; set; }
string CategoryName { get; set; }
string CategoryDescription { get; set; }
int Duration { get; set; }
int NumberofQueston { get; set; }
DateTime DateCreated { get; set; }
DateTime? DateModified { get; set; }
int PhotoId { get; set; }
string PhotoUrl { get; set; }
}
}<file_sep>/OnlineExamApp.API/Service/AppSettingsService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Service
{
public class AppSettingsService : IAppSettingsService
{
private readonly ISystemSettingRepository _systemSettings;
private readonly ICacheService _cacheService;
public AppSettingsService(ISystemSettingRepository systemSettings, ICacheService cacheService)
{
_systemSettings = systemSettings;
_cacheService = cacheService;
}
public Task<string> BaseUrl => SystemSettings("BaseUrl");
public Task<string> QuestionRipperUrl => SystemSettings("QuestionRipperUrl");
public Task<string> TerminalId => SystemSettings("TerminalId");
public Task<string> SendGridAPIKey => SystemSettings("SendGridAPIKey");
public Task<string> AdminEmail => SystemSettings("AdminEmail");
public Task<string> AdminName => SystemSettings("AdminName");
public Task<string> DeactivateDay => SystemSettings("DeactivateDay");
public async Task<string> SystemSettings(string key)
{
var value = _cacheService.Get<string>($"::{key}::");
if(value == null)
{
var settings = await GetSettings();
var setting = settings.Where(p=>p.Key.Equals(key)).SingleOrDefault();
value = setting.Value;
_cacheService.Add<string>($"::{key}::", value);
}
return value;
}
#region System Settings CRUD
public async Task<IList<Setting>> GetSettings()
{
var settings = await _systemSettings.GetSettings();
return settings;
}
public async Task<ISetting> GetSetting(int settingId)
{
if(settingId <= 0) throw new ArgumentNullException(nameof(settingId));
return await _systemSettings.GetSetting(settingId);;
}
public async Task<string> AddSetting(ISetting setting)
{
string result = string.Empty;
if(setting == null) return $"Setting is null";
var stn = await _systemSettings.AddSetting(setting);
if(stn == null) return $"Request was not successful";
return result;
}
public async Task<string> EditSetting(ISetting setting)
{
string result = string.Empty;
if(setting == null) return $"Setting is null";
var stn = await _systemSettings.UpdateSetting(setting);
if(stn == null) return $"Request was not successful";
return result;
}
public async Task<string> RemoveSetting(ISetting setting)
{
string result = string.Empty;
if(setting == null) return $"Setting is null";
var stn = await _systemSettings.RemoveSetting(setting);
if(stn == null) return $"Request was not successful";
return result;
}
#endregion
}
}<file_sep>/OnlineExamApp.API/Helpers/StatisticExtensionHelpers.cs
namespace OnlineExamApp.API.Helpers
{
public static class StatisticExtensionHelpers
{
public static decimal Average(this decimal[] arr)
{
decimal sum = 0;
for(int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
return sum/arr.Length;
}
}
}<file_sep>/OnlineExamApp.API/Factory/ScoreDetailsEmail.cs
using System.Threading.Tasks;
using OnlineExamApp.API.Dto;
namespace OnlineExamApp.API.Factory
{
public class ScoreDetailsEmail : IEmailTemplate
{
public int _score { get; set; }
public async Task<EmailTemplateResponse> Template()
{
var template = new EmailTemplateResponse();
template.Subject = "TISA Score";
template.PlainTextContent = $"Your {_score}";
template.HtmlContent = $"<p>Your {_score}<p>";
return template;
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/IUserService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IUserService
{
Task<IPerformanceDisplayDto> GetUserPerformanceByCatetgory(int userId, int categoryId);
Task<IUser> GetUserById(int id);
Task<string> Activate(IUser user);
Task<string> RemoveUser(IUser user);
Task<string> Deactivate(IUser user);
Task<string> AddUser(IUser user);
Task<IList<User>> Users();
Task<string> EditUser(IUser user);
Task<IList<string>> UserToRole(User user);
Task<string> AddUserToRole(User user, string role);
Task<string> RemoveUserFromRole(User user, string role);
}
}<file_sep>/OnlineExamApp.API/Interfaces/ICategoryRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface ICategoryRepository
{
Task<ICategory> GetCateogoryByCategoryId(int categoryId);
Task<IEnumerable<ICategory>> GetCateogory();
Task<ICategory> GetCateogoryByName(string categoryName);
Task<string> SaveCategory(ICategory category);
Task<string> EditCategory(ICategory category);
Task<string> DeleteCategory(int categoryId);
}
}<file_sep>/OnlineExamApp.API/Repository/RoleRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using OnlineExamApp.API.Interfaces;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Repository
{
public class RoleRepository : IRoleRepository
{
private readonly RoleManager<Role> _role;
private readonly ILogger<RoleRepository> _logger;
public RoleRepository(RoleManager<Role> role, ILogger<RoleRepository> logger)
{
this._role = role;
this._logger = logger;
}
public async Task<Role> AddRole(Role role)
{
if(role == null) throw new ArgumentNullException(nameof(role));
try
{
await this._role.CreateAsync(role);
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return role;
}
public async Task<Role> EditRole(Role role)
{
if(role == null) throw new ArgumentNullException(nameof(role));
try
{
await this._role.UpdateAsync(role);
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return role;
}
public async Task<Role> GetRole(int id)
{
if(id <= 0) throw new ArgumentNullException(nameof(id));
Role role = null;
try
{
role = await this._role.FindByIdAsync(id.ToString());
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return role;
}
public async Task<Role> RemoveRole(Role role)
{
if(role == null) throw new ArgumentNullException(nameof(role));
try
{
await this._role.DeleteAsync(role);
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return role;
}
public async Task<IList<Role>> Roles()
{
IList<Role> roles = new List<Role>();
try
{
roles = this._role.Roles.ToList();
}
catch(Exception e)
{
_logger.LogError(e.Message);
}
return roles;
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/IUserScoreRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Interfaces
{
public interface IUserScoreRepository
{
Task<IEnumerable<IUserScore>> GetUserScoresByUserId(int userId);
Task<IEnumerable<IUserScore>> GetUserScoresByUserIdAndCategoryId(int userId, int categoryId);
Task<IEnumerable<IUserScore>> GetUserScoresByCategoryId(int categoryId);
Task<string> SaveUserScore(IUserScore userScore);
}
}<file_sep>/OnlineExamApp.API/Interfaces/IUserRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineExamApp.API.Model;
namespace OnlineExamApp.API.Interfaces
{
public interface IUserRepository
{
Task<IUser> GetUserById(int userId);
Task<string> Activate(IUser user);
Task<string> RemoveUser(IUser user);
Task<string> DeactivateUser(IUser user, int days = 30);
Task<string> AddUser(IUser user);
Task<IList<User>> Users();
Task<string> EditUser(IUser user);
Task<string> AddUserToRole(User user, string role);
Task<string> RemoveUserFromRole(User user1, string role);
Task<IList<string>> UserToRole(User user);
}
}<file_sep>/OnlineExamApp.API/Factory/AccountVerificationEmail.cs
using System.Threading.Tasks;
using OnlineExamApp.API.Dto;
using OnlineExamApp.API.Interfaces;
using Mono.Web;
namespace OnlineExamApp.API.Factory
{
public class AccountVerificationEmail : IEmailTemplate
{
public string _email { get; set; }
public string _token { get; set; }
public IAppSettingsService _appSettingsService { get; }
public AccountVerificationEmail(IAppSettingsService appSettingsService)
{
_appSettingsService = appSettingsService;
}
public async Task<EmailTemplateResponse> Template()
{
var template = new EmailTemplateResponse();
var confirmationURL = $"{await _appSettingsService.BaseUrl}/api/account/confirmemail?email={_email}&token={_token}";
template.Subject = "Activate Account";
template.PlainTextContent = "Welcome to Online Exam Platform./n Practice for your Jamb, NECO and WAEC with past questions and practice center./n You have a 3 free test trial sessions";
template.HtmlContent = $"<h3>Welcome to Online Exam Platform</h3><p>Practice for your Jamb, NECO and WAEC with past questions and practice center.</p><p>You have a 3 free test trial sessions.</p><p><a href=\"{confirmationURL}\">Click to Activate your account.</a></p>";
return template;
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/IQuestion.cs
using System;
namespace OnlineExamApp.API.Interfaces
{
public interface IQuestion
{
int QuestionId { get; set; }
string Questions { get; set; }
int CategoryId { get; set; }
DateTime DateCreated { get; set; }
DateTime? DateModified { get; set; }
}
}<file_sep>/OnlineExamApp.API/Service/CacheService.cs
using System;
using System.Threading;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Service
{
public class CacheService : ICacheService
{
private readonly IMemoryCache _memoryCache;
private readonly ILogger<CacheService> _logger;
public CacheService(IMemoryCache memoryCache, ILogger<CacheService> logger)
{
_memoryCache = memoryCache;
_logger = logger;
}
public T Get<T>(string key) where T : class
{
return _memoryCache.Get<T>(key);
}
private static CancellationTokenSource _cts;
public static CancellationTokenSource GetGlobalCancellationTokenSource()
{
if(_cts == null)
{
_cts = new CancellationTokenSource();
}
return _cts;
}
public void Add<T>(string key, T data, double? expiration = null) where T : class
{
var entryOptions = new MemoryCacheEntryOptions();
if(expiration != null)
{
entryOptions.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(expiration.Value));
}
else
{
var cts = GetGlobalCancellationTokenSource();
entryOptions.AddExpirationToken(new CancellationChangeToken(cts.Token));
}
entryOptions.RegisterPostEvictionCallback((cacheKey, value, reason, substrate) =>
{
_logger.LogDebug($"{cacheKey} was evicted from cache. Reason {reason}");
});
_memoryCache.Set(key, data, entryOptions);
}
public void Remove(string cacheKey)
{
_memoryCache.Remove(cacheKey);
}
public void RemoveAllFromCache()
{
if(_cts == null) return;
_cts.Cancel();
_cts = null;
_logger.LogInformation($"Cache resynced successfully");
}
}
}<file_sep>/OnlineExamApp.API/Service/PaymentService.cs
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Service
{
public class PaymentService : IPaymentService
{
private readonly ITransactionRepository _transactionRepository;
public PaymentService(ITransactionRepository transactionRepository)
{
this._transactionRepository = transactionRepository;
}
}
}<file_sep>/OnlineExamApp.API/Interfaces/IOptionRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace OnlineExamApp.API.Interfaces
{
public interface IOptionRepository
{
Task<IEnumerable<IOption>> GetOptionsByQuestionId(int questionId);
Task<IEnumerable<IOption>> GetCorrectOptionByQuestionId(int questionId);
Task<IOption> SaveQuestionOption(IOption option);
Task<IOption> UpdateOption(IOption option);
Task<IOption> DeleteOption(IOption option);
Task<IOption> AddOption(IOption option);
}
}<file_sep>/OnlineExamApp.API/Dto/ScoreDto.cs
using System;
using OnlineExamApp.API.Interfaces;
namespace OnlineExamApp.API.Dto
{
public class ScoreDto : IScoreDto
{
public int ScoreId { get; set; }
public decimal Value { get; set; }
public string Username { get; set; }
public int UserId { get; set; }
public string CategoryName { get; set; }
public int CategoryId { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
}
}<file_sep>/OnlineExamApp-SPA/src/app/layout/charts/charts.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChartsModule as Ng2Charts } from 'ng2-charts';
import { ChartsRoutingModule } from './charts-routing.module';
import { ChartsComponent } from './charts.component';
import { PageHeaderModule, AuthGuard } from '../../shared';
import { ProviderAst } from '@angular/compiler';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { ProgressResolver } from 'src/app/resolver/progress-list.resolver';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [CommonModule, Ng2Charts, ChartsRoutingModule,
BsDropdownModule.forRoot(), PageHeaderModule, FormsModule],
declarations: [ChartsComponent],
providers: [ProgressResolver, AuthGuard]
})
export class ChartsModule {}
|
bd7b9d7dd04f932a78b32e840fcf418d998199c1
|
[
"C#",
"TypeScript",
"HTML"
] | 127 |
C#
|
jokoyoski/OnlineExam
|
a6c4fa01ee236a59967870d24d2b833e6127ab44
|
c43cc9dadc4853943d8aa9357f131b79b5ac1a17
|
refs/heads/master
|
<repo_name>sam2/hockey<file_sep>/ConsoleApplication1/ConsoleApplication1/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
class Program
{
static void Main(string[] args)
{
Process[] p = Process.GetProcessesByName("hockey");
uint PROCESS_ALL_ACCESS = 0x1F0FFF;
int processHandle = OpenProcess(PROCESS_ALL_ACCESS, false, p[0].Id);
int ICE_SCALE = 0x0045436C;
float gOld = System.BitConverter.ToSingle(ReadMemory(ICE_SCALE, 4, processHandle), 0);
Console.WriteLine(gOld);
float g = System.BitConverter.ToSingle( System.BitConverter.GetBytes(31f), 0);
Console.WriteLine(g);
WriteMemory(ICE_SCALE, BitConverter.GetBytes(31f), processHandle);
float gNew = System.BitConverter.ToSingle(ReadMemory(ICE_SCALE, 4, processHandle), 0);
Console.WriteLine(gNew);
Console.WriteLine("ice resized by " + (gOld - gNew) + " meters");
while(true)
{ }
}
[DllImport("kernel32.dll")]
public static extern int OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, byte[] buffer, int size, int lpNumberOfBytesRead);
[DllImport("kernel32.dll")]
public static extern bool WriteProcessMemory(int hProcess, int lpBaseAddress, byte[] buffer, int size, int lpNumberOfBytesWritten);
public static byte[] ReadMemory(int adress, int processSize, int processHandle)
{
byte[] buffer = new byte[processSize];
ReadProcessMemory(processHandle, adress, buffer, processSize, 0);
return buffer;
}
public static void WriteMemory(int adress, byte[] processBytes, int processHandle)
{
int bytesWritten = 0;
WriteProcessMemory(processHandle, adress, processBytes, processBytes.Length, bytesWritten);
}
public static int GetObjectSize(object TestObject)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] Array;
bf.Serialize(ms, TestObject);
Array = ms.ToArray();
return Array.Length;
}
}<file_sep>/HockeyTrainer/HockeyTrainer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XnaGeometry;
namespace HockeyTrainer
{
class HockeyTrainer
{
public HockeyEditor editor = new HockeyEditor();
public float shotPower = 0.5f;
public float passAccuracy = 0.5f;
//must be called before anything
public void Init()
{
editor.Init();
}
public void PassToPlayer()
{
Vector3 passVector = editor.GetPlayerStickPosition() - editor.GetPuckPosition();
passVector = Vector3.Normalize(passVector);
editor.SetPuckVelocity(passVector * (0.5f + (1.5 * (shotPower / 10))) * 0.25f);
}
public void ResetPuckToCenter()
{
editor.SetPuckRotationalVelocity(Vector3.Zero);
editor.SetPuckVelocity(Vector3.Zero);
editor.SetPuckPosition(new Vector3(15, 2, 30.5));
}
}
}
<file_sep>/HockeyTrainer/HockeyEditor.cs
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Diagnostics;
using XnaGeometry;
class HQMMemAddress
{
//these values are for hockey.exe, NOT dedicated server
public static int PUCK_POS = 0x07D1C290;
public static int PUCK_VELOCITY = 0x07D1C2CC;
public static int PUCK_ROT_VELOCITY = 0x07D1C2E4;
public static int PLAYER_POS = 0x04C25258;
public static int PLAYER_STICK_POS = 0X07D1CEF8;
}
class HockeyEditor
{
const int PROCESS_ALL_ACCESS = 0x1F0FFF;
Process hockeyProcess = null;
IntPtr hockeyProcessHandle;
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(int hProcess, int lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesWritten);
public void Init()
{
Process.Start("hockey.exe");
try
{
hockeyProcess = Process.GetProcessesByName("hockey")[0];
}
catch (System.IndexOutOfRangeException e) // CS0168
{
System.Console.WriteLine(e.Message);
throw new System.ArgumentOutOfRangeException("no hockey.exe found", e);
}
hockeyProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, false, hockeyProcess.Id);
}
public void SetPuckPosition(Vector3 pos)
{
WriteVector3(pos, HQMMemAddress.PUCK_POS);
}
public Vector3 GetPuckPosition()
{
return ReadVector3(HQMMemAddress.PUCK_POS);
}
public void SetPuckVelocity(Vector3 pos)
{
WriteVector3(pos, HQMMemAddress.PUCK_VELOCITY);
}
public Vector3 GetPuckVelocity()
{
return ReadVector3(HQMMemAddress.PUCK_VELOCITY);
}
public void SetPuckRotationalVelocity(Vector3 pos)
{
WriteVector3(pos, HQMMemAddress.PUCK_ROT_VELOCITY);
}
public Vector3 GetPuckRotationalVelocity()
{
return ReadVector3(HQMMemAddress.PUCK_ROT_VELOCITY);
}
public Vector3 GetPlayerPosition()
{
return ReadVector3(HQMMemAddress.PLAYER_POS);
}
public Vector3 GetPlayerStickPosition()
{
return ReadVector3(HQMMemAddress.PLAYER_STICK_POS);
}
public float GetGravity()
{
throw new NotImplementedException();
}
public void SetGravity(float grav)
{
throw new NotImplementedException();
}
private void WriteVector3(Vector3 v, int address)
{
int bytesWritten = 0;
var buffer = new byte[12];
var posArray = new float[] { (float)v.X, (float)v.Y, (float)v.Z };
Buffer.BlockCopy(posArray, 0, buffer, 0, buffer.Length);
WriteProcessMemory((int)hockeyProcessHandle, address, buffer, buffer.Length, ref bytesWritten);
}
private Vector3 ReadVector3(int address)
{
int bytesRead = 0;
byte[] buffer = new byte[12];
ReadProcessMemory((int)hockeyProcessHandle, address, buffer, buffer.Length, ref bytesRead);
Vector3 v = new Vector3(System.BitConverter.ToSingle(buffer.Take(4).ToArray(), 0),
System.BitConverter.ToSingle(buffer.Skip(4).Take(4).ToArray(), 0),
System.BitConverter.ToSingle(buffer.Skip(8).Take(4).ToArray(), 0));
return v;
}
}
<file_sep>/HockeyTrainer/Form1.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 HockeyTrainer
{
public partial class Form1 : Form
{
static HockeyTrainer trainer = new HockeyTrainer();
public Form1()
{
trainer.Init();
InitializeComponent();
PassStr.Value = 5;
}
private void ResetPuck_Click(object sender, EventArgs e)
{
trainer.ResetPuckToCenter();
}
private void PassStr_Scroll(object sender, EventArgs e)
{
trainer.shotPower = PassStr.Value;
}
public static void PassToPlayer()
{
trainer.PassToPlayer();
}
private void PassAcc_Scroll(object sender, EventArgs e)
{
trainer.passAccuracy = PassAcc.Value;
}
}
}
|
4c41179fae174405885f67acb50fa159820a6cba
|
[
"C#"
] | 4 |
C#
|
sam2/hockey
|
1d647c38601584fcf566f66e4e8346b6d64329b3
|
691c8afafa4fff1b90223eccb219f24baf99d269
|
refs/heads/master
|
<file_sep>package db;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.Service;
import org.hibernate.service.ServiceRegistry;
public class MyHibernateSessionFactory {
private static SessionFactory sessionFactory;// 会话工厂属性
// 构造方法私有化,保证单例模式
private MyHibernateSessionFactory() {
}
//公有的静态方法,获得会话工厂对象
public static SessionFactory getSeesionFactory(){
if(sessionFactory==null){
Configuration config=new Configuration();
ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().configure().build();
sessionFactory=config.buildSessionFactory(serviceRegistry);
return sessionFactory;
}else{
return sessionFactory;
}
}
}
<file_sep>package service.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import db.MyHibernateSessionFactory;
import entity.Students;
import service.StudentsDao;
public class StudentsDaoImpl implements StudentsDao {
@Override
public List<Students> queryAllStudents() {
Transaction ts = null;
List<Students> list = null;
String hql = "";
try {
Session session = MyHibernateSessionFactory.getSeesionFactory()
.getCurrentSession();
ts=session.beginTransaction();
hql = "from Students";
Query query = session.createQuery(hql);
list = query.list();
ts.commit();
return list;
} catch (Exception e) {
e.printStackTrace();
return list;
} finally {
if(ts!=null){
ts=null;
}
}
}
@Override
public Students queryStudentById(String sid) {
Transaction ts = null;
Students s=null;
try {
Session session = MyHibernateSessionFactory.getSeesionFactory()
.getCurrentSession();
ts=session.beginTransaction();
s=session.get(Students.class, sid);
ts.commit();
return s;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(ts!=null){
ts=null;
}
}
return null;
}
@Override
public boolean addStudent(Students s) {
Transaction ts=null;
s.setSid(getNewSid());
try {
Session session = MyHibernateSessionFactory.getSeesionFactory()
.getCurrentSession();
ts=session.beginTransaction();
session.save(s);
ts.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if(ts!=null){
ts=null;
}
}
}
@Override
public boolean updateStudents(Students s) {
Transaction ts=null;
try {
Session session = MyHibernateSessionFactory.getSeesionFactory()
.getCurrentSession();
ts=session.beginTransaction();
session.update(s);
ts.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if(ts!=null){
ts=null;
}
}
}
@Override
public boolean deleteStudent(String id) {
Transaction ts = null;
try {
Session session = MyHibernateSessionFactory.getSeesionFactory()
.getCurrentSession();
ts=session.beginTransaction();
Students s=session.get(Students.class, id);
session.delete(s);
ts.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if(ts!=null){
ts=null;
}
}
}
//生成学生的学号
public String getNewSid(){
Transaction ts = null;
String hql="";
String sid= null;
try {
Session session = MyHibernateSessionFactory.getSeesionFactory()
.getCurrentSession();
ts=session.beginTransaction();
hql="select max(sid) from Students";
Query query=session.createQuery(hql);
sid=(String) query.uniqueResult();
if(sid==null||"".equals(sid)){
sid="S201501";
}else{
String temp=sid.substring(1);
int i=Integer.parseInt(temp);
++i;
temp=String.valueOf(i);
for(int j=0;j<6-temp.length();j++){
temp=temp+"0";
}
sid="S"+temp;
}
return sid;
} catch (Exception e) {
e.printStackTrace();
return "";
} finally {
if(ts!=null){
ts=null;
}
}
}
}
<file_sep>package ahpu.ssh.city.dao;
import ahpu.ssh.city.model.City;
public interface CityDao extends BaseDao<City> {
}<file_sep>package serviceTest;
import org.junit.Test;
import junit.framework.Assert;
import service.UsersDao;
import service.impl.UsersDaoImpl;
import entity.Users;
public class TestUsersDaoImpl {
@Test
public void testuserLogin(){
Users user=new Users(1,"zhangsan","123456");
UsersDao dao=new UsersDaoImpl();
Assert.assertEquals(true, dao.userLogin(user));
}
}
<file_sep>package ahpu.ssh.city.model;
import java.util.Set;
/**
* Province entity. @author MyEclipse Persistence Tools
*/
public class Province extends AbstractProvince implements java.io.Serializable {
// Constructors
/** default constructor */
public Province() {
}
/** full constructor */
public Province(String name, Set cities) {
super(name, cities);
}
}
<file_sep>package ahpu.ssh.city.dao.impl;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import ahpu.ssh.city.dao.BaseDao;
public class BaseDaoImpl<T> implements BaseDao<T> {
private Session session;
private Class<?> entityClass; //泛型参数对应的实际实体类
public BaseDaoImpl() {
Type type = ((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
entityClass = (Class<?>) type;
}
public void setSession(Session session) {
if (this.session == null || !session.isOpen()) {
this.session = session;
}
}
public List<T> findAll() {
// 不指定任何参数名即为查找所有实体对象
return find(new String[0], new Object[0]);
}
public T find(Serializable id) {
return (T)session.get(entityClass, id);
}
public List<T> find(String[] paramNames, Object[] paramValues) {
StringBuffer sb = new StringBuffer("from " + entityClass.getSimpleName() + " where 1=1");
for (int i = 0; i < paramNames.length; i++) {
sb.append(" and ");
sb.append(paramNames[i]);
sb.append("=?");
}
Query q = session.createQuery(sb.toString());
for (int i = 0; i < paramNames.length; i++) {
q.setParameter(i, paramValues[i]);
}
List<T> entities = q.list();
return entities;
}
}<file_sep>package service;
import entity.Users;
//用户罗辑接口
public interface UsersDao {
public boolean userLogin(Users u);
}
<file_sep>package ahpu.ssh.city.dao;
import ahpu.ssh.city.model.Province;
public interface ProvinceDao extends BaseDao<Province> {
}<file_sep>package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.StudentsDao;
import service.impl.StudentsDaoImpl;
import entity.Students;
public class test {
public static void main(String[] args) {
List list2=new ArrayList();
Map<String, Object> map=new HashMap<String, Object>();
map.put("sid", 1);
map.put("sname", "张三");
map.put("gender", "男");
map.put("birthday", "2012-1-1");
map.put("address", "地球");
map.put("status", "删除");
Map<String,Object> json=new HashMap<String, Object>();
list2.add(map);
json.put("rows", list2);
json.put("total", list2.size());
JSONArray o=JSONArray.fromObject(json);
String jsonString=o.toString();
System.out.println(jsonString);
}
}
<file_sep>package ahpu.ssh.city.action;
import ahpu.ssh.city.service.ProvinceService;
import ahpu.ssh.city.service.impl.ProvinceServiceImpl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class CityAction extends ActionSupport {
//在Action层创建Service对象
private ProvinceService provinceService = new ProvinceServiceImpl();
// 页面中的省份下拉列表
private int provinceId;
public String execute() {
// 获得所有省份并写入action
ActionContext.getContext().put("all_provinces", provinceService.getAllProvinces());
// 获得选择的省份下所有的城市并写入action
ActionContext.getContext().put("cities", provinceService.getCitiesOfProvince(provinceId));
return "index";
}
// gettes and setters
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}
|
b08d739f922cb24188fa4829f34e79d564590564
|
[
"Java"
] | 10 |
Java
|
guiguzi21/lab7
|
a184cb5fcdd3d88a8f7ca0dcdff2cc3430249778
|
887811917551ec68ac9d415aecd9cae504485563
|
refs/heads/master
|
<repo_name>CodeAcademyP403/03-06-2018restoranappbasketadmin-Soltanaa<file_sep>/RestoranOrderSystem/AdminForm.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 RestoranOrderSystem
{
public partial class AdminForm : Form
{
public AdminForm()
{
InitializeComponent();
}
Admin admin = new Admin();
private void label1_Click(object sender, EventArgs e)
{
}
private void btn_Login_Click(object sender, EventArgs e)
{
if(txbx_Login.Text.ToString()==admin.Name && txbx_Password.Text==admin.Password.ToString())
{
this.Hide();
Form1 MainForm = new Form1(this);
MainForm.Show();
}
else { MessageBox.Show("Login ve Password <PASSWORD>"); }
}
}
}
<file_sep>/RestoranOrderSystem/Admin.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RestoranOrderSystem
{
public class Admin
{
public string Name = "admin";
public int Password = <PASSWORD>;
}
}
<file_sep>/RestoranOrderSystem/RestoranForm.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;
using System.Collections;
namespace RestoranOrderSystem
{
public partial class Form1 : Form
{
private AdminForm _Form;
public Form1(AdminForm adminForm):this()
{
_Form = adminForm;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmbx_Category.DataSource = Enum.GetValues(typeof(ProductCategory));
}
//ArrayList MyArrayList = new ArrayList();
List<Product> list = new List<Product>();
public void MakeFood()
{
list.AddRange(new Product[]
{
new Product{Name = "Kabab",Count = 2,ProductCategory= ProductCategory.MainFoods},
new Product{Name = "Sezar",Count = 5,ProductCategory= ProductCategory.Salats},
new Product{Name = "Cola",Count = 12,ProductCategory= ProductCategory.Drinks},
new Product{Name = "Merci",Count = 2,ProductCategory= ProductCategory.Soups}
});
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
_Form.Close();
}
private void button1_Click(object sender, EventArgs e)
{
cmbx_Name.Text="";//cmbx_Name metnini sil,ve elave et basket systemi duzeldib ora.
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cmbx_Category_SelectedIndexChanged(object sender, EventArgs e)
{
MakeFood();
string selectedvalue = (sender as ComboBox).SelectedItem.ToString();
ProductCategory selectingcategory = (ProductCategory)Enum.Parse(typeof(ProductCategory), selectedvalue);
cmbx_Name.Items.Clear();
foreach (Product item in list)
{
if (item.ProductCategory == selectingcategory)
{
cmbx_Name.Items.Clear();
cmbx_Name.Items.Add(item.Name);
}
}
}
}
}
<file_sep>/RestoranOrderSystem/ProductCategory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RestoranOrderSystem
{
public enum ProductCategory
{
MainFoods,
Soups,
Salats,
Deserts,
Drinks
}
}
|
b5f5f28d671b2f36bd3cb6c208ec2d71bd095d9b
|
[
"C#"
] | 4 |
C#
|
CodeAcademyP403/03-06-2018restoranappbasketadmin-Soltanaa
|
a51416f0b24f758a730d2bccc97b633cec7362ea
|
0d1f02f75f4bb1a53e4b292dc67635101a047c48
|
refs/heads/master
|
<repo_name>GaryAshby/getdata-Course-Project<file_sep>/README.md
#Course Project for GetData Coursera Project
Data was extract from this location https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip
The primary tasks are to compelte the following
1) You should create one R script called run_analysis.R that does the following.
2) Merges the training and the test sets to create one data set.
3) Extracts only the measurements on the mean and standard deviation for each measurement.
4) Uses descriptive activity names to name the activities in the data set
5) Appropriately labels the data set with descriptive variable names.
6) From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
#Outcome
The results are uploaded and store in the course project submission page.
<file_sep>/run_analysis.R
#run_analysis.R
#1) You should create one R script called run_analysis.R that does the following.
#2) Merges the training and the test sets to create one data set.
#3) Extracts only the measurements on the mean and standard deviation for each measurement.
#4) Uses descriptive activity names to name the activities in the data set
#5) Appropriately labels the data set with descriptive variable names.
#6) From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
#SetWD("C:\Gary\RData\GETDATA-032")
#2) Merges the training and the test sets to create one data set.
#3) Extracts only the measurements on the mean and standard deviation for each measurement.
library(dplyr)
if (!file.exists("getdata-projectfiles-UCI HAR Dataset.zip"))
{
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(fileUrl, destfile = "getdata-projectfiles-UCI HAR Dataset.zip")
unzip("getdata-projectfiles-UCI HAR Dataset.zip", exdir = ".")
}
#Load Features (variable names)
feature <- read.table("./UCI HAR Dataset/features.txt")
names(feature) <- c("featureid","feature")
feature_filtered <- filter(feature, grepl("std|mean", as.character(feature$feature), ignore.case = TRUE))
feature_filtered <- filter(feature_filtered, !grepl("angle", as.character(feature_filtered$feature), ignore.case = TRUE))
#Load Activity Labels
activity_labels <- read.table("UCI HAR Dataset/activity_labels.txt")
activity_labels <- rename(activity_labels, label = V1, label_description = V2)
#Load Training Data
train_subject <- read.table("UCI HAR Dataset/train/subject_train.txt")
train_set <- read.table("UCI HAR Dataset/train/x_train.txt")
train_labels <- read.table("UCI HAR Dataset/train/y_train.txt")
train_subset <- select(train_set, feature_filtered$featureid)
names(train_subset) <- feature_filtered$feature
#Load Test Data
test_subject <- read.table("UCI HAR Dataset/test/subject_test.txt")
test_set <- read.table("UCI HAR Dataset/test/x_test.txt")
test_labels <- read.table("UCI HAR Dataset/test/y_test.txt")
test_subset <- select(test_set, feature_filtered$featureid)
names(test_subset) <- feature_filtered$feature
#combine extra variables
test_data <- mutate(test_subset, label = as.integer(test_labels$V1))
test_data <- mutate(test_data, subject = as.integer(test_subject$V1))
train_data <- mutate(train_subset, label = as.integer(train_labels$V1))
train_data <- mutate(train_data, subject = as.integer(train_subject$V1))
#Combined all the data.
complete_data <- rbind(train_data, test_data)
complete_data <- merge(complete_data, activity_labels)
#6) From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
complete_data_grouped <- group_by(complete_data, label_description, subject)
complete_data_grouped_summarised <- summarise_each(complete_data_grouped, funs(mean))
write.table(complete_data_grouped_summarised, "CompleteTidyData.txt", row.names = FALSE)
<file_sep>/CodeBook.md
#Install Libraries used in the package.
```R
library(dplyr)
```
#check if the data exists, if not download.
```R
if (!file.exists("getdata-projectfiles-UCI HAR Dataset.zip"))
{
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(fileUrl, destfile = "getdata-projectfiles-UCI HAR Dataset.zip")
unzip("getdata-projectfiles-UCI HAR Dataset.zip", exdir = ".")
}
```
#Load Features (variable names)
```R
feature <- read.table("./UCI HAR Dataset/features.txt")
names(feature) <- c("featureid","feature")
feature_filtered <- filter(feature, grepl("std|mean", as.character(feature$feature), ignore.case = TRUE))
feature_filtered <- filter(feature_filtered, !grepl("angle", as.character(feature_filtered$feature), ignore.case = TRUE))
```
#Load Activity Labels
```R
activity_labels <- read.table("UCI HAR Dataset/activity_labels.txt")
activity_labels <- rename(activity_labels, label = V1, label_description = V2)
```
#Load Training Data
```R
train_subject <- read.table("UCI HAR Dataset/train/subject_train.txt")
train_set <- read.table("UCI HAR Dataset/train/x_train.txt")
train_labels <- read.table("UCI HAR Dataset/train/y_train.txt")
train_subset <- select(train_set, feature_filtered$featureid)
names(train_subset) <- feature_filtered$feature
```
#Load Test Data
```R
test_subject <- read.table("UCI HAR Dataset/test/subject_test.txt")
test_set <- read.table("UCI HAR Dataset/test/x_test.txt")
test_labels <- read.table("UCI HAR Dataset/test/y_test.txt")
test_subset <- select(test_set, feature_filtered$featureid)
names(test_subset) <- feature_filtered$feature
```
#Combine extra variables
```R
test_data <- mutate(test_subset, label = as.integer(test_labels$V1))
test_data <- mutate(test_data, subject = as.integer(test_subject$V1))
train_data <- mutate(train_subset, label = as.integer(train_labels$V1))
train_data <- mutate(train_data, subject = as.integer(train_subject$V1))
```
#Combined all the data.
```R
complete_data <- rbind(train_data, test_data)
complete_data <- merge(complete_data, activity_labels)
```
#Create Tidy Dataset
```R
complete_data_grouped <- group_by(complete_data, label_description, subject)
complete_data_grouped_summarised <- summarise_each(complete_data_grouped, funs(mean))
write.table(complete_data_grouped_summarised, "CompleteTidyData.txt", row.names = FALSE)
```
|
76c760ee36f50c02b2ed8f68264c5fd6e2a42db2
|
[
"Markdown",
"R"
] | 3 |
Markdown
|
GaryAshby/getdata-Course-Project
|
d18534490a01aa6c723089af2b3d2912a0b3cfcb
|
7cecd969ebbe328af380c1ab8018c8a544b71781
|
refs/heads/master
|
<file_sep>export const REMOVE_TASK = "REMOVE_TASK";
export const CHANGE_TASK = "CHANGE_TASK";
export const SET_LOADING = "SET_LOADING";
export const LOAD_USER = "LOAD_USER";
export const LOAD_TODOS = "LOAD_TODOS";
export const UPDATE_TODO = "UPDATE_TODO";
export const TOGGLE_EDIT = "TOGGLE_EDIT";
export const ADD_TODO = "ADD_TODO";
export const DELETE_TODO = "DELETE_TODO";
<file_sep>describe(`Пошаговое прохождение всех функциональных эллементов:
переход на страницу Пингвина,
добывление новой задачи,
Редактирование задачи,
Сохранение отредактированной задачи,
удаление задачи.
`, () => {
it("By step do all actions in a funny organizer", () => {
cy.fixture("cypressTest").then(data => {
cy.log("Переход на главную страницу")
cy.visit("http://localhost:3000/")
cy.log("ожидаем 2 секунды")
cy.wait(2000)
cy.log("Проверяем адаптивную верстку на разных устройствах")
cy.viewport('macbook-15')
cy.wait(500)
cy.viewport('macbook-13')
cy.wait(500)
cy.viewport('macbook-11')
cy.wait(500)
cy.viewport('ipad-2')
cy.wait(500)
cy.viewport('ipad-mini')
cy.wait(500)
cy.viewport('iphone-6+')
cy.wait(500)
cy.viewport('iphone-6')
cy.wait(500)
cy.viewport('iphone-5')
cy.wait(500)
cy.viewport('iphone-4')
cy.wait(500)
cy.viewport('iphone-3')
cy.wait(500)
cy.viewport('ipad-2', 'portrait')
cy.wait(500)
cy.viewport('iphone-4', 'landscape')
cy.wait(500)
cy.viewport(1920, 1000)
cy.log("ожидаем 2 секунды")
cy.wait(2000)
cy.log("Выбор первого элемента из списка")
cy.get('div.card .card-body h5.card-title a:first').click()
cy.log("Добавляем новую задачу")
cy.get(".addTaskForm-input").click().type("<NAME>ЕРОМ")
cy.get(".addTaskForm .btn").click()
cy.log("ожидаем 3 секунды")
cy.wait(3000)
cy.log("Редактируем созданную задачу")
cy.get(".card .card-body .btn-primary:first").click()
cy.get(".radio-done").click()
cy.get(".update-input").click().type(" - ДОБАВИЛ ПАРСЕР ПРИ РЕДАКТИРОВАНИИ")
cy.get(".card .card-body .btn-primary:first").click()
cy.log("Удаляем добавленный элемент")
cy.get(".btn-danger:first").click()
})
})
}) <file_sep>import { Todo } from './todo.interface'
import { User } from './user.interface';
export interface IProfileState {
todos: Todo[],
user: User | null,
loading: boolean
}<file_sep>export const FETCH_USERS_START = "FETCH_USERS_START";
export const FETCH_USERS_SUCCESS = "FETCH_USERS_SUCCESS";
export const FETCH_USERS_ERROR = "FETCH_USERS_ERROR";
export const FETCH_USERS_TASKS_START = "FETCH_USERS_TASKS_START";
export const FETCH_USERS_TASKS_SUCCESS = "FETCH_USERS_TASKS_SUCCESS";
export const FETCH_USERS_TASKS_ERROR = "FETCH_USERS_TASKS_ERROR";<file_sep>
import { combineReducers } from "redux";
import homeReducer from './home';
import profileReducer from './tasks';
export default combineReducers({
home: homeReducer,
profile: profileReducer
})<file_sep>import { FETCH_USERS_SUCCESS, FETCH_USERS_START, FETCH_USERS_ERROR } from "./actionTypes";
import { User } from "../../interfaces/user.interface"
export function fetchUsers() {
return async (dispatch: any) => {
try {
dispatch(fetchUsersStart());
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const usersData = await response.json();
dispatch(fetchUsersSuccess(usersData))
} catch (error) {
fetchUsersError(error)
}
}
}
export function fetchUsersStart() {
return {
type: FETCH_USERS_START
}
}
export function fetchUsersSuccess(usersData: User[]) {
return {
type: FETCH_USERS_SUCCESS,
users: usersData
}
}
export function fetchUsersError(error: string) {
return {
type: FETCH_USERS_ERROR,
error
}
}<file_sep>import { FETCH_USERS_START, FETCH_USERS_SUCCESS, FETCH_USERS_ERROR } from "../actions/actionTypes"
const initialState = {
users: [],
loading: true,
error: null
}
export default function homeReducer(state = initialState, action: any) {
switch (action.type) {
case FETCH_USERS_START:
return {
...state, loading: true
}
case FETCH_USERS_SUCCESS:
return {
...state, loading: false, users: action.users
}
case FETCH_USERS_ERROR:
return {
...state, loding: false, error: action.error
}
default:
return state
}
}<file_sep>import { createContext } from "react";
export const ProfileContext = createContext<any | any>(undefined);
<file_sep>export interface IMainInterface { }<file_sep>import { LOAD_TODOS, LOAD_USER, DELETE_TODO, SET_LOADING, UPDATE_TODO, ADD_TODO } from '../types';
import { IProfileState } from '../../interfaces/profileState.interface';
import { Todo } from '../../interfaces/todo.interface';
const handlers: any = {
[LOAD_USER]: (state: IProfileState, { payload }: any): IProfileState => {
return { ...state, user: { ...payload }, loading: false }
},
[LOAD_TODOS]: (state: IProfileState, { payload }: any) => ({ ...state, todos: payload, loadingTodos: false }),
[SET_LOADING]: (state: IProfileState) => ({ ...state, loading: true }),
[UPDATE_TODO]: (state: IProfileState, { payload }: any) => {
let todos = state.todos;
const { id } = payload;
const index = todos.findIndex((todo: Todo) => todo.id === id);
todos[index] = payload;
return { ...state, todos };
},
[DELETE_TODO]: (state: IProfileState, { id }: any) => {
let todos = state.todos;
const index = todos.findIndex((todo: Todo) => todo.id === id);
if (index !== -1)
todos = todos.splice(index, 1);
return { ...state, todos };
},
[ADD_TODO]: (state: IProfileState, { payload }: any) => {
return { ...state, todos: [payload, ...state.todos] }
},
DEFAULT: (state: IProfileState) => state
}
export const profileReducer = (state: IProfileState, action: any) => {
const handler = handlers[action.type] || handlers.DEFAULT
return handler(state, action)
}<file_sep>import { FETCH_USERS_TASKS_SUCCESS, FETCH_USERS_TASKS_START, FETCH_USERS_TASKS_ERROR } from "./actionTypes";
import { Todo } from "../../interfaces/todo.interface";
export function fetchUsersTasks() {
return async (dispatch: any) => {
try {
dispatch(fetchUsersTasksStart());
const response = await fetch("https://jsonplaceholder.typicode.com/todos");
const usersTasksData = await response.json();
dispatch(fetchUsersTasksSuccess(usersTasksData))
} catch (error) {
fetchUsersTasksError(error)
}
}
}
export function fetchUsersTasksStart() {
return {
type: FETCH_USERS_TASKS_START
}
}
export function fetchUsersTasksSuccess(usersTasksData: Todo[]) {
return {
type: FETCH_USERS_TASKS_SUCCESS,
users: usersTasksData
}
}
export function fetchUsersTasksError(error: string) {
return {
type: FETCH_USERS_TASKS_ERROR,
error
}
}<file_sep>import { FETCH_USERS_TASKS_START, FETCH_USERS_TASKS_SUCCESS, FETCH_USERS_TASKS_ERROR } from "../actions/actionTypes"
const initialState = {
usersTasks: [],
loading: true,
error: null
}
export default function profileReducer(state = initialState, action: any) {
switch (action.type) {
case FETCH_USERS_TASKS_START:
return {
...state, loading: true
}
case FETCH_USERS_TASKS_SUCCESS:
return {
...state, loading: false, users: action.users
}
case FETCH_USERS_TASKS_ERROR:
return {
...state, loding: false, error: action.error
}
default:
return state
}
}
|
59466e4c50771139be937e783c91bad60579302c
|
[
"JavaScript",
"TypeScript"
] | 12 |
TypeScript
|
VasilyKonnov/funny-organizer-ts
|
be9219756a126e793e25f97df6c6da5d196148e3
|
e7a439652f75cc46c1f91ffa48fff51b520f08c6
|
refs/heads/master
|
<repo_name>cryptol0g1c/ico-tokensale<file_sep>/test/GenericToken.js
const GenericToken = artifacts.require('GenericToken');
const { BigNumber } = web3;
const should = require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should();
const utils = require('./utils/index');
import { increaseTimeTo, duration } from 'zeppelin-solidity/test/helpers/increaseTime';
import latestTime from 'zeppelin-solidity/test/helpers/latestTime';
contract('GenericToken', addresses => {
let genericToken;
// initial parameters
let _openingTime;
let notOwnerAddress = addresses[1];
const _name = 'testcoin';
const _symbol = 'test';
const _decimals = 18;
beforeEach(async() => {
_openingTime = await latestTime(web3) + duration.weeks(1);
genericToken = await GenericToken.new(_openingTime, _name, _symbol, _decimals);
});
describe('GenericToken', () => {
it('should initialize parameters correctly', async() => {
(await genericToken.NAME()).should.equal(_name);
(await genericToken.SYMBOL()).should.equal(_symbol);
(await genericToken.DECIMALS()).should.bignumber.equal(_decimals);
});
it('should be locked by default', async() => {
(await genericToken.isLocked()).should.equal(true);
});
it('should not unlock if the current timestamp is before openingTime', async() => {
try {
await genericToken.unlockTransfer();
} catch (error) {
utils.assertRevert(error);
}
});
it('should not unlock if the sender is not the owner', async() => {
await increaseTimeTo(_openingTime);
try {
await genericToken.unlockTransfer({sender: notOwnerAddress});
} catch (error) {
utils.assertRevert(error);
}
});
it('should unlock if the sender is the owner and timestamp is after openingTime', async() => {
await increaseTimeTo(_openingTime);
await genericToken.unlockTransfer();
(await genericToken.isLocked()).should.equal(false);
utils.assertEvent(GenericToken, {
event: 'Unlocked',
logIndex: 0,
args: {
_isLocked: true
}
});
});
});
});
|
90d393e8c290525eddd037c3d62fdecb631e8ecb
|
[
"JavaScript"
] | 1 |
JavaScript
|
cryptol0g1c/ico-tokensale
|
8848b6d421b25a1669182f16e03efadc564fdaab
|
063e527be9ca6cb3b266fbe851b6717ce1950ec4
|
refs/heads/master
|
<repo_name>Venkata121/Opes<file_sep>/README.md
# Resource Bank
[](https://app.circleci.com/pipelines/github/sarthaktexas/resourcebank)

## 🌎 Languages


## 🖼️ Frameworks


## 🛠 Continous Integration

## Browser Compatibility
|  |  |  |  |  |  |
|-|-|-|-|-|-|
| Latest ✔ | Latest ✔ | 11+ ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
##### Icons:
- File: fas fa-file
- Link: fas fa-paperclip
- Video: fas fa-video
- Quizlet: fas fa-shapes
- Textbook: fas fa-book
- Top-Level Resource: fas fa-star<file_sep>/public/scripts/search.js
const resourcesList = document.getElementById("resourcesList");
const searchBar = document.getElementById("searchBar");
let freeResources = [];
searchBar.addEventListener("keyup", e => {
const searchString = e.target.value.toLowerCase();
const filteredResources = freeResources.filter(resource => {
return (
resource.icon.toLowerCase().includes(searchString) ||
resource.subject.toLowerCase().includes(searchString) ||
resource.name.toLowerCase().includes(searchString) ||
resource.link.toLowerCase().includes(searchString)
);
});
displayResources(filteredResources);
});
const loadResources = async () => {
try {
const res = await fetch("/free-resources_data.json");
freeResources = await res.json();
displayResources(freeResources);
} catch (err) {
console.error(err);
}
};
const displayResources = resources => {
const htmlString = resources
.map(resource => {
return `
<li class="card card-body customfloatleft">
<i class="${resource.icon} card-title"></i>
<h6 class="text-warning">${resource.subject}</h5>
<h5 class="card-title">${resource.name}</h5>
<a href="${resource.link}" class="btn btn-primary">Link</a>
</li>
`;
})
.join("");
resourcesList.innerHTML = htmlString;
};
loadResources();
|
0a247730608bea6e05aec92dc469a22d80ae9487
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
Venkata121/Opes
|
ccde9023f1d73d239d3a4df1db9d1fc07f2a0702
|
666a28259912b7c8b9c61683639f346fc757938d
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use APP\Slide;
// use App\rest\TokenHolder;
include(app_path().'/rest/TokenHolder.php');
use Illuminate\Http\Request;
class PageController extends Controller
{
private static $token = null;
private static $expirationDate = 0;
public function getIndex(){
return view('page.trangchu');
}
public function getContactus(){
return view('page.contact_us');
}
public function getAbout(){
return view('page.about');
}
public function getPage404(){
return view('page.404');
}
// ==========
public function testApi(){
$origin = 'LAX';
$destination = 'JFK';
$departureDate = '2018-01-20';
// $origin = '';
$result = $this->executeGetCall("/v2/shop/flights/fares", $this->getRequest($origin, $destination, $departureDate));
echo $result;
}
private function getRequest($origin, $destination, $departureDate) {
$request = array(
"lengthofstay" => "5",
"pointofsalecountry" => "US",
"origin" => $origin,
"destination" => $destination,
"departuredate" => $departureDate
);
return $request;
}
public function executeGetCall($path, $request) {
$result = curl_exec($this->prepareCall('GET', $path, $request));
return json_decode($result);
}
private function buildHeaders() {
// $token = new TokenHolder::getToken();
$token = $this->getToken();
dd($token);
$headers = array(
'Authorization: Bearer '.$token->access_token,
'Accept: */*'
);
return $headers;
}
private function prepareCall($callType, $path, $request) {
$domain = 'https://api.test.sabre.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $callType);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = $this->buildHeaders();
switch ($callType) {
case 'GET':
$url = $path;
if ($request != null) {
$url = $domain.$path.'?'.http_build_query($request);
// $url = $this->config->getRestProperty("environment").$path.'?'.http_build_query($request);
}
// curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => true));
curl_setopt($ch, CURLOPT_URL, $url);
break;
case 'POST':
curl_setopt($ch, CURLOPT_URL, $domain.$path);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
array_push($headers, 'Content-Type: application/json');
break;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
return $ch;
}
public function getToken() {
if (self::token == null || time() > self::expirationDate) {
self::token = $this->callForToken();
// $this->tokeno = time() + TokenHolder::$token->expires_in;
}
return self::token;
}
public function callForToken() {
$domain = 'https://api.test.sabre.com';
$ch = curl_init($domain."/v2/auth/token");
$vars = "grant_type=client_credentials";
$headers = array(
'Authorization: Basic '.$this->buildCredentials(),
'Accept: */*',
'Content-Type: application/x-www-form-urlencoded'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
private function buildCredentials() {
$credentials = "V1:f2sfnbqa11kavp7w:DEVCENTER:EXT";
$clientSecret = 'D04GelUg';
$secret = base64_encode($clientSecret);
return base64_encode(base64_encode($credentials).":".$secret);
}
// ===end====
}
|
1146676df50f815b32fbfd04aaa667cb7afb0d36
|
[
"PHP"
] | 1 |
PHP
|
zet0402/travelsource
|
d759c74dba54b39f09f64df8d641a405fe431763
|
1f9c85a926abe666035654f626ca3fcbc5456cf8
|
refs/heads/master
|
<repo_name>i-708/BlockChain-study<file_sep>/BitCoin-Transaction-study/btc.js
// 参考
// ブラウザでBTC送金トランザクション
// https://memo.appri.me/programming/btc-tx-on-browser
// ブロックチェーン実戦入門 ビットコインからイーサリアム、DApp開発まで
// https://www.amazon.co.jp/gp/product/B08LCWD7FY/ref=ppx_yo_dt_b_d_asin_title_o01?ie=UTF8&psc=1
// BitcoinJSライブラリの初期化
const btc = require('bitcoinjs-lib');
// 対象ネットワークの設定(今回はビットコインのテストネットワーク)
const network = btc.networks.testnet;
// トランザクションをGETしたりPOSTしたりするパブリックノードのAPIエンドポイント
// 今回はビットコインのテストネットワーク用のBlockCypherのAPIを使用
const blockCypherTestnetApiEndpoint = 'https://api.blockcypher.com/v1/btc/test3/';
// 送金側と受取側のそれぞれの鍵ペアを作成
// 鍵ペアを作成したら、それ以降は利用しない
var getKeys = function(){
// BitcoinJSライブラリのECPairクラスを用いてmakeRandomメソッドを呼び、
// テストネットワーク用のランダムな鍵ペアを作成
const aliceKeys = btc.ECPair.makeRandom({
network: network
});
const bobKeys = btc.ECPair.makeRandom({
network: network
});
const alicePrivate = aliceKeys.toWIF();
// キーペア生成:
const aliceKeyPair = btc.ECPair.fromWIF(alicePrivate, network)
// アドレス取得:
const { aliceAddress } = btc.payments.p2pkh({
pubkey: aliceKeyPair.publicKey,
network,
});
console.log("アリスのPublicKey:", aliceAddress);
console.log("アリスのPrivateKey:", alicePrivate);
const bobPrivate = bobKeys.toWIF();
// キーペア生成:
const bobKeyPair = btc.ECPair.fromWIF(bobPrivate, network)
// アドレス取得:
const { bobAddress } = btc.payments.p2pkh({
pubkey: bobKeyPair.publicKey,
network,
});
console.log("ボブのPublicKey:", bobAddress);
console.log("ボブのPrivateKey:", bobPrivate);
};
// getKeys();
/**
* 実行した結果
* Alice
* public:
* <KEY>
* private:
* <KEY>
* Bob
* public:
* <KEY>
* private:
* <KEY>
* ビットコイン返還先
* <KEY>
*/
// アリスとボブの鍵を用意
// ボブのアドレスにビットコインを準備しておく
const alicePublic = '<KEY>';
const alicePrivateKey = '<KEY>';
const bobPublic = '<KEY>';
const bobPrivateKey = '<KEY>'
// BlockCypherのAPIを使用し、ビットコインのテストネットにおける
// ボブのアドレスの未使用アウトプットを取得
var request = require('request');
var getOutputs = function(){
var url = blockCypherTestnetApiEndpoint + 'addrs/' +
bobPublic + '?unspentOnly=true';
return new Promise(function(resolve, reject){
request.get(url,function(err,res,body){
if (err){
reject(err);
}
resolve(body);
});
});
};
getOutputs().then(function (res){
// ビットコインのトランザクションを準備
// 未使用アウトプットの1つめを使用し、インプットへ追加
const utxo = JSON.parse(res.toString()).txrefs;
const transaction = new btc.TransactionBuilder(network);
transaction.addInput(utxo[0].tx_hash, utxo[0].tx_output_n);
// MAXビットコイン(プログラムを実行前)
// 1Satoshi = 0.00000001BTC
const utxoSatoshi = utxo[0].value;
// 送信する量(utxoSatoshiの10%)
const sendSatoshi = utxoSatoshi / 10;
// 手数料として払う量(0.0001BTC)
const feeSatoshi = 10000;
// 戻す量
const backSatoshi = utxoSatoshi - (sendSatoshi+feeSatoshi);
// アウトプットの追加
// インプットとアウトプットの差額がトランザクションの手数料になる
transaction.addOutput(alicePublic,sendSatoshi);
transaction.addOutput(bobPublic,backSatoshi);
// トランザクションインプットに署名
transaction.sign(0,btc.ECPair.fromWIF(bobPrivateKey,network));
// トランザクションの16進数表記の作成
const transactionHex = transaction.build().toHex();
// ネットワークにトランザクションをブロードキャスト
const txPushUrl = blockCypherTestnetApiEndpoint + 'txs/push';
request.post({
url: txPushUrl,
json:{
tx: transactionHex
}
}, function(err, res, body) {
if(err){
console.log(err);
}
console.log(res);
console.log(body);
});
})
<file_sep>/python-blockchain/blockchain.py
'''
参考
ブロックチェーン技術及び関連技術(ブロックチェーン実装あり) - Qiita
https://qiita.com/michimichix521/items/1485f05a45a37d7ffe08
'''
import hashlib
class Block:
def __init__(self, index, timestamp, data, previousHash = ""):
self.index = index
self.previousHash = previousHash
self.timestamp = timestamp
self.data = data
self.hash = self.calculateHash()
# ハッシュ値の計算
# ハッシュ値の元となるデータが1ビットでも異なると全く異なる値となる
# ハッシュ値から入力データを計算することや推測することは困難であるという性質を備える
# sha256はどんな入力データに対しても長さが256ビットのハッシュ値を出力する。
# そのため、大きなサイズのデータ同士を比較することなく一致性を確認できるようになる
# ハッシュ値を用いることによってデータの識別や改ざん検知が容易になる
def calculateHash(self):
return (hashlib.sha256((str(self.index) + str(self.previousHash) + str(self.timestamp) + str(self.data)).encode('utf-8')).hexdigest())
def setdict(self):
d = {"index":self.index, "previousHash":self.previousHash, "timestamp":self.timestamp, "data":self.data, "hash":self.hash}
return d
class Blockchain:
def __init__(self):
self.chain = [self.createGenesisBlock().setdict()]
# ブロックチェーン上の最初のブロックを生成
def createGenesisBlock(self):
return Block(0, "2021/08/24", "Genesis block", "0")
# 一番後ろに繋がっているブロック
def getLatestBlock(self):
return self.chain[len(self.chain) - 1]
# ブロックの追加
def addBlock(self, newBlock):
newBlock.previousHash = self.getLatestBlock()["hash"]
newBlock.hash = newBlock.calculateHash()
self.chain.append(newBlock.setdict())
def main():
coin = Blockchain()
coin.addBlock(Block(1, "2021/08/24", "amount: 10"))
coin.addBlock(Block(2, "2021/08/25", "amount: 100"))
coin.addBlock(Block(3, "2021/08/26", "amount: 10000"))
for block in coin.chain:
print(block)
'''
実行結果
{'index': 0, 'previousHash': '0', 'timestamp': '2021/08/24', 'data': 'Genesis block', 'hash': '44e3811fe65a8596ca1b6414fadfb6f38bfd24bb54f9574ee5e82e9b7b3876e5'}
{'index': 1, 'previousHash': '44e3811fe65a8596ca1b6414fadfb6f38bfd24bb54f9574ee5e82e9b7b3876e5', 'timestamp': '2021/08/24', 'data': 'amount: 10', 'hash': '9b057d5d043988bba41859ebf38cfee58ce7c5e1d25e3a667a6b093da16e7355'}
{'index': 2, 'previousHash': '9b057d5d043988bba41859ebf38cfee58ce7c5e1d25e3a667a6b093da16e7355', 'timestamp': '2021/08/25', 'data': 'amount: 100', 'hash': '2b808d6db2f0e588fa8457c391da02bb464530b78604b4e46d673454e1d92c36'}
{'index': 3, 'previousHash': '2b808d6db2f0e588fa8457c391da02bb464530b78604b4e46d673454e1d92c36', 'timestamp': '2021/08/26', 'data': 'amount: 10000', 'hash': '16e952f32d9de7b21e69ee67147680ad30b91dfdebcdf2d65874fec09d50c216'}
一文字変えた場合(完全に異なる)
{'index': 0, 'previousHash': '0', 'timestamp': '2021/08/24', 'data': 'Genesis block', 'hash': '44e3811fe65a8596ca1b6414fadfb6f38bfd24bb54f9574ee5e82e9b7b3876e5'}
{'index': 1, 'previousHash': '44e3811fe65a8596ca1b6414fadfb6f38bfd24bb54f9574ee5e82e9b7b3876e5', 'timestamp': '2021/08/24', 'data': 'amount: 1', 'hash': '11b64728eaba296c55cbfb294a9b81d670a7c266681356a735fbfb3a27318af2'}
{'index': 2, 'previousHash': '11b64728eaba296c55cbfb294a9b81d670a7c266681356a735fbfb3a27318af2', 'timestamp': '2021/08/25', 'data': 'amount: 100', 'hash': 'afd17dc3f9b251904bbda335bf613b92efb7bd781e0951115b9919c863057d1f'}
{'index': 3, 'previousHash': 'afd17dc3f9b251904bbda335bf613b92efb7bd781e0951115b9919c863057d1f', 'timestamp': '2021/08/26', 'data': 'amount: 10000', 'hash': '24d9f9d1738c923ae6f3f27bdff33675a994fa738406cfa0081ab868ee2bdf44'}
'''
if __name__ == "__main__":
main()
<file_sep>/README.md
# BlockChain-study
ブロックチェーンに関する勉強用リポジトリ<file_sep>/javascripts-BlockChain/BlockChain1.js
// 参考
// EnterChain
// JavaScriptで作るオリジナル仮想通貨① 基本構造の作成と検証
// https://enterchain.online/
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(timestamp, data, previousHash) {
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash();
}
// ハッシュ値の計算
calculateHash() {
return SHA256(this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
// ジェネシスブロックの作成
createGenesisBlock() {
return new Block("05/02/2019", "GenesisBlock", "0");
}
// 最後に追加したブロックを取得
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
// ブロックの追加
addBlock(newBlock) {
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
// チェーンの妥当性をチェック
isChainValid() {
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
// 現在のブロックのハッシュが書き換わっていないか
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
// 現在のブロックに含まれる一つ前のハッシュと一つ前のブロックのハッシュが同じかどうか
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
}
let originalCoin = new Blockchain();
originalCoin.addBlock(new Block("06/02/2019", {SendCoinToA: 3}));
originalCoin.addBlock(new Block("07/03/2019", {SendCoinToB: 8}));
console.log(JSON.stringify(originalCoin, null, 2));
console.log('ブロックの中身が正常な状態:' + originalCoin.isChainValid());
originalCoin.chain[1].data = {SendCoinToA: 200};
console.log(JSON.stringify(originalCoin, null, 2));
console.log('ブロックの中身を書き換えた状態:' + originalCoin.isChainValid());
// ブロックのデータを書き換えた状態で、更にハッシュ値を再計算する
originalCoin.chain[1].hash = originalCoin.chain[1].calculateHash();
console.log(JSON.stringify(originalCoin, null, 2));
console.log('ハッシュ値を再計算した場合:' + originalCoin.isChainValid());
// 実行した結果
/**
* {
"chain": [
{
"timestamp": "05/02/2019",
"data": "GenesisBlock",
"previousHash": "0",
"hash": "125382495ef973ca5a10e9072963cc8d1f39693bc0271dbd889876b4aa498d64"
},
{
"timestamp": "06/02/2019",
"data": {
"SendCoinToA": 3
},
"previousHash": "125382495ef973ca5a10e9072963cc8d1f39693bc0271dbd889876b4aa498d64",
"hash": "9357a90d3df4676a000ac24e5fe1c61a2ceabcb1bd2a7235006bec8515c15c9e"
},
{
"timestamp": "07/03/2019",
"data": {
"SendCoinToB": 8
},
"previousHash": "9357a90d3df4676a000ac24e5fe1c61a2ceabcb1bd2a7235006bec8515c15c9e",
"hash": "038a24ad189aaf8093ec4e67fe300e8798d28e052ad76ddd9b438cc77d002d00"
}
]
}
ブロックの中身が正常な状態:true
{
"chain": [
{
"timestamp": "05/02/2019",
"data": "GenesisBlock",
"previousHash": "0",
"hash": "125382495ef973ca5a10e9072963cc8d1f39693bc0271dbd889876b4aa498d64"
},
{
"timestamp": "06/02/2019",
"data": {
"SendCoinToA": 200
},
"previousHash": "125382495ef973ca5a10e9072963cc8d1f39693bc0271dbd889876b4aa498d64",
"hash": "9357a90d3df4676a000ac24e5fe1c61a2ceabcb1bd2a7235006bec8515c15c9e"
},
{
"timestamp": "07/03/2019",
"data": {
"SendCoinToB": 8
},
"previousHash": "9357a90d3df4676a000ac24e5fe1c61a2ceabcb1bd2a7235006bec8515c15c9e",
"hash": "038a24ad189aaf8093ec4e67fe300e8798d28e052ad76ddd9b438cc77d002d00"
}
]
}
ブロックの中身を書き換えた状態:false
{
"chain": [
{
"timestamp": "05/02/2019",
"data": "GenesisBlock",
"previousHash": "0",
"hash": "125382495ef973ca5a10e9072963cc8d1f39693bc0271dbd889876b4aa498d64"
},
{
"timestamp": "06/02/2019",
"data": {
"SendCoinToA": 200
},
"previousHash": "125382495ef973ca5a10e9072963cc8d1f39693bc0271dbd889876b4aa498d64",
"hash": "09f96986321b8f9188bc65211e39debbcf5b92cf03899373bedc6b68d7ae2404"
},
{
"timestamp": "07/03/2019",
"data": {
"SendCoinToB": 8
},
"previousHash": "9357a90d3df4676a000ac24e5fe1c61a2ceabcb1bd2a7235006bec8515c15c9e",
"hash": "038a24ad189aaf8093ec4e67fe300e8798d28e052ad76ddd9b438cc77d002d00"
}
]
}
ハッシュ値を再計算した場合:false
*/
|
fa7b14f4b1940f3e2ab51fde9a56a169ff4e02d3
|
[
"JavaScript",
"Python",
"Markdown"
] | 4 |
JavaScript
|
i-708/BlockChain-study
|
ad103b2205982dd751338a9db06036aa8cff497e
|
fa950f764837fe76a0e4f3eaf31d5472fe7ec2a1
|
refs/heads/master
|
<repo_name>fjnoyp/IntroCSLabs<file_sep>/FirstRecursionLab/SpiralRecursion/ShadowGuide.java
import objectdraw.*;
import java.awt.*;
/**
This is the first oval in the shadow "chain" of ovals. This oval moves, thereby causing all the other circles down the chain
to move with it.
*/
public class ShadowGuide extends ActiveObject
{
private static final int OVAL_SIZE = 50;
//We need the filledOval (which is the moving object) and the other segments. We use these segments to find the new
//location for where the filledOval should move to
private FilledOval firstOval;
private Segment currentSegment;
private Segment moveSegment;
//activates and deactivates the shadow guide run method
private boolean running = true;
/**
* Constructor for objects of class ShadowGuide
*/
public ShadowGuide(Segment moveSegmentRef, Segment currentSegmentRef, DrawingCanvas canvas)
{
//create the oval, the height and width of this object will determine the height and width of all the other ovals
//down the line
//100,100 is the location of the firstOval when it is first created, but it is not significant since the oval moves
//along the spiral's segments after a spiral has been created
firstOval = new FilledOval(100,100,OVAL_SIZE,OVAL_SIZE,canvas);
firstOval.hide();
//the segments are necessary so that we have a reference for the spiral's line segments' locations
currentSegment = currentSegmentRef;
moveSegment = moveSegmentRef;
this.start();
}
//Moves this oval along the spiral
public void run()
{
while(running){
if(currentSegment!=null){
///Find the distance we need to travel to get to the next segment of the spiral
int count = 0;
double dx = moveSegment.returnLocation().getX()-firstOval.getX();
double dy = moveSegment.returnLocation().getY()-firstOval.getY();
//move the oval to the target location in increments
while(count<10){
firstOval.move(dx/10,dy/10);
count++;
pause(10);
}
//in case the oval isn't exactly on the spot of the next line segment, force it to do so
firstOval.moveTo(moveSegment.returnLocation());
//get the next line segment in the spiral which we will use as the new target location for where to move to
moveSegment = moveSegment.getLast();
//If this segment doesn't actually exist, go back to the last segment of the spiral
//this is the reason we need two segments in this class's parameter
//while they are both the same at first, one is used as a reference back to the last segment in the spiral
if(moveSegment.getLast()==null)
moveSegment = currentSegment;
}
else break;
}
}
//moves the oval
public void moveTo(Location point)
{
firstOval.moveTo(point);
}
//returns the oval of this shadowGuide
public FilledOval getOval()
{
return firstOval;
}
//remove the shadow guide whenever the canvas is cleared and end the run method
public void removeFromCanvas()
{
running = false;
firstOval.removeFromCanvas();
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
}
<file_sep>/Class-FinalProject/Zapper.java
import objectdraw.*;
import java.awt.*;
public class Zapper {
//Size of zapper
public static final int ZAPPER_SIZE = 24;
private static final int GUN_SIZE = ZAPPER_SIZE/8;
//Zapper step
private static final int ZAPPER_STEP = 10;
//Body of zapper
private FilledRect body;
private FilledRect gun;
//Score reference
public ScoreKeeper score;
//Canvas reference
private DrawingCanvas canvas;
//Zapper constructor class
public Zapper(Location point, ScoreKeeper score, DrawingCanvas canvas)
{
//REVIEW ALL CLASSES FOR CORRECT INSTANCE VARIABLE PLACEMENT
//Draws the zapper
body = new FilledRect(point, ZAPPER_SIZE, ZAPPER_SIZE, canvas);
body.setColor(Color.RED);
//Draw gun
gun = new FilledRect(body.getX()+(ZAPPER_SIZE-GUN_SIZE)/2,body.getY()-GUN_SIZE,GUN_SIZE,GUN_SIZE,canvas);
gun.setColor(Color.RED);
//score reference
this.score = score;
this.canvas = canvas;
}
public void left(){
if(body.getX()>0){
body.move(-ZAPPER_STEP,0);
gun.move(-ZAPPER_STEP,0);
}
}
public void right(){
if(body.getX()+ZAPPER_SIZE<canvas.getWidth()){
body.move(ZAPPER_STEP,0);
gun.move(ZAPPER_STEP,0);
}
}
public void shoot(Field field, Centipede centipede){
Location gunEnd = new Location(gun.getX()+GUN_SIZE/2,gun.getY());
new Missile(gunEnd,field,score,centipede,canvas);
}
public boolean overlaps(VisibleImage image){
return (body.overlaps(image) || gun.overlaps(image));
}
}
<file_sep>/README.md
# IntroCSLabs
Select labs from my first class in computer science. Files with "class" in front of their folder indicate labs done for class, otherwise, these files are 5-10 hours side projects I undertook to learn more about a certain CS concept that I was interested in. The most notable project is "GrowingTree" which simulated tree growths.
<file_sep>/GrowingTree/Trunk.java
import java.awt.*;
import javax.swing.*;
import objectdraw.*;
public class Trunk extends ActiveObject implements TreeInterface
{
Line trunk;
TreeTall tree;
double X,Y = 0;
public Trunk(double startX, double startY, double endX, double endY, TreeTall tree, DrawingCanvas canvasRef)
{
trunk = new Line(startX,startY,endX,endY,canvasRef);
this.tree = tree;
start();
}
public void run()
{
System.out.println("TRUNK" + tree.currentHeight);
pause(19);
}
public void move(double dx,double dy)
{
//issue with wrong dx dy input to tree currentx and currentHeight ?
//or wrong currentX currentHeight
trunk.move(dx,dy);
//something fundamentally wrong with variables in tree class
//note that the first segment always works when moved
//tree.currentX += dx;
//tree.currentHeight += dy; //original
//The commented out code with //original at their ends
//why did this system not work?
//System.out.println((double)tree.currentHeight);
}
public Location getEnd()
{
return trunk.getEnd();
}
public void setEnd(double x, double y)
{
trunk.setEnd(x,y);
}
}
<file_sep>/Class-Photoshop/InvertDialog.java
/*
* Your Name and Lab Here...
*
* A dialog box that takes a visible image and inverts the
* shade of each pixel.
*/
public class InvertDialog extends AdjustmentDialog {
//invert the pixels
protected int[][] adjustPixelArray(int[][] pixels) {
for(int x = 0; x<pixels.length; x++)
for(int y = 0; y<pixels[0].length; y++)
pixels[x][y] = 255 - pixels[x][y];
return pixels;
}
}
<file_sep>/MiniShooter/TurretBall.java
import objectdraw.*;
import java.awt.*;
import java.applet.*;
/**
* CS 134 Laboratory 1 / Section 5
* <NAME>
* 9/10/12
*/
public class TurretBall extends WindowController {
//I wanted to add onto the exising BoxBall class but the features that I was thinking about adding conflict with the features
//that we need to have in the box ball program. This game is based on the boxBall idea but I have another version, BoxBall in
//this same folder that follows all the guidelines that you requested we have for this lab. The main difference from the BoxBall
//lab guidelines is that the projectile's power can be adjusted and changed based on the rotation of the turret, and that the projectile
//comes from a turret rather than a single mouse click.
//Please note this is a work in progress so some code that isn't explicitly used is still important for me
//as I need to use them in the future or for guiding my work
//PIE! - I need this for the trigonometry in this program
public static final double PI = 3.14159265359;
//Valuable text that tells me about the game variables, i keep this because I will be using it in the future if I add other features
private Text debug;
//currently, the debug text object displays the "power" of the projectile as it is shot from the turret. It's location just on top of the
//power level rectangle makes its meaning implied since its value changes whenever the user shoots the projectile at different power levels
//Angles for detecting the angle between the center point and mouse point
public double angle;
private double finalAngle;
//Line drawn between center and mouse point
//1,1,1,1 since the line is modified immediately when the mouse moves (so these values are insignificant)
private Line line = new Line(1,1,1,1,canvas);
//The center point where the platform character will be created
//600 and 500 is the location of center
private Location center = new Location(600,550);
//test 2 is the platform + turret on the screen
//it is called test 2 because there are still more features I'd like to add to it
//private RotatableRect test;
private Platform test2;
//Audio files , turn on your speakers!
private AudioClip cannonFire;
//Determines length of mouse click, this is for finding power of the shot
private double startTime;
public double clickLength;
//Objects for projectile power
private FramedRect powerLevelFrame;
private Text powerLabel;
private PowerLevel powerBar;
//Canvas reference
DrawingCanvas canvasRef;
//Previous point
private Location prevPoint;
//Resource Objects, hitting these with the projectile should increase score
//they are called resource objects and energy because I originally intended to use them for powering the cannon
private ResourceFormat energy;
//Text for score
private Text scoreText;
public int score;
//Text for instructions
private Text instructions;
//The below disabled code was my attempt to create an array to hold the points of the resourceFormat objects that I created. My goal was to have
//multiple resourceFormat class objects be created on screen at once but I didn't know how to pass as a parameter all of their points
//so that the projectile created by the Platform would know when to register a hit. I thought that an array might work but ran out of time to implement
//this idea fully. When we want to detect collision between one object and many other objects, how would one do this if the collision detection
//runs in the object's run method?
/*
//Create an array to hold the location points of the moving object (energy) so that projectile knows if collision has occured
//Create excess space if other points are added if the feature of creating new resource formats is created
private static final int NUM_POINTS = 20; //constants should be on top but it's easier if it's here
Location[] collisionPoints = new Location[NUM_POINTS];
*/
public void begin() {
/*
//fill the Location array with blank locations so that nullPointReference won't happen in case some array spots aren't taken
for(int i = 0; i < NUM_POINTS; i ++){
Location locationPlaceHolder = new Location(-100,0);
collisionPoints[i] = locationPlaceHolder;
}
*/
//Create instructions (60,10 are coordinates of instuctions)
instructions = new Text("Shoot the moving object with your cannon! Shoot farther by holding the mouse button before releasing", 60, 10, canvas);
//Create score Text (10,240 coordinates of scoreText)
scoreText = new Text("Score:" + score,10,240,canvas);
//beta stage of the resource format rotatable object
//this is the weird bulging object on the stage
Location energyLocation = new Location(-100,50);
energy = new ResourceFormat(energyLocation,100,100,canvas,1.1,-1.7,-1,.7);
//Canvas reference
canvasRef = canvas;
//Objects for projectile power
//10,20 are x coordinates, 30, 190 are powerLevelFrame width and height
powerLevelFrame = new FramedRect(10,20,30,190,canvas);
powerLabel = new Text("Power Level", 10, 215, canvas);
//Resize canvas
this.resize(1200,1200);
//Audio files
cannonFire = getAudio("cannon_fire.wav");
//Location of debug text, 10, 10
debug = new Text("", 10,0,canvas);
//Have test 2 create the platform + turret that we see on stage
test2 = new Platform(center,canvas);
}
public void onMouseMove(Location point) {
//Reference for the mouse point on the stage, there is a double reference to the mouse point
//since the location of p1 might be changed to be another location
Location p1 = new Location(point.getX(),point.getY());
//Reset and draw the line each time mouse moves, draw line between platform's point and the mouse point
line.removeFromCanvas();
line = new Line(test2.turretLocation,p1,canvas);
//find angle between two points on the 360 degree plane
angle = Math.atan2((p1.getY()-center.getY()), p1.getX()-center.getX());
//modify angle found by atan2 (since output values are not 0 to 360 degrees)
if(angle >= -PI && angle < 0){
finalAngle = -angle;
}
if(angle >= 0 && angle <= PI){
finalAngle = 2*PI - angle;
}
//The above code finds the angle between the center point of the platform and the mouse point
//This code is no longer in use, but I use it for reference for other programs
//On mouse move, adjust the rotation of the turret on the platform
test2.cannonRotation(finalAngle, p1);
}
public void onMouseEnter(Location point) {
}
public void onMouseExit(Location point) {
}
public void onMousePress(Location point) {
//Find the start time of mouse press
startTime = System.currentTimeMillis();
//Create a new power bar that will tell us how long we have clicked
powerBar = new PowerLevel(canvasRef);
//Parameter for platform recoil, we need the previous point so any mouse changes won't mess
//up the fire method of the platform class
prevPoint = point;
}
public void onMouseClick(Location point) {
}
public void onMouseRelease(Location point) {
//Determine the length of the click
//The lenght of the click is passed as a parameter to test2 and determines strenght of the shot
clickLength = System.currentTimeMillis() - startTime;
clickLength = clickLength/50;
//Restrict the max value of the click to 60
if(clickLength > 60)clickLength = 60;
//Tells me the power of the shot, for debug purpose
debug.setText(clickLength);
//change 60 back to click length
//Run the fire method of the platform class, this recoils the turret and creates a projectile
test2.fire(prevPoint,angle,clickLength,scoreText,score,energy);
//sound effects!
cannonFire.play();
//remove the powerbar that told us the duration of our shot
powerBar.removeFromCanvas();
}
public void onMouseDrag(Location point){
}
}<file_sep>/GrowingTree/TreeV.java
import objectdraw.*;
import java.awt.*;
import java.util.Vector;
public class TreeV extends ActiveObject implements TreeInterface
{
//PI constant for trig
private final static double PI = 3.141593;
//angle randomizer to change angle difference between branching pairs
private RandomDoubleGenerator angleRand = new RandomDoubleGenerator(-.328,0.328);
//randomize time waited before creating next branch segment of growth
private RandomIntGenerator pauseRand = new RandomIntGenerator(1,200);
//All references to be passed from constructor to run method
double startX = 0;
double startY = 0;
int currentBranch = 0;
double branchLength = 0;
double currentAngle = 0;
Color currentColor;
int branchMaximum = 0;
DrawingCanvas canvasRef;
//The branches
Line branchI;
Line branchII;
//Increments until branch grows to its spot
double incrementXI = 0;
double incrementYI = 0;
double incrementXII = 0;
double incrementYII = 0;
//Degree references
double degreeI;
double degreeII;
//Array references
//Line [] branchesArray;
//int arrayNumber;
//Vector reference
public Vector branchVector;
private TreeV childI, childII;
//Dx and Dy references (no longer in use)
private double dx;
private double dy;
public TreeV(double x, double y, int count, double currentLength, double angle, Color color, int maxBranches, Vector branchVectorRef, DrawingCanvas canvas)
{
//pass references to run method
//reference to start position of this branch
startX = x;
startY = y;
currentBranch = count;
branchLength = currentLength;
currentAngle = angle;
currentColor = color;
branchMaximum = maxBranches;
canvasRef = canvas;
branchVector = branchVectorRef;
start();
}
public void run()
{
//The two new branches that grow
branchI = new Line (startX,startY,startX,startY,canvasRef);
branchII = new Line (startX,startY,startX,startY,canvasRef);
//branchVector.add(branchI);
//branchVector.add(branchII);
this.branchVector.add(this);
//System.out.println(this);
//arrayNumber+=2;
//multi use of array
//Set Color
if(currentBranch!=branchMaximum-1){
branchI.setColor(currentColor);
branchII.setColor(currentColor);
}
else{
currentColor = new Color(85,107,47);
branchI.setColor(currentColor);
branchII.setColor(currentColor);
}
//Target locations for branches to grow to
//randomize angle differences between branches
//Anglef or branch I , slightly randomize
double angleDiff = PI/10 + angleRand.nextValue();
//target values for where the branchI should be growing to
double xTargetI = branchLength*Math.cos(currentAngle - angleDiff);
double yTargetI = -branchLength*Math.sin(currentAngle - angleDiff);
//Angle for the branchII , slightly randomize
double angleDiff2 = PI/10 + angleRand.nextValue();
//target value for where the branchII should be growing to
double xTargetII = branchLength*Math.cos(currentAngle + angleDiff2);
double yTargetII = -branchLength*Math.sin(currentAngle + angleDiff2);
//Initialize increments of movement for branchI and branch II
incrementXI = startX;
incrementYI = startY;
incrementXII = startX;
incrementYII = startY;
//counter for while loop
int count = 0;
while(count<20)
{
//Slowly move branch to target growth point
branchI.setEnd(incrementXI,incrementYI);
branchII.setEnd(incrementXII,incrementYII);
//Slowly move increment values to target value
count ++;
incrementXI += xTargetI/20;
incrementYI += yTargetI/20;
incrementXII += xTargetII/20;
incrementYII += yTargetII/20;
pause(42);
}
//diminish future branch length
branchLength = branchLength * .8;
//count to maximum branches
currentBranch ++;
//Create two new branches one at each of this branch's end
//Do not do this when the current branch (or the layer of newly created branches) has reached a level equal to the branchMaximum
if(currentBranch!=branchMaximum){
TreeV childI = new TreeV(branchI.getEnd().getX(),branchI.getEnd().getY(),currentBranch,branchLength,currentAngle - angleDiff,currentColor,branchMaximum,branchVector,canvasRef);
TreeV childII = new TreeV(branchII.getEnd().getX(),branchII.getEnd().getY(),currentBranch,branchLength,currentAngle + angleDiff2,currentColor,branchMaximum,branchVector,canvasRef);
}
/*
double dyI = branchI.getEnd().getY() - branchI.getStart().getY();
double dxI = branchI.getEnd().getX() - branchI.getStart().getX();
double dyII = branchII.getEnd().getY() - branchII.getStart().getY();
double dxII = branchII.getEnd().getX() - branchII.getStart().getX();
double degreeI = Math.atan2(dyI,dxI);
double degreeII = Math.atan2(dyII,dxII);
double theta = 0;
while(true)
{
childI.moveTo(this.thisEnd());
childII.moveTo(this.thisEnd());
degreeI = degreeI + 0.05*Math.cos(theta);
degreeII = degreeII + 0.05*Math.cos(theta);
branchI.moveTo(startX,startY);
branchII.moveTo(startX,startY);
branchI.setEnd(startX+branchLength*1.25*Math.cos(degreeI),startY+branchLength*1.25*Math.sin(degreeI));
branchII.setEnd(startX+branchLength*1.25*Math.cos(degreeII),startY+branchLength*1.25*Math.sin(degreeII));
//adjust these values to get better performance
theta += 0.1;
pause(100);
}
*/
}
/*
public Location thisEnd()
{
Location End = new Location(startX+branchLength*1.25*Math.cos(degreeI), startY+branchLength*1.25*Math.sin(degreeI));
return End;
}
public void moveTo(Location point)
{
this.moveTo(point);
}
*/
public void move(double dx,double dy)
{
branchI.move(dx,dy);
branchII.move(dx,dy);
incrementXI += dx;
incrementYI += dy;
incrementXII += dx;
incrementYII += dy;
}
}
<file_sep>/Class-Photoshop/BrightnessDialog.java
import javax.swing.*;
import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import cs134lib.*;
//brightness changer
public class BrightnessDialog extends AdjustmentDialog implements ChangeListener
{
private JSlider percent;
private JLabel label;
//create the sliders and jlabel that are unique for this dialog box
public BrightnessDialog() {
percent = new JSlider(JSlider.HORIZONTAL,0,200,50);
label = new JLabel("Brightness:",JLabel.CENTER);
JPanel topContents = new JPanel(new GridLayout(2,1));
topContents.add(label);
topContents.add(percent);
Container contentPanes = this.getContentPane();
contentPanes.add(topContents, BorderLayout.NORTH);
contentPanes.validate();
percent.addChangeListener(this);
}
//change brightness based on slider values
protected int[][] adjustPixelArray(int[][] pixels) {
//Multiply each pixel of the image by the percentage that it will be based on the new brightness
for(int x = 0; x<pixels.length; x++)
for(int y = 0; y<pixels[0].length; y++){
double sliderValue = pixels[x][y]*(percent.getValue()/100.0);
pixels[x][y] = (int) sliderValue;
}
return pixels;
}
//whenever the slider is changed, call the adjust image method on the display image again
public void stateChanged(ChangeEvent e)
{
this.adjustImage();
label.setText("Brightness: " + percent.getValue() + "%");
}
}
<file_sep>/FirstRecursionLab/SpiralRecursion/EmptySpiralSegment.java
import objectdraw.*;
import java.awt.*;
/**
Empty spiral so no coding here!
*/
public class EmptySpiralSegment implements Segment
{
public EmptySpiralSegment()
{
}
public void removeFromCanvas()
{
}
public Location returnLocation()
{
return null;
}
public Segment getLast()
{
return null;
}
}
<file_sep>/Class-Photoshop/AdjustmentDialog.java
import javax.swing.*;
import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import cs134lib.*;
/*
The superclass for all the dialogs. This creates the basic dialog box that appears whenever the user
clicks apply. The subclasses differ by making changes to the protected function adjust pixels array
*/
public class AdjustmentDialog extends JDialog implements ActionListener {
// Location and size of dialog box
private static final int LOCATION_X = 400;
private static final int LOCATION_Y = 200;
private static final int WIDTH = 250;
private static final int HEIGHT = 140;
// Buttons to accept or reject the change.
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
// The image display in the canvas of the main window
private VisibleImage display;
// The Image representation of the displayed image prior to transforming it.
private Image original;
public AdjustmentDialog() {
// configure the title, screen location, size, etc. of the dialog box
this.setModal(true);
this.setTitle(this.getClass().getName());
this.setLocation(LOCATION_X,LOCATION_Y);
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
// add the ok and cancel buttons to the dialog box
Container contentPane = this.getContentPane();
JPanel buttons = new JPanel();
buttons.add(okButton);
buttons.add(cancelButton);
contentPane.add(buttons, BorderLayout.SOUTH);
contentPane.validate();
// listen for events on our buttons
okButton.addActionListener(this);
cancelButton.addActionListener(this);
}
/*
* Apply the image transformation and ask user to accept/reject.
*/
public void applyAdjustment(VisibleImage theDisplay) {
// remember the visible image we are to update, as well as the
// image currently being shown.
//display is the visible image, display.getImage() is the actual image
//note that applyAdjustment method automatically gets display image so we don't need to pass a parameter to
//adjustImage anymore
display = theDisplay;
original = display.getImage();
this.adjustImage();
this.setVisible(true);
}
/*
* Handle both button events. Right now, we just close
* the dialog box by setting it to not be visible.
*/
public void actionPerformed(ActionEvent e) {
//if the cancel button is selected keep original image
if(e.getSource()==cancelButton)
display.setImage(original);
//always remove dialogue box after
this.setVisible(false);
}
/*
* Applies the desired transformation to the image. Make separate color arrays for each color value, r, g, b and apply
* the adjustPixelArray method to each color spectrum
*/
protected void adjustImage() {
int[][] red = Images.imageToPixelArray(original,Images.RED_CHANNEL);
int[][] green = Images.imageToPixelArray(original,Images.GREEN_CHANNEL);
int[][] blue = Images.imageToPixelArray(original,Images.BLUE_CHANNEL);
Image newImage = Images.pixelArraysToImage(this.adjustPixelArray(red),this.adjustPixelArray(green),this.adjustPixelArray(blue));
display.setImage(newImage);
}
//varies between subclasses
protected int[][] adjustPixelArray(int[][] pixels) {
return pixels;
}
}
<file_sep>/MiniShooter/ResourceFormat.java
import objectdraw.*;
import java.awt.*;
public class ResourceFormat extends ActiveObject
{
//This class is a variation of the rotatable rectangle. The difference is that the angle constants can be modified so that
//the object bulges and warps as it rotates in space
//pie constant
private static final double PI = 3.14159265359;
//public as they are used in reference elsewhere
//points of the rectanglish object
public Location center,p1,p2,p3,p4;
//lines connecting these points
public Line line1,line2,line3,line4;
//the distance between p1 and center
private double diagonalLength;
//constant angles between the points and the center
private double angleConstant, angle1, angle2, angle3, angle4;
//current rotation, constantly add to this value so that the object rotates
private double theta;
//angle modifiers that change the angle constants between the center point and the exterior points
private double a,b,c,d;
//This class is different in that angle values modify the angle difference between the points and the center points thereby
//adding in special effects such as bulging or twisting
public ResourceFormat(Location centerInit, double width, double height, DrawingCanvas canvas, double aTemp,double bTemp,double cTemp,double dTemp)
{
//centerInit : Initial center
//diagonalLength length between center and p1, necessary since points are always a certain distance from the center
diagonalLength = Math.sqrt((width/2)*(width/2)+(height/2)*(height/2));
//make points same distance from center and place them so they form a rectangle
p1 = new Location(centerInit.getX()+width/2,centerInit.getY()+height/2);
p2 = new Location(centerInit.getX()-width/2,centerInit.getY()+height/2);
p3 = new Location(centerInit.getX()-width/2,centerInit.getY()-height/2);
p4 = new Location(centerInit.getX()+width/2,centerInit.getY()-height/2);
//draw lines between points
line1 = new Line(p1,p2,canvas);
line2 = new Line(p2,p3,canvas);
line3 = new Line(p3,p4,canvas);
line4 = new Line(p4,p1,canvas);
//find the constant angle between the center point and the exterior points, while the angle between them changes as the rectangle
//rotates, current rectangle rotation - angle constant is always amount of radians currently rotated
angleConstant = Math.atan(height/width);
angle1 = angleConstant;
angle2 = PI - angleConstant;
angle3 = angleConstant + PI;
angle4 = 2*PI - angleConstant;
//reference to center point of rectangle
center = centerInit;
//pass references from parameters to this class's doubles
a = aTemp;
b = bTemp;
c = cTemp;
d = dTemp;
this.start();
}
public void rotation(double finalAngle,double a, double b, double c, double d)
{
//reference diagonalLength to shorten code
finalAngle = -finalAngle;
double dl = diagonalLength;
//a,b,c,d modify the angle constants between the point and the center giving this object rotational effects
//cool side note: having different angles for cos/sin adds a "bulge" effect on rotation
p1 = new Location (center.getX()+dl*Math.cos(angle1 + finalAngle),center.getY()+dl*Math.sin(angle1 + a + finalAngle));
p2 = new Location (center.getX()+dl*Math.cos(angle2 + finalAngle),center.getY()+dl*Math.sin(angle2 + b + finalAngle));
p3 = new Location (center.getX()+dl*Math.cos(angle3 + finalAngle),center.getY()+dl*Math.sin(angle3 + c + finalAngle));
p4 = new Location (center.getX()+dl*Math.cos(angle4 + finalAngle),center.getY()+dl*Math.sin(angle4 + d + finalAngle));
line1.setEndPoints(p1,p2);
line2.setEndPoints(p2,p3);
line3.setEndPoints(p3,p4);
line4.setEndPoints(p4,p1);
}
public void moveTo(double x, double y)
{
double dx = x - center.getX();
double dy = y - center.getY();
this.move(dx,dy);
}
public void move(double dx, double dy)
{
center = new Location (center.getX()+dx,center.getY()+dy);
p1 = new Location(p1.getX()+dx,p1.getY()+dy);
p2 = new Location(p2.getX()+dx,p2.getY()+dy);
p3 = new Location(p3.getX()+dx,p3.getY()+dy);
p4 = new Location(p4.getX()+dx,p4.getY()+dy);
line1.setEndPoints(p1,p2);
line2.setEndPoints(p2,p3);
line3.setEndPoints(p3,p4);
line4.setEndPoints(p4,p1);
}
public void run()
{
//while, true so it always runs continously
while(center.getX()<1300)
{
theta += .05;
this.rotation(theta,a,b,c,d);
this.move(1,5*Math.sin(theta));
pause(10);
if(center.getX()>1250)this.moveTo(-100,100);
}
}
}
<file_sep>/Class-Photoshop/NotNotPhotoShop.java
import cs134lib.*;
import objectdraw.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*
The lab. There is an extra feature for having a puzzle game. The code for this feature is within the puzzleDialog
*/
public class NotNotPhotoShop extends WindowController implements ActionListener {
// Size of window when created
private static final int WINDOW_WIDTH = 640;
private static final int WINDOW_HEIGHT = 560;
// Buttons to open a new image file and take a picture
// with the camera
private JButton openFileButton;
private JButton snapshotButton;
//private JButton invertButton;
//private JButton flipButton;
private JButton applyButton;
private JComboBox actionChoice;
// The image we are editing
private VisibleImage display;
//The dialog boxes
private InvertDialog invert = new InvertDialog();
private FlipDialog flip = new FlipDialog();
private BrightnessDialog brightness = new BrightnessDialog();
private PosterizeDialog posterize = new PosterizeDialog();
private PuzzleDialog puzzle = new PuzzleDialog(canvas);
// visible image puzzle piece that we can move
private VisibleImage puzzlePiece;
//previous point for puzzle moving
private Location previousPoint;
//element for letting the user swap puzzle pieces
private boolean previousPuzzle = false;
private VisibleImage piece1, piece2;
/*
* Create the GUI components and load the original image from the harddrive.
* You will change this method when adding new componenets to the interface.
*/
public void begin() {
this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Create the buttons and add them to the window
openFileButton = new JButton("Open");
snapshotButton = new JButton("Take Picture");
applyButton = new JButton("Apply");
//JComboBox for selecting different actions
actionChoice = new JComboBox();
actionChoice.addItem("puzzle");
actionChoice.addItem("invert");
actionChoice.addItem("flip");
actionChoice.addItem("brightness");
actionChoice.addItem("posterize");
JPanel bottomPanel = new JPanel(new GridLayout(2,2));
bottomPanel.add(openFileButton);
bottomPanel.add(snapshotButton);
bottomPanel.add(actionChoice);
bottomPanel.add(applyButton);
// Add the components to the window
Container contentPane = getContentPane();
contentPane.add(bottomPanel, BorderLayout.SOUTH);
contentPane.validate();
// Make me listen for button clicks
snapshotButton.addActionListener(this);
openFileButton.addActionListener(this);
applyButton.addActionListener(this);
// load the beach scene at startup
display = new VisibleImage(getImage("gray-1.jpg"), 0, 0, canvas);
}
/*
* Handle events from the buttons.
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openFileButton) {
//Create chooser to get files
JFileChooser chooser = new JFileChooser();
//display new image if an actual image is selected
if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getAbsolutePath();
Image newImage = Toolkit.getDefaultToolkit().getImage(name);
display.setImage(newImage);
}
} else if (e.getSource() == snapshotButton) {
//Camera snapshot, get image from the camera
Camera camera = new Camera();
Image newImage = camera.getImage();
display.setImage(newImage);
//Based on the selected actionChoice, call a different adjustment class on the display image
} else if (e.getSource() == applyButton) {
if(actionChoice.getSelectedItem() == "flip")
flip.applyAdjustment(display);
else if(actionChoice.getSelectedItem() == "invert")
invert.applyAdjustment(display);
else if(actionChoice.getSelectedItem() == "brightness")
brightness.applyAdjustment(display);
else if (actionChoice.getSelectedItem() == "posterize")
posterize.applyAdjustment(display);
else if (actionChoice.getSelectedItem() == "puzzle")
puzzle.createPuzzle(display);
}
}
//if the display is hidden, that means that the puzzle game has been activated. If so, get the puzzlePiece
//that the mouse contains
public void onMousePress(Location point){
if(display.isHidden())puzzlePiece = puzzle.imageSelected(point);
previousPoint = point;
}
//if the puzzle piece is not null, move it
public void onMouseDrag(Location point){
if(puzzlePiece!=null){
double dx = point.getX() - previousPoint.getX();
double dy = point.getY() - previousPoint.getY();
puzzlePiece.move(dx,dy);
previousPoint = point;
}
}
//if the display is hidden, that means that the puzzle game has been activated.
//if so, get the piece that the mouse has clicked on
//if the user clicks again, swap the locations of the two pieces that have been clicked on
public void onMouseClick(Location point){
if(display.isHidden()){
//if there is no first piece selected get the first piece
if(piece1==null){
piece1 = puzzle.imageSelected(point);
previousPuzzle = (piece1 != null);
}
//if we click again, get the second piece and swap their locations
else {
piece2 = puzzle.imageSelected(point);
if(piece2 != null){
Location tempLoc = piece2.getLocation();
piece2.moveTo(piece1.getLocation());
piece1.moveTo(tempLoc);
//reset for next swap
previousPuzzle = false;
piece1 = null;
piece2 = null;
}
}
}
}
}<file_sep>/Class-Photoshop/PuzzleDialog.java
import javax.swing.*;
import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import cs134lib.*;
/*
* This dialog box opens up a non modal box. Upon opening, this class chops up the display image
* into 100 images. The user can interact with these images by clicking and dragging them and by double clicking
* to swap positions of clicked on images. The user can move a slider and then click on randomize
* to have all the images swap their positions to varying degrees (based on the slider's current value)
*/
public class PuzzleDialog extends JDialog implements ActionListener, ChangeListener
{
// Location and size of dialog box
private static final int LOCATION_X = 400;
private static final int LOCATION_Y = 200;
private static final int WIDTH = 450;
private static final int HEIGHT = 140;
//revert back to original button
private JButton cancelButton = new JButton("Revert Back");
// The image display in the canvas of the main window
private VisibleImage display;
// The Image representation of the displayed image prior to transforming it.
private Image original;
//we need a reference to the canvas
private DrawingCanvas canvas;
//array to hold visible images created from cutting up the original image
private VisibleImage[] imageBlocks = new VisibleImage[100];
//elements for randomizing the locations of the visible images
private JSlider randomization;
private JButton label;
//helps choose a random element in the visible images array
private RandomIntGenerator chooser = new RandomIntGenerator(0,99);
//Create GUI components of the dialog box
public PuzzleDialog(DrawingCanvas canvasRef) {
// configure the title, screen location, size, etc. of the dialog box :
this.setTitle(this.getClass().getName());
this.setLocation(LOCATION_X,LOCATION_Y);
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
// add the ok and cancel buttons to the dialog box
Container contentPane = this.getContentPane();
JPanel buttons = new JPanel();
buttons.add(cancelButton);
contentPane.add(buttons, BorderLayout.SOUTH);
contentPane.validate();
// listen for events on our buttons
cancelButton.addActionListener(this);
//provide reference to the stage
canvas = canvasRef;
//elements for randomizing locations of puzzle pieces :
randomization = new JSlider(JSlider.HORIZONTAL,0,200,50);
label = new JButton("Randomize to: ");
//local variable for insructions
JLabel instructions = new JLabel("Dragmouse to move image, click on two images to swap their positions");
JPanel topContents = new JPanel(new GridLayout(3,1));
topContents.add(label);
topContents.add(randomization);
topContents.add(instructions);
Container contentPanes = this.getContentPane();
contentPanes.add(topContents, BorderLayout.NORTH);
contentPanes.validate();
randomization.addChangeListener(this);
label.addActionListener(this);
}
/*
Create a puzzle out of the visible image
*/
public void createPuzzle(VisibleImage theDisplay) {
// remember the visible image we are to update, as well as the
// image currently being shown.
//display is the visible image, display.getImage() is the actual image
//note that applyAdjustment method automatically gets display image so we don't need to pass a parameter to
//adjustImage anymore
display = theDisplay;
display.hide();
//extract image from display to divide it into puzzle pieces
original = display.getImage();
//call the method to create puzzle pieces out of the display image
this.createPuzzlePieces();
this.setVisible(true);
}
//conver the image into a pixel array and then call divideImage method on that array
public void createPuzzlePieces() {
int[][] pixelArray = Images.imageToPixelArray(original);
divideImage(pixelArray);
}
//This method creates 100 individual visible images out of the display image. These 100 images are accessible
//through the imageBlocks array
protected void divideImage(int[][] pixels){
//<NAME> taught me how to manage the starting values and end values of the x and y for loops
//contained below
//These variables keep track of the positions in the array that holds the pixels in one of the
//100 image blocks
int tempX;
int tempY;
//iterate 100 times thereby creating 100 visible images
//each visible image is 64 by 48 pixels, 100 of them make up the entire original display image
for(int i = 0; i<100; i++)
{
//for every iteration, create a new array that holds the pixels for the current image
int[][] array = new int[64][48];
//reset x for every iteration
tempX = 0;
//change the starting and end limits of the x for loop
//this for loop goes through all the x pixels of the new visible image
//we move through the display pixel array by going from left to right 10 times for each row and 100 times in total
//i%10 keeps "i" from 0 to 9, our start position for creatin each array
for(int x = 64*(i%10); x<64*(i%10)+64; x++){
//reset y for each for loop y iteration
tempY = 0;
//due to the GUI panels, the actual y dimension of the pixel image is 480 and not 560 (stageWidth)
for(int y = 48*(i/10); y<48*(i/10)+48; y++){
//tempX and tempY must always go from 0 to 64 and 0 to 48 and these pixels are set to specific pixels
//in the pixel array of the display image
array[tempX][tempY] = pixels[x][y];
tempY++;
}
tempX ++;
}
//after we create each new box, turn it into a visible image and add it into the visible images array
Image tempImage;
tempImage = Images.pixelArrayToImage(array);
VisibleImage tempVisImage = new VisibleImage(tempImage,64*(i%10),48*(i/10),canvas);
imageBlocks[i] = tempVisImage;
}
//array length of 64, array[63] is the last element
//0,1,2,3 ... length-1
}
//returns the visible image that contains the point
public VisibleImage imageSelected(Location point)
{
for(int i = 0; i<100; i++)
{
if(imageBlocks[i].contains(point)){
imageBlocks[i].sendToFront();
//visually the block is sent to front but we need to change its location in the array
//so that code-wise this block is in front
//store element we are moving to front
VisibleImage tempImage = imageBlocks[i];
//move through elements in front of stored element and move them up a position
int k = i;
for(; k>0; k--)
{
imageBlocks[k] = imageBlocks[k-1];
}
//the first element of the array is now the original imageBlocks[i]
imageBlocks[0] = tempImage;
return tempImage;
}
}
return null;
}
/*
* Handle both button events. Right now, we just close
* the dialog box by setting it to not be visible.
*/
public void actionPerformed(ActionEvent e) {
//if the cancel button is selected keep original image
if(e.getSource()==cancelButton){
for(int i = 0; i<100; i++) imageBlocks[i].removeFromCanvas();
display.show();
this.setVisible(false);
}
//If we click on the randomize button, make the images swap their locations with another image's location
//for the value of the randomization slider bar
if(e.getSource()==label){
//get two random images that are part of the visible images array and have them swap locations
for(int i = 0; i<randomization.getValue(); i++){
VisibleImage temp = imageBlocks[chooser.nextValue()];
VisibleImage temp2 = imageBlocks[chooser.nextValue()];
Location tempLoc = temp2.getLocation();
temp2.moveTo(temp.getLocation());
temp.moveTo(tempLoc);
//is there a better way to do this?
}
}
}
//change the display when the slider is moved
public void stateChanged(ChangeEvent e) {
label.setText("Randomize to: " + randomization.getValue());
}
}
|
dbac67d92378ad4d5bcc9f6a980f93d76177482e
|
[
"Markdown",
"Java"
] | 13 |
Java
|
fjnoyp/IntroCSLabs
|
988e2b0ce8a003366b0a188773bf933c500c918d
|
505bbdf607d9b1a4a00e9c90c26ae31319e0f82f
|
refs/heads/master
|
<file_sep>/**
* This file houses a listing of files to bake into the final build.js bundle.
*
* They must be defined here due to the fact that the bundler cannot follow any
* dependency graphs that lead to these particular files from the entry-point in
* app.js (that information is derived at runtime).
*
* NOTE
* In a larger Enterprise-sized application, you will probably want to split
* out your modules into different directories and have a bundle.js equivalent
* for each module, so that you can have the System-loader only pull those
* chunks of your application if requested (e.g. some Users may never touch a
* particular module, in which case it's nice to have those corresponding files
* in their own bundle(s) so they don't get required at runtime if not required).
*
* This is a small project, so I just chose to bake the entire site into the bundle.js
* and not worry about loading different bundles.
*
*/
// Aurelia Dependencies
import "aurelia-history-browser"
import "aurelia-html-template-element"
import "aurelia-loader-default"
import "aurelia-templating-binding"
import "aurelia-templating-resources"
import "aurelia-templating-router"
import "core-js"
import "webcomponents/webcomponentsjs/HTMLImports.min"
// Behaviours
import "./site-header"
// Routes/views
import "./app"
import "./about"
import "./home"
import "./projects"
import "./toolbox"
<file_sep>/**
* See: https://github.com/SAAirey/aurelia-skeleton-navigation-bundling
*/
var gulp = require('gulp'),
gShell = require('gulp-shell'),
paths = require('../paths');
var bundles = [{
module: 'main',
name: 'build.js'
}];
var bundle = function(minify) {
return bundles.map(function (bundle) {
var jspmCmd = 'jspm bundle ' + bundle.module + ' ' + paths.clientOutputDir + bundle.name;
if (minify)
jspmCmd += " --minify";
return jspmCmd;
})
}
/**
* Task: bundle-client
*
* Uses 'jspm bundle' to build a final output file and corresponding
* source-map for Production use.
*/
gulp.task('bundle-client', gShell.task(
bundle(true)
));
gulp.task('bundle-client-no-minify', gShell.task(
bundle()
));
<file_sep>import "toolbox.html!text"
export class Toolbox {
}<file_sep>let express = require('express'),
router = express.Router();
// Currently only need to support / since we're doing a SPA on the root
router.get('/', function(req, res, next) {
res.render('index', { env: process.env.NODE_ENV, title: '<NAME> - Software / Network Chemist' });
});
export default router;
<file_sep>import {Router} from "aurelia-router"
import "styles/jgarfield!css"
export class App {
static inject() { return [Router]; }
constructor(router) {
this.router = router;
this.router.configure(config => {
config.title = "<NAME> - Software / Network Chemist";
config.map([
{ route: ["home", ""], moduleId: "./home", nav: true },
{ route: "resume", moduleId: "./resume", nav: true },
{ route: "about", moduleId: "./about", nav: true }
]);
});
}
}<file_sep># Description
Code for the jgarfield.com web site.
# To setup and use
* npm install
* jspm install
* npm start
# Todo
* Screw with the Aurelia router some more to figure out how to properly accomplish a sub-menu / drop-down menu on the navbar w/ Bootstrap
* Build system still needs some work, as well as handling changelog and release prepping
* Rather than simply catch the System.import Promise for aurelia-bootstrapper, need to make the error message display on the screen or direct to a new page rather than just output to the Console.
* Setup pushState
* Import Google Docs Resume version as HTML vs. loading via iFrame since it looks horrible and wastes space
* Finish setting up headless browser to render for Google / Search Bots
<file_sep>var gulp = require('gulp'); // The streaming build system
var runSequence = require('run-sequence'); // Run a series of dependent gulp tasks in order
var changed = require('gulp-changed'); // Only pass through changed files
var plumber = require('gulp-plumber'); // Prevent pipe breaking caused by errors from gulp plugins
var babel = require('gulp-babel'); // Turn ES6 code into vanilla ES5 with no runtime required
var sourcemaps = require('gulp-sourcemaps'); // Source map support for Gulp.js
var assign = Object.assign || require('object.assign'); // Native mixin support
var paths = require('../paths'); // Custom
var compilerOptions = require('../babel-options'); // Custom
// copies changed html files to the output directory
gulp.task('build-html', function () {
return gulp.src(paths.clientHtmlFiles)
.pipe(changed(paths.clientHtmlFiles, { extension: '.html' }))
.pipe(gulp.dest(paths.clientOutputDir));
});
// copies changed html files to the output directory
gulp.task('build-css', function () {
return gulp.src(paths.clientCssFiles)
.pipe(changed(paths.clientCssFiles, { extension: '.css' }))
.pipe(gulp.dest(paths.clientOutputDir));
});
// this task calls the clean task (located
// in ./clean.js), then runs the build-system
// and build-html tasks in parallel
// https://www.npmjs.com/package/gulp-run-sequence
gulp.task('build', function(callback) {
return runSequence(
'clean',
['build-client', 'build-html', 'build-css'],
callback
);
});
<file_sep>// import the bundle file so that the bundler knows what our dependencies are for bundling
import './bundle-runtime-dependencies';
import "aurelia-bootstrapper";<file_sep>var path = require("path"),
appRoot = path.join(__dirname, "../");
module.exports = {
appRoot: appRoot,
clientSourceFiles: appRoot + "public/src/**/*.js",
clientHtmlFiles: appRoot + "public/src/**/*.html",
clientCssFiles: appRoot + 'public/css/**/*.css',
clientOutputDir: appRoot + "public/dist/"
};
<file_sep>import {Behavior} from 'aurelia-framework';
import "site-header.html!text"
export class SiteHeader {
static metadata(){ return Behavior.withProperty('router'); }
}<file_sep>// This example shows how to render pages that perform AJAX calls
// upon page load.
//
// Instead of waiting a fixed amount of time before doing the render,
// we are keeping track of every resource that is loaded.
//
// Once all resources are loaded, we wait a small amount of time
// (resourceWait) in case these resources load other resources.
//
// The page is rendered after a maximum amount of time (maxRenderTime)
// or if no new resources are loaded.
var resourceWait = 300,
maxRenderWait = 10000;
var page = require("webpage").create(),
system = require("system"), // PhantomJS
count = 0,
forcedRenderTimeout,
renderTimeout;
page.viewportSize = { width: 1280, height : 1024 };
function doRender() {
var content = page.content;
process.stdout.write(content);
phantom.exit();
}
page.onResourceRequested = function (req) {
count += 1;
clearTimeout(renderTimeout);
};
page.onResourceReceived = function (res) {
if (!res.stage || res.stage === 'end') {
count -= 1;
if (count === 0) {
renderTimeout = setTimeout(doRender, resourceWait);
}
}
};
page.open(system.args[1], function (status) {
if (status !== "success") {
phantom.exit();
} else {
forcedRenderTimeout = setTimeout(function () {
doRender();
}, maxRenderWait);
}
});
<file_sep>var gulp = require('gulp');
var paths = require('../paths');
var yuidoc = require('gulp-yuidoc');
// uses yui to generate documentation to doc/api.json
gulp.task('doc-generate', function(){
return gulp.src(paths.clientSourceFiles)
.pipe(yuidoc.parser(null, 'api.json'))
.pipe(gulp.dest(paths.documentOutputDir));
});
<file_sep>/**
* Currently this file is used to launch the Application in AWS Elastic Beanstalk.
*
* NOTE
* This file must remain in ES5 at this point in time. This is run BEFORE any of
* the ES6 loaders and Transpilers are loaded, meaning that the environment at
* this point has no concept of ES6 at all.
*/
var System = require('systemjs');
// Tell System where Babel is and to use it as the ES6 Transpiler.
// TODO: This should be obsolete within the next few revs of SystemJS. Talked with guybedford and he said he's planning on having all of this "just work" eventually.
System.config({
transpiler: 'babel',
paths: {
// This probably seems strange pointing to browser.js on the server-side, but this is the
// only way to make the SystemJS Loader work in Node.js land right now. This will change in
// future releases as more metadata becomes available to the Loader.
babel: 'node_modules/babel-core/browser.js'
}
});
// Currently, if we access __dirname in code, it will resolve to the es6-module-loader\dist
// folder since that ends up being where everything loads from at the moment.
// TODO: Check to see if there's a better way to handle the relative path of the app outside of passing in __dirname
System.import("src/application")
.then(function(module) {
var App = module.Application;
new App(__dirname);
})
.catch(function(err) {
console.log("There was an error starting the application: " + err);
});
<file_sep>import "home.html!text"
export class Home {
}<file_sep>import "about.html!text"
export class About {
}<file_sep>var application = require('../');
describe('exports', function(){
it("should expose an object", function() {
application.should.be.a.Object;
});
it("should not expose a function", function() {
application.should.not.be.a.Function;
});
});
|
53388df8fa5b1e870496bd0ae318551a3d2cbfb2
|
[
"JavaScript",
"Markdown"
] | 16 |
JavaScript
|
Tri4ce/jgarfield-com
|
419222ccc434fd559d66c44be45be24affcdb4d5
|
286ac3d8e90ad4d5b469cc2a4bc9dbbc55f71f6f
|
refs/heads/main
|
<file_sep>interface IStyleRules {
[ruleName: string]: string
}
declare const ruleNames: IStyleRules
declare module '*.css' {
export = ruleNames
}
declare module '*.scss' {
export = ruleNames;
}
<file_sep>This project is an [AppRun](https://apprun.js.org/) library test.
It consists of a litle form to type a few user data. And, as user types, it will show the typed data under the form. (There is no validation implemented)
In this package are beeing used:
* Stylelint for CSS, Sass, PostCSS, etc
* Tailwindcss as styling framework
* Prettier as code formatter
* Typescript as language for JS typing
* Rollup as bundler - with Terser plugin for minifying
* Live-server for development<file_sep>{
"compilerOptions": {
"target": "ESNEXT",
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"reactNamespace": "app",
"lib": ["ESNext", "DOM", "ScriptHost", "ES2021"],
"experimentalDecorators": true,
"sourceMap": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"paths": {
"@/": ["./src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.css", "src/**/*.scss"],
"exclude": [
"node_modules",
"public",
"tests/**/*.test.tsx"
]
}
|
c6d4576178e818191cd573f0b4127dafe0dbfb90
|
[
"Markdown",
"TypeScript",
"JSON with Comments"
] | 3 |
TypeScript
|
rogersanctus/test-apprun-full
|
376bc717456416bd7a3b48759e24a25747c67519
|
5a77bcf6412daa5a77054fb2f99659f5be5980a4
|
refs/heads/master
|
<file_sep># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'VKAuth' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for VKAuth
target 'VKAuthTests' do
inherit! :search_paths
# Pods for testing
end
target 'VKAuthUITests' do
inherit! :search_paths
# Pods for testing
end
platform :ios, '6.0'
pod "VK-ios-sdk"
end
|
aec63d70814739bc6da6256d9e6cb7724d296230
|
[
"Ruby"
] | 1 |
Ruby
|
root0x251/VKAuth
|
31b67447e9a3ce9908770ef426425793a238b326
|
647118c9148e2481bb9841df4685e89b5d78db8e
|
refs/heads/master
|
<file_sep>package by.buzzit.belprint.constants;
/**
* Created by dzmitrykankalovich on 6/14/15.
*/
public class PagesConstants {
public static final String ORDERS = "/pages/orders";
public static final String AUTH_ERROR_PAGE = "/pages/auth_error.jsp";
public static final String COMMON_ERROR = "/pages/common_error.jsp";
}
<file_sep>package by.buzzit.belprint.commands;
import by.buzzit.belprint.constants.AppConstants;
import by.buzzit.belprint.constants.PagesConstants;
import by.buzzit.belprint.domain.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by dzmitrykankalovich on 6/14/15.
*/
public class AuthCommand extends Command {
@Override
public Page execute(HttpServletRequest request, HttpServletResponse response) {
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
//Здесь должно быть обращение к базе
if(true) {
HttpSession session = request.getSession();
session.setAttribute(AppConstants.ATTRIBUTE_USER, new User("admin"));
return new Page(Page.DISPATCH_REDIRECT, PagesConstants.ORDERS);
} else {
return new Page(Page.DISPATCH_REDIRECT, PagesConstants.AUTH_ERROR_PAGE);
}
}
}
<file_sep>package by.buzzit.belprint.commands;
/**
* Created by dzmitrykankalovich on 6/14/15.
*/
public class Page {
public static final String DISPATCH_FORWARD = "forward";
public static final String DISPATCH_REDIRECT = "redirect";
private String dispatchType;
private String pageUrl;
public Page(String dispatchType, String pageUrl) {
this.dispatchType = dispatchType;
this.pageUrl = pageUrl;
}
public String getDispatchType() {
return dispatchType;
}
public void setDispatchType(String dispatchType) {
this.dispatchType = dispatchType;
}
public String getPageUrl() {
return pageUrl;
}
public void setPageUrl(String pageUrl) {
this.pageUrl = pageUrl;
}
}
|
ae9321fb36d5db384faad16fc7db19c57fa4bc91
|
[
"Java"
] | 3 |
Java
|
Dminevsky/bp
|
426985a21b45f2c918dea6fbf6c0c2234c5a13a8
|
aa594b76375822ed5670527e040d5a7323d2c32e
|
refs/heads/main
|
<file_sep><!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link href="css/style.css" rel="stylesheet" >
<title>Hello, world!</title>
</head>
<body>
<div class="tudo">
<nav class="navbar navbar-light bg-light">
<a class="navbar-brand" href="#">
<!-- <img src="http://localhost/CursoPHP/botstrap/imagens/Dre.png" class="d-inline-block align-top img" alt=""> -->
</a>
<ul class="nav justify-content-end">
<li class="nav-item">
<a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Sobre <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item ">
<a class="nav-link" href="#">Contato <span class="sr-only">(current)</span></a>
</li>
</ul>
</nav>
<section class="banner">
<div class="overlay"></div>
<div class="container chamada-banner">
<div class="row">
<div class="col-md-12 text-center">
<h2><?php echo htmlentities('<'); ?>New. Project<?php echo htmlentities('>'); ?></h2>
<p>Empresa voltada para desenvolvimento web e marketing digital</p>
<a href="">Saiba Mais!</a>
</div>
</div>
</div>
</section>
<section class="cadastro-lead">
<div class="container">
<div class="row text-center">
<div class="col-md-6">
<h2><svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-bookmark-check-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M4 0a2 2 0 0 0-2 2v13.5a.5.5 0 0 0 .74.439L8 13.069l5.26 2.87A.5.5 0 0 0 14 15.5V2a2 2 0 0 0-2-2H4zm6.854 5.854a.5.5 0 0 0-.708-.708L7.5 7.793 6.354 6.646a.5.5 0 1 0-.708.708l1.5 1.5a.5.5 0 0 0 .708 0l3-3z"/>
</svg> Entre na nossa lista!</h2>
</div>
<div class="col-md-6">
<form method="post">
<input type="text" name="nome" /><input type="submit" value="Enviar" />
</form>
</div>
</div>
</div>
</section>
<section class="depoimento text-center">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Depoimento</h2>
<blockquote>
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eget lorem varius, pellentesque ipsum convallis, suscipit neque. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam quis orci quam. Phasellus dictum erat at nibh bibendum, eget porta urna pretium. Maecenas vel augue massa. Nulla facilisi. Nulla a suscipit quam, eu pharetra justo."</p>
</blockquote>
</div>
</div>
</div>
</section>
<section class="diferenciais text-center">
<h2>Conheça nossa empresa!</h2>
<div class="container diferenciais-container">
<div class="row">
<div class="col-md-4 quadrado">
<h3> <h3><svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-check-circle" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path fill-rule="evenodd" d="M10.97 4.97a.75.75 0 0 1 1.071 1.05l-3.992 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.236.236 0 0 1 .02-.022z"/>
</svg></h3></span></h3>
<h2>Diferencial #1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent lorem nisi, faucibus vestibulum pellentesque a, malesuada vel metus. Aliquam iaculis, quam sed tempus posuere, nulla metus ullamcorper turpis, ut fringilla dolor risus eget elit. Pellentesque elementum iaculis ex. Morbi quis molestie purus. Donec dapibus turpis ac imperdiet rhoncus. </p>
</div>
<div class="col-md-4 quadrado">
<h3><svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-check-circle" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path fill-rule="evenodd" d="M10.97 4.97a.75.75 0 0 1 1.071 1.05l-3.992 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.236.236 0 0 1 .02-.022z"/>
</svg></h3>
<h2> Diferencial #2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent lorem nisi, faucibus vestibulum pellentesque a, malesuada vel metus. Aliquam iaculis, quam sed tempus posuere, nulla metus ullamcorper turpis, ut fringilla dolor risus eget elit. Pellentesque elementum iaculis ex. Morbi quis molestie purus. Donec dapibus turpis ac imperdiet rhoncus.</p>
</div>
<div class="col-md-4 quadrado">
<h3><svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-check-circle" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path fill-rule="evenodd" d="M10.97 4.97a.75.75 0 0 1 1.071 1.05l-3.992 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.236.236 0 0 1 .02-.022z"/>
</svg></h3> <h2>Diferencial #3</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent lorem nisi, faucibus vestibulum pellentesque a, malesuada vel metus. Aliquam iaculis, quam sed tempus posuere, nulla metus ullamcorper turpis, ut fringilla dolor risus eget elit. Pellentesque elementum iaculis ex. Morbi quis molestie purus. Donec dapibus turpis ac imperdiet rhoncus.</p>
</div>
</div>
</section>
<section class="equipe">
<h2>Equipe</h2>
<div class="container equipe-container">
<div class="row">
<div class="col-md-6">
<div class="equipe-single">
<div class="row">
<div class="col-md-2">
<div class="user-picture">
<div class="user-picture-child"></div>
</div>
</div>
<div class="col-md-10">
<h3>Evellyn</h3>
<p>Aliquam iaculis, quam sed tempus posuere, nulla metus ullamcorper turpis, ut fringilla dolor risus eget elit. </p>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="equipe-single">
<div class="row">
<div class="col-md-2">
<div class="user-picture">
<div class="user-picture-child"></div>
</div>
</div>
<div class="col-md-10">
<h3>Evellyn</h3>
<p>Aliquam iaculis, quam sed tempus posuere, nulla metus ullamcorper turpis, ut fringilla dolor risus eget elit. </p>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="equipe-single">
<div class="row">
<div class="col-md-2">
<div class="user-picture">
<div class="user-picture-child"></div>
</div>
</div>
<div class="col-md-10">
<h3>Evellyn</h3>
<p>Aliquam iaculis, quam sed tempus posuere, nulla metus ullamcorper turpis, ut fringilla dolor risus eget elit. </p>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="equipe-single">
<div class="row">
<div class="col-md-2">
<div class="user-picture">
<div class="user-picture-child"></div>
</div>
</div>
<div class="col-md-10">
<h3>Evellyn</h3>
<p>Aliquam iaculis, quam sed tempus posuere, nulla metus ullamcorper turpis, ut fringilla dolor risus eget elit. </p>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="final-site">
<div class="container">
<div class="row">
<div class="col-md-6">
<h2>Fale conosco</h2>
<form>
<div class="form-group">
<label for="email">Nome:</label>
<input type="text" name="nome" class="form-control" id="nome">
</div>
<div class="form-group">
<label for="email">E-mail:</label>
<input type="email" name="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="email">Mensagem:</label>
<textarea class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="col-md-6">
<h2>Nossos planos</h2>
<table class="table">
<thead>
<tr>
<th>Plano Semanal</th>
<th>Plano Diário</th>
<th>Plano Anual</th>
</tr>
</thead>
<tbody>
<tr>
<td>R$199,00</td>
<td>R$299,00</td>
<td>R$399,00</td>
</tr>
<tr>
<td>R$199,00</td>
<td>R$299,00</td>
<td>R$399,00</td>
</tr>
<tr>
<td>R$199,00</td>
<td>R$299,00</td>
<td>R$399,00</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
<footer>
<p class="text-center">Todos os direitos reservados!</p>
</footer>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
|
b09079a309109c70488f312833ff5839574566dc
|
[
"PHP"
] | 1 |
PHP
|
evellyntauany/Projeto---PHP---Bootstrap
|
9b02d206129ac336b1d99ed46c2bedeaf8a84022
|
fbe5ab772ed23a5e55cd3d6ef5c5bed26be81ac0
|
refs/heads/master
|
<file_sep>#include <IRremote.h> // 引用 IRRemote 函式库
// 头文件已经定义PIN 3为信号输出。。
// 所以只能连接PIN 3 ,若更改请在头文件更改
//Mega2560对应的是引脚9
IRsend irsend; // 定义 IRsend 物件来发射红外线讯号
void setup()
{
//
}
void loop()
{
irsend.sendNEC(0xC728D, 32); //关——编码
delay(2000);
}
<file_sep># Code-for-Arduino
Code to store Arduino
123
|
9fbf69746047e005b3f88a9a2ad1afafb766b94c
|
[
"Markdown",
"C++"
] | 2 |
C++
|
Arvin-666/Code-for-Arduino
|
b4e54ee61f3c9b757d1748cc8a7b8106779e1cad
|
b462cdb38e08421270f6967c55493c9a0d749f8c
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python2
#
# Demonstrates how to parse URLs with Python
# This version creates a Weblog object. For details review
# http://stackoverflow.com/questions/472000/python-slots
import re # bring in regular expression package
from dateutil import parser
class Weblog(object):
__slots__ = ['ip','timestamp','request','result','user','agent',
'referrer','url','date']
clf_regex = '([(\d\.)]+) [^ ]+ [^ ]+ \[(.*)\] "(.*)" (\d+) [^ ]+ ("(.*)")? ("(.*)")?'
clf_parser = re.compile(clf_regex)
def __init__(self,line):
m = self.clf_parser.match(line)
if not m:
raise ValueError("invalid logfile line: "+line)
self.ip = m.group(1)
self.timestamp = m.group(2)
self.request = m.group(3)
self.result = m.group(4)
self.user = m.group(5)
self.agent = m.group(6)
self.referrer = m.group(7)
self.url = self.request.split(" ")[1]
self.date = parser.parse(self.timestamp.replace(":", " ", 1)).isoformat()
# test the parser
if __name__=="__main__":
line = '172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] "GET /hello.html HTTP/1.1" 401 - "" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827"'
a = WeblogParser(line)
print("url: %s date: %s" % (a.url,a.date))
<file_sep>#!/usr/bin/env python2
# This is the final wordcount program.
# the mapper outputs <word,1>
# the reducer receives <word,(1,1,1,...)> and outputs <word,COUNT>
import mrjob
from mrjob.job import MRJob
from weblog import Weblog # imports class defined in weblog.py
import os
class WeblogBounds(MRJob):
def mapper(self, _, line):
# Get the name of the input file, per mrjob v0.4.6 documentation
# https://pythonhosted.org/mrjob/utils-compat.html
filename = mrjob.compat.jobconf_from_env("map.input.file")
# parse the weblog input line
log = Weblog(line)
# output <filename,date>
yield filename,log.date
def reducer(self, key, values):
# find the minimum and the maximum date for each key
# notice that we can't simply say min(values) and max(values), because we need to compute
# both at the same time (we don't want to consume the values)
vmin = None
vmax = None
for v in values:
if v<vmin or not vmin: vmin=v
if v>vmax or not vmax: vmax=v
yield (key,(vmin,vmax))
if __name__=="__main__":
WeblogBounds.run()
|
313c5c734871c8a8511048247dddf56d90d76a82
|
[
"Python"
] | 2 |
Python
|
arifyali/ANLY502
|
3997929a2a12d2fce7014e941b5bf35939799200
|
5a52a7db3ddcc58868d6d514f21108d6b85a1749
|
refs/heads/master
|
<repo_name>macagua/django-user-language-middleware<file_sep>/tests/test_middleware.py
try:
from unittest.mock import Mock
from unittest.mock import patch
except ImportError:
from mock import Mock
from mock import patch
from django.test import SimpleTestCase
from user_language_middleware import UserLanguageMiddleware
from user_language_middleware import middleware
class UserLanguageMiddlewareTest(SimpleTestCase):
def setUp(self):
self.mock_request = Mock()
self.mock_response = Mock()
self.LANGUAGE_SESSION_KEY = ''
self.mock_request.session = {self.LANGUAGE_SESSION_KEY: ''}
self.ulm = UserLanguageMiddleware()
@patch.object(middleware, 'translation')
def test_process_response_user_not_authenticated(self, mock_translation):
self.mock_request.user.is_authenticated = False
res = self.ulm.process_response(self.mock_request, self.mock_response)
assert 0 == mock_translation.activate.call_count
assert res is self.mock_response
@patch.object(middleware, 'translation')
def test_process_response_with_same_language(self, mock_translation):
self.mock_request.user.is_authenticated = True
self.mock_request.user.language = 'en'
mock_translation.get_language.return_value = 'en'
res = self.ulm.process_response(self.mock_request, self.mock_response)
assert 0 == mock_translation.activate.call_count
assert res is self.mock_response
@patch.object(middleware, 'translation')
def test_process_response_activate_user_language(self, mock_translation):
self.mock_request.user.is_authenticated = True
self.mock_request.user.language = 'fr'
mock_translation.get_language.return_value = 'en'
user_lang = self.mock_request.user.language
session_lang = self.mock_request.session
session_lang[self.LANGUAGE_SESSION_KEY] = user_lang
res = self.ulm.process_response(self.mock_request, self.mock_response)
assert 1 == mock_translation.activate.call_count
assert 'fr' == session_lang[self.LANGUAGE_SESSION_KEY]
assert res is self.mock_response
@patch.object(middleware, 'translation')
def test_process_response_no_language(self, mock_translation):
del self.mock_request.user.language
res = self.ulm.process_response(self.mock_request, self.mock_response)
assert 0 == mock_translation.activate.call_count
assert res is self.mock_response
@patch.object(middleware, 'translation')
def test_process_response_no_user(self, mock_translation):
del self.mock_request.user
res = self.ulm.process_response(self.mock_request, self.mock_response)
assert 0 == mock_translation.activate.call_count
assert res is self.mock_response
<file_sep>/README.rst
************************
User Language Middleware
************************
.. image:: https://travis-ci.org/laura-barluzzi/django-user-language-middleware.svg?branch=master
:target: https://travis-ci.org/laura-barluzzi/django-user-language-middleware
.. image:: https://img.shields.io/pypi/v/django-user-language-middleware.svg
:target: https://pypi.python.org/pypi/django-user-language-middleware/
What's this?
============
This package contains a middleware that activates translations based on the
language field in the user model. This enables easy user-specific localization
of a Django application: just add a language string field to the user model,
install this middleware and you're good to go!
Usage
=====
Add a language field to your user model:
.. code-block:: python
class User(auth_base.AbstractBaseUser, auth.PermissionsMixin):
# ...
language = models.CharField(max_length=10,
choices=settings.LANGUAGES,
default=settings.LANGUAGE_CODE)
Install the middleware from pip:
.. code-block:: sh
pip install django-user-language-middleware
and then add it to your middleware class list to listen to requests:
.. code-block:: python
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'user_language_middleware.UserLanguageMiddleware',
...
]
Supported versions
==================
Python:
- 2.7
- 3.4 to 3.6
Django:
- 1.8 to 1.11
- 2.0
|
0863cf099ae446f5387183ef8a65926891a4b1eb
|
[
"Python",
"reStructuredText"
] | 2 |
Python
|
macagua/django-user-language-middleware
|
7b746c7356f0f5cfd16d3023a8f0ad14c016f399
|
a1d969b746bbeb8b1dac9171d0aeaaa24d74b304
|
refs/heads/master
|
<file_sep>from django.contrib import admin
from .models import User, AuctionListings, Bids, Comments, Watchlists
# Register your models here.
admin.site.register(User)
admin.site.register(AuctionListings)
admin.site.register(Bids)
admin.site.register(Comments)
admin.site.register(Watchlists)
<file_sep>from django import forms
class CreateListingForm(forms.Form):
title = forms.CharField(
label="Title:",
required=True,
widget=forms.TextInput(attrs={
"class": "form-control"
})
)
description = forms.CharField(
label="Description:",
required=True,
widget=forms.Textarea(attrs={
"class": "form-control",
"row": "5"
})
)
bid = forms.IntegerField(
label="Starting Bid:",
min_value=1,
required=True,
widget=forms.NumberInput(attrs={
"class": "form-control"
}),
)
image_url = forms.URLField(
label="URL to Listing Image:",
required=False,
widget=forms.TextInput(attrs={
"class": "form-control"
})
)
category = forms.CharField(
label="Category:",
required=False,
widget=forms.TextInput(attrs={
"class": "form-control"
})
)
# class PlaceBidForm(forms.Form):
# place_bid = forms.IntegerField(
# required=True,
# widget=forms.NumberInput(attrs={
# "class": "form-control",
# "placeholder": "Bid"
# }),
# )
class CommentForm(forms.Form):
comment = forms.CharField(
required=True,
widget=forms.Textarea(attrs={
"class": "form-control",
"placeholder": "Comment",
"rows": 3
})
)
<file_sep>from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class AuctionListings(models.Model):
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="listings")
active_status = models.BooleanField(default=True)
title = models.CharField(max_length=200)
description = models.CharField(max_length=1000)
image_url = models.URLField(max_length=200, blank=True, default="")
category = models.CharField(
max_length=50, blank=True, default="No Category Listed")
creation_time = models.DateTimeField(auto_now_add=True, blank=True)
class Bids(models.Model):
listing_id = models.ForeignKey(
AuctionListings, on_delete=models.CASCADE, related_name="bid")
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="bids")
amount = models.IntegerField()
creation_date = models.DateTimeField(auto_now=True)
class Comments(models.Model):
listing_id = models.ForeignKey(
AuctionListings, blank=True, on_delete=models.CASCADE, related_name="comments")
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="comments")
text = models.TextField()
created_date = models.DateTimeField(auto_now=True)
class Watchlists(models.Model):
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="watchlists")
item = models.ManyToManyField(
AuctionListings, blank=True, related_name="watchlists")
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("categories", views.categories, name="categories"),
path("watchlist", views.watchlist, name="watchlist"),
path("create_listing", views.create_listing, name="create_listing"),
path("listing/<str:_listing_id>", views.listing, name="listing"),
path("place_bid/<str:_listing_id>", views.place_bid, name="place_bid"),
path("watchlist_add/<str:_listing_id>",
views.watchlist_add, name="watchlist_add"),
path("close_listing/<str:_listing_id>",
views.close_listing, name="close_listing"),
path("delete_listing/<str:_listing_id>",
views.delete_listing, name="delete_listing"),
path("make_commtnt/<str:_listing_id>",
views.make_comment, name="make_comment")
]
<file_sep># Generated by Django 3.1.1 on 2020-10-03 05:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0004_watchlists'),
]
operations = [
migrations.AddField(
model_name='auctionlistings',
name='active_status',
field=models.BooleanField(default=True),
),
]
<file_sep>from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.db.models import Max
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from .models import User, AuctionListings, Bids, Comments, Watchlists
from .forms import CreateListingForm, CommentForm
def index(request):
return render(request, "auctions/index.html", {
"active_listings": AuctionListings.objects.all(),
})
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["<PASSWORD>"]
user = authenticate(request, username=username, password=<PASSWORD>)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "auctions/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "auctions/login.html")
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["<PASSWORD>"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "auctions/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "auctions/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
return render(request, "auctions/register.html")
def categories(request):
if request.method == "POST":
category = request.POST["category"]
category_list = AuctionListings.objects.filter(category=category)
return render(request, "auctions/categories.html", {
"category_list": category_list
})
categories = AuctionListings.objects.order_by().values_list("category").distinct()
categories_list = map(lambda c: c[0], categories)
return render(request, "auctions/categories.html", {
"categories": categories_list
})
@login_required(login_url="login")
def watchlist(request):
my_watchlist = Watchlists.objects.filter(user_id=request.user)
return render(request, "auctions/watchlist.html", {
"my_watchlist": my_watchlist
})
@login_required(login_url="login")
def create_listing(request):
if request.method == "POST":
title = request.POST["title"]
description = request.POST["description"]
bid = request.POST["bid"]
image_url = request.POST["image_url"]
category = request.POST["category"]
try:
auction_listing = AuctionListings(
user_id=request.user,
title=title,
description=description,
image_url=image_url,
category=category
)
bid = Bids(
listing_id=auction_listing,
user_id=request.user,
amount=bid
)
auction_listing.save()
bid.save()
message = "Saved..."
except IntegrityError:
if auction_listing.id:
auction_listing.delete()
if bid.id:
bid.delete()
message = "Error. Fill the form correctly."
return render(request, "auctions/create_listing.html", {
"message": message,
"create_listing_form": CreateListingForm()
})
return render(request, "auctions/create_listing.html", {
"create_listing_form": CreateListingForm()
})
@login_required(login_url="login")
def listing(request, _listing_id):
get_listing = AuctionListings.objects.get(pk=_listing_id)
max_bid = get_max_bid(get_listing, Bids)
get_watchlist = Watchlists.objects.filter(
user_id=request.user, item=get_listing.id).exists()
return render(request, "auctions/listing.html", {
"listing": get_listing,
"max_bid": Bids.objects.filter(amount=max_bid).first(),
"on_watchlist": get_watchlist,
"comment_form": CommentForm(),
"comments": Comments.objects.filter(listing_id=get_listing).order_by("-created_date")
})
@login_required(login_url="login")
def place_bid(request, _listing_id):
if request.method == "POST":
_place_bid = request.POST["place_bid"]
try:
p_bid = Bids(
user_id=request.user,
listing_id=AuctionListings.objects.get(id=_listing_id),
amount=_place_bid
)
p_bid.save()
return HttpResponseRedirect(reverse("listing", args=[_listing_id]))
except IntegrityError:
return HttpResponseRedirect(reverse("listing", args=[_listing_id]))
return render(request, "auctions/index.html", {
"message": "Select a product first to bid...",
"active_listings": AuctionListings.objects.all(),
})
@login_required(login_url="login")
def watchlist_add(request, _listing_id):
get_listing = get_object_or_404(AuctionListings, pk=_listing_id)
get_watchlist = Watchlists.objects.filter(
user_id=request.user, item=get_listing.id)
if get_watchlist.exists():
get_watchlist.delete()
return HttpResponseRedirect(reverse("listing", args=[_listing_id]))
user_watchlist, created = Watchlists.objects.get_or_create(
user_id=request.user)
user_watchlist.item.add(get_listing)
return HttpResponseRedirect(reverse("listing", args=[_listing_id]))
@login_required(login_url="login")
def close_listing(request, _listing_id):
get_listing = get_object_or_404(AuctionListings, pk=_listing_id)
max_bid = get_max_bid(get_listing, Bids)
get_watchlist = Watchlists.objects.filter(
user_id=request.user, item=get_listing.id).exists()
if Bids.objects.filter(amount=max_bid).first().user_id != request.user:
get_listing.active_status = False
get_listing.save()
return HttpResponseRedirect(reverse("listing", args=[_listing_id]))
return render(request, "auctions/listing.html", {
"listing": get_listing,
"max_bid": Bids.objects.filter(amount=max_bid).first(),
"on_watchlist": get_watchlist,
"close_listing_message": "No Highest bidder except the Auctioneer."
})
@login_required(login_url="login")
def delete_listing(request, _listing_id):
get_listing = get_object_or_404(AuctionListings, pk=_listing_id)
if request.method == "POST":
get_listing.delete()
return HttpResponseRedirect(reverse("index"))
return render(request, "auctions/delete_listing.html", {
"listing": get_listing
})
@login_required(login_url="login")
def make_comment(request, _listing_id):
get_listing = get_object_or_404(AuctionListings, pk=_listing_id)
if request.method == "POST":
comment = request.POST["comment"]
try:
m_comment = Comments(
user_id=request.user,
listing_id=AuctionListings.objects.get(id=_listing_id),
text=comment
)
m_comment.save()
return HttpResponseRedirect(reverse("listing", args=[_listing_id]))
except IntegrityError:
return HttpResponseRedirect(reverse("listing", args=[_listing_id]))
return HttpResponseRedirect(reverse("index"))
def get_max_bid(listing, bid):
return bid.objects.filter(listing_id=listing).aggregate(
Max('amount')).get("amount__max")
<file_sep># Generated by Django 3.1.1 on 2020-10-02 05:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0002_auto_20201002_1029'),
]
operations = [
migrations.AlterField(
model_name='auctionlistings',
name='description',
field=models.CharField(max_length=1000),
),
]
<file_sep># Generated by Django 3.1.1 on 2020-10-02 04:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auctions', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='bids',
name='creation_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AddField(
model_name='bids',
name='user_id',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='bids', to='auctions.user'),
preserve_default=False,
),
migrations.AddField(
model_name='comments',
name='user_id',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='auctions.user'),
preserve_default=False,
),
migrations.AlterField(
model_name='comments',
name='listing_id',
field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='auctions.auctionlistings'),
),
]
|
e16835a4f1cd3e5fefb959f23b774f9345c7ea64
|
[
"Python"
] | 8 |
Python
|
landxcape/commerce
|
bc65952997967b5a7d68e8a18e085f5ab18c8b56
|
2dd86b14e622105eee07e2341ad40a97d8e5db2c
|
refs/heads/master
|
<file_sep>#!C:\ProgramData\Anaconda3\python.exe
import cgi
import cgitb
cgitb.enable()
print('Content-type: text/html \n')
print('Hello There')<file_sep>class Node:
def __init__(self,data):
self.value = data
self.link = None
class LinkedList:
def __init__(self):
self.start = None
def insert(self,data):
if self.start is None:
self.start = Node(data)
else:
x = self.start
while x.link is not None:
x = x.link
x.link = Node(data)
def display(self):
if self.start is None:
print("List is Empty")
else:
x=self.start
while x is not None:
print(x.value, end = " ")
x = x.link
def middleElement(self):
if self.start is None :
print("Empty List")
else:
spointer = self.start
fpointer = self.start
while fpointer is not None and fpointer.link is not None:
spointer = spointer.link
fpointer = fpointer.link.link
print("\nMiddle Element : " + str(spointer.value))
obj=LinkedList()
obj.insert(1)
obj.insert(2)
obj.insert(3)
obj.insert(4)
obj.insert(5)
obj.display()
obj.middleElement()
obj.insert(6)
obj.display()
obj.middleElement()<file_sep>class BinaryTree:
def __init__(self,data):
self.data=data
self.lchild = None
self.rchild = None
def create(self,node,data):
if node.data == data:
print("Duplicate Data. Cannot insert into the tree")
return
if data < node.data and node.lchild is None:
node.lchild = BinaryTree(data)
return
if data > node.data and node.rchild is None:
node.rchild = BinaryTree(data)
return
if data < node.data and node.lchild is not None:
node.create(node.lchild,data)
if data > node.data and node.rchild is not None:
node.create(node.rchild,data)
def level_order_traversal(self,node):
pass
root = BinaryTree(12)
root.create(root,5)
root.create(root,3)
root.create(root,4)
root.create(root,1)
root.create(root,15)
root.create(root,11)
root.create(root,18)
root.create(root,10)
root.create(root,20)
root.create(root,2)
<file_sep>
public class StaticMethods {
public static void main(String[] args) {
System.out.println("Inside Main Method.");
StaticMethods.method1();
}
static void method1() {
System.out.println("Inside Static Method 1");
}
static {
System.out.println("Inside static Block");
StaticMethods.method1();
}
}
|
8671c4a137d33d4376b9c48970405f96cc805711
|
[
"Java",
"Python"
] | 4 |
Python
|
HK002/JavaBasics
|
8a6fae5114b9ad8ee1e8d5c6f869cddd5601efb1
|
bc1505f193226546f3775d584dd9067ff8761335
|
refs/heads/master
|
<repo_name>JohnathanMB/ApiPruebaAcc<file_sep>/src/routes/clienteRoute.js
const express = require('express');
const router = express.Router();
const cliente = require('../models/cliente');
router.get('/clientes', (req, res) => {
cliente.getUsers((err, data) =>{
res.status(200).json(data);
} );
});
router.post('/clientes', (req, res)=>{
//console.log(req.body);
const clienteData = {
cc: req.body.cc,
nombre: req.body.nombre,
apellido: req.body.apellido,
fecha_nacimiento: req.body.fecha_nacimiento
};
if(calcularEdad(clienteData.fecha_nacimiento) >= 18){
cliente.insertCliente(clienteData, (err, data)=>{
if(data && data.insertDone){
res.status(200).json({
succes: true,
msg: 'Cliente Ingresado',
data: data
});
}else{
res.status(500).json({
succes: false,
msg: 'Error',
error: err
});
//throw err;
}
})
}else{
res.status(400).json({
succes: false,
msg: 'Menor de edad',
err: {
code: 'menor'
}
});
}
});
router.get('/clientes/:clienteId', (req, res)=>{
clienteId = req.params.clienteId;
cliente.getIdUser(clienteId, (err, data) =>{
if(data != null){
res.status(200).json(data);
}else{
res.status(404).json({
code: 'No se encuentre cliente'
});
}
} );
});
router.post('/clientes/login', (req, res)=>{
const cc = req.body.cc;
cliente.getIdUser(cc, (err, data) =>{
if(data != null){
res.status(200).json(data);
}else{
res.status(404).json({
code: 'No se encuentre cliente'
});
}
});
});
function calcularEdad(fecha) {
var hoy = new Date();
var cumpleanos = new Date(fecha);
var edad = hoy.getFullYear() - cumpleanos.getFullYear();
var m = hoy.getMonth() - cumpleanos.getMonth();
if (m < 0 || (m === 0 && hoy.getDate() < cumpleanos.getDate())) {
edad--;
}
return edad;
};
module.exports = router;<file_sep>/db/pruebaAcc.sql
CREATE DATABASE pruebaacc;
USE pruebaacc;
CREATE TABLE IF NOT EXISTS `cliente` (
`cc` int(20) NOT NULL,
`nombre` VARCHAR(50) NOT NULL,
`apellido` VARCHAR(50) NOT NULL,
`fecha_nacimientoi` date NOT NULL,
PRIMARY KEY(`cc`)
)ENGINE=InnoDB DEFAULT CHARACTER SET=utf8;
Describe cliente;
<file_sep>/src/models/cliente.js
const mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '<PASSWORD>',
database: 'pruebaacc'
});
let clienteModel = {};
clienteModel.getUsers = (callback) => {
if(connection){
console.log('conection');
connection.query('SELECT * FROM cliente;',
(err, rows) => {
if(err){
throw err;
}else {
callback(null, rows);
}
})
}else{
throw err;
}
};
clienteModel.insertCliente = (clienteData, callback) => {
if(connection){
connection.query(
'INSERT INTO cliente SET ?', clienteData,
(err, result)=>{
if(err){
callback(err, {
'insertDone': false
});
}else{
callback(null, {
'insertDone': true,
'cc': clienteData.cc
});
}
}
)
}
};
clienteModel.getIdUser = (clienteId, callback) => {
if(connection){
connection.query(
'SELECT * FROM cliente WHERE cc = ?', clienteId,
(err, rows) => {
if(err){
throw err;
}else {
callback(null, rows[0]);
}
}
)
}
}
module.exports = clienteModel;
<file_sep>/README.md
# ApiPruebaAcc
Api de registro y consultas transaccionales
<file_sep>/src/routes/consultaRoute.js
const express = require('express');
const router = express.Router();
router.post('/consulta', (req, res) =>{
const fecha_inicio = req.body.fecha_inicio;
var consulta;
if(mayorAnioYMedio(fecha_inicio)){
const salario = req.body.salario;
if(salario > 4000000){
res.status(200).json({
aprobado: true,
credito: "50000000",
mensaje: "Credito aprobado de $50.000.000"
});
}else if(salario > 1000000){
res.status(200).json({
aprobado: true,
credito: "20000000",
mensaje: "Credito aprobado de $20.000.000"
});
}else if(salario > 800000){
res.status(200).json({
aprobado: true,
credito: "5000000",
mensaje: "Credito aprobado de $5.000.000"
});
}else{
res.status(200).json({
aprobado: false,
credito: "0",
mensaje: "Su credito no es aprobado\nSu salario debe ser mayor a $8.000.000"
});
}
}else{
res.status(200).json({
aprobado: false,
credito: "0",
mensaje: "Su credito no es aprobado\nDebe tener mas de un anio y medio de antiguedad en la empresa"
});
}
} );
function mayorAnioYMedio(fechaCadena){
var acierto = false;
var fechaReal = new Date(fechaCadena);
fechaReal.setDate(fechaReal.getDate() + 548);
const hoyCadena = new Date().toISOString().substring(0, 10);
const hoyFecha = new Date(hoyCadena);
if(hoyFecha >= fechaReal){
acierto = true;
}
return acierto;
}
/*
router.post('/clientes/login', (req, res)=>{
const cc = req.body.cc;
cliente.getIdUser(cc, (err, data) =>{
if(data != null){
res.status(200).json(data);
}else{
res.status(404).json({
code: 'No se encuentre cliente'
});
}
});
});
*/
module.exports = router;
|
9f2dbffdc5494ea8cb8811fb03caaaa9873ae668
|
[
"JavaScript",
"SQL",
"Markdown"
] | 5 |
JavaScript
|
JohnathanMB/ApiPruebaAcc
|
1d549f0148c8dae42714277d10d5fe55c5c09a33
|
0d59b1223556732cbe3f1c9506eeb59158453f81
|
refs/heads/master
|
<file_sep># MillenniumGroundGuide-3.0
Version 3.0 of Millennium Ground Guide iPhone App
<file_sep>//
// FoodDrinkViewController.swift
// Millennium
//
// Created by Macbook Pro on 15/01/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class FoodDrinkViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK: - Navigation
@IBAction func backBtn(_ sender: Any) {
performSegue(withIdentifier: "backToHome", sender: self)
}
}
<file_sep>//
// ViewController.swift
// Millennium
//
// Created by <NAME> on 13/01/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import StoreKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func navBackToHome( _ seg: UIStoryboardSegue) {
//NSLog("Unwind")
}
}
|
01c16675f30b0b21d18f073576d441bf73a8d81f
|
[
"Markdown",
"Swift"
] | 3 |
Markdown
|
danielearl77/Millennium
|
562c41b476781b638b923b7b3d476018a11ddfe5
|
14429dd2150c97bff5f58bbd905d0a53bce8a1cc
|
refs/heads/master
|
<file_sep>using System;
namespace SignalR_Common_Features.Services
{
// ReSharper disable once InconsistentNaming
public static class LoggerIO
{
public static void PrintEvent(string methodName, string content) => Console.WriteLine(
$@"Method '{methodName}': {content}");
}
}
<file_sep>using System;
using Microsoft.AspNet.SignalR.Client;
using SignalR_Client.Abstractions;
using SignalR_Client.Service;
using SignalR_Common_Features;
using SignalR_Common_Features.Models;
using static System.Console;
namespace SignalR_Client
{
class Program
{
static void Main(string[] args)
{
WriteLine($"Client is starting on {Constants.Url}");
var hubConnection = new HubConnection(Constants.Url);
Write("Enter username:");
string username = ReadLine();
IHubService hubService = new ChatService()
{
User = new User() {Username = username,Id = "null",Color = (ConsoleColor) Enum.ToObject(typeof(ConsoleColor), new Random().Next(1, 15))}
};
hubService.ConfigureProxy(hubConnection).Wait();
hubService.Connect().Wait();
while (true)
{
string message = ReadLine();
if (message != null && message.Contains("_exit_"))
{
hubService.Disconnect().Wait();
break;
}
if(string.IsNullOrWhiteSpace(message))
continue;
hubService.SendData(message).Wait();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SignalR_Common_Features.Models;
namespace SignalR_Client.Abstractions
{
interface IUsableUsers
{
User User { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Hubs;
using SignalR_Client.Abstractions;
using SignalR_Common_Features;
using SignalR_Common_Features.Models;
using static System.Console;
namespace SignalR_Client.Service
{
class ChatService : IHubService, IUsableUsers
{
public User User { get; set; }
public IHubProxy HubProxy { get; set; }
public HubConnection HubConnection { get; set; }
public Task ConfigureProxy(HubConnection hubConnection)
{
HubConnection = hubConnection;
HubProxy = HubConnection.CreateHubProxy("MarkHub");
HubProxy.On<Message>("addMessage", message =>
{
ForegroundColor = message.Sender.Color;
WriteLine(message.ToString());
ResetColor();
});
HubProxy.On<string>("onConnected", s => {
ForegroundColor = ConsoleColor.Red;
WriteLine(s + " is connected");
ResetColor();
});
HubProxy.On<string>("onDisconnected", s => {
ForegroundColor = ConsoleColor.Red;
WriteLine(s + " is disconnected");
ResetColor();
});
return hubConnection.Start();
}
public Task Connect()
{
return HubProxy.Invoke<string>("onConnected", User.Username)
.ContinueWith(task =>
{
if (task.IsFaulted) WriteLine($"Exception:{task.Exception.InnerException.Message}");
});
}
public Task SendData(string data)
{
return HubProxy.Invoke("addMessage",
new Message {Sender = User, Text = data, Date = DateTime.Now})
.ContinueWith(task =>
{
if (task.IsFaulted) WriteLine($"Exception:{task.Exception.InnerException.Message}");
});
}
public Task Disconnect()
{
return Task.Run(() =>
{
HubConnection.Stop();
});
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using SignalR_Common_Features;
using SignalR_Common_Features.Models;
using SignalR_Common_Features.Services;
namespace SignalR_Server
{
[HubName("MarkHub")]
public class MyChatHub : Hub
{
private static readonly List<User> Users;
static MyChatHub()
{
Users = new List<User>();
}
[HubMethodName("addMessage")]
public Task SendMessage(Message message)
{
return Task.Run(() =>
{
LoggerIO.PrintEvent(nameof(SendMessage),
$@"sender '{message.Sender}' content '{message.Text}' date '{message.Date}'");
Clients.All.addMessage(message);
});
}
[HubMethodName("onConnected")]
public Task Connect(string username)
{
return Task.Run(() =>
{
if (Users.All(x => x.Id != Context.ConnectionId))
{
Users.Add(new User {Id = Context.ConnectionId, Username = username});
Clients.Others.onConnected(username);
OverideEvents(nameof(OnConnected), Context.ConnectionId);
}
});
}
[HubMethodName("onDisconnected")]
public override Task OnDisconnected(bool stopCalled)
{
Task.Run(() =>
{
var user = Users.FirstOrDefault(x => x.Id == Context.ConnectionId);
Clients.All.onDisconnected(user.Username);
Users.Remove(user);
OverideEvents(nameof(OnDisconnected), Context.ConnectionId);
})
.Wait();
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
OverideEvents(nameof(OnReconnected), Context.ConnectionId);
return base.OnReconnected();
}
private void OverideEvents(string method, string id) => LoggerIO.PrintEvent(method, $"Hub {method} {id}");
}
}
<file_sep>using System;
using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using SignalR_Common_Features;
using SignalR_Server;
using static System.Console;
[assembly:OwinStartup(typeof(Startup))]
namespace SignalR_Server
{
class Program
{
static void Main(string[] args)
{
try
{
//Start SignalR server which defined in assemblies and startup
using (WebApp.Start(Constants.Url))
{
WriteLine($"Server is starting on {Constants.Url}");
while (true) ;
}
}
catch (Exception e)
{
WriteLine(e.Message);
}
}
}
}
<file_sep>using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Diagnostics;
using Owin;
using SignalR_Server;
namespace SignalR_Server
{
class Startup
{
public void Configuration(IAppBuilder app)
{
//Setting route for hubs
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration();
map.UseErrorPage(ErrorPageOptions.ShowAll);
hubConfiguration.EnableDetailedErrors = true;
map.RunSignalR(hubConfiguration);
});
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SignalR_Common_Features
{
public static class Constants
{
public static string Url => "http://localhost:61195";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Hubs;
namespace SignalR_Client.Abstractions
{
interface IHubService
{
/// <summary>
/// Client side socket
/// </summary>
IHubProxy HubProxy { get; set; }
/// <summary>
/// Connectline for interaction with server(hub)
/// </summary>
HubConnection HubConnection { get; set; }
/// <summary>
/// Config hub`s methods
/// </summary>
/// <param name="hubConnection"></param>
/// <returns></returns>
Task ConfigureProxy(HubConnection hubConnection);
/// <summary>
/// Event while user is connecting
/// </summary>
/// <returns></returns>
Task Connect();
/// <summary>
/// Sending message
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
Task SendData(string data);
/// <summary>
/// Event while user is disconnecting
/// </summary>
/// <returns></returns>
Task Disconnect();
}
}
|
5e43504627df609a8004f0a0ff492fc477683b59
|
[
"C#"
] | 9 |
C#
|
KuchmyndaMarkiian/SignalR_example
|
6f059b669a8959c067630954a62029cf9a737250
|
cf60a334c569eaee8a86aa966b4796033534bf03
|
refs/heads/main
|
<repo_name>dgrothman/homebridge-crestron<file_sep>/src/crestron-crosscolours.ts
import {
API,
APIEvent,
Characteristic,
CharacteristicEventTypes,
CharacteristicSetCallback,
CharacteristicValue,
DynamicPlatformPlugin,
HAP, Logger,
PlatformAccessory,
PlatformAccessoryEvent, PlatformConfig,
Service
} from "homebridge";
import {PLATFORM_NAME, PLUGIN_NAME} from "./settings";
import {CrestronProcessor} from "./crestron-processor";
/**
* HomebridgeCrestronCrosscolours
* This class is the main constructor for your plugin, this is where you should
* parse the user config and discover/register accessories with Homebridge.
*/
export class CrestronCrosscolours implements DynamicPlatformPlugin {
public readonly Service: typeof Service = this.api.hap.Service;
public readonly Characteristic: typeof Characteristic = this.api.hap.Characteristic;
public readonly Processor: CrestronProcessor;
public readonly HAP: HAP = this.api.hap;
public readonly Accessory: typeof PlatformAccessory = this.api.platformAccessory;
// this is used to track restored cached accessories
public accessories: PlatformAccessory[] = [];
constructor(
public readonly log: Logger,
public readonly config: PlatformConfig,
public readonly api: API,
) {
// @ts-ignore
this.Processor = new CrestronProcessor(config.ipAddress, config.port, log, config.slot);
this.log.debug("CCCP finished initializing!");
/*
* When this event is fired, homebridge restored all cached accessories from disk and did call their respective
* `configureAccessory` method for all of them. Dynamic Platform plugins should only register new accessories
* after this event was fired, in order to ensure they weren't added to homebridge already.
* This event can also be used to start discovery of new accessories.
*/
api.on(APIEvent.DID_FINISH_LAUNCHING, () => {
this.log.debug("CrestronCrossColours platform 'didFinishLaunching'");
this.discoverDevices().then(() => {});
});
};
/*
* This function is invoked when homebridge restores cached accessories from disk at startup.
* It should be used to setup event handlers for characteristics and update respective values.
*/
configureAccessory(accessory: PlatformAccessory): void {
this.log.info(`Configuring accessory ${accessory.displayName} with UUID ${accessory.UUID}`);
this.accessories.push(accessory);
accessory.on(PlatformAccessoryEvent.IDENTIFY, () => {
this.log.info(`${accessory.displayName} identified!`);
});
if(accessory.context.type == undefined) return;
this.log.info(`Setting up accessory type of ${accessory.context.type}`);
switch (accessory.context.type) {
case 'Lightbulb':
this.log.info(`Found a Lightbulb accessory to configure`);
const lightbulbService = accessory.getService(this.Service.Lightbulb);
if(lightbulbService === undefined) return;
lightbulbService!.getCharacteristic(this.Characteristic.On)
.on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => {
this.log.info(`${accessory.displayName} Light was set to: ${value}`);
this.Processor.loadDim(accessory.context.id, +!!accessory.context.power * accessory.context.bri);
callback(null);
})
.on(this.HAP.CharacteristicEventTypes.GET, (callback) => {
this.log.debug(`getPower ${accessory.context.id} = ${accessory.context.power}`);
callback(null, accessory.context.power);
});
if(accessory.context.subtype == "dimmer" || accessory.context.subtype == "rgb") {
this.log.info(`Light is dimmable`);
lightbulbService.getCharacteristic(this.Characteristic.Brightness)
.on(this.HAP.CharacteristicEventTypes.SET, (level : CharacteristicValue, callback: CharacteristicSetCallback) => {
this.log.debug(`setBrightness ${accessory.context.id} = ${level}`);
accessory.context.bri = parseInt(level.toString());
accessory.context.power = (accessory.context.bri > 0);
this.Processor.loadDim(accessory.context.id, accessory.context.bri);
callback(null);
})
.on(this.HAP.CharacteristicEventTypes.GET, (callback) => {
this.log.info(`getBrightness ${accessory.context.id} = ${accessory.context.bri}`);
callback(null, accessory.context.bri);
})
}
if (accessory.context.subtype == "rgb") {
this.log.info(`Light is rgb`);
lightbulbService.getCharacteristic(this.Characteristic.Saturation)
.on(this.HAP.CharacteristicEventTypes.SET, (level, callback) => {
this.Processor.loadSaturationChange(accessory.context.id, level)
callback(null);
})
.on(this.HAP.CharacteristicEventTypes.GET, (callback) => {
callback(null, accessory.context.sat);
});
lightbulbService.getCharacteristic(this.Characteristic.Hue)
.on(this.HAP.CharacteristicEventTypes.SET, (level, callback) => {
accessory.context.power = true;
accessory.context.hue = level;
this.Processor.loadRgbChange(accessory.context.id, accessory.context.hue, accessory.context.sat, accessory.context.bri)
callback(null);
})
.on(this.HAP.CharacteristicEventTypes.GET, (callback) => {
callback(null, accessory.context.hue);
});
}
break;
case 'WindowCovering':
this.log.info(`Found a WindowCovering accessory to configure`);
accessory.getService(this.Service.WindowCovering)!.getCharacteristic(this.Characteristic.TargetPosition)
.on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => {
this.log.info(`${accessory.displayName} WindowCovering was set to: ${value}`);
this.Processor.setWindowPosition(accessory.context.id,value);
callback(null);
})
.on(CharacteristicEventTypes.GET, (callback) => {
this.log.info(`GET target position for accessory ${accessory.context.id}`);
const pos = this.Processor.getWindowPosition(accessory.context.id);
callback(null, pos);
})
accessory.getService(this.Service.WindowCovering)!.getCharacteristic(this.Characteristic.CurrentPosition)
.on(CharacteristicEventTypes.GET, (callback) => {
this.log.info(`GET current position for accessory ${accessory.context.id}`);
const pos = this.Processor.getWindowPosition(accessory.context.id);
callback(null, pos);
});
accessory.getService(this.Service.WindowCovering)!.getCharacteristic(this.Characteristic.PositionState)
.on(CharacteristicEventTypes.GET, (callback) => {
this.log.info(`GET position state for accessory ${accessory.context.id}`);
const state = this.Processor.getWindowState(accessory.context.id);
callback(null, state);
});
break;
}
}
// --------------------------- CUSTOM METHODS ---------------------------
addAccessory(accessory: PlatformAccessory) {
this.log.info(`Adding new accessory with name ${accessory.displayName}`);
const service = new this.Service.AccessoryInformation();
service.setCharacteristic(this.Characteristic.Name, accessory.displayName)
.setCharacteristic(this.Characteristic.Manufacturer, "Crestron")
.setCharacteristic(this.Characteristic.Model, accessory.context.type + " Device")
.setCharacteristic(this.Characteristic.SerialNumber, "ID " + accessory.context.id);
switch (accessory.context.type) {
case 'Lightbulb':
accessory.addService(this.Service.Lightbulb,accessory.displayName);
accessory.context.bri = 100;
accessory.context.power = false;
accessory.context.sat = 0;
accessory.context.hue = 0;
break;
case 'WindowCovering':
accessory.addService(this.Service.WindowCovering,accessory.displayName);
break;
}
this.configureAccessory(accessory); // abusing the configureAccessory here
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);
}
// ----------------------------------------------------------------------
private async discoverDevices() {
this.log.info('discoverDevices');
// Get Lights
const lights = await this.Processor.getLights();
lights.forEach((load) => {
const uuid = this.HAP.uuid.generate(`${load.displayName}${load.id}`);
if(this.accessories.find(accessory => accessory.UUID === uuid)) return;
this.log.info(`Adding light ${uuid}`);
const newAccessory = new this.Accessory(`${load.displayName}${load.id}`, uuid);
newAccessory.context.id = load.id;
newAccessory.context.type = 'Lightbulb'
newAccessory.context.subtype = load.subtype;
this.addAccessory(newAccessory);
});
// Get Shades
const shades = await this.Processor.getShades();
shades.forEach((load) => {
const uuid = this.HAP.uuid.generate(`${load.displayName}${load.id}`);
if(this.accessories.find(accessory => accessory.UUID === uuid)) return;
const newAccessory = new this.Accessory(`${load.displayName}${load.id}`, uuid);
newAccessory.context.id = load.id;
newAccessory.context.type = 'WindowCovering'
newAccessory.context.subtype = 'shade';
this.addAccessory(newAccessory);
});
// Remove deleted ones
let requireRemoval: PlatformAccessory[] = [];
this.accessories.forEach((accessory) => {
if(accessory.context.type == 'Lightbulb') {
if(!lights.find(light => light.id == accessory.context.id && accessory.context.type == 'Lightbulb')) {
this.log.info(`Removing accessory not found in config ${accessory.displayName} ${accessory.context.id}`);
requireRemoval.push(new this.api.platformAccessory(accessory.displayName, accessory.UUID));
}
} else if(accessory.context.type == 'WindowCovering') {
if(!shades.find(shade => shade.id == accessory.context.id && accessory.context.type == 'WindowCovering')) {
this.log.info(`Removing accessory not found in config ${accessory.displayName} ${accessory.context.id}`);
requireRemoval.push(new this.api.platformAccessory(accessory.displayName, accessory.UUID));
}
}
});
this.log.info(`Removing ${requireRemoval.length} items`);
requireRemoval.forEach(item => {
this.accessories = this.accessories.filter(obj => obj !== item);
this.api.unregisterPlatformAccessories(PLUGIN_NAME,PLATFORM_NAME,[item]);
});
}
}
<file_sep>/src/index.ts
import { API } from 'homebridge';
import { CrestronCrosscolours } from './crestron-crosscolours';
import {PLATFORM_NAME} from "./settings";
/**
* This method registers the platform with Homebridge
*/
export = (api: API) => {
api.registerPlatform(PLATFORM_NAME, CrestronCrosscolours);
};
<file_sep>/src/testing/test-logger.ts
import {Logging, LogLevel} from "homebridge";
// @ts-ignore
export class TestLogger implements Logging{
public readonly prefix: string;
constructor(prefix: string) {
this.prefix = prefix;
}
info(message: string, ...parameters: any[]): void {
console.info(message, ...parameters);
}
warn(message: string, ...parameters: any[]): void {
console.warn(message, ...parameters);
}
error(message: string, ...parameters: any[]): void {
console.error(message, ...parameters);
}
debug(message: string, ...parameters: any[]): void {
console.debug(message, ...parameters);
}
log(level: LogLevel, message: string, ...parameters: any[]): void {
console.log(message, ...parameters);
}
}
<file_sep>/README.md
# homebridge-crestron
<file_sep>/src/crosscolour-light.ts
import {CrossColourAccessory} from "./crosscolours-accessory";
import {ConfigRoom} from "./model/CrosscolourConfig";
export interface CrosscolourLight extends CrossColourAccessory {
area: ConfigRoom;
hue: number;
brightness: number;
saturation: number;
}
export class CrosscolourLight implements CrosscolourLight{
get dimmable(): boolean {
return this.subtype === 'dimmer';
}
get rgb(): boolean {
return this.subtype === 'rgb';
}
constructor(name: string, id: number, area?: ConfigRoom) {
this.hue = 0;
this.type = 'Lightbulb';
this.subtype = 'dimmer';
this.brightness = 0;
this.saturation = 0;
this.displayName = name;
this.id = id;
if(area != undefined) {
this.area = area;
}
}
}
<file_sep>/src/crestron-processor.test.ts
import {CrestronProcessor} from "./crestron-processor";
import {TestLogger} from "./testing/test-logger";
describe('Processor Testing', () => {
let logger: TestLogger;
let processor: CrestronProcessor;
beforeEach(() => {
logger = new TestLogger('getLights verification');
// @ts-ignore
processor = new CrestronProcessor('192.168.0.249',41900,logger,1);
});
test('getLights',async () => {
const lights = await processor.getLights();
expect(lights.length).toEqual(3);
});
test('getShades',async () => {
const shades = await processor.getShades();
expect(shades.length).toEqual(4);
});
test('sendData loadDim', async () => {
processor.setWindowPosition(1032,0);
await setTimeout((id) => {
const pos = processor.getWindowPosition(id);
},10000, 1032);
processor.getWindowPosition(1032);
})
});
<file_sep>/src/cretron-crosscolours.test.ts
import {TestLogger} from "./testing/test-logger";
import {CrestronCrosscolours} from "./crestron-crosscolours";
import {mocked} from "ts-jest";
jest.mock('./crestron-crosscolours',() => {
return {
CrestronCrosscolours: jest.fn().mockImplementation(() => {
return {
};
})
}
});
describe('Homebridge plugin test', () => {
const MockedCrestronCrosscolours = mocked(CrestronCrosscolours, true);
beforeEach(() => {
MockedCrestronCrosscolours.mockClear();
});
it('discoverDevices check', () => {
});
});
<file_sep>/src/crosscolour-shade.ts
import {CrossColourAccessory} from "./crosscolours-accessory";
import {ConfigRoom} from "./model/CrosscolourConfig";
export interface CrosscolourShade extends CrossColourAccessory {
area: ConfigRoom;
position: number;
state: number;
}
export class CrosscolourShade {
constructor(name: string, id: number, area?: ConfigRoom) {
this.position = 0;
this.state = 2;
this.displayName = name;
this.type = 'WindowCovering';
this.subtype = 'shade';
this.id = id;
if(area != undefined) {
this.area = area
}
}
}
<file_sep>/src/model/CrosscolourConfig.ts
export interface CrosscolourConfig {
data: {
SysConfig: {
JobInfo: {
Name: string;
},
Room: ConfigRoom[],
Source: ConfigSource[],
Profile: ConfigProfile[],
TProfile: ConfigTProfile[],
LLoad: ConfigLLoad[],
SLoad: ConfigSLoad[],
Floors: ConfigFloor[]
}
}
}
export interface ConfigRoom {
Name: string;
RoomOrder: number;
RoomID: number;
LightsID: number;
ThermoID: number;
ShadesID: number;
DoorsID: number;
FireID: number;
Sources: number[];
RoomOptions: string[];
ActiveSRC: number;
Floor: number;
}
export interface ConfigSource {
Name: string;
ID: number;
Icon: number;
ARoute: number;
VRoute: number;
SRCType: number;
Speakers: number;
AudioOnly: boolean;
GlobalSrc: boolean;
}
export interface ConfigProfile {
Name: string;
ID: number;
VisibleRooms: number[];
VisibleLightAreas: number[];
VisibleLightLoads: number[];
VisibleClimate: number[];
VisibleFire: number[];
VisibleDoor: number[];
VisibleShadesAreas: number[];
VisibleShadesLoads: number[];
Visible: number;
}
export interface ConfigTProfile {
TPID: number;
ProfID: number;
DefaultProfile: number;
}
export interface ConfigLLoad {
Name: string;
AreaID: number;
LoadID: number;
RGB: boolean;
Dimmable: boolean;
}
export interface ConfigSLoad {
Name: string;
AreaID: number;
LoadID: number;
}
export interface ConfigFloor {
Position: number;
Name: string;
VisibleFloors: number[];
}
<file_sep>/src/crestron-processor.ts
import {Socket} from "net";
import {Logging} from "homebridge";
import {CrosscolourLight} from "./crosscolour-light";
import {CrosscolourConfig} from "./model/CrosscolourConfig";
import {CrosscolourShade} from "./crosscolour-shade";
import {CoreTag, EventTag, HubEventArgs,} from "./model/WeakEntitites";
const axios = require('axios');
const JsonSocket = require('json-socket');
export class CrestronProcessor {
private readonly ipAddress: string;
private readonly port: number;
private readonly slot: number;
private client = new JsonSocket(new Socket());
private config: CrosscolourConfig | undefined;
private lights: CrosscolourLight[] = [];
private shades: CrosscolourShade[] = [];
private readonly log: Logging;
constructor(ipAddress: string, port: number, log: Logging, slot: number) {
this.ipAddress = ipAddress;
this.port = port;
this.log = log;
this.slot = slot < 10 ? slot : 0;
this.slot = parseInt('4171' + slot.toString());
this.connectToServer();
}
connectToServer() {
this.log.info(`CCCP connection info: ${this.ipAddress}:${this.port}`);
this.log.info("CrestronCrossColours ConnectingToServer");
this.client.connect({host: this.ipAddress, port: this.port});
this.client.on('connect', () => {
console.log('Server Connected');
});
this.client.on('message', (data)=> {
this.log.info(`message received ${data}`);
});
this.client.on('data', (data) => {
this.log.info(`data received ${data}`);
let hea: HubEventArgs = new HubEventArgs(0,0,0,0,0,"","");
try {
hea = JSON.parse(data.toString());
} catch (e) {
this.log.warn(`json parse failed for ${data.toString()}`);
}
switch (hea.Domain) {
case CoreTag.tagLight:
const load = this.lights.find(l => l.id === hea.requestBy);
if(load == undefined) return;
if(hea.etag == EventTag.tagUpdate) {
load.brightness = hea.Level;
}
break;
case CoreTag.tagShade:
const shade = this.shades.find(s => s.id === hea.requestBy);
if(shade == undefined) return;
this.log.info(`Shade ${shade.displayName} update`);
if(hea.etag == EventTag.tagUpdate as number) {
if(shade.position < hea.Level) {
shade.state = 0;
this.log.info(`Shade ${shade.displayName} state decreasing`);
} else {
shade.state = 1;
this.log.info(`Shade ${shade.displayName} state increasing`);
}
shade.position = hea.Level;
this.log.info(`Shade ${shade.displayName} position ${hea.Level}`);
setTimeout((id) => {
const shade = this.shades.find(s => s.id === hea.requestBy);
if(shade == undefined) return;
shade.state = 2;
this.log.info(`Shade ${shade.displayName} state stopped`);
}, 15000, shade.id);
}
break;
}
});
this.client.on('close',async () => {
this.log.info('connection closed');
try {
await this.delay(10000);
this.client.connect({port: this.port, host: this.ipAddress});
} catch (err) {
this.log.error(`CCCP Error reconnecting to server, ${err}`);
}
});
}
async sendData(data : HubEventArgs) {
try {
var stringData = JSON.stringify(data);
this.log.info(`sending cmd ${stringData}`);
await this.client.sendMessage(JSON.stringify(data));
} catch (e) {
this.log.error(`Unable to send Data, socket not connected`);
}
}
loadDim(id, level) {
const hea = new HubEventArgs(id,0,EventTag.tagLevelSet,EventTag.tagPress,level,"",CoreTag.tagLight);
this.sendData(hea);
}
loadSaturationChange(id, s) {
}
queryAccessory(id, domain) {
const hea = new HubEventArgs(id, 0, EventTag.tagQuery, EventTag.tagQuery, 0, "", domain);
this.log.info(`query for ${domain} with id ${id}`)
this.sendData(hea);
}
getLoadLevel(id): number {
const load = this.lights.find(l => l.id === id);
if(load === undefined) return(0);
return load.brightness;
}
getWindowPosition(id): number {
const shade = this.shades.find(s => s.id === id);
if(shade === undefined) return(0);
return shade.position;
}
getWindowState(id): number {
const shade = this.shades.find(s => s.id === id);
if(shade === undefined) return(0);
return shade.state;
}
loadRgbChange(id, h, s, l) {
const hslRgb = require('hsl-rgb');
const rgb: number[] = hslRgb(h,s/100,l/100);
let hea = new HubEventArgs(id,0,EventTag.tagLevelSet,EventTag.tagPress,rgb[0],"R",CoreTag.tagLight);
this.sendData(hea);
hea = new HubEventArgs(id,0,EventTag.tagLevelSet,EventTag.tagPress,rgb[1],"G",CoreTag.tagLight);
this.sendData(hea);
hea = new HubEventArgs(id,0,EventTag.tagLevelSet,EventTag.tagPress,rgb[2],"B",CoreTag.tagLight);
this.sendData(hea);
}
setWindowPosition(id, position) {
let hea = new HubEventArgs(id,0,EventTag.tagLevelSet,EventTag.tagPress,position,"R",CoreTag.tagShade);
this.sendData(hea);
}
async getConfig() {
this.log.debug(`Getting Config from http://${this.ipAddress}:${this.slot}/xml/api/config`);
this.config = await axios.get(`http://${this.ipAddress}:${this.slot}/xml/api/config`);
this.log.info(`Got Config From API with ${this.config?.data.SysConfig.Room.length} Areas`);
// Lights
this.lights = [];
this.config?.data.SysConfig.LLoad.forEach(async (load) => {
const loadArea = this.config?.data.SysConfig.Room.find((room) => room.LightsID === load.AreaID);
const light = new CrosscolourLight(load.Name,load.LoadID,loadArea);
light.subtype = 'rgb';
this.lights.push(light);
await this.delay(5000);
this.queryAccessory(load.LoadID, CoreTag.tagLight);
});
// Shades
this.shades = [];
this.config?.data.SysConfig.SLoad.forEach( async (load) => {
const loadArea = this.config?.data.SysConfig.Room.find((room) => room.ShadesID === load.AreaID);
const shade = new CrosscolourShade(load.Name,load.LoadID,loadArea);
this.shades.push(shade);
await this.delay(5000);
this.queryAccessory(load.LoadID, CoreTag.tagShade);
});
}
async getLights(): Promise<CrosscolourLight[]> {
if(this.config == undefined) await this.getConfig();
return this.lights;
}
async getShades(): Promise<CrosscolourShade[]> {
if(this.config == undefined) await this.getConfig();
return this.shades;
}
delay(ms: number) {
return new Promise( resolve => setTimeout(resolve, ms) );
}
}
<file_sep>/src/crosscolours-accessory.ts
export interface CrossColourAccessory {
id: number;
type: string;
subtype: string;
displayName: string;
}
<file_sep>/src/model/WeakEntitites.ts
export class CoreTag {
public static readonly tagLight: string = "LightCore";
public static readonly tagArea: string = "AreaCore";
public static readonly tagShade: string = "ShadeCore";
public static readonly tagTP: string = "TPCore";
}
export enum EventTag {
tagRaise = 1,
tagLower,
tagOn,
tagOff,
tagToggle,
tagLevelSet,
tagPreset,
tagQuery,
tagUpdate,
tagNameChange,
tagAreaStatus,
tagAreaVC,
tagXml,
tagOpen,
tagClose,
tagStop,
tagAreaController,
tagPress = 101,
tagRelease,
tagColorSet = 201,
tagStarTwinklePress,
tagStarDimmPress,
}
export class HubEventArgs {
public requestTo: number;
public requestBy: number;
public etag: number;
public etype: number;
public Level: number;
public DeviceName: string;
public Domain: string;
constructor(requestTo: number, requestBy: number, tag: number, type: number, level: number, name: string, domain: string) {
this.requestBy = requestBy;
this.requestTo = requestTo;
this.etag = tag;
this.etype = type;
this.Level = level;
this.DeviceName = name;
this.Domain = domain;
}
}
|
5651ee00b6bcf89d6f23fd00ba175796fd7c5519
|
[
"Markdown",
"TypeScript"
] | 12 |
TypeScript
|
dgrothman/homebridge-crestron
|
fc4fc3a9a3d0cba7c24d3211f792743628958331
|
7d09cfb969e22e1a01aed78628a12bb42103a18d
|
refs/heads/master
|
<repo_name>bejoyzm/lyricService<file_sep>/src/test/java/com/bison/service/lyric/LyricServiceApplicationTests.java
package com.bison.service.lyric;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = LyricServiceApplication.class)
public class LyricServiceApplicationTests {
@Test
public void contextLoads() {
}
}
<file_sep>/src/main/java/com/bison/service/lyric/LyricServiceApplication.java
package com.bison.service.lyric;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LyricServiceApplication {
public static void main(String[] args) {
SpringApplication.run(LyricServiceApplication.class, args);
}
}
|
11a3c383f816175408f938c457bec44c54150391
|
[
"Java"
] | 2 |
Java
|
bejoyzm/lyricService
|
aec9641e37a5cca18a6bda9cdf63f66e412c7968
|
4dd1bbe3e23c5e1a0d54bb78bdd96903f8b22831
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace OpenSourceTees.Models
{
public class PurchaseOrder
{
/// <summary>
/// Primary Key of the purchase order object
/// </summary>
[Key]
public string Id { get; set; }
/// <summary>
/// total price of the purchase order
/// </summary>
[Required]
public double TotalPrice { get; set; }
/// <summary>
/// individual item price
/// </summary>
[Required]
public double ItemPrice { get; set; }
/// <summary>
/// quantity of the items on the order
/// </summary>
[Required]
public int Quantity { get; set; }
/// <summary>
/// Buyers Id, foreign key
/// </summary>
[Required(ErrorMessage = "You must be signed in to purchase!")]
[ForeignKey("ApplicationUser")]
public string BuyerId { get; set; }
/// <summary>
/// Image Id, foreign key
/// </summary>
[ForeignKey("Image")]
public string ImageId { get; set; }
/// <summary>
/// foreign key image
/// </summary>
public virtual Image Image { get; set; }
/// <summary>
/// foreign key user
/// </summary>
public virtual ApplicationUser ApplicationUser { get; set; }
/// <summary>
/// no arg constructor
/// </summary>
public PurchaseOrder()
{
}
/// <summary>
/// Object representation of a Purchase Order
/// </summary>
/// <param name="itemPrice">price of the item</param>
/// <param name="qty">wuantity of item</param>
/// <param name="totalPrice">total price of the order</param>
/// <param name="image">string id of the image</param>
/// <param name="buyer">string if of the buyer</param>
public PurchaseOrder(double itemPrice, int qty, double totalPrice, string image, string buyer)
{
TotalPrice = totalPrice;
ItemPrice = itemPrice;
Quantity = qty;
BuyerId = buyer;
ImageId = image;
}
/// <summary>
/// Object representation of a Purchase Order
/// </summary>
/// <param name="itemPrice">price of the item</param>
/// <param name="qty">wuantity of item</param>
/// <param name="buyer">string if of the buyer</param>
/// <param name="image">string id of the image</param>
public PurchaseOrder(double itemPrice, int qty, string buyer, string image)
{
TotalPrice = qty * TotalPrice;
ItemPrice = itemPrice;
Quantity = qty;
BuyerId = buyer;
ImageId = image;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using CodeFirstStoreFunctions;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace OpenSourceTees.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public string UserRole { get; set; }
public ApplicationUser()
{
UserImages = new HashSet<Image>();
}
public ICollection<Image> UserImages { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<Image> Images { get; set; }
public DbSet<PurchaseOrder> PurchaseOrders { get; set; }
public DbSet<OrderProcessing> OrderProcessings { get; set; }
public DbSet<KeyRank> KeyRanks { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Add(new FunctionsConvention<ApplicationDbContext>("dbo"));
}
[DbFunction(nameof(ApplicationDbContext), nameof(udf_imageSearch))]
public IQueryable<KeyRank> udf_imageSearch(string keywords, int? skipN, int? takeN)
{
//throw new NotSupportedException();
var querykeywordsParameter = keywords != null ?
new ObjectParameter("keywords", keywords) :
new ObjectParameter("keywords", typeof(string));
var queryskipNParameter = skipN != null ?
new ObjectParameter("SkipN", skipN) :
new ObjectParameter("SkipN", typeof(int?));
var querytakeNParameter = takeN != null ?
new ObjectParameter("TakeN", takeN) :
new ObjectParameter("TakeN", typeof(int?));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<KeyRank>(
$"[{nameof(ApplicationDbContext)}].[udf_imageSearch](@keywords, @SkipN, @TakeN)",
new ObjectParameter[] { querykeywordsParameter, queryskipNParameter, querytakeNParameter });
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace OpenSourceTees.Models
{
/// <summary>
/// object representation of a ranking in the database
/// </summary>
public class KeyRank
{
/// <summary>
/// string Id representation of the object being ranked
/// </summary>
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual string Id { get; set; }
/// <summary>
/// ranking of the object being ranked
/// </summary>
public virtual int? Ranking { get; set; }
}
}<file_sep>export const LANG_DICT = {
"play_tooltip": {
"ru": "воспроизвести",
"en": "play",
"elem_id": "play_btn"
},
"pause_tooltip": {
"ru": "пауза",
"en": "pause",
"elem_id": "play_btn"
},
"sound_on_tooltip": {
"ru": "вкл. звук",
"en": "sound on",
"elem_id": "sound_btn"
},
"sound_off_tooltip": {
"ru": "выкл. звук",
"en": "sound off",
"elem_id": "sound_btn"
},
"fs_on_tooltip": {
"ru": "вкл. полноэкранный режим",
"en": "full-screen on",
"elem_id": "fullscreen_btn"
},
"fs_off_tooltip": {
"ru": "выкл. полноэкранный режим",
"en": "full-screen off",
"elem_id": "fullscreen_btn"
},
"autorotate_on_tooltip": {
"ru": "вкл. автовращение",
"en": "autorotation on",
"elem_id": "auto_rotate_btn"
},
"autorotate_off_tooltip": {
"ru": "выкл. автовращение",
"en": "autorotation off",
"elem_id": "auto_rotate_btn"
},
"def": {
"ru": "стерео режим / Отключено",
"en": "Stereo mode / disabled"
},
"anag": {
"ru": "анаглиф",
"en": "anaglyph"
},
"side": {
"ru": "sidebyside",
"en": "sidebyside"
},
"hmd": {
"ru": "hmd",
"en": "hmd"
},
"cam_type": {
"static": {
"ru": "Static camera controls",
"en": "Static camera controls"
},
"hover": {
"ru": "Hover camera controls",
"en": "Hover camera controls"
},
"target": {
"ru": "Target camera controls",
"en": "Target camera controls"
},
"eye": {
"ru": "Eye camera controls",
"en": "Eye camera controls"
}
}
}
export const HELP_DICT = {
"desk": {
// TARGET
"help_target_rotate": {
"t": {
"ru": "Перемещение Камеры",
"en": "Camera Movement"
},
"ru": "Чтобы выполнить вращение камеры относительно её цели нужно, с зажатой левой клавишей, перемещать мышь влево/вправо, вперёд/назад, аналогичные действия выполняют клавиши A, R, D, F и стрелки клавиатуры.",
"en": "Hold the left mouse button and move the mouse left/right or forward/backward to rotate the camera across its target; the camera can also be rotated using arrow keys or A, R, D and F keys on the keyboard."
},
"help_target_zoom": {
"t": {
"ru": "Приближение Камеры",
"en": "Camera Zoom"
},
"ru": "Чтобы приблизиться/отдалиться отцели камеры нужно, прокрутить среднее колесо мыши вперёд/назад, аналогичные действия выполняют клавишы S и W клавиауры.",
"en": "Rotate the mouse wheel forward or backward to move the camera closer to or farther from the target; the S and W keys on the keyboard can also be used for this."
},
"help_target_interact": {
"t": {
"ru": "Взаимодействие",
"en": "Interaction"
},
"ru": "Для взаимодействия с интерактивными элементами сцены нужно однократно нажать левую клавишу мыши.",
"en": "Click interactive elements in the scene with the left mouse button to use them."
},
// STATIC
"help_static": {
"ru": "Данный тип камеры не может контролироваться пользователем. Это — программируемый тип камеры.",
"en": "This is a programmable camera type; it cannot be controlled by the user."
},
// EYE
"help_eye_rotation": {
"t": {
"ru": "Вращение камеры",
"en": "Camera rotation"
},
"ru": "Чтобы выполнить вращение камеры относительно своего центра нужно, с зажатой левой клавишей, перемещать мышь влево/вправо, вперёд/назад, анологичные действия выполняют стрелки клавиатуры.",
"en": "Hold the left mouse button and move the mouse right or left to rotate the camera across its center. The camera can also be moved using arrow keys on the keyboard."
},
"help_eye_zoom": {
"t": {
"ru": "Движение камеры вперёд/назад",
"en": "Camera Zoom"
},
"ru": "Чтобы выполнить движение камерой вперёд/назад нужно, соответственно нажать клавиши клавиатуры W/S.",
"en": "To move the camera forward or backward, press W or S key respectively."
},
"help_eye_move_cam_space": {
"t": {
"ru": "Перемещение камеры",
"en": "Camera Movement"
},
"ru": "Чтобы переместить камеру в горизонтальном или вертикальном направлении нужно, нажать клавиши клавиатуры A/D (влево/вправо), R/F (вперёд/назад).",
"en": "To move the camera horizontally or vertically, press A/D (left and right) or R/F (forward and backward) keys on the keyboard."
},
// HOVER
"help_hover_lean": {
"t": {
"ru": "Изменение угла наклона камеры",
"en": "Changing camera angle"
},
"ru": "Чтобы измененить угол поворота камеры относительно горизонтальной плоскости, нужно прокрутить среднее колесо мыши вперёд/назад, аналогичные действия выполняют клавишы R и F клавиауры.",
"en": "Rotate the mouse wheel forward or backward to change the angle of camera inclination from the horizontal plane. This can also be done using R and F keys on the keyboard."
},
"help_hover_rotate": {
"t": {
"ru": "Вращение камеры",
"en": "Camera rotation"
},
"ru": "Чтобы повернуть камеру вокруг вертикальной оси (Z), нужно, с зажатой правой клавишей, перемещать мышь в горизонтальном направлении влево/вправо.",
"en": "Hold right mouse button and move mouse left or right to rotate the camera across the vertical (Z) axis."
},
"help_hover_move": {
"t": {
"ru": "Перемещение камеры",
"en": "Camera move"
},
"ru": "Чтобы переместить камеру в горизонтальном или вертикальном направлении нужно, с зажатой левой клавишей, перемещать мышь влево/вправо, вперёд/назад, анологичные действия выполняют клавиши A, W, S, D и стрелки клавиатуры.",
"en": "Hold the left mouse button and move the mouse left/right or forward/backward to move the camera vertically or horizontally. Arrow keys and W, A, S and D keys on the keyboard can also be used to move camera."
},
"help_hover_interact": {
"t": {
"ru": "Взаимодействие",
"en": "Interaction"
},
"ru": "Для взаимодействия с интерактивными элементами сцены нужно однократно нажать левую клавишу мыши.",
"en": "To use an interactive element in a scene, click it with the left mouse button."
},
"tmpl": {
"t": {
"ru": "",
"en": ""
},
"ru": "",
"en": ""
},
},
"mobile": {
// STATIC
"help_static": {
"ru": "Данный тип камеры не может контролироваться пользователем. Это — программируемый тип камеры.",
"en": "This is a programmable camera type; it cannot be controlled by the user."
},
// EYE
"help_eye_rotation": {
"ru": "Вращение камеры относительно собственного центра.",
"en": "Camera rotation across its center point."
},
"help_eye_interact": {
"ru": "Взаимодействие с интерактивными элементами",
"en": "Interaction with interactive elements"
},
// HOVER
"help_hover_zoom": {
"ru": "Изменение угла наклона камеры относительно горизонтальной плоскости.",
"en": "Changing the angle of camera inclination relative to the horizontal plane."
},
"help_hover_rotate": {
"ru": "Поворот камеры вокруг вертикальной оси (Z).",
"en": "Camera rotation across the vertical (Z) axis."
},
"help_hover_move": {
"ru": "Перемещение камеры в горизонтальном или вертикальном направлении.",
"en": "Moving camera horizontally or vertically."
},
"help_hover_interact": {
"ru": "Взаимодействие с интерактивными элементами.",
"en": "Using interactive elements."
},
// TARGET
"help_target_zoom": {
"ru": "Приближение и отдаление относительно цели (наезд/отъезд).",
"en": "Move camera closer to of farther from the target (zoom in/zoom out)."
},
"help_target_rotate": {
"ru": "Вращение камеры относительно цели в любом направлении.",
"en": "Rotate camera across the target in any direction. "
},
"help_target_interact": {
"ru": "Взаимодействие с интерактивными элементами.",
"en": "Using interactive elements."
},
"tmpl": {
"t": {
"ru": "",
"en": ""
},
"ru": "",
"en": ""
},
}
}
<file_sep>import b4w from "blend4web";
import * as locale from "./locale.js";
import style from "../scss/webplayer.scss";
const m_app = b4w.app;
const m_camera_anim = b4w.camera_anim;
const m_camera = b4w.camera;
const m_cfg = b4w.config;
const m_cont = b4w.container;
const m_ctl = b4w.controls;
const m_data = b4w.data;
const m_gp_conf = b4w.gp_conf;
const m_hmd = b4w.hmd;
const m_nla = b4w.nla;
const m_hmd_conf = b4w.hmd_conf;
const m_input = b4w.input;
const m_main = b4w.main;
const m_math = b4w.math;
const m_quat = b4w.quat;
const m_scs = b4w.scenes;
const m_screen = b4w.screen;
const m_sfx = b4w.sfx;
const m_storage = b4w.storage;
const m_trans = b4w.transform;
const m_util = b4w.util;
const m_vec3 = b4w.vec3;
const m_version = b4w.version;
const m_time = b4w.time;
const DEFAULT_LANG = "en";
const BUILT_IN_SCRIPTS_ID = "built_in_scripts";
const DEFAULT_QUALITY = "HIGH";
const DEFAULT_STEREO = "NONE";
const CAMERA_AUTO_ROTATE_SPEED = 0.3;
const CIRCUMFERENCE = 2 * Math.PI * 54;
const DEFAULT_CAM_TYPE = m_camera.MS_STATIC;
const TWITTER_CHAR = "t";
const FB_CHAR = "f";
const GOOGLE_CHAR = "g";
const VK_CHAR = "v";
const WEIBO_CHAR = "w";
let _nla_fps = 24;
let _no_social = false;
let _socials = [];
let _lang = DEFAULT_LANG;
let _preloader_cont;
let _logo_cont;
let _circle;
let _btns_cont;
let _quality_btn;
let _stereo_btn;
let _social_btn;
let _help_cont;
let _help_btn;
let _selected_object;
let _stereo_mode;
let _ctrl_cont;
let _canvas_cont;
let _stereo_menu;
let _social_menu;
let _quality_menu;
let _timeline_cont;
let _ctrl_wrap;
let _vec2_tmp = new Float32Array(2);
let _vec3_tmp = new Float32Array(3);
let _vec3_tmp2 = new Float32Array(3);
let _quat_tmp = new Float32Array(4);
let _is_touch = false;
let _is_down = false;
let _pick = m_scs.pick_object;
let _active_elem = null;
let _active_cb = null;
let _window_width = 0;
let _focus_cb = function () {};
let _blur_cb = function () {};
let _player_btns = [{
type: "simple_button",
id: "close_help",
callback: close_help
},
{
type: "simple_button",
id: "ru",
callback: switch_ru
},
{
type: "simple_button",
id: "en",
callback: switch_en
},
{
type: "simple_button",
id: "low",
callback: change_quality
},
{
type: "simple_button",
id: "high",
callback: change_quality
},
{
type: "simple_button",
id: "ultra",
callback: change_quality
},
{
type: "simple_button",
id: "none",
callback: change_stereo
},
{
type: "simple_button",
id: "hmd",
callback: change_stereo
},
{
type: "simple_button",
id: "anaglyph",
callback: change_stereo
},
{
type: "simple_button",
id: "sidebyside",
callback: change_stereo
},
{
type: "menu_button",
id: "help_btn",
callback: open_help
},
{
type: "menu_button",
id: "soc_btn",
callback: open_social
},
{
type: "menu_button",
id: "stereo_btn",
callback: open_stereo
},
{
type: "menu_button",
id: "quality_btn",
callback: open_quality
},
{
type: "trigger_button",
id: "sound_btn",
callback: play_sound
},
{
type: "trigger_button",
id: "play_btn",
callback: play_engine
},
{
type: "trigger_button",
id: "fullscreen_btn",
callback: fullscreen_cb
},
{
type: "trigger_button",
id: "auto_rotate_btn",
callback: rotate_camera
}
]
const LOAD_PARAM_STR = "__ASSETS_LOADING_PATH__";
const PVR_PARAM_STR = "__COMPRESSED_TEXTURES_PVR__";
const DDS_PARAM_STR = "__COMPRESSED_TEXTURES_DDS__";
const FPS_PARAM_STR = "__SHOW_FPS__";
const SOCIAL_PARAM_STR = "__NO_SOCIAL__";
const ALPHA_PARAM_STR = "__ALPHA__";
const MIN_CAP_PARAM_STR = "__MIN_CAPABILITIES__";
const AUTOROTATE_PARAM_STR = "__AUTOROTATE__";
const GZIP_PARAM_STR = "__COMPRESSED_GZIP__";
const _url_params = {
"load": LOAD_PARAM_STR,
"compressed_textures_pvr": PVR_PARAM_STR,
"compressed_textures_dds": DDS_PARAM_STR,
"show_fps": FPS_PARAM_STR,
"no_social": SOCIAL_PARAM_STR,
"alpha": ALPHA_PARAM_STR,
"min_capabilities": MIN_CAP_PARAM_STR,
"autorotate": AUTOROTATE_PARAM_STR,
"compressed_gzip": GZIP_PARAM_STR
};
function switch_ru() {
let en = document.querySelector("#en");
en.classList.remove("active");
this.classList.add("active");
_lang = "ru";
switch_lang();
}
function switch_en() {
let ru = document.querySelector("#ru");
ru.classList.remove("active");
this.classList.add("active");
_lang = "en";
switch_lang();
}
const init = function () {
init_help();
let is_debug = (m_version.type() == "DEBUG");
let is_html = b4w.module_check(m_cfg.get("built_in_module_name"));
let url_params = m_app.get_url_params();
let load = "";
if (url_params && _url_params["load"] != LOAD_PARAM_STR)
load = _url_params["load"];
else
load = window.location.href;
let show_fps = _url_params["show_fps"] != FPS_PARAM_STR;
let allow_cors = check_cors();
let alpha = _url_params["alpha"] != ALPHA_PARAM_STR;
let dds_available = _url_params["compressed_textures_dds"] != DDS_PARAM_STR;
let min_capabilities = _url_params["min_capabilities"] != MIN_CAP_PARAM_STR;
let pvr_available = _url_params["compressed_textures_pvr"] != PVR_PARAM_STR;
let gzip_available = _url_params["compressed_gzip"] != GZIP_PARAM_STR;
_no_social = _url_params["no_social"] != SOCIAL_PARAM_STR;
let min50_available = false;
if ((dds_available || pvr_available) && !is_html && !is_debug)
min50_available = true;
if (url_params) {
if (!is_html && !is_debug) {
if (!dds_available && "compressed_textures" in url_params) {
min50_available = true;
dds_available = true;
}
if (!pvr_available && "compressed_textures_pvr" in url_params) {
min50_available = true;
pvr_available = true;
}
if (!gzip_available && "compressed_gzip" in url_params)
gzip_available = true;
}
if (!show_fps && "show_fps" in url_params)
show_fps = true;
if (!_no_social && "no_social" in url_params)
_no_social = true;
if (!alpha && "alpha" in url_params)
alpha = true;
if ("load" in url_params)
load = url_params["load"];
if (!min_capabilities && "min_capabilities" in url_params)
min_capabilities = true;
if ("socials" in url_params) {
let socials = url_params["socials"].split("");
_socials = socials.filter(function (value, index, array) {
return array.indexOf(value) == index;
})
}
}
m_storage.init("b4w_webplayer:" + load);
cache_dom_elems();
set_quality_config();
update_quality_menu(m_storage.get("quality"));
if (!alpha)
m_cfg.set("background_color", [0.224, 0.224, 0.224, 1.0]);
// disable physics in HTML version
m_app.init({
canvas_container_id: "main_canvas_cont",
callback: init_cb,
gl_debug: is_debug,
physics_enabled: !is_html,
show_fps: show_fps,
report_init_failure: false,
console_verbose: is_debug,
error_purge_elements: ["control_panel"],
alpha: alpha,
allow_cors: allow_cors,
key_pause_enabled: false,
fps_elem_id: "fps_cont",
fps_wrapper_id: "fps_cont",
assets_pvr_available: pvr_available,
assets_dds_available: dds_available,
assets_min50_available: min50_available,
min_capabilities: min_capabilities,
assets_gzip_available: gzip_available,
shaders_path: "../../../shaders/"
})
}
function init_cb(canvas_element, success) {
set_stereo_config();
check_preview_image();
if (!success) {
display_no_webgl_bg();
return;
}
_window_width = window.innerWidth;
m_main.pause();
add_engine_version();
fill_tooltips();
check_touch();
check_cors();
check_fullscreen();
set_quality_btn();
prevent_context_menu();
init_ctrl_btns();
calc_stereo_menu_pos();
prepare_soc_btns();
init_links();
m_gp_conf.update();
let file = search_file();
if (!file)
return;
anim_logo(file);
window.addEventListener("resize", on_resize);
add_keycodes();
on_resize();
}
function check_cors() {
let url_params = m_app.get_url_params();
if (url_params && "allow_cors" in url_params)
return true;
return false;
}
function check_touch() {
_is_touch = "ontouchstart" in window || navigator.maxTouchPoints;
}
function fill_tooltips() {
let tooltips = document.querySelectorAll(".tooltip");
for (let i = 0; i < tooltips.length; i++) {
tooltips[i].innerText = locale.LANG_DICT[tooltips[i].id][_lang];
let tooltip_offset = tooltips[i].offsetWidth / 2;
let elem = document.querySelector("#" + locale.LANG_DICT[tooltips[i].id]["elem_id"]);
if (!elem)
continue;
let elem_offset = elem.offsetWidth / 2;
let elem_offset_left = elem.getBoundingClientRect();
let offset_left = window.innerWidth - elem_offset_left.right;
let max_offset_left = window.innerWidth - elem_offset_left.right + elem_offset;
if (tooltip_offset > max_offset_left)
tooltips[i].style.right = "0";
else
tooltips[i].style.right = (max_offset_left - tooltip_offset) + "px";
}
}
function check_lang() {
let url_params = m_app.get_url_params();
if (url_params) {
if ("lang" in url_params && (url_params["lang"] == 1 || url_params["lang"] == "ru"))
_lang = "ru";
} else
_lang = "en";
let device_type = (_is_touch ? "mobile" : "desk");
let cam_type = "static";
let cam = m_scs.get_active_camera();
if (m_camera.is_target_camera(cam))
cam_type = "target";
if (m_camera.is_hover_camera(cam))
cam_type = "hover";
if (m_camera.is_eye_camera(cam))
cam_type = "eye";
let text_string = "#help_body div .wrap." + device_type + "." + cam_type + "." + _lang;
let help_text = document.querySelector(text_string);
let cam_type_head = document.querySelector(".cam_type");
cam_type_head.innerText = locale.LANG_DICT["cam_type"][cam_type][_lang];
help_text.classList.add("active");
}
function switch_lang() {
let help_text = document.querySelector("#help_cont .wrap.active");
let device_type = _is_touch ? "mobile" : "desk";
let cam_type = "static";
let cam = m_scs.get_active_camera();
if (m_camera.is_target_camera(cam))
cam_type = "target";
if (m_camera.is_hover_camera(cam))
cam_type = "hover";
if (m_camera.is_eye_camera(cam))
cam_type = "eye";
if (help_text)
help_text.classList.remove("active");
help_text = document.querySelector("#help_cont .wrap." + _lang + "." + device_type + "." + cam_type);
help_text.classList.add("active");
fill_tooltips();
}
function check_preview_image() {
let url_params = m_app.get_url_params();
if (!url_params)
return;
let bg = "";
if ("preview_image" in url_params)
bg = url_params["preview_image"];
else
return;
_preloader_cont.querySelector("#bg").style.backgroundImage = "url(" + bg + ")";
}
function add_keycodes() {
}
function prepare_soc_btns() {
if (_no_social) {
_social_btn.parentNode.remove(_social_btn);
return;
}
let socials = _socials;
if (!socials.length)
return;
const char_btns_array = [TWITTER_CHAR, FB_CHAR, GOOGLE_CHAR, VK_CHAR, WEIBO_CHAR];
socials = socials.filter(function (value, index, array) {
return char_btns_array.indexOf(value) >= 0;
})
if (!socials.length)
return;
const elem_ids = ["tw", "fb", "gplus", "vk", "weibo"];
let ordered_elem_ids = [];
let removing_elem_ids = [];
for (var i = 0; i < socials.length; i++) {
switch (socials[i]) {
case TWITTER_CHAR:
ordered_elem_ids.push("tw");
break;
case FB_CHAR:
ordered_elem_ids.push("fb");
break;
case GOOGLE_CHAR:
ordered_elem_ids.push("gplus");
break;
case VK_CHAR:
ordered_elem_ids.push("vk");
break;
case WEIBO_CHAR:
ordered_elem_ids.push("weibo");
break;
}
}
for (var i = 0; i < elem_ids.length; i++)
if (ordered_elem_ids.indexOf(elem_ids[i]) < 0)
removing_elem_ids.push(elem_ids[i])
for (var i = 0; i < removing_elem_ids.length; i++) {
let elem = document.getElementById(removing_elem_ids[i]);
elem.parentElement.removeChild(elem);
}
let children = _social_menu.children;
let ar = [];
if (children.length > 5) {
_social_menu.classList.remove("short");
_social_menu.classList.add("long");
} else {
_social_menu.classList.remove("long");
_social_menu.classList.add("short");
}
ar.slice.call(children).sort(function (a, b) {
return ordered_elem_ids.indexOf(a.id) - ordered_elem_ids.indexOf(b.id);
}).forEach(function (next) {
_social_menu.appendChild(next);
})
}
function display_no_webgl_bg() {
const url_params = m_app.get_url_params(true);
if (url_params && url_params["fallback_image"]) {
const image_wrapper = document.createElement("div");
image_wrapper.className = "image_wrapper";
image_wrapper.style.backgroundImage = "url(" + url_params["fallback_image"] + ")";
_preloader_cont.style.display = "none";
document.body.appendChild(image_wrapper);
} else if (url_params && url_params["fallback_video"]) {
const video_wrapper = document.createElement("div");
const video_elem = document.createElement("video");
video_wrapper.className = "video_wrapper";
video_elem.autoplay = true;
for (let i = 0; i < url_params["fallback_video"].length; i++) {
const source = document.createElement("source");
source.src = url_params["fallback_video"][i];
video_elem.appendChild(source);
}
video_wrapper.appendChild(video_elem);
_preloader_cont.style.display = "none";
document.body.appendChild(video_wrapper);
} else
show_error("Browser could not initialize WebGL", "For more info visit",
"https://www.blend4web.com/doc/en/problems_and_solutions.html#problems-upon-startup");
}
function cache_dom_elems() {
_preloader_cont = document.querySelector("#preloader_cont");
_canvas_cont = document.querySelector("#main_canvas_cont");
_logo_cont = document.querySelector("#logo_cont");
_ctrl_cont = document.querySelector("#ctrl_cont");
_timeline_cont = document.querySelector("#timeline_cont");
_circle = _logo_cont.querySelector("circle");
_btns_cont = document.querySelector("#btns_cont");
_quality_btn = document.querySelector("#quality_btn");
_stereo_btn = document.querySelector("#stereo_btn");
_social_btn = document.querySelector("#soc_btn");
_social_menu = document.querySelector("#social");
_stereo_menu = document.querySelector("#stereo");
_quality_menu = document.querySelector("#quality");
_help_cont = document.querySelector("#help_cont");
_help_btn = document.querySelector("#help_btn");
_ctrl_wrap = document.querySelector("#ctrl_wrap");
_circle.style["strokeDasharray"] = CIRCUMFERENCE;
_circle.style["strokeDashoffset"] = CIRCUMFERENCE;
_circle.setAttribute("transform", _circle.getAttribute("transform"));
}
function add_engine_version() {
const version = m_version.version_str();
if (version) {
let version_cont = document.querySelector("#rel_version");
version_cont.innerHTML = m_version.version_str();
}
}
function check_fullscreen() {
let fullscreen_btn = document.querySelector("#fullscreen_btn");
if (!m_screen.check_fullscreen() && !m_screen.check_fullscreen_hmd())
fullscreen_btn.parentElement.removeChild(fullscreen_btn);
}
function check_autorotate() {
let autorotate_on_button = document.querySelector("#auto_rotate_btn");
if (!m_camera_anim.check_auto_rotate())
autorotate_on_button.parentElement.removeChild(autorotate_on_button);
}
function set_quality_btn() {
let quality = m_storage.get("quality") || DEFAULT_QUALITY;
if (quality == "CUSTOM") {
quality = DEFAULT_QUALITY;
m_storage.set("quality", quality);
}
let menu_elem = document.querySelector("#quality #" + quality.toLowerCase());
menu_elem.classList.add("activated");
// menu_elem.parentNode.removeChild(menu_elem);
switch (quality) {
case "LOW":
_quality_btn.classList.add("low");
break;
case "HIGH":
_quality_btn.classList.add("high");
break;
case "ULTRA":
_quality_btn.classList.add("ultra");
break;
}
}
function render_mode_to_id(mode) {
switch (mode) {
case "ANAGLYPH":
return "anaglyph";
break;
case "SIDEBYSIDE":
return "sidebyside";
break;
case "HMD":
return "hmd";
break;
case "NONE":
return "none";
break;
}
}
function update_mode_menu(stereo) {
let main_stereo_items = _stereo_menu.querySelectorAll(".item");
for (let i = 0; i < main_stereo_items.length; i++) {
let item = main_stereo_items[i];
item.classList.remove("activated");
if (item.id == render_mode_to_id(stereo))
item.classList.add("activated");
}
check_hmd();
// update stereo_btn icon
_stereo_btn.classList.remove("none", "anaglyph", "sidebyside", "hmd");
_stereo_btn.classList.add(render_mode_to_id(stereo));
}
function update_quality_menu(quality) {
_quality_btn.classList.remove("low", "high", "ultra");
_stereo_btn.classList.add(quality.toLowerCase());
}
function prevent_context_menu() {
window.oncontextmenu = function (e) {
e.preventDefault();
e.stopPropagation();
return false;
}
}
function calc_menu_pos(btn, menu) {
let items = menu.querySelectorAll(".item");
let max = 0;
for (let i = 0; i < items.length; i++) {
var item = items[i];
if (item.classList.contains("disabled"))
continue;
let w = item.querySelector("div").getBoundingClientRect().width +
item.querySelector("svg").getBoundingClientRect().width;
if (w > max)
max = w;
}
max = max + 24;
let rect = btn.getBoundingClientRect();
let btn_right = window.innerWidth - rect.right + rect.width;
if (btn_right >= (max + 16))
menu.style.right = Math.ceil(btn_right - max) + "px";
else
menu.style.right = "16px";
menu.style.width = Math.ceil(max) + "px";
}
function calc_stereo_menu_pos() {
calc_menu_pos(_stereo_btn, _stereo_menu);
}
function calc_quality_menu_pos() {
calc_menu_pos(_quality_btn, _quality_menu);
}
function init_ctrl_btns() {
let mousedown_event = _is_touch ? "touchstart" : "mousedown";
let mouseup_event = _is_touch ? "touchend" : "mouseup";
let mousemove_event = _is_touch ? "touchmove" : "mousemove";
for (let i = 0; i < _player_btns.length; i++) {
let button = _player_btns[i];
let elem = document.getElementById(button.id);
if (!elem)
continue;
elem.addEventListener(mousedown_event, function () {
if (!this.classList.contains("hover"))
this.classList.add("hover");
});
elem.addEventListener(mouseup_event, function () {
setTimeout(() => {
if (this.classList.contains("hover"))
this.classList.remove("hover");
}, 20);
});
elem.addEventListener("mouseenter", function () {
if (!this.classList.contains("hover"))
this.classList.add("hover");
});
elem.addEventListener("mouseleave", function () {
if (this.classList.contains("hover"))
this.classList.remove("hover");
});
switch (button.type) {
case "menu_button":
elem.addEventListener("click", function () {
show_hide_menu(elem, button.callback);
})
break;
case "simple_button":
elem.addEventListener(mouseup_event, button.callback);
case "trigger_button":
elem.addEventListener(mouseup_event, button.callback);
elem.addEventListener("mouseenter", function () {
});
elem.addEventListener("mouseenter", function () {
});
}
}
let timeout = null;
let init_x, init_y, final_x, final_y;
_canvas_cont.addEventListener(mousedown_event, function (e) {
_is_down = true;
init_x = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
init_y = e.changedTouches ? e.changedTouches[0].clientY : e.clientY;
window.addEventListener(mousemove_event, on_mousemove);
if (_ctrl_cont.parentNode.parentNode.classList.contains("ctrl_active")) {
_ctrl_cont.parentNode.parentNode.classList.remove("active","ctrl_active");
}
});
window.addEventListener(mouseup_event, function () {
if (_is_down && (_stereo_mode == "HMD" || _stereo_mode == "SIDEBYSIDE") ) {
hide_active_elems();
window.removeEventListener(mousemove_event, on_mousemove);
} else if (_is_down && !(_stereo_mode == "HMD" || _stereo_mode == "SIDEBYSIDE") ) {
clearTimeout(timeout);
_is_down = false;
_ctrl_cont.parentNode.parentNode.classList.add("active");
window.removeEventListener(mousemove_event, on_mousemove);
}
});
function on_mousemove(e) {
final_x = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
final_y = e.changedTouches ? e.changedTouches[0].clientY : e.clientY;
let x_abs = Math.abs(init_x - final_x);
let y_abs = Math.abs(init_y - final_y);
if (x_abs > 20 || y_abs > 20) {
if (_stereo_mode == "HMD" || _stereo_mode == "SIDEBYSIDE") {
clearTimeout(timeout);
_ctrl_cont.parentNode.parentNode.classList.add("active", "ctrl_active");
} else {
hide_active_elems();
_ctrl_cont.parentNode.parentNode.classList.remove("active");
}
}
}
}
function search_file() {
let module_name = m_cfg.get("built_in_module_name");
let file = "";
if (b4w.module_check(module_name)) {
let bd = b4w.require(module_name);
file = bd["data"]["main_file"];
remove_built_in_scripts();
return file;
} else {
let url_params = m_app.get_url_params();
if (url_params && url_params["load"]) {
file = url_params["load"];
return file;
} else if (url_params && _url_params["load"] && _url_params["load"] != "__ASSETS_LOADING_PATH__") {
file = _url_params["load"];
return file;
} else {
show_error("Please specify a scene to load",
"For more info visit",
"https://www.blend4web.com/doc/en/web_player.html#scene-errors");
return null;
}
}
}
function anim_logo(file) {
_logo_cont.classList.add("active");
setTimeout(function () {
m_main.resume();
m_data.load(file, loaded_callback, preloader_callback, false);
}, 800);
}
function show_hide_menu(elem, cb) {
let active = elem.classList.contains("active");
hide_active_elems();
_social_menu.classList.remove("active");
_stereo_menu.classList.remove("active");
_quality_menu.classList.remove("active");
if (!active) {
cb();
elem.classList.add("active");
elem.classList.add("manual_hover");
} else {
elem.classList.remove("manual_hover");
}
}
function hide_active_elems() {
let btns = document.querySelectorAll(".ctrl_btn");
_social_menu.classList.remove("active");
_stereo_menu.classList.remove("active");
_quality_menu.classList.remove("active");
for (let i = 0; i < btns.length; i++)
btns[i].classList.remove("active", "manual_hover", "hover");
}
function hide_menu(menu_elem) {
menu_elem.classList.remove("active");
}
function btn_on(btn) {
btn.classList.add("active");
}
function btn_off(btn) {
btn.classList.remove("active");
}
function open_help() {
_help_cont.classList.toggle("active");
init_swipe();
}
function close_help() {
_help_btn.classList.remove("active", "hover", "manual_hover");
_help_cont.classList.remove("active");
}
function rotate_camera() {
let rotate_btn = document.querySelector("#auto_rotate_btn");
let is_rotate = rotate_btn.classList.contains("on");
let tooltip_on = document.querySelector("#autorotate_on_tooltip");
let tooltip_off = document.querySelector("#autorotate_off_tooltip");
let timeout;
if (!is_rotate) {
if (m_main.is_paused()) {
let play_btn = document.querySelector("#play_btn");
play_btn.classList.add("on");
play_btn.classList.remove("off");
m_main.resume();
}
}
rotate_btn.classList.toggle("on");
m_camera_anim.auto_rotate(CAMERA_AUTO_ROTATE_SPEED, function () {
let rotate_btn = document.querySelector("#auto_rotate_btn");
let is_rotate = rotate_btn.classList.contains("on");
if (is_rotate) {
rotate_btn.classList.toggle("on");
}
});
if (is_rotate) {
tooltip_off.classList.add("active");
clearTimeout(timeout);
timeout = setTimeout(function () {
tooltip_off.classList.remove("active");
}, 400)
tooltip_on.classList.remove("active");
} else {
tooltip_on.classList.add("active");
clearTimeout(timeout);
timeout = setTimeout(function () {
tooltip_on.classList.remove("active");
}, 400)
tooltip_off.classList.remove("active");
}
}
function play_sound() {
let tooltip_on = document.querySelector("#sound_on_tooltip");
let tooltip_off = document.querySelector("#sound_off_tooltip");
let timeout;
if (m_sfx.is_muted()) {
m_sfx.mute(null, false);
this.classList.add("on");
this.classList.remove("off");
tooltip_on.classList.add("active");
clearTimeout(timeout);
timeout = setTimeout(function () {
tooltip_on.classList.remove("active");
}, 400)
tooltip_off.classList.remove("active");
} else {
m_sfx.mute(null, true);
this.classList.add("off");
this.classList.remove("on");
tooltip_off.classList.add("active");
clearTimeout(timeout);
timeout = setTimeout(function () {
tooltip_off.classList.remove("active");
}, 400)
tooltip_on.classList.remove("active");
}
}
function play_engine() {
let tooltip_on = document.querySelector("#play_tooltip");
let tooltip_off = document.querySelector("#pause_tooltip");
let timeline_cont = document.querySelector("#timeline_cont");
let timeline_bar = timeline_cont.querySelector("#line");
let cur_frame = m_nla.get_frame();
let start_frame = m_nla.get_frame_start();
let end_frame = m_nla.get_frame_end();
let nla_frame_length = end_frame - start_frame;
let cur_frame_in_percent = cur_frame * 100 / nla_frame_length;
if (cur_frame_in_percent < 0)
cur_frame_in_percent = 0;
if (cur_frame_in_percent > 100)
cur_frame_in_percent = 100;
timeline_bar.style.transition = "none";
timeline_bar.style.width = cur_frame_in_percent + "%";
timeline_bar.innerText;
let timeout;
if (m_main.is_paused()) {
let cur_sec = cur_frame / _nla_fps;
let nla_sec_lenght = nla_frame_length / _nla_fps;
let nla_left_sec = nla_sec_lenght - cur_sec;
timeline_bar.style.transition = "width " + nla_left_sec + "s linear";
timeline_bar.innerText;
timeline_bar.style.width = "100%";
m_main.resume();
this.classList.add("on");
this.classList.remove("off");
tooltip_on.classList.add("active");
clearTimeout(timeout);
timeout = setTimeout(function () {
tooltip_on.classList.remove("active");
}, 400)
tooltip_off.classList.remove("active");
} else {
let rotate_btn = document.querySelector("#auto_rotate_btn");
let is_rotate;
if (rotate_btn)
is_rotate = rotate_btn.classList.contains("on");
if (is_rotate && rotate_btn) {
m_camera_anim.auto_rotate(CAMERA_AUTO_ROTATE_SPEED);
rotate_btn.classList.remove("on");
}
m_main.pause();
this.classList.add("off");
this.classList.remove("on");
tooltip_off.classList.add("active");
clearTimeout(timeout);
timeout = setTimeout(function () {
tooltip_off.classList.remove("active");
}, 400);
tooltip_on.classList.remove("active");
}
}
function enter_fullscreen() {
let elem = document.querySelector("#fullscreen_btn");
elem.classList.add("on");
}
function fullscreen_cb() {
let elem = document.querySelector("#fullscreen_btn");
let is_fs = elem.classList.contains("on");
const is_hmd = m_screen.check_fullscreen_hmd();
let exec_method = function () {};
if (is_hmd) {
if (is_fs)
exec_method = m_screen.exit_fullscreen_hmd;
else
exec_method = m_screen.request_fullscreen_hmd;
} else {
if (is_fs)
exec_method = m_screen.exit_fullscreen;
else
exec_method = m_screen.request_fullscreen;
}
exec_method(document.body, enter_fullscreen, exit_fullscreen);
}
function exit_fullscreen() {
let elem = document.querySelector("#fullscreen_btn");
elem.classList.remove("on");
}
function on_resize() {
m_cont.resize_to_container();
_window_width = window.innerWidth;
}
function get_selected_object() {
return _selected_object;
}
function set_selected_object(obj) {
_selected_object = obj;
}
function mouse_cb() {
if (!m_scs.can_select_objects())
return;
const canvas_elem = m_cont.get_canvas();
const mdevice = m_input.get_device_by_type_element(m_input.DEVICE_MOUSE, canvas_elem);
let loc = m_input.get_vector_param(mdevice, m_input.MOUSE_LOCATION, _vec2_tmp);
main_canvas_clicked(loc[0], loc[1]);
}
function touch_cb(touches) {
if (!m_scs.can_select_objects())
return;
for (var i = 0; i < touches.length; i++)
main_canvas_clicked(touches[i].clientX, touches[i].clientY);
}
function register_canvas_click() {
const canvas_elem = m_cont.get_canvas();
const mdevice = m_input.get_device_by_type_element(m_input.DEVICE_MOUSE, canvas_elem);
const tdevice = m_input.get_device_by_type_element(m_input.DEVICE_TOUCH, canvas_elem);
if (mdevice)
m_input.attach_param_cb(mdevice, m_input.MOUSE_DOWN_WHICH, mouse_cb);
if (tdevice)
m_input.attach_param_cb(tdevice, m_input.TOUCH_START, touch_cb);
}
function main_canvas_clicked(x, y) {
let prev_obj = get_selected_object();
if (prev_obj && m_scs.outlining_is_enabled(prev_obj) && prev_obj.render.outline_on_select)
m_scs.clear_outline_anim(prev_obj);
let obj = _pick(x, y);
set_selected_object(obj);
}
function check_nla() {
if (!m_nla.check_nla() || m_nla.check_logic_nodes()) {
if (!_ctrl_wrap.classList.contains("no_timer")) _ctrl_wrap.classList.add("no_timer");
return;
}
let mousedown_event = _is_touch ? "touchstart" : "mousedown";
let mouseup_event = _is_touch ? "touchend" : "mouseup";
let mousemove_event = _is_touch ? "touchmove" : "mousemove";
m_nla.stop();
let timeline_cont = document.querySelector("#timeline_cont");
let time_cont = document.querySelector("#time_cont");
let timer = document.querySelector("#timer");
let timeline_bar = timeline_cont.querySelector("#line");
let start_frame = m_nla.get_frame_start();
let end_frame = m_nla.get_frame_end();
let nla_frame_length = end_frame - start_frame;
let nla_sec_lenght = nla_frame_length / _nla_fps;
let tmp_delta_time = 0;
let tmp_width = 0;
let ms = nla_sec_lenght % 1 * 100;
let m = Math.floor(nla_sec_lenght / 60);
let s = 0;
timeline_cont.style.display = "block";
timeline_cont.classList.add("active");
m_main.set_render_callback(function (e) {
let cur_frame = m_nla.get_frame();
time_cont.innerText = get_str_time(cur_frame) + " / " + get_str_time(end_frame);
})
function get_str_time(cur_frame) {
if (cur_frame < 0)
return "00 : 00";
let cur_sec = cur_frame / _nla_fps;
let m = Math.floor(cur_sec / 60);
let s = cur_sec - m * 60;
let ms = cur_sec % 1 * 100;
let str = "";
if (m) {
if (m > 9)
str += m.toFixed(0) + " : ";
else
str += "0" + m.toFixed(0) + " : ";
}
if (s) {
if (s > 9)
str += s.toFixed(0) + " : ";
else
str += "0" + s.toFixed(0) + " : ";
}
if (ms) {
if (ms > 9)
str += ms.toFixed(0);
else
str += "0" + ms.toFixed(0);
}
if (str)
return str;
return "00 : 00";
}
timeline_cont.addEventListener(mousedown_event, on_mousedown);
document.addEventListener("visibilitychange", on_visibilitychange);
function on_visibilitychange(e) {
if (!document.hidden)
on_focus();
}
function on_focus() {
if (m_main.is_paused())
return;
let cur_frame = m_nla.get_frame();
let cur_frame_in_percent = cur_frame * 100 / nla_frame_length;
if (cur_frame_in_percent < 0)
cur_frame_in_percent = 0;
if (cur_frame_in_percent > 100)
cur_frame_in_percent = 100;
let cur_sec = cur_frame / _nla_fps;
let nla_left_sec = nla_sec_lenght - cur_sec;
timeline_bar.style.width = cur_frame_in_percent + "%";
timeline_bar.innerText;
timeline_bar.style.transition = "width " + nla_left_sec + "s linear";
timeline_bar.style.width = "100%";
}
function on_mouseup(e) {
if (m_main.is_paused())
return;
let x = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
window.removeEventListener(mousemove_event, on_mousemove);
let cur_frame_in_percent = x / _window_width * 100;
if (cur_frame_in_percent < 0)
cur_frame_in_percent = 0;
if (cur_frame_in_percent > 100)
cur_frame_in_percent = 100;
let cur_frame = cur_frame_in_percent * nla_frame_length / 100;
let cur_sec = cur_frame / _nla_fps;
let nla_left_sec = nla_sec_lenght - cur_sec;
m_nla.set_frame(cur_frame);
timeline_bar.style.transition = "width " + nla_left_sec + "s linear";
timeline_bar.style.width = "100%";
timer.style.display = "none";
timeline_bar.classList.remove('inactive-pointer');
window.removeEventListener(mouseup_event, on_mouseup);
m_nla.set_frame(cur_frame);
play_nla();
}
function on_mousedown(e) {
if (m_main.is_paused())
return;
let x = e.touches ? e.touches[0].clientX : e.clientX;
m_nla.stop();
timeline_bar.style.transition = "none";
window.addEventListener(mousemove_event, on_mousemove);
window.addEventListener(mouseup_event, on_mouseup);
let cur_frame_in_percent = x / _window_width * 100;
if (cur_frame_in_percent < 0)
cur_frame_in_percent = 0;
if (cur_frame_in_percent > 100)
cur_frame_in_percent = 100;
let cur_frame = cur_frame_in_percent * nla_frame_length / 100;
m_nla.set_frame(cur_frame);
timeline_bar.style.width = cur_frame_in_percent + "%";
timer.style.left = cur_frame_in_percent + "%";
timer.innerText = get_str_time(cur_frame);
if (x - 4 <= timer.getBoundingClientRect().width)
timer.classList.add("rotated");
else
timer.classList.remove("rotated");
timer.style.display = "block";
timeline_bar.classList.add('inactive-pointer');
}
function on_mousemove(e) {
let x = e.touches ? e.touches[0].clientX : e.clientX;
timeline_bar.style.transition = "none";
let cur_frame_in_percent = x / _window_width * 100;
if (cur_frame_in_percent < 0)
cur_frame_in_percent = 0;
if (cur_frame_in_percent > 100)
cur_frame_in_percent = 100;
let cur_frame = cur_frame_in_percent * nla_frame_length / 100;
let cur_sec = cur_frame / _nla_fps;
m_nla.set_frame(cur_frame);
timeline_bar.style.width = cur_frame_in_percent + "%";
timer.innerText = get_str_time(cur_frame);
timer.style.left = cur_frame_in_percent + "%";
if (x - 4 <= timer.getBoundingClientRect().width)
timer.classList.add("rotated");
else
timer.classList.remove("rotated");
}
function reset_nla() {
timeline_bar.style.width = "0%";
timeline_bar.style.transition = "none";
m_nla.stop();
m_nla.set_frame(start_frame);
}
function start_bar_anim() {
timeline_bar.innerText;
timeline_bar.style.transition = "width " + nla_sec_lenght + "s linear";
timeline_bar.style.width = "100%";
play_nla();
}
function play_nla() {
m_nla.play(function () {
reset_nla();
start_bar_anim();
});
}
start_bar_anim();
}
function loaded_callback(data_id, success) {
if (!success) {
show_error("Could not load the scene",
"For more info visit",
"https://www.blend4web.com/doc/en/web_player.html#scene-errors");
return;
}
_nla_fps = m_time.get_framerate();
check_lang();
register_canvas_click();
check_autorotate();
check_nla();
m_app.enable_camera_controls(false, false, false, null, true);
var mouse_move = m_ctl.create_mouse_move_sensor();
var mouse_click = m_ctl.create_mouse_click_sensor();
var canvas_cont = m_cont.get_container();
function move_cb() {
canvas_cont.className = "move";
}
function stop_cb(obj, id, pulse) {
if (pulse == -1)
canvas_cont.className = "";
}
m_ctl.create_sensor_manifold(null, "MOUSE_MOVE", m_ctl.CT_SHOT, [mouse_click, mouse_move], function (s) {
return s[0] && s[1]
}, move_cb);
m_ctl.create_sensor_manifold(null, "MOUSE_STOP", m_ctl.CT_TRIGGER, [mouse_click], function (s) {
return s[0]
}, stop_cb);
var url_params = m_app.get_url_params();
if (url_params && "autorotate" in url_params ||
_url_params["autorotate"] != AUTOROTATE_PARAM_STR)
rotate_camera();
var meta_tags = m_scs.get_meta_tags();
if (meta_tags.title)
document.title = meta_tags.title;
check_hmd();
if (_stereo_mode == "HMD")
set_hmd()
}
function check_hmd() {
let hmd_mode_button = document.querySelector("#hmd");
if (!m_input.can_use_device(m_input.DEVICE_HMD)) {
hmd_mode_button.classList.add("disabled");
m_input.remove_click_listener(hmd_mode_button, change_stereo);
}
}
function preloader_callback(percentage, load_time) {
let dashoffset = CIRCUMFERENCE * (1 - percentage / 100);
_circle.style["strokeDashoffset"] = dashoffset;
if (percentage == 100) {
if (!m_sfx.get_speaker_objects().length) {
let sound_btn = document.querySelector("#sound_btn");
sound_btn.parentElement.removeChild(sound_btn);
}
_logo_cont.classList.remove("active");
_preloader_cont.classList.remove("active");
setTimeout(function () {
if(_stereo_mode !== "HMD" && _stereo_mode !== "SIDEBYSIDE")
_ctrl_cont.parentNode.parentNode.classList.add("active");
_preloader_cont.parentNode.removeChild(_preloader_cont);
}, 1200)
}
}
function extend_objs_props(objs, common_obj) {
for (var i = objs.length; i--;)
for (var prop in common_obj)
objs[i][prop] = common_obj[prop];
}
function remove_built_in_scripts() {
let scripts = document.getElementById(BUILT_IN_SCRIPTS_ID);
scripts.parentElement.removeChild(scripts);
}
function change_quality() {
if (this.classList.contains("activated"))
return;
let qual = this.id.toUpperCase();
let cur_quality = m_cfg.get("quality");
if (cur_quality == qual)
return;
m_storage.set("quality", qual);
reload_app();
}
function set_hmd() {
if (m_input.can_use_device(m_input.DEVICE_HMD))
m_hmd_conf.update();
if (m_camera_anim.is_auto_rotate()) {
rotate_camera();
update_auto_rotate_button();
}
var cam = m_scs.get_active_camera();
var pos = m_trans.get_translation(cam, _vec3_tmp);
var quat = m_trans.get_rotation(cam, _quat_tmp);
var new_x = m_vec3.transformQuat(m_util.AXIS_X, quat, _vec3_tmp2);
new_x[2] = 0;
m_vec3.normalize(new_x, new_x);
var offset_quat = m_quat.rotationTo(m_util.AXIS_X, new_x, _quat_tmp);
m_hmd.set_position(pos);
m_hmd.set_rotate_quat(offset_quat);
m_hmd.enable_hmd(m_hmd.HMD_ALL_AXES_MOUSE_NONE);
_pick = m_scs.pick_center;
// Check if app is in fullscreen mode.
let in_fullscreen = document.querySelector("#fullscreen.on");
if (!in_fullscreen)
fullscreen_cb();
_ctrl_cont.parentNode.parentNode.classList.remove("active");
}
function change_stereo() {
if (this.classList.contains("activated"))
return;
let stereo = this.id.toUpperCase();
let reload = false;
switch (stereo) {
case "NONE":
m_storage.set("stereo", "NONE");
if (_stereo_mode == "ANAGLYPH" || _stereo_mode == "SIDEBYSIDE")
reload = true;
else {
m_hmd.disable_hmd();
_pick = m_scs.pick_object;
}
break;
case "ANAGLYPH":
m_storage.set("stereo", "ANAGLYPH");
reload = true;
break;
case "SIDEBYSIDE":
m_storage.set("stereo", "SIDEBYSIDE");
reload = true;
_ctrl_cont.parentNode.parentNode.classList.remove("active");
break;
case "HMD":
m_storage.set("stereo", "HMD");
if (_stereo_mode == "NONE") {
set_hmd();
} else {
// m_storage.set("stereo", "NONE");
reload = true;
}
break;
}
document.getElementById("stereo").classList.remove("active");
if (reload) {
reload_app();
} else {
update_mode_menu(stereo);
}
_stereo_mode = stereo;
}
function reload_app() {
setTimeout(function () {
window.location.reload();
}, 100);
}
function set_quality_config() {
let quality = m_storage.get("quality");
if (!quality || quality == "CUSTOM") {
quality = DEFAULT_QUALITY;
m_storage.set("quality", quality);
}
let qual = m_cfg.P_LOW;
switch (quality) {
case "HIGH":
qual = m_cfg.P_HIGH;
break;
case "ULTRA":
qual = m_cfg.P_ULTRA;
break;
}
m_cfg.set("quality", qual);
}
function open_social() {
_social_menu.classList.add("active");
}
function open_stereo() {
calc_stereo_menu_pos();
_stereo_menu.classList.toggle("active");
_stereo_btn.classList.toggle("active");
_active_cb = open_stereo;
}
function open_quality(is_elem) {
calc_quality_menu_pos();
_quality_menu.classList.toggle("active");
_quality_btn.classList.toggle("active");
_active_cb = open_quality;
}
function set_stereo_config() {
let stereo = m_storage.get("stereo") || DEFAULT_STEREO;
_stereo_mode = stereo;
// updating menu before HMD detection
update_mode_menu(stereo);
if (stereo == "NONE" && m_input.can_use_device(m_input.DEVICE_HMD))
stereo = "HMD";
m_cfg.set("stereo", stereo);
}
function create_help_structure(help_desc, device_type, lang) {
let help_body = document.createElement("div");
for (let key in help_desc) {
let wrap = document.createElement("div");
help_body.appendChild(wrap);
wrap.classList.add("wrap");
wrap.classList.add(device_type);
wrap.classList.add(key);
wrap.classList.add(lang);
let ul = document.createElement("ul");
wrap.appendChild(ul);
for (let i = 0; i < help_desc[key].length; i++) {
let li = document.createElement("li");
ul.appendChild(li);
let id = help_desc[key][i];
let title = "t" in locale.HELP_DICT[device_type][id] ? locale.HELP_DICT[device_type][id]["t"][lang]: "";
let help_entry = (new DOMParser())
.parseFromString(
"<div> \
<h3>" + title + "</h3>\
<div> \
</div> \
<div> \
<p>" + locale.HELP_DICT[device_type][id][lang] + "</p> \
</div> \
</div>", 'text/html')
.body.childNodes[0];
help_entry.id = id;
help_entry.classList.add("help_entry");
li.appendChild(help_entry);
}
}
return help_body;
}
function init_help() {
let languages = ["ru", "en"];
let help_desktop_description = {
"hover": [ "help_hover_rotate", "help_hover_lean", "help_hover_move", "help_hover_interact" ],
"eye": [ "help_eye_rotation", "help_eye_zoom", "help_eye_move_cam_space"],
"target": [ "help_target_rotate", "help_target_zoom", "help_target_interact" ],
"static": [ "help_static" ]
}
let help_mobile_description = {
"hover": [ "help_hover_zoom", "help_hover_rotate", "help_hover_move", "help_hover_interact" ],
"eye": [ "help_eye_rotation", "help_eye_interact"],
"target": [ "help_target_zoom", "help_target_rotate", "help_target_interact" ],
"static": [ "help_static" ]
}
let help_body = document.querySelector("#help_body");
for (let l in languages) {
let desk = create_help_structure(help_desktop_description, "desk", languages[l]);
help_body.appendChild(desk);
let mob = create_help_structure(help_mobile_description, "mobile", languages[l]);
help_body.appendChild(mob);
}
}
function show_error(text_message, link_message, link) {
let error_name = document.querySelector("#error_name");
let error_info = document.querySelector("#error_info");
let error_cont = document.querySelector("#error_cont");
error_name.innerHTML = text_message;
error_info.innerHTML = link_message + " <a href=" + link + ">" + link.replace("https://www.", "") + "</a>";
error_cont.style.display = "block";
}
function init_swipe() {
let initial_point;
let final_point;
let help_container = document.getElementById("help_cont");
help_container.addEventListener('touchstart', function(event) {
event.preventDefault();
event.stopPropagation();
initial_point=event.changedTouches[0];
}, false);
help_container.addEventListener('touchend', function(event) {
event.preventDefault();
event.stopPropagation();
final_point=event.changedTouches[0];
let x_abs = Math.abs(initial_point.pageX - final_point.pageX);
let y_abs = Math.abs(initial_point.pageY - final_point.pageY);
if (x_abs > 20 || y_abs > 20) {
if (x_abs <= y_abs && final_point.pageY < initial_point.pageY) {
close_help();
/*Swipe to the top*/
}
}
}, false);
}
function init_links() {
var button_links = document.querySelectorAll("#social a");
for (var i = 0; i < button_links.length; i++) {
var link = button_links[i];
if (link.hasAttribute("href"))
link.href += document.location.href;
}
}
// to allow early built-in module check
window.addEventListener("load", function () {
init();
});<file_sep>using Microsoft.AspNet.Identity;
using OpenSourceTees.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http.Cors;
using System.Web.Mvc;
namespace OpenSourceTees.Controllers
{
public class DesignController : Controller
{
BlobUtility utility;
ApplicationDbContext db;
string ContainerName = ConfigurationManager.AppSettings["BlobStorageBlobName"];
public DesignController()
{
utility = new BlobUtility();
db = new ApplicationDbContext();
}
// GET: Design
public ActionResult Index()
{
string loggedInUserId = User.Identity.GetUserId();
List<Image> userImages = (from r in db.Images where r.UserId == loggedInUserId select r).ToList();
ViewBag.PhotoCount = userImages.Count;
if (Request.IsAjaxRequest())
return PartialView(userImages);
return RedirectToAction("Index", "Home");
}
// Post
public ActionResult DeleteImage(string id)
{
if (Request.IsAjaxRequest()){
Image userImage = db.Images.Find(id);
db.Images.Remove(userImage);
db.SaveChanges();
string BlobNameToDelete = userImage.ImageUrl.Split('/').Last();
utility.DeleteBlob(BlobNameToDelete, "blobs");
return RedirectToAction("Index");
}
return RedirectToAction("Index", "Home");
}
// GET
[HttpGet]
public ActionResult UploadImage()
{
if (Request.IsAjaxRequest())
return PartialView();
return RedirectToAction("Index", "Home");
}
// GET
[HttpPost]
public ActionResult UploadImage(TeeShirtUploadViewModel tee)
{
if (Request.IsAjaxRequest())
{
if (tee.File != null)
{
tee.File = tee.File ?? Request.Files["file"];
string fileName = Path.GetFileName(tee.File.FileName);
Stream imageStream = tee.File.InputStream;
var result = utility.UploadBlob(fileName, ContainerName, imageStream);
if (result != null)
{
string loggedInUserId = User.Identity.GetUserId();
Image userimage = new Image();
userimage.Id = new Random().Next().ToString();
userimage.ImageUrl = result.Uri.ToString();
userimage.UserId = loggedInUserId;
userimage.Description = tee.Image.Description;
userimage.DesignName = tee.Image.DesignName;
userimage.Price = tee.Image.Price;
db.Images.Add(userimage);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
{
return PartialView(tee);
}
}
else
{
return PartialView(tee);
}
}
return RedirectToAction("Index", "Home");
}
// POST
[EnableCors(origins: "https://opensourceteeblob.blob.core.windows.net/", headers: "*", methods: "*")]
public ActionResult Search(string keywords, int? SkipN, int? TakeN)
{
//Console.WriteLine(db.udf_imageSearch(keywords, SkipN, TakeN).ToList());
//var SearchList = from m in db.udf_imageSearch(keywords, SkipN, TakeN)
// select m;
//var SearchList = from m in db.Images
// select m;
if (TakeN == 0 || TakeN == null)
{
TakeN = 10;
}
if (SkipN == null || SkipN == 10)
{
SkipN = 0;
}
if (String.IsNullOrEmpty(keywords) && Request.IsAjaxRequest())
{
return PartialView(from s in db.Images
select new RankedEntity<Image> { Entity = s, Rank = 1 });
}
var SearchList = from s in db.Images
join fts in db.udf_imageSearch(keywords, SkipN, TakeN) on s.Id equals fts.Id
select new RankedEntity<Image>
{
Entity = s,
Rank = fts.Ranking
};
if(keywords.Length > 3)
{
var list = SearchList;
}
if (Request.IsAjaxRequest())
return PartialView(SearchList.ToList());
return RedirectToAction("Index", "Home");
}
// GET
public ActionResult EditImage(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
if (Request.IsAjaxRequest())
return PartialView(image);
return RedirectToAction("Index", "Home");
}
// POST: Images/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditImage([Bind(Include = "Id,ImageUrl,UserId,DesignName,Description,Price")] Image image)
{
if (ModelState.IsValid)
{
db.Entry(image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return PartialView(image);
}
// GET: Images/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
if (Request.IsAjaxRequest())
return PartialView(image);
return RedirectToAction("Index", "Home");
}
// GET
public ActionResult Hot()
{
var list = (from i in db.Images
join po in db.PurchaseOrders on i.Id equals po.ImageId into mi
orderby mi.Count() descending
select i).Take(20).ToList();
if (Request.IsAjaxRequest())
return PartialView(list);
return RedirectToAction("Index", "Home");
}
// GET
public ActionResult New()
{
var list = (from i in db.Images
orderby i.CreatedDate descending
select i).Take(20).ToList();
if (Request.IsAjaxRequest())
return PartialView(list);
return RedirectToAction("Index", "Home");
}
]// GET
public ActionResult ByUser(string id)
{
List<Image> userImages = (from r in db.Images where r.UserId == id select r).ToList();
ViewBag.PhotoCount = userImages.Count;
if (Request.IsAjaxRequest())
return PartialView(userImages);
ViewBag.UserName = db.Users.Find(id).UserName;
return RedirectToAction("Index", "Home");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OpenSourceTees.Models
{
/// <summary>
/// Represents a ranked entity from the Database
/// </summary>
/// <typeparam name="E">Type of Entity to be ranked</typeparam>
public class RankedEntity<E>
{
/// <summary>
/// Ranked entity object
/// </summary>
public E Entity { get; set; }
/// <summary>
/// Rank if the entity
/// </summary>
public int? Rank { get; set; }
}
}<file_sep>const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlWebpackInlineSourcePlugin = require("html-webpack-inline-source-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackExcludeAssetsPlugin = require("html-webpack-exclude-assets-plugin");
const HtmlWebpackInlineSVGPlugin = require('html-webpack-inline-svg-plugin');
const webpack = require("webpack");
const base64 = require("postcss-base64");
const base64Font = require("postcss-font-base64");
const gen_externs = require("../../scripts/app_builder/gen_closure_externs.js");
const get_sdk_version = require("../../scripts/app_builder/get_sdk_version.js");
const fs = require("fs");
const htmlTemplatePath = "./src/template/template.pug";
const appName = "webplayer";
module.exports = function (env) {
var config = {
entry: "./src/js/webplayer.js",
output: {
path: path.resolve(__dirname, "build"),
filename: appName + ".js",
sourceMapFilename: appName + ".js.map"
},
module: {
rules: [
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "postcss-loader",
options: {
exec: false,
plugins: (loader) => [
base64({
extensions: [".svg", ".png"]
})
]
}
}, {
loader: "postcss-loader",
options: {
exec: false,
plugins: (loader) => [
base64Font({
extensions: [".woff", ".woff2"]
})
]
}
}, {
loader: "sass-loader"
}]
})
},
{
test: /\.(jpg|svg|png|woff|woff2)$/,
loader: "file-loader",
options: {
name: "[path][name].[ext]"
},
},
{
test: /\.pug$/,
loader: "pug-loader",
options: {
pretty: true,
self: true
},
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: htmlTemplatePath,
filename: path.join("template/" + appName + "_template.html"),
isTemplate: true,
excludeAssets: [/.*.js/, /.*.css/],
svgoConfig: {
removeTitle: false,
removeViewBox: true,
},
}),
new HtmlWebpackPlugin({
filename: appName + ".html",
template: htmlTemplatePath,
svgoConfig: {
removeTitle: false,
removeViewBox: true,
},
}),
new HtmlWebpackInlineSVGPlugin(),
new ExtractTextPlugin(appName + ".css"),
new HtmlWebpackExcludeAssetsPlugin()
],
resolve: {
alias: {
blend4web: path.resolve(path.join(__dirname, "..", ".."), "index.js")
}
},
devServer: {
contentBase: [path.join(__dirname, "..", ".."), __dirname],
host: "127.0.0.1"
},
};
var production = false;
if (env) {
if (env.production) {
production = true;
}
}
if (production) {
// patch version.js
var d = new Date();
var date_str = d.getFullYear() + ", " + (d.getMonth() + 1) + ", " + d.getDate() + ", " + d.getHours() + ", " + d.getMinutes() + ", " + d.getSeconds();
var version = get_sdk_version.get_sdk_version();
config.module.rules.push(
{
test: /version\.js/,
loader: 'string-replace-loader',
query: {
multiple: [
{ search: 'var TYPE = "DEBUG";', replace: 'var TYPE = "RELEASE";' },
{ search: 'var DATE = null;', replace: 'var DATE = new Date('+date_str+');' },
{ search: 'var VERSION = null;', replace: `var VERSION = [${parseInt(version[0])}, ${parseInt(version[1])}, ${parseInt(version[2])}] ;` },
{ search: 'var PREVENT_CACHE = "_b4w_ver_";', replace: 'var PREVENT_CACHE = "_b4w_ver_' + version.join('_') + '_";' }
]
}
})
// correct path to the uranium physics engine in config.js
config.module.rules.push(
{
test: /config\.js/,
loader: 'string-replace-loader',
query: {
multiple: [
{ search: 'B4W_URANIUM_PATH=/dist/uranium/', replace: 'B4W_URANIUM_PATH=uranium/' }
]
}
})
const ClosureCompilerPlugin = require('webpack-closure-compiler');
var externs_path = path.join("..", "..", "dist", "misc", "closure_externs")
gen_externs.write_externs(path.join(externs_path, "extern_b4w.js"));
var ClosureFlags = {
language_in: "ECMASCRIPT6",
jscomp_off: ["duplicate"],
externs: [
path.join(externs_path, "extern_b4w.js")
],
jscomp_warning: [
"checkVars",
"accessControls",
"ambiguousFunctionDecl",
"checkEventfulObjectDisposal",
"checkRegExp",
"const",
"constantProperty",
"deprecated",
"deprecatedAnnotations",
"duplicateMessage",
"es3",
"es5Strict",
"externsValidation",
"fileoverviewTags",
"functionParams",
"globalThis",
"internetExplorerChecks",
"missingPolyfill",
"missingProperties",
"missingReturn",
"msgDescriptions",
"suspiciousCode",
"strictModuleDepCheck",
"typeInvalidation",
"undefinedNames",
"undefinedVars",
"unknownDefines",
"uselessCode",
// "misplacedTypeAnnotation",
// "newCheckTypes",
// "unusedLocalVariables"
],
compilation_level: "ADVANCED_OPTIMIZATIONS",
};
config.plugins.push(
new ClosureCompilerPlugin({
compiler: ClosureFlags,
concurrency: 3,
})
)
} else {
config.plugins.push(
new webpack.SourceMapDevToolPlugin({
filename: '[file].map',
})
)
}
return config;
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OpenSourceTees.Models
{
/// <summary>
/// Represents the modle for uploading a TeeShirt image
/// </summary>
public class TeeShirtUploadViewModel
{
/// <summary>
/// file to be uploaded
/// </summary>
public HttpPostedFileBase File { get; set; }
/// <summary>
/// Image object to be palced in the db
/// </summary>
public Image Image { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using OpenSourceTees.Models;
namespace OpenSourceTees.Controllers
{
public class PurchaseOrdersController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: PurchaseOrders
public ActionResult Index()
{
var purchaseOrders = from order in db.PurchaseOrders
where(order.BuyerId == User.Identity.GetUserId())
select order;
if (Request.IsAjaxRequest())
return PartialView(purchaseOrders.ToList());
return RedirectToAction("Index", "Home");
}
// GET: PurchaseOrders/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PurchaseOrder purchaseOrder = db.PurchaseOrders.Find(id);
if (purchaseOrder == null)
{
return HttpNotFound();
}
if (Request.IsAjaxRequest())
return PartialView(purchaseOrder);
return RedirectToAction("Index", "Home");
}
// GET: PurchaseOrders/Create
public ActionResult Create()
{
if (Request.IsAjaxRequest())
return PartialView();
return RedirectToAction("Index", "Home");
}
// POST: PurchaseOrders/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "ItemPrice,Quantity,TotalPrice,ImageId,BuyerId")] PurchaseOrder purchaseOrder)
{
if (ModelState.IsValid)
{
//create order processing object
CreateOrder(purchaseOrder.Id);
//send emails
await SendConfirmationEmails(purchaseOrder);
db.PurchaseOrders.Add(purchaseOrder);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
if (Request.IsAjaxRequest())
return PartialView(purchaseOrder);
return RedirectToAction("Index", "Home");
}
// GET: PurchaseOrders/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PurchaseOrder purchaseOrder = db.PurchaseOrders.Find(id);
if (purchaseOrder == null)
{
return HttpNotFound();
}
if (Request.IsAjaxRequest())
return PartialView(purchaseOrder);
return RedirectToAction("Index", "Home");
}
// POST: PurchaseOrders/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
PurchaseOrder purchaseOrder = db.PurchaseOrders.Find(id);
db.PurchaseOrders.Remove(purchaseOrder);
db.SaveChanges();
return RedirectToAction("Index");
}
/// <summary>
/// sends emails to buyer and creator confirming the order
/// </summary>
/// <param name="purchaseOrder">purchase order emails need to be sent out on</param>
/// <returns>object representation of the task handled</returns>
private async Task SendConfirmationEmails(PurchaseOrder purchaseOrder)
{
EmailService email = new EmailService();
IdentityMessage buyerMessage = new IdentityMessage
{
Destination = purchaseOrder.ApplicationUser.Email,
Body = "",
Subject = "Your Order!"
};
//send email to buyer
await email.SendAsync(buyerMessage);
IdentityMessage sellerMessage = new IdentityMessage()
{
Destination = db.Users.Find(db.Images.Find(purchaseOrder.ImageId).UserId).Email,
Body = "",
Subject = "Someone Placed an Order!"
};
//send email to seller
await email.SendAsync(sellerMessage);
}
/// <summary>
/// creates the OrderProcess object to keep track of the order
/// </summary>
/// <param name="orderId">Id of the order </param>
private void CreateOrder(string orderId)
{
OrderProcessing order = new OrderProcessing()
{
OrderId = orderId,
IsAccepted = false,
IsCanceled = false,
IsDelivered = false,
IsProcessed = false,
IsShipped = false,
IsEmailSent = false
};
db.OrderProcessings.Add(order);
db.SaveChanges();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace OpenSourceTees.Models
{
/// <summary>
/// object representation of an image that was uploaded
/// </summary>
public class Image
{
/// <summary>
/// string representation of a the Id of the image
/// </summary>
[Key]
public string Id { get; set; }
/// <summary>
/// string URL/URI of the actual image
/// </summary>
[Required]
public string ImageUrl { get; set; }
/// <summary>
/// UserId of the poster of image, foreign key
/// </summary>
[ForeignKey("ApplicationUser")]
public string UserId { get; set; }
/// <summary>
/// image designs name
/// </summary>
[Required]
public string DesignName { get; set; }
/// <summary>
/// image designs description
/// </summary>
[Required]
public string Description { get; set; }
/// <summary>
/// the price of the design
/// </summary>
[Required]
public double Price { get; set; }
/// <summary>
/// date the design was created
/// </summary>
[Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreatedDate { get; set; }
/// <summary>
/// foreign key of UserId
/// </summary>
public virtual ApplicationUser ApplicationUser { get; set; }
/// <summary>
/// gets the designers UserName and returns it
/// </summary>
/// <returns>designers UserName</returns>
public string GetDesignerUserName()
{
ApplicationDbContext db = new ApplicationDbContext();
return (from user in db.Users
where (user.Id == UserId)
select user.UserName).ToList()[0].ToString();
}
}
}<file_sep>"use strict"
b4w.register("TeeShirt_main", function (exports, require) {
var m_app = require("app");
var m_cfg = require("config");
var m_data = require("data");
var m_preloader = require("preloader");
var m_ver = require("version");
var m_scenes = b4w.scenes
var DEBUG = (m_ver.type() == "DEBUG");
var APP_ASSETS_PATH = m_cfg.get_std_assets_path();
exports.init = function() {
m_app.init({
canvas_container_id: "main_canvas_container",
callback: init_cb,
show_fps: true,
autoresize: true,
assets_dds_available: !DEBUG,
assets_min50_available: !DEBUG,
console_verbose: true
});
}
function init_cb(canvas_elem, success) {
if (!success) {
console.log("b4w init failure");
return;
}
load();
}
function load() {
var preloader_cont = document.getElementById("preloader_cont");
m_data.load("./TeeShirtToExport.json", load_cb);
}
function preloader_cb(percentage) {
var prelod_dynamic_path = document.getElementById("prelod_dynamic_path");
var percantage_num = prelod_dynamic_path.nextElementSibling;
prelod_dynamic_path.style.width = percentage + "%";
percantage_num.innerHTML = percentage + "%";
if (percentage == 100) {
var preloader_cont = document.getElementById("preloader_cont");
preloader_cont.style.visibility = "hidden";
return;
}
}
function load_cb(data_id, success) {
if (!success) {
console.log("b4w load failure");
return;
}
m_app.enable_camera_controls(false, false, false, null, true);
//load_data();
}
function load_data() {
var shirt = m_scenes.get_object_by_name("T-Shirt");
var ctx_image = m_tex.get_canvas_ctx(shirt, "tex_canvas");
if (ctx_image) {
var img = new Image();
img.src = APP_ASSETS_PATH + "earth.jpg";
img.onload = function () {
ctx_image.drawImage(img, 0, 0, ctx_image.canvas.width,
ctx_image.canvas.height);
m_tex.update_canvas_ctx(shirt, "tex_canvas");
}
}
}
function loadImage(image) {
var shirt = m_scenes.get_object_by_name("T-Shirt");
m_tex.replace_image(shirt, "Texture", image);
}
function create_interface(obj) {
}
});
b4w.require("TeeShirt_main").init();<file_sep>namespace OpenSourceTees.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Images",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
ImageUrl = c.String(nullable: false),
UserId = c.String(maxLength: 128),
DesignName = c.String(nullable: false),
Description = c.String(nullable: false),
Price = c.Double(nullable: false),
CreatedDate = c.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()"),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
UserRole = c.String(),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
CreateTable(
"dbo.AspNetUserClaims",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
ClaimType = c.String(),
ClaimValue = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserLogins",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.KeyRanks",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Ranking = c.Int(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.OrderProcessings",
c => new
{
OrderId = c.String(nullable: false, maxLength: 128),
CreateDate = c.String(nullable: false, defaultValueSql: "GETUTCDATE()"),
IsEmailSent = c.Boolean(nullable: false),
IsAccepted = c.Boolean(nullable: false),
IsProcessed = c.Boolean(nullable: false),
ProcessorId = c.String(maxLength: 128),
IsShipped = c.Boolean(nullable: false),
IsDelivered = c.Boolean(nullable: false),
IsCanceled = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.OrderId)
.ForeignKey("dbo.AspNetUsers", t => t.ProcessorId)
.ForeignKey("dbo.PurchaseOrders", t => t.OrderId)
.Index(t => t.OrderId)
.Index(t => t.ProcessorId);
CreateTable(
"dbo.PurchaseOrders",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
TotalPrice = c.Double(nullable: false),
ItemPrice = c.Double(nullable: false),
Quantity = c.Int(nullable: false),
BuyerId = c.String(nullable: false, maxLength: 128),
ImageId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.BuyerId, cascadeDelete: true)
.ForeignKey("dbo.Images", t => t.ImageId)
.Index(t => t.BuyerId)
.Index(t => t.ImageId);
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
Sql(@"CREATE UNIQUE INDEX PK_Images_Id ON Images(Id)
GO
CREATE FULLTEXT CATALOG tags AS DEFAULT
GO
CREATE FULLTEXT INDEX ON Images(
Id,
DesignName,
Description
)
KEY INDEX PK_Images_Id
ON tags;", true);
Sql(@" create function udf_imageSearch
(@keywords nvarchar(4000),
@SkipN int,
@TakeN int)
returns @srch_rslt table (Id bigint not null, Ranking int not null )
as
begin
declare @TakeLast int
set @TakeLast = @SkipN + @TakeN
set @SkipN = @SkipN + 1
insert into @srch_rslt
select Images.Id, Ranking
from
(
select t.[KEY] as Id, t.[RANK] as Ranking, ROW_NUMBER() over (order by t.[Rank] desc) row_num
from containstable(Images,(Description, DesignName),@keywords)
as t
) as r
join Images on r.Id = Images.Id
where r.row_num between @SkipN and @TakeLast
order by r.Ranking desc
return
end "
);
}
public override void Down()
{
DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles");
DropForeignKey("dbo.OrderProcessings", "OrderId", "dbo.PurchaseOrders");
DropForeignKey("dbo.PurchaseOrders", "ImageId", "dbo.Images");
DropForeignKey("dbo.PurchaseOrders", "BuyerId", "dbo.AspNetUsers");
DropForeignKey("dbo.OrderProcessings", "ProcessorId", "dbo.AspNetUsers");
DropForeignKey("dbo.Images", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers");
DropIndex("dbo.AspNetRoles", "RoleNameIndex");
DropIndex("dbo.PurchaseOrders", new[] { "ImageId" });
DropIndex("dbo.PurchaseOrders", new[] { "BuyerId" });
DropIndex("dbo.OrderProcessings", new[] { "ProcessorId" });
DropIndex("dbo.OrderProcessings", new[] { "OrderId" });
DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" });
DropIndex("dbo.AspNetUserRoles", new[] { "UserId" });
DropIndex("dbo.AspNetUserLogins", new[] { "UserId" });
DropIndex("dbo.AspNetUserClaims", new[] { "UserId" });
DropIndex("dbo.AspNetUsers", "UserNameIndex");
DropIndex("dbo.Images", new[] { "UserId" });
DropTable("dbo.AspNetRoles");
DropTable("dbo.PurchaseOrders");
DropTable("dbo.OrderProcessings");
DropTable("dbo.KeyRanks");
DropTable("dbo.AspNetUserRoles");
DropTable("dbo.AspNetUserLogins");
DropTable("dbo.AspNetUserClaims");
DropTable("dbo.AspNetUsers");
DropTable("dbo.Images");
}
}
}
<file_sep>using OpenSourceTees.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Cors;
using System.Web.Mvc;
namespace OpenSourceTees.Controllers
{
public class HomeController : Controller
{
ApplicationDbContext db;
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
if (Request.IsAjaxRequest())
return PartialView();
return RedirectToAction("Index", "Home"); ;
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
if (Request.IsAjaxRequest())
return PartialView();
return RedirectToAction("Index", "Home");
}
public ActionResult Home()
{
db = new ApplicationDbContext();
var model = new HomePageModel();
model.NewFeed = (from i in db.Images
orderby i.CreatedDate descending
select i).Take(6).ToList();
model.HotFeed = (from i in db.Images
join po in db.PurchaseOrders on i.Id equals po.ImageId into mi
orderby mi.Count() descending
select i).Take(3).ToList();
if (Request.IsAjaxRequest())
return PartialView(model);
return RedirectToAction("Index", "Home");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace OpenSourceTees.Models
{
/// <summary>
/// Object representation of the Order Process
/// </summary>
public class OrderProcessing
{
/// <summary>
/// Primary key of the Order
/// </summary>
[Key]
[ForeignKey("Order")]
public string OrderId { get; set; }
/// <summary>
/// date the order was created
/// </summary>
[Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string CreateDate { get; set; }
/// <summary>
/// boolean representation of emails being sent
/// </summary>
public bool IsEmailSent { get; set; }
/// <summary>
/// boolean representation of order being accepted
/// </summary>
public bool IsAccepted { get; set; }
/// <summary>
/// boolean representation of order being processed
/// </summary>
public bool IsProcessed { get; set; }
/// <summary>
/// String Id of the processor handling the order, foreign key
/// </summary>
[ForeignKey("ApplicationUser")]
public string ProcessorId { get; set; }
/// <summary>
/// boolean representation of order being shipped
/// </summary>
public bool IsShipped { get; set; }
/// <summary>
/// boolean representation of order being delivered
/// </summary>
public bool IsDelivered { get; set; }
/// <summary>
/// boolean representation of order being canceled
/// </summary>
public bool IsCanceled { get; set; }
/// <summary>
/// foreign key application user of processor
/// </summary>
public virtual ApplicationUser ApplicationUser { get; set; }
/// <summary>
/// foreign key order of the OrderId
/// </summary>
public virtual PurchaseOrder Order { get; set; }
/// <summary>
/// gets and returns the Processors UserName
/// </summary>
/// <returns>UserName of the processor</returns>
public string GetProcessorUserName()
{
ApplicationDbContext db = new ApplicationDbContext();
return (from user in db.Users
where (user.Id == ProcessorId)
select user.UserName).ToList()[0].ToString();
}
}
}<file_sep>using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Configuration;
using System.IO;
namespace OpenSourceTees.Models
{
/// <summary>
/// object representation of the Blob Utility
/// </summary>
public class BlobUtility
{
/// <summary>
/// static storage account
/// </summary>
public CloudStorageAccount storageAccount;
/// <summary>
/// no arg constructor
/// </summary>
public BlobUtility()
{
string UserConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
storageAccount = CloudStorageAccount.Parse(UserConnectionString);
}
/// <summary>
/// Uploads the blob to the storage location
/// </summary>
/// <param name="BlobName">name of the blob to be uploaded</param>
/// <param name="ContainerName">name of the container used to upload and store the blob</param>
/// <param name="stream">file stream of file to obe uploaded</param>
/// <returns>CloundBlockBlob represents the uploaded blob</returns>
public CloudBlockBlob UploadBlob(string BlobName, string ContainerName, Stream stream)
{
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(ContainerName.ToLower());
container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });
container.CreateIfNotExists();
CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobName);
// blockBlob.UploadFromByteArray()
try
{
blockBlob.UploadFromStream(stream);
return blockBlob;
}
catch (Exception e)
{
var r = e.Message;
return null;
}
}
/// <summary>
/// delets the blob
/// </summary>
/// <param name="BlobName">blob name to be deleted</param>
/// <param name="ContainerName">name of the container the blob is in</param>
public void DeleteBlob(string BlobName, string ContainerName)
{
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(ContainerName);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobName);
blockBlob.Delete();
}
/// <summary>
/// initializes the download of a blob
/// </summary>
/// <param name="BlobName">blob name to be deleted</param>
/// <param name="ContainerName">name of the container the blob is in</param>
/// <returns>blob to be downloaded</returns>
public CloudBlockBlob DownloadBlob(string BlobName, string ContainerName)
{
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(ContainerName);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobName);
// blockBlob.DownloadToStream(Response.OutputStream);
return blockBlob;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OpenSourceTees.Models
{
/// <summary>
/// object representation of the HomePageModel
/// </summary>
public class HomePageModel
{
/// <summary>
/// List of images to be displayed in the "Hot Feed"
/// </summary>
public List<Image> HotFeed { get; set; }
/// <summary>
/// List of images to be displayed in the "New Feed"
/// </summary>
public List<Image> NewFeed { get; set; }
/// <summary>
/// no arg constructor
/// </summary>
public HomePageModel()
{
HotFeed = new List<Image>();
NewFeed = new List<Image>();
}
}
}
|
2d003f3a6d3fc2d866168f66564adcb8a0cbaae3
|
[
"JavaScript",
"C#"
] | 17 |
C#
|
KodaRayTominus/OpenSourceTees
|
345ff97eb459b17daecc18898b54b211f92852b9
|
e2d7fd6e0d67926f7b1c96f0a83330f6c1b88049
|
refs/heads/master
|
<file_sep>package junit5Tutorials;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertTimeout;
public class J06_PerformanceTesting {
@Test
void performance(){
assertTimeout(Duration.ofSeconds(1),()-> IntStream.rangeClosed(0,1000)).forEach(System.out::print);//Print süreye dahil değil
assertTimeout(Duration.ofMillis(100),()->IntStream.rangeClosed(0,100)).forEach(System.out::print);
}
}
<file_sep>package junit;
import java.util.stream.DoubleStream;
public class HesapMakinesi {
static double topla(double... sayilar){
return DoubleStream.of(sayilar).sum();
}
static double carp(double... sayilar){
return DoubleStream.of(sayilar).reduce(1,(a,b)->a*b);
}
public static class C02_StringChange {
/*
* verilen bir String deki ilk iki harf A ise bunları silen method create ediniz
*AACD->CD ABC->BC A->"" B->B
*/
public static String ilkIkiASil(String str) {
if (str.length() <= 2) {
return str.replaceAll("A", "");
}
String ilkIkiKarakter=str.substring(0,2);//0 dahil 2 dahil değil
String ilkIkiKarakterSonrasi=str.substring(2);
return ilkIkiKarakter.replaceAll("A","")+ilkIkiKarakterSonrasi;
}
}
}
<file_sep>package junit5Tutorials;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.Locale;
import static org.junit.jupiter.api.Assertions.*;
public class J01_Assertions {
@Test
@DisplayName("ToAssert Testi")
void testToAssert(){
int actual="Hakan".length();//5
int expected=5;
//1. assertEquals(); --> expected ve actual degerlerinin esit olma durumunda test Passed olur
assertEquals(expected,actual,"beklenen ve aktuel deger esit degil"); //hata verince bu mesaj gorunecek
//inLine style: her zaman kullanilmaz, simple test'e aykiridir. Code okunabilirligi acisindan tavsiye edilmez
assertEquals(5,"Hakan".length(),"bu yontem cok kullanilmaz");
//2. assertNotEquals(); --> expected ve actual degerlerinin esit olmama durumunda test Passed olur
expected=4;
assertNotEquals(expected,actual,"beklenen ve aktuel deger esit");
//3. assertTrue(); --> olusturulan sart (boolean) true ise test Passed
expected=5;
assertTrue(expected==actual, "sart saglanmadi false deger verdi");
//4. assertFalse(); --> olusturulan sart (boolean) false ise test Passed
expected=5;
assertFalse(expected!=actual, "sart saglandi ve true deger verdi");
}
@Test
@DisplayName("ToConvertUpper Testi")
void testToConvertUpper(){
String expected="BASRİ";
String actual="basri".toUpperCase();
assertEquals(actual,expected); //test data esitse passed
assertTrue(actual.equals(expected)); //test data true ise passed
assertFalse(!actual.equals(expected));
actual=null;
assertNull(actual,"actual deger null degil"); //parametre null ise Passed
//assertNotNull(actual, "actual deger null"); -->failed
actual="kenan";
assertNotNull(actual, "actual deger null");
}
@Test
@DisplayName("ToContain Testi")
void testToContain(){
boolean actual="erdem".contains("hi"); //false
boolean expected=false;
assertEquals(actual,expected, "degerler esit degil"); //actual=false, expected=false --> actual=expected (Passed)
}
@Test
@DisplayName("Arrays Testi")
void testWithArrays() {
String str = "junit ile ebik gabik testler";
String actual[] = str.split(" "); //{"junit", "ile", "ebik", "gabik","testler"}
//String expected[]={"junit", "ile", "ebik", "gabik","testler"};
String expected[] = {"junit", "ile", "ebik", "gabik", "testler"};
assertArrayEquals(expected, actual, "arrayler esit degil");
}
}
<file_sep>package junit;
import java.util.Arrays;
public class C03_ArrayEsitMi {
//iki arrayi kkiyaslayan method create ediniz
public static boolean diziKiyasla(Object[]a,Object[]b){
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a,b);
}
}
<file_sep>package junit5Tutorials;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class J05_RepeatedDisableTest {
/*
@RepeatedTest(a)-->Test edilecek metod a kadar döngü içinde test edilir
junit 5 ile gelmiştir.
*/
@AfterEach
void afterEachTest(){
System.out.println("after çalıştı");
System.out.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
}
@BeforeEach
void beforeEachTest(){
System.out.println("before çalıştı");
}
@RepeatedTest(7)
@DisplayName("Contains method 7 kez test ediliyor")
void containsTest() {
assertFalse("Erdem".contains("hi"));
System.out.println("contains method çalıştı");
}
@RepeatedTest(5)
@DisplayName("Topla method 5 kez test ediliyor")
void toplaTest() {
assertEquals(5,(2+3));
System.out.println("topla method çalıştı");
}
@Disabled("bu method ")
@Test
void karpuzTest(){
String karpuz="adana karpuzu, guldurur yuzu";
assertEquals(28,karpuz.length());
}
}
|
3d6ed87608e39b5bab3d947c60df6dd8fe55aa98
|
[
"Java"
] | 5 |
Java
|
erdemgocen44/UnitTest
|
f3fb214198937b785935c5d8707143308c1d27ff
|
d252f72a7bf99e7f95da3addf7640bff426defb4
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.